return

9 0 0
                                    

return - this keyword is used when you want your method to return something but it can also return nothing. If there is nothing to return, you can declare it void and has the option to use the return keyword followed by semi colon but without return type or just don't include it. But if there is something to return, then, you used the return keyword followed by the return value. Note that the return value must have the same data type with the declared return type.

========================

public void usingReturn(){

    System.out.println("Hello");

    return;

}

========================

Result:

Hello


Example 2:

==========================

class Example2{

  public static double addingDouble(double d1, double d2){

      return d1 + d2;

  }

  public static void main(String[] args){

      double d3 = Example2.addingDouble(5.0, 2.3);

      System.out.println("answer: " + d3);

  }

}

==========================

Result:

answer: 7.3


Note that the above example uses a static method. If you are using a static method or field, you don't need to create an object since they are class field or class method. It means that you can access the field and method through your class without creating an object but if it is not static, then, you need to instantiate an object through that class and reference that field or method using the object.


returning a class or an interface - if you want your method to return a class or an interface, make sure that the class you will return is the exact class or a sub class of that return type class but not the super class. This is known as the covariant return type.

==========================

class Example1{}

class Example2 extends Example1{}

class Example3 extends Example2{

    public Example2 myMethod(){

        return new Example3();

    }

}

==========================

In myMethod(), I decided that the return type is Example2. So, the value of return type should either Example2 or the subclass of Example2 which is Example3. This time, I used Example3 as a return value. But you cannot use Example1 since Example1 is the super class of Example2. The reason behind it is that it is possible that the Example2 can be a data type of Example1 but there is a possibility that the super class Example1 cannot be a data type of Example2. So, meaning if, you set the return type to a higher super class like an Object, you can return any subclass that is under it.  

Java ProgrammingWhere stories live. Discover now