Java return keyword example
- Details
- Written by Nam Ha Minh
- Last Updated on 20 August 2019   |   Print Email
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:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand how variables are passed in Java
- Understand encapsulation in Java
Comments