What is return types in Java with Examples

Return type in java is used inside of method for the purpose of returning value in program when method complete it’s execution. A java return type may be int, float, double, or void data type(void returns nothing).

It is reserved keyword in java and determine the ending of method.  

Example 1:

public class Main {
  static int add(int x) {
    return 5 + x;
  }

  public static void main(String[] args) {
    System.out.println(add(3));
  }
}

Output:

8

In the above example add() methods return 5+x as output which is 8.

Examples 2:

class A
 {
 byte b= 10;
 public int returnValue()
 {
 System.out.println("Hello");
 return b;
 }

 public static void main(String arg[])
 {
 A ob= new A();
 System.out.println(ob.returnValue());
 }
 } 

Example to return Integer Value in Java

Example 3:

 public class ReturnExample1 {  
      int display()  
     {  
         return 4;  
     }  
     public static void main(String[] args) {  
     ReturnExample1 e1 =new ReturnExample1();  
     System.out.println(e1.display());  
 }  
 }   

Output:

4

Let see can we use Return in Void method.

 public class ReturnExample2 {  
     void display()  
     {  
         return null;  
     }  
     public static void main(String[] args) {  
     ReturnExample2 e =new ReturnExample2();  
     e.display();  
 }  
     }   

Output:

Void methods cannot return a value

Program for Return value in java

// Java program to illustrate usage
 // of return keyword
 class A {
                 // Since return type of RR method is double
                 // so this method should return double value
                 double RR(double a, double b)
                 {
                                 double sum = 0;
                                 sum = (a + b) / 2.0;
                                 // return statement below:
                                 return sum;
                 }
                 public static void main(String[] args)
                 {
                                 System.out.println(new A().RR(5.5, 6.5));
                 }
 } 

Output:

6.0

Critical points of Return types in java.

  • Return type is used to exit from the method.
  • You cannot use return keyword in void method.
  • return statement need not to be last statement in a method, but it must be last statement to execute in a method.
  • The value passed with return keyword must match with return type of the method.

Leave a Reply