Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Void type - possible/allowed values?

Tags:

java

void

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.

like image 511
peter.petrov Avatar asked Jan 14 '16 13:01

peter.petrov


People also ask

What is the void type in Java?

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

Can we use void with variable?

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 .

Is void valid type in Java?

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.

Can you return with void Java?

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.


1 Answers

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.

like image 122
Mena Avatar answered Oct 05 '22 06:10

Mena