DEV Community

S Sarumathi
S Sarumathi

Posted on

Return Type In Java

1. What is Return Type in Java?

Return type in Java means what value a method gives back after execution.

Syntax:

returnType methodName(){
    // code
    return value;
}

Enter fullscreen mode Exit fullscreen mode

Example:

int add(){
    return 10;
}
Enter fullscreen mode Exit fullscreen mode

Here:

  • int → return type

  • add() → method name

  • return 10 → returning value

So this method returns integer value.

2. Why Return Type is Used

1. To Send Result Back

class Demo {
    static int add(){
        return 5 + 3;
    }

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

Output:

8
Enter fullscreen mode Exit fullscreen mode

Here:

  • add() returns 8

  • main method receives it

  • prints result

Without return → you cannot send value back.

Example Without Return Type:

class Demo {
    static void add(){
        System.out.println(5 + 3);
    }

    public static void main(String args[]){
        add();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

8
Enter fullscreen mode Exit fullscreen mode

Here:

  • void means no return value

  • Only prints

  • Can't store result

You cannot do this:

int result = add();   // ERROR
Enter fullscreen mode Exit fullscreen mode

Because void returns nothing.

Top comments (0)