Mastering Java Methods with Examples - RRTutors

In this section will discus about What is Method and How to create Methods in Java. A method in Java is a set of statements that are grouped together to perform various actions. For example, when a System.out.println()method is called, the system actually executes several statements in order to display messages on the console.

Next, learn how to create your own methods with or without return values, call methods with or without parameters, and apply method abstraction in programming.

1. Create method

Let's have a look at the syntax of the method −

public static int methodName(int a, int b) {

// body

}

In the syntax above,

  • public static− Rhetoric
  • int− the type of the return value
  • method Name− the name of the method
  • a, b− Formal parameters
  • int a, int b− parameter list

A method definition consists of a method header and a method body. The same is shown in the following syntax −

modifier returnType nameOfMethod (Parameter List) { // method body }

 
The syntax shown above includes −
  • modifier- It defines the access type of the method, it may be: public, private, protectedor not specified.
  • return Type- A method can return a value.
  • name Of Method- This is the method name, and the method signature consists of the method name and the parameter list.
  • Parameter List- The parameter list, which is the method's type, order and number of parameters. These are optional and methods may contain zero arguments.
  • method body- The method body defines what the method does to the statement.

example

The method is defined in the following code min(). This method takes two intparameters of type: num1and num2, and returns the maximum value between the two -

public static int minFunction(int n1, int n2) {

int min;

if (n1 > n2) min = n2;

else min = n1;

return min;

}



2. Method call

A method can be used by calling a method. There are two ways to call a method, that is, the method returns a value or does not return any value.

The process of method invocation is simple. When a program calls a method, program control is transferred to the called method. This called method then returns control to the caller on two conditions, namely −

  • return statement is executed.
  • It reaches the end of the method, the closing brace ( }).

A call to the returned voidmethod -

System.out.println("This is Java Language");

 
A call to a method that returns a value −

int result = sum(6, 9);

 
Following is an example that demonstrates how to define a method and how to call a method −

public class ExampleMinNumber {

public static void main(String[] args) {

int a = 111; int b = 125; int c = getMin(a, b); System.out.println("Min number = " + c);

} public static int getMin(int n1, int n2) {

int min;

if (n1 > n2) min = n2;

else min = n1;

return min;

}

}

 

Execute the above sample code and get the following results:

Min number = 111

3. void keyword

void The keyword allows the creation of methods that do not return a value. In the example below there is void a method with a return value of methodRankPoints, which does not return any value. Invoking a void method must be a statement i.e. methodRankPoints(245.67); it is a Java statement ending with a semicolon as shown in the following example −

public class ExampleVoid {

public static void main(String[] args) { methodRankPoints(245.67);

}

public static void methodRankPoints(double points) {

if (points >= 202.5) {

System.out.println("Rank:A1");

}else if (points >= 122.4) { System.out.println("Rank:A2");

}else {

System.out.println("Rank:A3");

}

}

}

 
Execute the above sample code and get the following results:
Rank:A1

4. Pass parameters by value

Parameters need to be passed when passing them by value. They should be in the same order as the parameters in the method specification. Parameters can be passed by value or reference.

Passing parameters by value is calling a method with parameters. By doing this the parameter value will be passed to the parameter.

example

The following program shows an example of passing parameters by value. Even after the method call, the value of the parameter remains the same.

public class swappingExample {

public static void main(String[] args) {

int a = 30;

int b = 45;

System.out.println("Before swapping, a = " + a + " and b = " + b);

swapFunction(a, b);

System.out.println("Now, Before and After swapping values will be same here:");

System.out.println("After swapping, a = " + a + " and b is " + b);

}

public static void swapFunction(int a, int b) { System.out.println("Before swapping(Inside), a = " + a + " b = " + b);

int c = a; a = b; b = c;

System.out.println("After swapping(Inside), a = " + a + " b = " + b);

}

}

 

Execute the above sample code and get the following results:

Before swapping, a = 30 and b = 45

Before swapping(Inside), a = 30 b = 45

After swapping(Inside), a = 45 b = 30

Now, Before and After swapping values will be same here:

After swapping, a = 30 and b is 45

 

5. Method overloading

When a class has two or more methods with the same name but different parameters, it is called method overloading. It's not the same as rewriting. In an override, methods have the same method name, type, number of parameters, etc.

In the example discussed earlier for finding the smallest number of an integer type, suppose you wanted to find doublethe smallest number of two types. The concept of overloading can be introduced to create two or more methods with the same name but different parameters.

Refer to the following sample code −

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 = getMin(a, b);

double result2 = getMin(c, d);

System.out.println("Minimum Value = " + result1);

System.out.println("Minimum Value = " + result2);

}

public static int getMin(int n1, int n2) {

int min;

if (n1 > n2) min = n2;

else min = n1;

return min;

}

public static double getMin(double n1, double n2) {

double min;

if (n1 > n2) min = n2;

else min = n1;

return min;

}

}




Execute the above sample code and get the following results:

Minimum Value = 6
Minimum Value = 7.3

Overloading methods makes programs readable. Here, two methods are given by the same name but have different parameter types. The result is to find the minimum number of inttypes and types.double

6. Using command line parameters

Some times it is desirable to pass some information to a program when it is run. It does so by passing command-line arguments to main().

Command-line arguments are information that directly follows the program name on the command line when executed. Accessing command line arguments in a Java program is very simple. They are stored as strings in main()the String typed array passed to .

example

The following program displays all the command line arguments passed to the program −

public class CommandLine {

   public static void main(String args[]) { 
      for(int i = 0; i<args.length; i++) {
         System.out.println("args[" + i + "]: " +  args[i]);
      }
   }
}

Execute this procedure using −

C:/> java CommandLine this is a command line 200 -100

Then the following result will be obtained:

args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100

7. this keyword

this is a keyword in Java used as a reference to the current class object, within an instance method or constructor. Use it to refer to members of a class such as constructors, variables and methods.

Note - this The keyword is only used in instance methods or constructors.

Usually, thiskeywords are used for −

  • Instance variables are distinguished from local variables if they have the same name within a constructor or method.

    class Student {
     private int age;   
     Student(int age) {
        this.age = age;
     }
    }
    
    Java
  • Invoking a type of constructor (either a parameterized constructor or a default) from another method in the class is called an explicit constructor call.

    class Student {
     int age
     Student() {
        this(20);
     }
    
     Student(int age) {
        this.age = age;    
     }
    }
    
    Java

Following is this an example of accessing class members using keywords −

public class ThisExample {
   
   int num = 10;
   ThisExample() {
      System.out.println("This is an example program on keyword this");    
   }

   ThisExample(int num) {
      
      this();

  
      this.num = num;
   }

   public void greet() {
      System.out.println("Hi Welcome to Yiibai");
   }

   public void print() {
      
      int num = 20;

      
      System.out.println("value of local variable num is : "+num);

      
      System.out.println("value of instance variable num is : "+this.num);

      
      this.greet();     
   }

   public static void main(String[] args) {
      
      ThisExample obj1 = new ThisExample();

      
      obj1.print();

      
      ThisExample obj2 = new ThisExample(30);

      
      obj2.print(); 
   }
}
Java

Execute the above sample code and get the following result −

This is an example program on keyword this 
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Yiibai
This is an example program on keyword this 
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Yiibai

8. Variable parameters (var-args)

JDK 1.5 allows a variable number of parameters of the same type to be passed to a method. The parameters in the method are declared as follows −

type Name... parameter Name
Java

In a method declaration, specify the type followed by an ellipsis ( ...). Only one variable-length parameter can be specified in a method, and this parameter must be the last parameter.

public class VarargsDemo {

   public static void main(String args[]) {
       
       printMax(314, 321, 213, 212, 356.5);
       printMax(new double[]{1, 2, 3});
   }

   public static void printMax( double... numbers) {
      if (numbers.length == 0) {
         System.out.println("No argument passed");
         return;
      }

      double result = numbers[0];

      for (int i = 1; i <  numbers.length; i++)
      if (numbers[i] >  result)
      result = numbers[i];
      System.out.println( result);
   }
}
Java

Execute the above sample code and get the following result −

356.5
3.0

9. finalize() method

The finalize() method is called before the object is finally destroyed by the garbage collector, and it can be used to ensure that the object is fully finalized. For example, you can use finalize()to ensure that open files owned by this object are closed.

To add a finalizer to a class, just define a finalize()method. It calls this method whenever a Java method wants to recycle an object of that class.

In the finalize()method, you will specify the actions that must be performed before the object is destroyed. finalize()A method has this general form -

protected void finalize( ) {
   // finalization code here
}
Here, keyword protectedis a specifier that prevents access by code defined outside the class finalize().
We have no way of knowing when or even if Java will execute the finalize()method. If the program ends before garbage collection occurs, it finalize()will not execute.