19

Possible Duplicate:
Uses for the Java Void Reference Type?

What is the real usage of Void class in real world problems? In which scenario can we use this class?

Community
  • 1
  • 1

6 Answers6

16

If you have an object (like an ExecutorService) that requires you to provide a Callable<T> object, you can pass it a Callable<Void> to indicate that your Callable doesn't return anything. Callable<T> has to be parameterized on some type, so Void is provided to indicate a lack of type.

mrb
  • 3,281
  • 1
  • 20
  • 31
13

- Unlike the other wrappers Void class doesn't store a value of type void in itself and hence is not a wrapper in true essence.

- The Void class according to javadoc exists because of the fact that some time we may need to represent the void keyword as an object.

- But at the same point we cannot create an instance of the Void class using the new operator.This is because the constructor in Void has been declared as private. Moreover the Void class is a final class which means that there is no way we can inherit this class.

- So the only purpose that remains for the existence of the Void class is reflection, where we can get the return type of a method as void.

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
7

Void class is used in Java-reflection.
see Method#getReturnType

Ilya
  • 29,135
  • 19
  • 110
  • 158
3

The java reflection API uses Void.TYPE to represent the return type of a method returning void as Luke Woodward points out. (Returning Void.class as I previously thought would cause an ambiguity with methods returning declaring a java.lang.Void return type).

 void test(){...};

 Method handleForTest = ...;
 assert(handleForTest.getReturnType() == Void.TYPE);

Post java 1.5 Void can be used in generic classes to indicate that they do not return a value - the Implementation still has to return null, but it can be ignored since that is the only valid value for the type Void.

interface<T> Example{
      //Implementations may do something and return a result
      T doSomeThing();
}

class ExampleVoid implements Example<Void>{
      //does something without returning a result
      Void doSomething(){return null;}
}

Also java allows to give a more specific return type when overwriting a method, this is basically the same as the generic example above, just to show that it works without generics if the original return type is Object. (it is limited to Object since Void follows the same rules as every other java type, sadly there is no way to use the nameless null-type for this)

interface Example{
      //Implementations may do something and return a result
      Object doSomeThing();
}

class ExampleVoid implements Example{
      //does something without returning a result
      Void doSomething(){return null;}
}
josefx
  • 15,506
  • 6
  • 38
  • 63
  • The Java reflection API uses `void.class` as the return type of `void` methods, not `Void.class`. In your first example, the assertion will fail. – Luke Woodward Nov 11 '12 at 17:25
2

JLS#14.8. Expression Statements

Unlike C and C++, the Java programming language allows only certain forms of expressions to be used as expression statements. Note that the Java programming language does not allow a "cast to void" - void is not a type - so the traditional C trick of writing an expression statement such as:

(void)... ;  // incorrect!

does not work. On the other hand, the Java programming language allows all the most useful kinds of expressions in expressions statements, and it does not require a method invocation used as an expression statement to invoke a void method, so such a trick is almost never needed. If a trick is needed, either an assignment statement (§15.26) or a local variable declaration statement (§14.4) can be used instead.

JLS#15.8.2. Class Literals

The type of void.class (§8.4.5) is Class<Void>.

JLS#8.4.5. Method Return Type

The result of a method declaration either declares the type of value that the method returns (the return type), or uses the keyword void to indicate that the method does not return a value.

Java doc Void

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

It is used for reflection purpose when you are want to check return type of a method

if (getClass().getMethod("someMethod").getReturnType() == Void.TYPE)

Same is applicable with Generic methods.

 final Callable<Void> callable = new Callable<Void>() {
        public Void call() {
             return null;
        }
    };
Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72
2

Reasons

The Void type was introduced to allow for call-backs and interfaces with external systems (JNI, JavaScript calls from applets, etc...), and has been around since the days of Java 1.1 for such cases where the interface type isn't known or enforced by the other interface (and thus where you can't use the void keyword). Java having been designed - except for primitives and null references - as an "everything is an object" kind of language, a dummy wrapper / placeholder was needed to indicate the absence of expected types.

Definition

A method, as defined by the method return type section of the JLS (§8.4.5), needs has to formally declare at return type:

The result of a method declaration either declares the type of value that the method returns (the return type), or uses the keyword void to indicate that the method does not return a value.

As mentioned in the JLS section for Class Literals (§15.8.2):

The type of void.class (§8.4.5) is Class<Void>

General Use

Its usage became more prominent with the introduction of generics in Java 5, as it allowed the definition of these interfaces to use generics and would allow to type-check the use of these interfaces and callbacks. Before, it would sometimes have been up to the implementer to know there was no passed object or no return object, for instance in the case of a priviledged execution block using the AccessController, very often used in Applet to define secure code paths:

  somemethod() {
     // ...normal code here...
     AccessController.doPrivileged(new PrivilegedAction<Void>() {
         public Void run() {
             // privileged code goes here, for example:
             System.loadLibrary("awt");
             return null; // nothing to return
         }
     });
     // ...normal code here...
 }

Note the difference with the Java 1.4 version of this same code, where it wasn't clear (and type-safe) to the caller that nothing is returned:

   somemethod() {
        // ...normal code here...
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                // privileged code goes here, for example:
                System.loadLibrary("awt");
                return null; // nothing to return
            }
        });
       // ...normal code here...
  }

Further Reading and Similar Questions

Community
  • 1
  • 1
haylem
  • 22,460
  • 3
  • 67
  • 96