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,738
  • 21
  • 105
  • 131
James Raitsev
  • 92,517
  • 154
  • 335
  • 470

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
  • 486,780
  • 108
  • 951
  • 1,012
  • 2
    *"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
  • 525,659
  • 79
  • 751
  • 1,130
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
  • 232,561
  • 37
  • 312
  • 386
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
  • 87,414
  • 12
  • 119
  • 157