1) In Java, I can do this:
Void z = null;
Is there any other value except null
I can assign to z
?
2) Consider the following code snipped:
Callable<Void> v = () -> {
System.out.println("zzz");
Thread.sleep(1000);
return null;
};
This compiles OK, but if I remove the last statement return null;
it doesn't. Why? After all, Void
is supposed to mean no return value.
The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.
In C++, a void pointer can point to a free function (a function that's not a member of a class), or to a static member function, but not to a non-static member function. You can't declare a variable of type void .
void is a type in the Java language (you can read that directly in the Java Language Specification). However the type void has no member values, that is no concrete value will ever have the type void.
You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value. Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.
From the docs:
The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.
So, no.
Void
is used by methods having to return an object, but really returning nothing.
A decent example can be observed with some usage of the AsyncTask in Android, in cases where you don't need to return any object after the task is complete.
You would then extend AsyncTask<[your params type], [your progress type], Void>
, and return null
in your onPostExecute
override.
You wouldn't need it in most cases though (for instance, Runnable
is typically more suitable than Callable<Void>
).
Ansering your question more specifically:
But if I remove the return null it does not compile?! Why?
... because a Void
is still an object. However, it can only have value null
.
If your method declares it returns Void
, you need to (explicitly) return null
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With