CKTIS / Java
void — a method with no return value
The `void` keyword indicates that a method returns no value. The method can still perform actions, such as printing text. Do not confuse `void` with the value `null` or with the `java.lang.Void` class.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
void methodName() { /* statements */ }void is a reserved Java keyword. In a method declaration, it occupies the position used for the return type and indicates that no value is returned. It is not a type you can use to declare a variable or parameter. It also does not mean that the method does nothing: the method can, for example, change an object's state or print text.
A method declared void can finish by reaching the end of its body or use return; to exit early. It cannot use return expression;, even when the expression is null. A constructor declares no result at all; adding void creates a method, not a constructor.
A call to a void method supplies no value, so you cannot assign its result to a variable or use it as an argument requiring a value. void is not the same as null: null is a reference value. The java.lang.Void class is an uninstantiable placeholder used to represent void in reflection, not a value returned by void methods.
In the example, printPositive(0) exits at return;, while printPositive(7) prints 7. Neither call returns a value. Then main prints Done.
Examples
public class VoidExample {
static void printPositive(int number) {
if (number <= 0) {
return;
}
System.out.println(number);
}
public static void main(String[] args) {
printPositive(0);
printPositive(7);
System.out.println("Done");
}
}Result
7 Done
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.
Sources
- Overview (Java SE 21 & JDK 21)
- The Java Language Specification, Java SE 21 — §3.9 Keywords
- The Java Language Specification, Java SE 21 — §8.4.5 Method Result
- The Java Language Specification, Java SE 21 — §14.17 The return Statement
- The Java Language Specification, Java SE 21 — §15.1 Evaluation, Denotation, and Result
- Void (Java SE 21 & JDK 21)