DEV Community

VIDHYA VARSHINI
VIDHYA VARSHINI

Posted on

Return types in Java

What is return type: A return type tells Java what type of data a method will return.

Example: int -> returns an integer value.
String -> returns a string.
boolean -> returns either true or false.
void -> returns nothing.

Why return type is needed: In Java, it must know what type of value the method will give back, how to store that value and how the method will be used later.
Static method can be called by both class and object. The method will sometime return the value or not. Method cannot be declared inside a main method.

Ex:

class Calculator {
    public static void main(String[] args) {
        Calculator casio = new Calculator();

        int result = casio.add(10, 20);   
        casio.divide(result, 2);          
    }

    public int add(int no1, int no2) {
        int result = no1 + no2;
        System.out.println(result);
        return result;
    }

    public void divide(int no1, int no2) {
        int output = no1 / no2;
        System.out.println(output);
    }
}

Enter fullscreen mode Exit fullscreen mode

Output:

30
15

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
harshmangalam profile image
Harsh Mangalam

Nice Vidya, keep it up.