What is the difference between java.lang.Void and void? What is the difference between java.lang.Void and void? java java

What is the difference between java.lang.Void and void?


java.lang.Void is analogous to java.lang.Integer. Integer is a way of boxing values of the primitive type int. Void is a way of boxing values of the primitive type void.

"But wait, void doesn't have any possible values!"

Right! That's what makes java.lang.Void "uninstantiable". :)

It's a nice feature of the Java type system that every primitive type has a boxed equivalent. int has Integer, long has Long, byte has Byte... and void has Void. It would be weird and asymmetrical if Void didn't exist.

"So what's the difference between java.lang.Void and void?"

Easy. void is a primitive type. Void is an reference type that inherits from Object. They're similar in that neither of them has any possible values; but nevertheless they are two very different types, from the type system's point of view.

"But I don't have any use for Void in my programs."

And I don't have any use for GarbageCollectorMXBean in mine. Some features don't have non-obscure uses. That's okay.


The most common use of Void is for reflection, but that is not the only place where it may be used.

void is a keyword that means that a function does not result a value.

java.lang.Void is a reference type, then the following is valid:

 Void nil = null;

(So far it is not interesting...)

As a result type (a function with a return value of type Void) it means that the function *always * return null (it cannot return anything other than null, because Void has no instances).

 Void function(int a, int b) {    //do something    return null; }

Why would I like a function that always returns null?

Before the invention of generics, I didn't have a use case for Void.

With generics, there are some interesting cases. For instance, a Future<T> is a holder for the result of an asynchronous operation performed by another thread. Future.get will return the operation value (of type T), and will block until the computation is performed.

But... What if there is nothing to return? Simple: use a Future<Void>. For instance, in Google App Engine the Asyncronous Datastore Service delete operation returns a future. Whenget()is invoked on that future,null` is returned after the deletion is complete. One could write a similar example with Callables.

Another use case is a Map without values, i.e. a Map<T,Void>. Such a map behaves like a Set<T>, then it may be useful when there is no equivalent implementation of Set (for instance, there is no WeakHashSet, then one could use a WeakHashMap<T,Void>).


The only point of Void is to hold Void.TYPE, which is sort of like void.class. If you have a reflective reference to a method that returns void, and you get its return type, it'll return Void.TYPE.

You cannot, and should not, use it for anything else.