12

If one needs return a Void type, which Javadoc describes as

A class that is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

Why does the following still require null to be returned?

public Void blah() {
    return null; // It seems to always want null
}
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
James Raitsev
  • 87,465
  • 141
  • 322
  • 462

4 Answers4

20

Void is a class like any other, so a function returning Void has to return a reference (such as null). In fact, Void is final and uninstantiable, which means that null is the only thing that a function returning Void could return.

Of course public void blah() {...} (with a lowercase v) doesn't have to return anything.

If you're wondering about possible uses for Void, see Uses for the Java Void Reference Type?

Community
  • 1
  • 1
NPE
  • 464,258
  • 100
  • 912
  • 987
  • 1
    *"Of course `public void blah() {...}` (with a lowercase v) doesn't have to return anything."* Indeed, **must** not. – T.J. Crowder Jan 10 '12 at 16:39
4

Void is the object "wrapper" for the void type. A return type of void doesn't return a return value but Void does. You can't use void or any primitive type in a generic.

Peter Lawrey
  • 513,304
  • 74
  • 731
  • 1,106
3

The correct keyword in Java is void, not Void (notice the use of lowercase at the beginning). Void (uppercase) is, according to the documentation:

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

Óscar López
  • 225,348
  • 35
  • 301
  • 374
1

As the doc says it is an uninstantiable placeholder class, thus you can't get an instance, but you have to return something since Void != void. Void actually is a class and thus treated like any other class/type which requires an instance or null to be returned.

Thomas
  • 84,542
  • 12
  • 116
  • 151