← Back to Core Java Course | Chapter 5: Methods & Arrays | Lesson 3 of 10

Java Return Values

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

java
public class Main {
	static int square(int n) {
		return n * n;
	}
	public static void main(String[] args) {
		System.out.println(square(5));
	}
}

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

java
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);
	}
}

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

java
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");
		}
	}
}

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

java
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]);
	}
}

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

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.