Java Return Values
In this page:
The return Keyword
The return keyword sends a value back to whatever code called the method, and that value's type must match (or be convertible to) the return type declared in the method's signature.
Example: The return Keyword
public class Main {
static int square(int n) {
return n * n;
}
public static void main(String[] args) {
System.out.println(square(5));
}
}
Login to try C/C++/Java/PHP code in the editor
Void Return Type
A method declared void promises to return nothing, but you can still write a bare return; with no value to exit the method early -- useful for stopping execution partway through under some condition.
Example: Void Return Type
public class Main {
static void checkAge(int age) {
if (age < 0) {
return;
}
System.out.println("Age: " + age);
}
public static void main(String[] args) {
checkAge(-1);
checkAge(25);
}
}
Login to try C/C++/Java/PHP code in the editor
Returning Boolean Values
A boolean-returning method (often named like isValid() or hasPermission()) reads naturally inside an if condition and is the standard shape for a yes/no check you plan to reuse elsewhere.
Example: Returning Boolean Values
public class Main {
static boolean isEven(int n) {
return n % 2 == 0;
}
public static void main(String[] args) {
if (isEven(4)) {
System.out.println("Even");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Returning Object References
Returning an object or array means the caller receives a reference to that same data, not a full copy -- and when the return type is an array, the declaration uses square brackets, like int[] getScores().
Example: Returning Object References
public class Main {
static int[] getScores() {
return new int[] {90, 85, 77};
}
public static void main(String[] args) {
int[] scores = getScores();
System.out.println(scores[0]);
}
}
Login to try C/C++/Java/PHP code in the editor
Return Statements in Loops
A return statement inside a loop exits the loop and the entire enclosing method in one step, immediately handing its value back to the caller without running any more of the method's code.
Example: Return Statements in Loops
public class Main {
static int findFirstEven(int[] nums) {
for (int n : nums) {
if (n % 2 == 0) {
return n;
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(findFirstEven(new int[] {1, 3, 4, 5}));
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: