As a java programmer, you must have witnessed “void” on different occasions. But do you know what exactly “void” is and what is the purpose of using void in Java? Well, the answer is very simple, it is a keyword that is used with the methods that return nothing.
This write-up will cover the below-given aspects of the void keyword in Java:
So, let’s get started!
What does Void mean in Java?
It is a keyword in java used with the method declaration to indicate that this particular method will not return anything. If a method is declared with some primitive data type such as string, int, etc. then it must return a value of that specific data type while the method declared with the void keyword doesn’t return anything. So all in all, we can say that the method declared with the void keyword doesn’t have any return type.
Basic Syntax
In Java, the void keyword has a very simple syntax as shown in the below snippet:
Here, in the above snippet, “exampleMethod” is any user-defined method name while void is a keyword that indicates that the “exampleMethod” will not return any value.
How to use void in Java?
In this section, we will consider some examples to understand the working of a void keyword in java.
Example 1
A simple Program to understand the working of void keyword:
In this example, we declared a method named “exampleMethod” with the void keyword. As the “exampleMethod” is declared with a void keyword so it will not return any value. Finally, we invoked the exampleMethod from the main method:
This is how the void keyword works in Java.
Example 2
If we tried to return something from the method that is declared with the void keyword then as a result we will encounter an error:
The above program will generate an “incompatible types“ error at compile time as shown in the below snippet:
The output verified that the void keyword doesn’t return any value.
Example 3
In the below-given example program we will create two methods “exampleMethod()” and “print()”. The exampleMethod() will return an integer value while print() method doesn’t return value:
The exampleMethod() takes two values 5 and 20 as argument and returns the sum of values. The complete code and respective output are shown in the below snippet:
Output verified that the method declared with a void keyword doesn’t return any value while the method declared with int returned an integer value.
Conclusion
In java, a method declared with a void keyword shows that this particular method will not return any value while a method declared primitive data type must return a value of that specific data type. In Java, the void keyword doesn’t have any return type, which means if someone tried to return a value from the method that is declared with the void keyword, consequently, he/she will encounter an error. This write-up explained various aspects of the void keyword with some appropriate examples.