Alex Rivera | Logout

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

Asked 2012-05-31T18:18:41.230
85

In API

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

  1. What is "uninstantiable" place holder class? When will java.lang.Void be used? If the class is "uninstantiable", what use is it?
  2. What is difference between java.lang.Void and void?
Edit
Report

1 Answer

82

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 that 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 Asynchronous Datastore Service delete operation returns a Future<Void>. When get() is invoked on that future, null is returned after the deletion is complete. One could write a similar example with answered 2013-03-15T05:20:14.030

Your Answer