Java Methods

Java methods are used to execute a block of codes that performs a task.

It is always a best practise to create a method that performs a single task for easy maintainance.

There are two types of methods available in java. They are

  • Standard Library Methods - These are built in methods provided by java in the package.
  • User-Defined Methods - These are methods created by users.

Example for Standard Library Methods

System.out.println("Welcome to Java");

User-Defined Method

The methods that are created by the user to perform some task is known as user-defined method.

Declaring a user-defined method

Syntax

// Method without parameter
returnType methodName() {
   // Block of code
}

// Method with parameter
returnType methodName(parameter1, parameter2,...){
    // Block of code
}

Example for method without parameter

public void print(){
   System.out.println("welcome to the tutorial");
}

In the above example, print() is the method name and void is its return type.

Call the Method

Once the function is declared and defined, we can call the method at any time by calling it with its function name.

Example

public void print(){
   System.out.println("welcome to the tutorial");
}
print();

Example for method without parameter

class Main {

    public void print(){
       System.out.println("welcome to the methods tutorial");
    }

  public static void main(String[] args) {
    
    // create an object of Main
    Main obj = new Main();
    // calling method
    obj.print();
  }
}

Output

welcome to the methods tutorial

In the above program, we have the print() method with return type of void.

We then create an object obj for the Main function and call the print() method.

Example for method with parameter

class Main {

  // create a method
  public int add(int a, int b) {
    // return the sum of a & b
    return  a + b;
  }

  public static void main(String[] args) {
    
    int number1 = 20;
    int number2 = 10;

    // create an object of Main
    Main obj = new Main();
    // calling method
    int result = obj.add(number1, number2);
    System.out.printf("Sum of %d and %d is %d",number1,number2, result);
  }
}

Output

Sum of 20 and 10 is 30

In the above program, the add() method takes 2 integer as parameter, add them and returns an integer as response.

To call the add() method, we create an object for the Main class and call the add() method with number1 and number2 as parameter.

Finally, print the result returned by the add() method.


Most Read