DEV Community

Cover image for Return Types in Java
Harini
Harini

Posted on

Return Types in Java

What is a Return Type?

A return type is the data type of the value that a method sends back to the calling method.

Syntax

returnType methodName(parameters) {
    // code
    return value;
}
Enter fullscreen mode Exit fullscreen mode
  • returnType → int, double, String, boolean, etc.
  • return value; → sends result back

Example 1: Returning an Integer

public class Example1 {

    public static void main(String[] args) {
        Example1 obj = new Example1();

        int result = obj.add(10, 5);
        System.out.println("Result = " + result);
    }

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

Output

Here:

  • Return type = int
  • Method returns an integer value

Flow of execution

  1. main() method starts execution
  2. Object obj is created
  3. add(10, 5) method is called
  4. Inside method → a + b is calculated
  5. Value 15 is returned to main()
  6. Stored in result and printed

Example 2: Returning a String

public class Example2 {

    public static void main(String[] args) {
        Example2 obj = new Example2();

        String message = obj.greet("Harini");
        System.out.println(message);
    }

    String greet(String name) {
        return "Hello " + name;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Flow of execution

  1. main() starts
  2. Object is created
  3. greet("Harini") is called
  4. Method creates "Hello Harini"
  5. Returns string to main()
  6. Printed on screen

Example 3: Returning a Boolean

public class Example3 {

    public static void main(String[] args) {
        Example3 obj = new Example3();

        boolean result = obj.isEven(4);
        System.out.println("Is Even? " + result);
    }

    boolean isEven(int number) {
        return number % 2 == 0;
    }


}
Enter fullscreen mode Exit fullscreen mode

Output

Flow of execution

  1. main() starts
  2. Object is created
  3. isEven(4) is called
  4. Condition 4 % 2 == 0 checked
  5. Returns true
  6. Printed as result

Example 4: void Return Type

public class Example4 {

     public static void main(String[] args) {
        Example4 obj = new Example4();

        obj.display();   // calling method
    }

    void display() {
        System.out.println("Hello");
    }


}
Enter fullscreen mode Exit fullscreen mode

Output

Flow of execution

  1. main() starts
  2. Object is created
  3. display() is called
  4. Method directly prints "Hello"
  5. No value returned

Top comments (0)