Methods in Java

Methods in Java are the block of code that performs a specific task. A method represents a collection of instructions that only run when called.

The methods are very useful, especially for code reusability. We can execute the same method from different places in the code. This eliminates the need for code duplication.

Create a method in Java

The syntax to declare a method is:

public void methodName() {
    // code to be executed 
  }

Let’s see what the definition of the method contains:

  • public – This is one of the Java access modifiers. Public means that the method will be visible within the entire program structure.
  • void – It is the return type of the method. It means it doesn’t return any value.
  • methodName – the name of the method.

Declaring a method that accepts parameters

Java method can also accept parameters. When we create a method, in parentheses ( ) we will specify what parameters the method should expect.

Example:

  
public void methodName(int num, String data) {
    // code to be executed 
  }

If a method is created with parameters, we need to pass the corresponding values while calling the method.

Calling a Method in Java

In the first example, we have a method that does not accept parameters, and we will call such a method as follows:

 methodName()

As you can see, to call a method, we need to specify its name and leave the parentheses empty if it does not accept the parameters.

Calling a Java method with parameters

We must pass the corresponding values inside parentheses to call a method with parameters.

methodName(10, "dataString");

In the above example, we passed two parameters, the first is a number of type int, and the second is just text of type String.

Let’s see a realistic, slightly more complicated example:

class Test {
   
  public int sumNumbers(int a, int b) {
    int sum = a + b;
    return sum;
  }

  public static void main(String[] args) {
    int num1 = 10;
    int num2 = 15;
        
    Test test = new Test();
    
    int result = test.sumNumbers(num1, num2);
    
    System.out.println("The sum is: " + result);
    }
}
Output: The sum is: 25
 
Here, in the sumNumbers method declaration, right in front of the name, we have a specified data type – int. That is the return type of the method. 
 
When we specify the return type in the method declaration, it means that it must return the value of that type. This method accepts two integer parameters, performs addition, and returns a result.
 
Here we also have the main method, it is the entry point of any Java program. Within the main method, we created an object of the type Test class and called the method via the object reference, and passed two integers. We stored the result obtained by calling the method in the variable result. And on the line below, we use the println method from the PrintStreamclass to print the result.

Types of Methods in Java

In Java, there are two types of methods:

  • User-defined Methods: The methods we create
  • Predefined Methods/Standard Library Methods: Built-in methods in Java that are available to use.

User-defined Methods

A method that we write ourselves is known as a user-defined method. In the above examples, we have already seen how we can create our own methods.

Here is one more example:

class Test {
    
  public static int square(int num) {
    return num * num;
  }
    
  public static void main(String[] args) {
    int result = square(10);
    System.out.println("The result is: " + result);
  }
}
Output: The result is: 100
 
Here we declare the square method, which accepts the integer type parameter, and returns the square of the number.
 
You see the new modifier in front of the return type. It is a static modifier. This means that the method belongs to the class itself, not the object. And it can be called from the main method without creating an object of a class because one static method can be accessed from another.

Predefined Method in Java

Predefined methods are those that come as part of existing Java packages and libraries. These methods are available for us to use.

We have already seen one of these: the println method of the PrintStream class. We have many other classes with various methods available.

Let’s see an example of methods from the Math class:

class Test {
    
  public static void main(String[] args) {
    int maxOfTwoNumbers = Math.max(2, 10);
        
    int minOfTwoNumbers = Math.min(2, 10);
    
    double sqrt = Math.sqrt(10);
      
    System.out.println("Max is: " + maxOfTwoNumbers);
    System.out.println("Min is: " + minOfTwoNumbers);
    System.out.println("The square root is: " + sqrt);
  }
}
Output: Max is: 10 Min is: 2 The square root is: 3.1622776601683795.
 
Here we have called three methods from the Math class. All three are static methods, so we could call them via the class name, for non-static methods, we would have to create an object of that class.
 
As you can see, the Math class has many useful methods available to us. We also have many other classes, packages, and libraries that are built-in and ready to use.
 
In the next tutorial, we will see more about static and non-static methods.

That’s it!

 

 

Leave a Reply

Your email address will not be published.