by Dinesh Thakur Category: Java Methods

A Java method is a collection of statements, all performing a particular operation.  Let’s say that you were calling the method called System.out.println(); Java executes some different statements that print a message to your console.  We’re going to look at the creation of methods or, as they often called, functions.

How to Create a Method

In Java, method definition usually consists of four fundamental parts, the name of the method, the object type or the data type that the method returns (referred to as return type), the list of parameters and the body of the method.

The first three constituents of the method definition are referred to as method declaration or method signature. The method declaration usually gives the important information about the method itself. A method structured in this way:

public static int methodName(int a, int b) { // body  }  
What does all of this mean?  
public static: this is a modifier  
int: this is the return type  
methodName: this is the name of the method
• a, b - these are formal parameters  
int a, int b – these are parameter lists  
Defining a method requires a method header and a method body, as you can see  here:  
modifier returnType nameOfMethod (Parameter List) {  // method body  }

In this example:  
modifier: defines the access type of the method and is optional.  void (if the method does not return a value at all)
return type:It refers to the type of value the method returns. It can be a primitive data type. 
Parameter List: this lists the parameters along with the type, the order and how many parameters are in the method. It is optional because methods don’t need parameters.  
nameOfMethod: is the name of the method and also has the list of parameters.  
method body:  this is where we define what the method do with your statements. 

If the method returns an array object, the array brackets are placed after the return type or after the parameter list.

The two ways of returning array type in a method are depicted below:

For example, the method signature

int[] method1(int a1, int a2) { // body of the method }

can also be written as follows:

int method1 (int a1, int a2)[] { // body of the method }

Out of these two representations, the first one is most commonly used.

The parameter list in the method definition is a set of variable declarations, separated by commas, inside parentheses (). These parameters become local variables in the body of the method, whose values are the objects or primitives passed in when the method is called.

The body of the method can consist of statements, expressions, method calls to other objects, conditionals, loops and so on.

If return type is real (that is, it is not void), a value should be returned explicitly in the body of method. Java provides the keyword return by means of which this can be done.

 In the next example, you can see the code of a method called max(). This method takes two parameters called num1 and num2, and we see the maximum between both of these parameters as the return:  
/** this code returns the maximum between the two numbers */

publicstatic int maxFunction(int n1, int n2) {
    int max;
    if(n1 > n2)
         max = n2;
     else max = n1;
        return max;

Calling Methods

When you want to use methods or functions, you have a choice of two ways to do it – either with a value or without a value. It is quite simple to call a method – this  means that the method gets invoked, program control goes to the method and then returned to the caller under two conditions:  

• When the execution of the return statement has finished.  
• When the method’s closing brace is reached.  

In the next example, we see how methods are defined and called:

publicclass ExampleMinNumber {
staticvoid main(String[] args){
           int a =11;
           int b =6;
           int c = minFunction(a, b);
           System.out.println("Minimum Value = "+ c);
       /** returns the minimum of two numbers */
      publicstaticint minFunction(int n1,int n2){
           int min;
           if(n1 > n2)
                min = n2;
           else min = n1;
               return min;

The void Keyword

If we didn’t want a value returned from the method, the void keyword would use. In the example below, we have a method named methodRankPoints – because we don’t want a value from this method it is a void method. To call it you need a statement as you can see in this example:

publicstatic void main(String[] args) {
publicstatic void methodRankPoints(double points) {
     if(points >=202.5){
    elseif(points >=122.4){

Passing Parameters by Value

When a method called, arguments must be passed and must be in the same order as the parameter that does with them in your method. Parameters may be passed in two ways – by value and by reference.  To pass them by value, a method  that has a parameter must be called, and this result in the argument value being  passed to the parameter, as you can see in this example:

publicclass SwappingExample {
      publicstaticvoid main(String[] args){
            int a =30;
            int b =45;
           System.out.println("Before swapping, a = "+a +" and b = "+ b);
           // Invoke the swap method
           swapFunction(a, b);
           System.out.println("\n**Now, Before and After swapping values will be same here**:");
           System.out.println("After swapping, a = "+a +" and b is "+ b);
      publicstaticvoid swapFunction(int a,int b){
          System.out.println("Before swapping(Inside), a = "+a+" b = "+ b);
             // Swap n1 with n2
          int c = a;
          a = b;
          b = c;
          System.out.println("After swapping(Inside), a = "+a+" b = "+ b);

Method Overloading

In other programming languages, method names (function, subroutine or procedure names) are unique; however, in Java, different methods can have the same name, but a different return type or argument list.

The process of having methods with the same name but with different return type is referred to as method overloading.

It is not the same as overriding a method – for this; each method would be identical in name, type, parameters, etc.
Let’s assume that we have a double type and we want to know what its minimum number is. Overloading would be introduced to create a minimum of two methods  of the same name but having different parameters, as such:

public class ExampleOverloading {
         public static void main(String[] args) {
              int a = 11;
              int b = 6;
              double c = 7.3;
              double d = 9.4;
              int result1 = minFunction(a, b);
              // same function name with different parameters
              double result2 = minFunction(c, d);
              System.out.println("Minimum Value = " + result1);
              System.out.println("Minimum Value = " + result2);
            // for integer
         public static int minFunction(int n1, int n2) {
             int min;
             if (n1 > n2)
                 min = n2;
              else min = n1;
                 return min;
           // for double
        public static double minFunction(double n1, double n2) {
               double min;
               if (n1 > n2)
                   min = n2;
               else min = n1;
               return min;

When you overload, you can make your code infinitely more natural to read. What we have done here is provided two methods with identical names but each with different parameters; the result is the minimum number from both int and from double.

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.