Java return Statement
The return statement in Java is used to explicitly exit a method and optionally return a value to the caller.
If a method is declared with a void return type, the return statement is not required. However, it can be used to exit the method early, as shown in the following example:
public class ReturnExample1 {
    public static void main(String[] args) {
        boolean t = true;
        System.out.println("Before return.");
        if (t) {
            return;
        }
        System.out.println("This line will not be executed.");
    }
}
Output of this code:
Before return.Using return to Return a Value
If a method is declared to return a value, the return statement must be used. It must be followed by the value that should be returned from the method:
public class ReturnExample2 {
    public static void main(String[] args) {
        double d = getRandomValue(3);
        System.out.println(d);
    }
    public static double getRandomValue(int i) {
        return Math.random() * i;
    }
} Курс 'Java для начинающих' на Udemy
             Курс 'Java для начинающих' на Udemy
         
Please log in or register to have a possibility to add comment.