In Java, the return keyword is used to stop execution of a method and return a value for the caller. Usage of this keyword is as following:

return value;

where value is can be of:

    • A reference of any Java object.
    • A literal of String, boolean, number or null.

For example:

String getName() {
    return "Peter";
}

int getAge() {
    int myAge = 29;
    return myAge;
}

Object getObject() {
    Object myObject = new Object();
    // do something with my object...
    return myObject;
}

 

The return keyword can also be used to stop execution of a void method and return to the caller, for example: 

void doSomething() {
	// do something
	if (condition) {
		return;
	}
}

Related keyword: void. See all keywords in Java.

 

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment