Java - Method void return

Get to know void return

void return does not return a value.

You use void as the return type for such a method.

The following method creates a method print();

void print() {
        System.out.println("A");
        System.out.println("B");
        System.out.println("C");
        System.out.println("from book2s.com");
}

The print method uses void as its return type, which means that it does not return a value to its caller.

print method does not have any parameters, which means it does not accept any input values from its caller.

To call the print method, write the following statement:

print();

You cannot use a call to this method as part of any expression where a value is expected.

int x = print(); // A compile-time error

When a method's return type is void, you do not need to use a return statement to return from the method.

To early end a method you can use return simply to end the execution of the method.

Demo

public class Main {
  public static void main(String[] args) {
    print(10) ;/*  w w w. j  a  va  2  s. c  o m*/
    print(1) ;
    print(2) ;
  }

  static void print(int n) {
    if (n < 1 || n > 2) {
      System.out.println("Cannot print #" + n);
      return; // End the method call
    }

    if (n == 1) {
      System.out.println("A");
      System.out.println("B");
      System.out.println("C");
      System.out.println("from book2s.com");
    } else if (n == 2) {
      System.out.println("X");
      System.out.println("Y");
      System.out.println("Z");
      System.out.println("from book2s.com");
    }
  }
}

Result

Related Topic