Java Void Type: Usage, Tutorial and Practical Examples
Java is a strictly strongly typed programming language, meaning every declared method must specify an explicit return type, unlike weakly typed languages such as PHP. For example, a method defined as public String fetchMessage() must return a value of the String type, or any other valid primitive or reference type.
A method can also use the void keyword as its return type. At first glance, it may be unclear whether void qualifies as a data type, since Java only defines two core data type categories: primitive types and reference types. In practice, void can be treated as a special pseudo-data type, or alternatively as a method moidfier that signals the method does not return any value.
Every primitive Java type has a corresponding wrapper class, such as Integer for int and Character for char. The void type follows this pattern, with its wrapper class being java.lang.Void. The Void class is a non-instantiable placeholder class that holds the Class object corresponding to the Java void keyword. This class cannot be subclassed or instantiated, and any method that declares Void as its return type must explicitly return null.
Example Code Analysis
-
Distinguishing
VoidClass andvoidTypepackage com.example.voidcheck; public class VoidTypeDemo { public static void main(String[] args) throws Exception { System.out.println(Void.class); System.out.println(void.class); System.out.println(Integer.class); System.out.println(int.class); } }Running this code will produce the following output:
class java.lang.Void void class java.lang.Integer int -
Return Value Rules
- For methods with a
voidreturn type, thereturnstatement is optional. If used, it takes no value:public void logMessage(String text) { System.out.println(text); return; // This line is optional } - For methods with a
Voidwrapper class return type, you must return exactlynull:public Void getVoidWrapperInstance() { return null; }
- For methods with a