Examples of Method in Java

Rumman Ansari   Software Engineer   2022-03-02   7934 Share
☰ Table of Contents

Table of Content:


Example 1

Following is the example to demonstrate how to define a method and how to call it

public class ExampleMinNumber {

   public static void main(String[] args) {
      int a = 15;
      int b = 78;
      int c = minFunction(a, b);
      System.out.println("Minimum Value = " + c);
   }

   /** returns the minimum of two numbers */
   public static int minFunction(int num1, int num2) {
      int min;
      if (num1 > num2)
         min = num2;
      else
         min = num1;

      return min;
   }
}

Output:

Minimum Value = 15
Press any key to continue . . .

Example 2

The void keyword allows us to create methods which do not return a value. Following is the example to demonstrate how to define a method and how to call it

public class ExampleVoidMethod {

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

   public static void methodRankPoints(double points) {
      if (points >= 202.5) {
         System.out.println("Position of Points: A1");
      }else if (points >= 122.4) {
         System.out.println("Position of Points: A2");
      }else {
         System.out.println("Position of Points: A3");
      }
   }
}

Output:

Position of Points: A1
Press any key to continue . . .

Example 3

The printGrade method is a void method because it does not return any value. A call to a void method must be a statement. Therefore, it is invoked as a statement in the main method. Like any Java statement, it is terminated with a semicolon.

public class VoidMethodExample {
 public static void main(String[] args) {
 System.out.print("The grade is ");
 printGrade(78.5);

 System.out.print("The grade is ");
 printGrade(59.5);
 }

 public static void printGrade(double score) {
 	if (score >= 90.0) {
 		System.out.println('A');
 	}
 	else if (score >= 80.0) {
 		System.out.println('B');
	 }
 	else if (score >= 70.0) {
 		System.out.println('C');
 	}
    else if (score >= 60.0) {
 		System.out.println('D');
    }
    else {
	 System.out.println('F');
 	}
 }
}

Output:

The grade is C
The grade is F
Press any key to continue . . .

Example 4

Value-returning method getGrade, returns the grade as shown in below example

public class ReturnGradeMethod {
  public static void main(String[] args) {
   System.out.print("The grade is " + getGrade(78.5) );
   System.out.print("\nThe grade is " + getGrade(59.9) );
 }

public static char getGrade(double score) {
	if (score >= 90.0)
		return 'A';
	else if (score >= 80.0)
		return 'B';
	else if (score >= 70.0)
		return 'C';
	else if (score >= 60.0)
		return 'D';
	else
		return 'F';
	}
}

Output:

 
The grade is C
The grade is FPress any key to continue . . .

Example 5

When you invoke a method with an argument, the value of the argument is passed to the parameter. This is referred to as pass-by-value. If the argument is a variable rather than a literal value, the value of the variable is passed to the parameter. The variable is not affected, regardless of the changes made to the parameter inside the method. As shown in below example, the value of x ( 1 ) is passed to the parameter num to invoke the increment method. The parameter num is incremented by 1 in the method, but x is not changed no matter what the method does.

public class IncrementExample {
 public static void main(String[] args) {
 	int x = 1;
 	System.out.println("Before the call, x is " + x);

 	increment(x);

 	System.out.println("After the call, x is " + x);
 }

 public static void increment(int num) {
 	num++;
 	System.out.println("n inside the method is " + num);
 	}
 }

Output:

 
Before the call, x is 1
n inside the method is 2
After the call, x is 1
Press any key to continue . . .

Example 6

Methods can be used to reduce redundant code and enable code reuse. Methods can also be used to modularize code and improve the quality of the program.


Below program that prompts the user to enter two integers and displays their greatest common divisor. You can rewrite the program using a method, as shown below.

import java.util.Scanner;

 public class GreatestCommonDivisorMethod {
 /** Main method */
 	public static void main(String[] args) {
 	// Create a Scanner
	 Scanner input = new Scanner(System.in);

 	// Prompt the user to enter two integers
 	System.out.print("Enter first integer: ");
 	int n1 = input.nextInt();
 	System.out.print("Enter second integer: ");
 	int n2 = input.nextInt();

  	System.out.println("The greatest common divisor for " + n1 + " and " + n2 + " is " + gcd(n1, n2) );
 }

 /** Return the gcd of two integers */
public static int gcd(int n1, int n2) {
 	int gcd = 1; // Initial gcd is 1
 	int k = 2; // Possible gcd

	 while (k <= n1 && k <= n2) {
 		if (n1 % k == 0 && n2 % k == 0)
 		gcd = k; // Update gcd
 		k++;
 	}

	 return gcd;// Return gcd
 	}
 }

Output:

 
Enter first integer: 12
Enter second integer: 15
The greatest common divisor for 12 and 15 is 3
Press any key to continue . . .