Return Types in Java

# beginners# java# programming# tutorial
Return Types in JavaSILAMBARASAN A

What is a Return Type? In Java, a return type means the type of value a method gives back...

What is a Return Type?

In Java, a return type means the type of value a method gives back after execution.

Syntax :

returnType methodName() {
    // code
    return value;
}
Enter fullscreen mode Exit fullscreen mode

Types of Return

1. void (No return value)

Method does not return anything

class Demo {
    void display() {
        System.out.println("Hello");
    }
}
Enter fullscreen mode Exit fullscreen mode

Use: When you just want to print / perform action

2. Return with value (int, String, etc.)

Method returns a value

class Demo {
    int add(int a, int b) {
        return a + b;
    }
}
Enter fullscreen mode Exit fullscreen mode

Calling:

int result = add(10, 20);
System.out.println(result); // 30
Enter fullscreen mode Exit fullscreen mode

3. String return type

class Demo {
    String getName() {
        return "Silambu";
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Boolean return type

class Demo {
    boolean isEven(int n) {
        return n % 2 == 0;
    }
}
Enter fullscreen mode Exit fullscreen mode

Flow of Execution

Let’s understand step-by-step:

Example:


class Demo {

    int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        Demo obj = new Demo();
        int result = obj.add(5, 3);
        System.out.println(result);
    }
}
Enter fullscreen mode Exit fullscreen mode

Flow:

  1. Program starts from main()
  2. Object is created → Demo obj = new Demo();
  3. Method call happens → obj.add(5, 3)
  4. Control goes to add() method
  5. Calculation happens → 5 + 3 = 8
  6. return 8 → value goes back to main()
  7. Stored in result
  8. Printed → 8
  • void → no return
  • Other types (int, String, etc.) → must use return
  • Return value goes back to caller method
  • Execution always starts from main()

Return type in Java defines what type of value a method returns after execution.