Java - Core Java - Methods in Java

Methods in java

A method is a collection of statements that perform specific task and return result to the caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping the code. In Java, every method must be part of some class which is declared inside a class only.

Calling a method

The method needs to be called for using its method name with arguments. There can be three situations when a method is called. A method returns to the code that invoked it when:

  • It completes all the statements in the method
  • It reaches a return statement
  • Throws an exception
  • Program to demonstrate methods in java
    class Addition {     
        int sum = 0;
        public int addTwoInteger(int a, int b){         
            sum = a + b;         
            return sum; //returning addition of two values
    class GFG {
        public static void main (String[] args) {     
            // creating an instance of Addition class 
            Addition add = new Addition();         
            // calling addTwoInteger() method to add two integer using instance created
            int s = add.addTwoInteger(4,5);
            System.out.println("Sum of two integer values :"+ s);