DEV Community

Sasireka
Sasireka

Posted on

Return Types in Java

Return Type in Java

  • In Java, the return type means what kind of value a method gives back after it finishes execution.

  • Syntax:

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

1) Integer Return Type (int)

public class Sum {

    public static void main(String[] args) {
        Sum num = new Sum();
        int result = num.add(5, 3);
        System.out.println("Sum = " + result);
    }
    public int add(int a, int b) {
        return a + b;
    }
}
Enter fullscreen mode Exit fullscreen mode
  • int - return type

  • Method returns an integer value

Output:

2) String Return Type (string)

public class Demo {

    public static void main(String[] args) {
        Demo str = new Demo();
        String name = str.getName();
        System.out.println("Name : " + name);
    }
    public String getName() {
        return "Sasireka";
    }
}
Enter fullscreen mode Exit fullscreen mode
  • String - return type

  • Method returns a text (group of characters)

Output:

3) Double Return Type (double)

public class DemoDouble {

    public static void main(String[] args) {
        DemoDouble obj = new DemoDouble();
        double value = obj.getValue();
        System.out.println("Value = " + value);
    }
    public double getValue() {
        return 10.5;
    }
}
Enter fullscreen mode Exit fullscreen mode
  • double - return type

  • Method returns a decimal number

Output:

4) Void Return Type (void)

public class DemoVoid {

    public static void main(String[] args) {
        DemoVoid obj = new DemoVoid();
        obj.display();
    }
    public void display() {
        System.out.println("Hello, Welcome!");
    }
}
Enter fullscreen mode Exit fullscreen mode
  • void - return type

  • Method does not return anything

Output:

Top comments (0)