Understanding Void and Null in Java with Examples

Tapas Sarkar
2 min readMay 10, 2023

--

In Java programming language, two of the most commonly used keywords are Void and Null. They are both used to represent nothingness in different contexts. However, their usage and behaviour are different from each other. In this essay, we will explore the differences between Void and Null and provide some examples to illustrate their usage.

Void
In Java, the keyword Void is used to represent the absence of a value. It is typically used as a return type for methods that do not return a value. Void methods are executed for their side effects, such as printing something to the console or changing the state of an object.

Here’s an example of a Void method:

public void printMessage(String message) {
System.out.println(message);
}

In this example, the printMessage method takes a String argument called message and prints it to the console using the System.out.println() method. The return type of the method is Void, which means that the method does not return a value.

Null
On the other hand, Null is used to represent the absence of an object reference. It is commonly used in Java to initialize variables or to indicate that an object does not exist. Null is not a keyword in Java, but a reserved word that represents a literal value that can be assigned to any object reference variable.

Here’s an example of using Null to initialize a variable:

String message = null;

In this example, the message variable is initialized to Null. This means that it does not point to any object in memory.

Differences between Void and Null
The main difference between Void and Null is that Void represents the absence of a value, while Null represents the absence of an object reference. Void is used to declare methods that do not return a value, while Null is used to initialize variables or to indicate that an object does not exist.

Another difference between Void and Null is that Void is a keyword in Java, while Null is a reserved word. Void is also used in Java to declare generic types, such as Void<T>, which represent a generic type that does not contain any data.

In addition, Void can only be used as a return type for methods, while Null can be assigned to any object reference variable.

Conclusion
In summary, Void and Null are both important concepts in Java programming language. Void represents the absence of a value and is commonly used as a return type for methods that do not return a value. Null, on the other hand, represents the absence of an object reference and is commonly used to initialize variables or to indicate that an object does not exist. By understanding the differences between Void and Null, Java developers can write more effective and efficient code.

--

--

Tapas Sarkar

Experienced Java Spring Boot Dev with 9+yrs expertise in RESTful, Kubernetes, AWS, DBs. Passionate about world travel for personal & professional growth.