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

7

83

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?
Neumark answered 31/5, 2012 at 18:18 Comment(0)
H
60

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.

Hb answered 31/5, 2012 at 18:19 Comment(7)
Thanks Louis Wasserman.Void.Type can say "primitive type" or any thingNeumark
Wait, what? That's...not true. Void.TYPE only means void. This isn't C.Hb
@LouisWasserman Void can be used with certain classes that use generics. For example SwingWorker. I point this out because you said it cannot be used for anything else.Complicacy
That's true; it can substitute generally for a class that's not meant to have any instances except null. But more generally, the Void class is just where you go to find Void.TYPE, which is like a Class<void>.Hb
I don't think this answer stands up to scrutiny. I've added an example of one area where Void may be used below.Abilene
You also can use Void to create and submit Callable implementations which return void. While using Runnable would probably be prefereable, you may have the submission inside a generic implementation which receives Callables.Flavory
@Flavory Or you may need to throw an exception from the Callable. Also it's perhaps worth noting that call in a Callable cannot actually be void, but may have return type Void (and thus must return null), in order to imitate a void function.Kendy
A
114

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.

Arithmomancy answered 27/9, 2012 at 22:0 Comment(2)
void is a keyword but not a primitive type actually, Void.TYPE is used as a representation of void keywordBamby
> java.lang.Void is analogous to java.lang.Integer < if that were the case I'd be able to assign Void to a 'void' method. Void is clearly the old one out compared to the other primitive boxings.Phylys
A
79

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>).

Accusative answered 15/3, 2013 at 5:20 Comment(4)
This is a great explanation: essentially, the Void is a way to statically enforce that a type has absolutely no possibility of returning anything at all. Its much more unambiguous than, for example WeakHashMap<T,Object> , which is what you would have to do otherwise.Traylor
+1 for the examples and insight about using Maps containing Voids to emulate Sets. However, a WeakHashMap of Voids is not a great example as such a construct would be no better than a plain HashSet (no benefit from the 'Weak' functionality). (Interestingly, a HashSet<E> is actually backed by a HashMap<E,Object>.)Abdella
@Dave, actually they are different, because a WeakHashMap has weak references to its keys (while the values are strongly referenced), but a plain HashSet keeps strong references to its keys.Accusative
@Accusative Yes, you are right. I was mistakenly thinking that the values were weak. My bad.Abdella
H
60

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.

Hb answered 31/5, 2012 at 18:19 Comment(7)
Thanks Louis Wasserman.Void.Type can say "primitive type" or any thingNeumark
Wait, what? That's...not true. Void.TYPE only means void. This isn't C.Hb
@LouisWasserman Void can be used with certain classes that use generics. For example SwingWorker. I point this out because you said it cannot be used for anything else.Complicacy
That's true; it can substitute generally for a class that's not meant to have any instances except null. But more generally, the Void class is just where you go to find Void.TYPE, which is like a Class<void>.Hb
I don't think this answer stands up to scrutiny. I've added an example of one area where Void may be used below.Abilene
You also can use Void to create and submit Callable implementations which return void. While using Runnable would probably be prefereable, you may have the submission inside a generic implementation which receives Callables.Flavory
@Flavory Or you may need to throw an exception from the Callable. Also it's perhaps worth noting that call in a Callable cannot actually be void, but may have return type Void (and thus must return null), in order to imitate a void function.Kendy
H
5

Void is a AutoBoxing feature (since JDK 1.5) of void.

well its self explanatory that Void is reference whereas void is a primitive type.

So, where the requirement comes to have to use Void ???

One common usage with Generic types where we can't use primitive.

Say, in case of Android AsyncTaks<Params, Progress, Result> what if I don't want to get Progress update. I can't use void (primitive type) here we require java.lang.Void

Hollyanne answered 19/10, 2014 at 16:5 Comment(1)
JavaDocs mention Void Since: 1.1Elena
F
2

Another example for using Void is SwingWorker

new SwingWorker<Void, Integer> () {
    @Override
    protected Void doInBackground(){
        ...
    }
    @Override
    protected void process(List<Integer> chunk){
        ...
    }
    @Override
    public void done(){
        ...
    }
}.execute();
Fontainebleau answered 31/8, 2016 at 4:18 Comment(0)
A
1

Void is useful because sometimes you need to specify the return type of a method outside the method itself.

For example take this java 8 lambda expression, which checks whether an EventResource object has certain properties, using a method called checkBenefitConcertInCentralPark, passed into the method checkCreatedEvent:

eventChecker.checkCreatedEvent(TestEvents::checkBenefitConcertInCentralPark);

The checkBenefitConcertInCentralPark method is defined like this (note the use of Void):

    public static Void checkBenefitConcertInCentralPark(EventResource eventResource) { 
        // JUnit code here...
        // assertThat(blablabla  :)  )

        return null; // we can only return null at the end of a method when returning Void
    }

and then the checkBenefitConcertInCentralPark method is passed into the method checkCreatedEvent.

    // Function<EventResource, Void> describes the checkBenefitConcertInCentralPark method
    public void checkCreatedEvent(Function<EventResource, Void> function) { 
        function.apply(this.eventResource);
    }
Abilene answered 23/5, 2016 at 10:47 Comment(1)
You don't explain why you'd need a Function returning Void instead of just using a Consumer.Hb
W
0

I've personally used it like this:

@FunctionalInterface
interface MyPackagePrivateInterface<T, Next> {
   //Returns next
   Next compareAndSwap(T prev);
}

@FunctionalInterface
public interface ClientPublicInterface<T> extends MyPackagePrivateInterface<T, Void> {
}

My reasoning is this:

computations based on user input, may create new Type allocations, that your system may need.

The action may KEEP its namesake since in the eyes of the client it is performing what it is saying, but in sublayers within the system an equivalent action is taking place but with completely different Types, Types which ONLY your system should be aware.

This may relate to a principle of "Self similarity" in which a system is composed of smaller components similar to itself, so it may be logical to reuse interfaces with different Types and similar namesake, this system also implies that reification (transforming something abstract into real) is intrinsical to the System state hence the user is not interested in an immediate reading of a return value, but the aim relies on the Object's change of state.

Now this particular example is for atomic operations, and TBH I cannot think of a different situation in which this may be needed, the reason being that native atomic operations are reliant in time-space(space = memory scope) snapshots for them to perform accurately.

This new allocations are not important to the client but only to the system's functionality.

Wilmer answered 11/6, 2022 at 17:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.