Creating a method in java / How to call a method in java

What is a method
Suppose there are a few lines of code which need to be used at multiple places. Now repeating these lines everywhere has following 2 problems
1. It will increase number of lines of code unnecessarily.
2. If you need to make a single change to these repeating lines(either due to change of logic or refactoring), then it needs to be done at multiple places.
To eliminate the above problems, these repeating code lines are grouped into a named code block enclosed within curly braces({ and }) which is called a method. In order to use this block it is called by using its name. This post shall cover method declaration, calling a method(both static and instance), passing arguments to method and much more.
Thus, a method is a block of code which has a name and can be called using this name. A method may or may not return a value.

Declaring a method
A method can be created using a pre-defined syntax as below.

<access modifier> <return type> <method name>(optional arguments) {
// method code
}

Access modifier defines the visibility of a method can be either public, private, protected or default(no modifier). You can learn more about access specifiers here.

If a method is declared privatein a class, then it can only be called from within the same class, not even from sub-classes since it will not be visible outside the class.

Return type represents the type of value returned by the method. It should be void if the method does not return a value.
Method name is a user defined name. Name should follow some rules which are listed next.
Method name should be followed by parenthesis which may be empty or contain arguments. Arguments are the values which are supplied to a method and are declared just like normal variables are defined. Multiple arguments are separated by a comma.
If the method is static, then static keyword also needs to be placed after or before access modifier.
Whole method should begin and end with curly braces({ and }). All code between these braces is considered to be part of method and is called method body.
Examples of method declaration are given below.

// method with no arguments and no return value
public void printWelcomeMessage() {
System.out.println(“Welcome to codippa.com”);
}

// method with 1 argument of type String and no return value
public void printMessage(String message) {
System.out.println(message);
}

// method with 2 integer arguments and no return value
public void addNumbers(int numOne, int numTwo) {
int sum = numOne + numTwo;
System.out.println(sum);
}

// method with 2 integer arguments returning an integer
public void getSum(int numOne, int numTwo) {
int sum = numOne + numTwo;
return sum;
}

Method naming rules
Name of method is user defined name which should follow below rules to prevent compiler errors.

  1. It should start with an alphabet or an underscore. It should not start with a number or a special character though numbers are allowed in between method name.
  2. A method name cannot contain special characters such as !, @, #, % etc. $ is allowed in between method name.
  3. Method names should be in camel case(first letter of name in lower case and first letter of every word in upper case). Examples, getLetterCount, printMessage etc. Violating this will not result in compiler error but it is a convention.
  4. Method names should be meaningful and should represent the purpose of the method. Names such as myMethod, method1, test etc. should be discouraged. Violating this will also not raise a compiler error but following this will enhance code readability.

Calling a method
In order to execute a method it needs to be called(or invoked). A method can be called using its name followed by parenthesis containing appropriate arguments, if it expects any. There is some difference when calling static and non-static(or instance) methods.
Calling non-static(or instance) methods
Below code shows an example of calling a method.

public class MethodDemo {
  // defining a method
  public void printWelcomeMessage() {
     System.out.println("Welcome to codippa.com");
  }
 
  public static void main(String[] args) {
     // create an instance of this class
     MethodDemo obj = new MethodDemo();
     // call the method
     obj.printWelcomeMessage();
  }
}

Method defined above does not return a value and does not accept any arguments. Also, it is an instance or non-static method. Thus, for calling this method, we need an instance(or object) of its class. An instance is created and method is called on this instance.
Remember that if we are calling a method from another method, we can call it directly using method name as shown below.

public class MethodDemo {
  // defining a method
  public void printWelcomeMessage() {
     System.out.println("Welcome to codippa.com");
     // call another method of same class
     printAnotherMessage();
  }
 
  public void printAnotherMessage() {
    System.out.println("Method called from other method");
  }
  public static void main(String[] args) {
     // create an instance of this class
     MethodDemo obj = new MethodDemo();
     // call the method
     obj.printWelcomeMessage();
  }
}

Above example calls a method from main method using the class instance. Another method is called from this method but without using an instance of the class. This is because when the second method is being called, there is already an instance of the class which is executing the first method.

Calling static methods
static methods are class level methods and are shared by all objects of the class. Thus, for calling static methods, there is no need of having an instance of the class, they can be called directly using the class name as shown below.

public class MethodDemo {
  // defining a static method
  public static void printWelcomeMessage() {
     System.out.println("Welcome to codippa.com");
  }
 
  public static void main(String[] args) {
     // call the static method
     MethodDemo.printWelcomeMessage();
  }
}

Notice the way static method has been called directly using the class name, no instance is required. If you are calling a static method from another static method, you can omit the class name also. Thus in the above example, printWelcomeMessage can also be called by only using its name.

Calling method from outside of class
It is also possible to call a method defined in a class from another class. For this, an object of the class containing the method to be called is required. In case of static methods, even the object is also not required. Remember that for a method to be called from outside its class, it should not be private and should be visible to the calling class as per its access modifier. Example,

// class containing a method
public class ExternalMethod {
  // method definition
  public void printWelcomeMessage() {
     System.out.println("Welcome to codippa.com");
  }
  // static method definition
  public static void printAnotherMessage() {
     System.out.println("This is a static method");
  }
}
public class CallingExternalMethod {
   public static void main(String[] args) {
     // create an instance of external class
     ExternalMethod obj = new ExternalMethod();
     // call external method
     obj.printWelcomeMessage();
     // call static method
     ExternalMethod.printAnotherMessage();
  }
}

In the above example, it is assumed that both the classes are in the same package. Notice how both static and non-static methods have been invoked.

Passing arguments to method
Arguments are the values passed to a method. This makes a method more dynamic and reusable. Consider a method that adds 2 numbers. Instead of writing the numbers inside the method, if the numbers to be added are supplied to it as arguments, then this method will be able to add any two numbers, thus making the method reused at places where addition of two numbers is required.
Passing arguments is a two step process.
1. Method should declare that it will accepts arguments.
2. Supplying values matching argument types at the time of calling method.
Example,

public class MethodDemo {
   // accept two integer arguments
   public void addNumbers(int numOne, int numTwo) {
      int sum = numOne + numTwo;
      System.out.println(sum);
   }
 
   public static void main(String[] args) {
     // create an instance of this class
     MethodDemo obj = new MethodDemo();
     // call the method
     obj.addNumbers(1, 2);
  }
}

Remember that the type of arguments provided while calling a method should be same as the method expects and in the same order else there will be a compiler error.

Returning values from a method
A method may or may not return a value. Often a method should return some value to the calling method which is used for further computation. Example, consider a method which accepts a number, checks whether it is even or odd and returns true or false accordingly. Now the calling method prints the result based on the value returned by this method.
A method can return a value by using return keyword followed by the value to be returned. If a method returns some value, then it should declare the type of value it will return in its definition. Also, the value returned by a method should be stored in a variable of same type(as returned by the method) in the calling method. If a method does not return any value then its return type should be void and there is no need to place return statement in it(this will be a compiler error anyway).
Example follows.

public class MethodDemo {
   // accept an integer argument and declare the return type
   public boolean checkEvenOdd(int num) {
      // check if remainder after division by 2 is 0
      if(num % 2 == 0) {
         // number is even
         return true;
      }
      return false;
   }
 
   public static void main(String[] args) {
     // create an instance of this class
     MethodDemo obj = new MethodDemo();
     // call the method and store its returned value
     boolean isEven = obj.checkEvenOdd(5);
     if(isEven) {
        System.out.println("Number is even");
     } else {
        System.out.println("Number is odd");
     }
  }
}

return statement should be the last statement in the method. Any code written after return will raise a compiler error.

Hope this post helped in understanding the concept of methods in java. For any doubts/clarifications do not hesitate to write in the comments section.

0

Leave a Reply

Mark Your Impression

  Subscribe  
Notify of
Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.