So I wanted to test Void
type then I wrote this simple program :
package ehsan;
public class NumTest {
public static Void main(String[] args) {
System.out.println("Hello, World!");
return null; /* The compiler forced me to do so. I just can't realize what is the point in returning in Void type!? */
}
}
So now when I want to compile, the compiler complains :
main method must return a value of type void
Why can't the compiler see that I'm returning nothing and am using Void
?
You should use void
(lowercase v
) not Void
object. Void
object is not going to get autoboxing like e.g. int
/Integer
, see Java Language Specification for a list of autoboxing objects.
Void
is not a wrapper for void
, it is just an object that has a very similar name so it can be used in places where you need to specify a return type (like e.g. Callable<T>
), it is just for documentation purposes and to workaround some generic classes return types.
Second use case is in reflection (when you want to check the return value of a void
function, you will get Void.TYPE
).
Correct line is:
public static void main(String[] args)