public class foo{
    public int max(int a, int b){
        if(a>b) return a;
        else return b;
    }
}

The above method will return a value. In Java return is how a method will provide a output. There are two phases of this. The first is to define the return type which is done in the method definition. The next is the return statement which will actually return the value.

When return is called any code after the return statement is ignored. Further more the return statement will make the code jump back to where the method was called from.

foo myFoo = new foo();
int biggest = myFoo.max(6,9);
System.out.println(biggest);

This code will display the value 9. max(int,int) will be called with the values 6 and 9. The max method then compares a > b or 6> 9. This evaluates to false which means that the else statement is run. This says return b (or 9). The method then jumps back to assign the value 9 to biggest.

public int example(){
    if(5==5) return 4;
    System.out.println("Never run");
}

Java should comlain about this code and with good reason. The line "Never run" will do exactly that. Never run! As the return statement is on the if and the if always evaluates to true that means the following line will not run. This is an example of how return works and also how you should not use it! If possible return should be the last statement in your methods to make your code more reliable.

next summary >>

 
Basics
Menu
Search