How to exit a method in Java?

To stop a method in Java, use the return keyword.

In a void method you can exit without returning anything:

void printIfMoreThanTwo(int value) {
  if (value <= 2) {


In a non-void method you need to return a value that corresponds to the return type.

For example, here the return type is int, so we need to return an integer to stop the method:

int twoOrThree(int value) {
  if (value) {
    return 2;

  return 3;