How To Call a Method in Java – [With Examples]

A method in Java is a group of lines that performs a single action or operation. It is commonly use because it allows code to be reuse, which implies that you can write once and use it many times. It also allows for easy customization. Each approach has its own name that it is referred to by. The method is called and the stated task is performed when the compiler reads the method name. We’ll learn how to call pre-defined, user-defined, static, and abstract methods in Java in this section.

Creating Method

Consider the following example to demonstrate a method’s syntax:

Syntax:

public static int nameOfMethod(int param_1, int param_2) {
   // body
}

Here,

  • public static − modifier
  • int − return type
  • nameOfMethod − name of the method
  • param_1, param_2 − formal parameters
  • int param_1, int param_2 − list of parameters

A method header plus a method body make up a method definition. The following syntax demonstrates the same.

Syntax:

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

The syntax shown above includes −

  • modifier It specifies the method’s access type and is optional to use.
  • returnType A value can be returned by a method.
  • methodName This is the name of the method. The method signature is made up of the method name and a list of parameters.
  • Parameter List: A method’s parameter list, which includes the type, order, and a number of parameters. These are optional; the method could have no parameters.
  • method body The method body specifies how the method interacts with the statements.

Example:

The source code for the above-mentioned Sum method may be found here. This method accepts two parameters, num1 and num2, and returns the greatest difference between them.

import java.util.Scanner;
class SumMethod{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1=sc.nextInt();
System.out.print("Enter the second number: ");
int num2=sc.nextInt();
sc.close();
Sum(num1,num2); 
}
//Sum method
public static void Sum(int num_A,int num_B){
int sum=0;
sum=num_A+num_B;
System.out.println("Sum of two numbers  "+sum);
}
}

Output:

method in Java img1

Method Calling

It is necessary to call a method in order to use it. A method can be call in two ways: it can return a value or it can return nothing.

Method calling is a straightforward procedure. When a program calls a method, control is passed from the calling program to the called method.

When the return statement is executed or the method ending closing brace is reached, this called method returns control to the caller in one of two ways.

A call to a statement is define as a method that returns void. Consider the following scenario.

System.out.println("Softhunt.net!");

The following example demonstrates how a method returns a value.

int result = sum(12, 7);

The following is an example of how to define a method and then call it.

Example:

class findMinMethod{
   public static void main(String[] args) {
      int a = 12;
      int b = 7;
      int c = minimumNumberFunction(a, b);
      System.out.println("Minimum Value = " + c);
   }
   public static int minimumNumberFunction(int num1, int num2) {
      int minimum;
      if (num1 > num2)
         minimum = num2;
      else
         minimum = num1;

      return minimum; 
   }
}

Output:

method in Java img2

The void Keyword

We can use the void keyword to define methods that don’t return a value. In the following example, we’ll look at a void method called gradeFinder. This is a void method, which means it returns nothing. A statement must be use to call a void method, such as gradeFinder(84);. As illustrated in the following example, it is a Java statement that concludes with a semicolon. As a result, you’ll get the Output: A.

Example: Using Values to Pass Parameters

Arguments must be pass while working in the calling procedure. These should be listed in the method specification in the same order as their corresponding parameters. Parameters can be given in two ways: as a value or as a reference.

Calling a method with a parameter is known as passing parameters by value. The argument value is provided to the parameter this way.

class methodWithVoid{
   public static void main(String[] args) {
      gradeFinder(84);
   }
   public static void gradeFinder(double points) {
      if (points >= 85) {
         System.out.println("Grade:A1");
      }else if (points >= 80) {
         System.out.println("Grade:A");
      }else if(points >= 75){
         System.out.println("Grade:B");
      }else{
         System.out.println("Grade:B");
}
   }
}

Output:

method in Java img3

Method Overloading

When a class has two or more methods with the same name but different parameters, this is known as method overloading. It’s not the same as taking control. When a method is overridden, it has the same name, type, number of parameters, and so on.

Consider the example of finding the smallest integer numbers given above. Let’s say we’re looking for the smallest number of double types. Then, to build two or more methods with the same name but different parameters, the notion of overloading will be introduce.

The following example clarifies the situation.

Example:

public class methodOverloading{

   public static void main(String[] args) {
      int intNum_01 = 43;
      int intNum_02 = 55;
      double doubleNum_01 = 4.3;
      double doubleNum_02  = 3.23;
      int result_01 = minimumNumFun(intNum_01 , intNum_02 );
      
      // same function name with different parameters
      double result_02 = minimumNumFun(doubleNum_01 , doubleNum_01 );
      System.out.println("Minimum Value = " + result_01);
      System.out.println("Minimum Value = " + result_02);
   }

   // for integer
   public static int minimumNumFun(int n1, int n2) {
      int min;
      if (n1 > n2)
         min = n2;
      else
         min = n1;

      return min; 
   }
   
   // for double
   public static double minimumNumFun(double n1, double n2) {
     double min;
      if (n1 > n2)
         min = n2;
      else
         min = n1;

      return min; 
   }
}

Output:

method in Java img4

Overloading methods make the program readable. Here, two methods are given by the same name but with different parameters. The minimum number from integer and double types is the result.

Calling Static Method in Java

A static method in Java is one that is invoke or call without first constructing an object of the class in which it is define. Static methods are any methods that have the keyword static before the method name. We may also use the static keyword before the method name to create a static method. We can use the ClassName.methodName to call a static method.

The main() function is the best example of a static method. It is called without the object being created.

The static method of the Math class, entitled min(), is call in the following program to return the minimum value of two numbers.

Example:

class StaticMethod
{
public static void main(String args[]) 
{
int num;
num=Math.min(21,12);
System.out.println("Minimum number is: " + num);
}
}

Output:

img5

Calling the Pre-Defined Method in Java

Pre-defined methods are methods that have already been define in the classes in Java. When a pre-defined method is necessary, we simply call it by its name.

We utilized the hashCode() function of the class Object in the following example. And generated an object obj of the Object class to call the pre-defined function hashCode() because it is a method of the Object class. We used the object to call the hashCode() method, which returns the object’s hash code value.

Example:

class PredefinedMethod
{
public static void main(String[] args) 
{
int num;    
Object obj_01 = new Object();    
num=obj_01.hashCode();
System.out.println("Hash Code of the object is: " + num);
}
}

Output:

img6

Calling User-Defined Method in Java

We construct a method first, then call it to call a user-defined method. In the class, a method must be establish with the name of the method follows by parentheses (). The method definition is made up of a method header and a method body.

We can use the following syntax to call a method:

method name();

We use the following if the method is a static method:

/ obj.method name() / obj.method name() / obj.method_

Where obj is the class’s object.

We’ve developed two user-defined methods, showMessage() and displayMessage(), in the following example. The static method showMessage() is different from the non-static function displayMessage().

It’s worth noting that we didn’t use the object to call the showMessage() method. While the class’s object is use to invoke the displayMessage() method

Example:

class userDefinedMethod
{
static void showMessage() 
{
System.out.println("Static method.");
}
void displayMessage() 
{
System.out.println("Non-static method.");
}
public static void main(String[] args) 
{
showMessage(); 
userDefinedMethod method=new userDefinedMethod();
method.displayMessage();
}
}

Output:

img7

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Suggested Articles:

  1. What is Treemap in Java?
  2. What is a Thread in Java?

Leave a Comment