Java - A method without a return statement
When learning Java, you probably encounter a quiz that asks what will happen when a method has no return statement.
The quiz would go as follows:
If a method does not have a return statement, then:
- a. it will produce a syntax error when compiled
- b. it must be a
voidmethod - c. it cannot be called from outside the class that defined the method
- d. it must be defined to be a
publicmethod - e. it must be an
int,double,float, orStringmethod
The answer to the question above is b.
This is because a Java method with a void return type returns nothing.
For example, the following hello() method prints a message to the console without returning anything:
void hello() {
System.out.println("Hello World!");
}
When you change the return type to one of the valid Java types, an error will be thrown without a return statement:
int hello() {
System.out.println("Hello World!");
} // ERROR: Missing return statement
It doesn’t matter if the method is a public, protected, private, or default access level.
A method with a void return type will work fine when you omit the return statement.
The right answer to the quiz is b.
More Java tutorials
See allJava
How to fix Index 0 out of bounds for length 0 Java exception
Apr 28, 2023
Java
How to get the length of a 2D array in Java
Dec 19, 2022
Java
How to serialize and deserialize a binary tree in Java
Apr 6, 2022
Java
How to create a singleton class in Java
Apr 5, 2022
Java
Java abstract class - with code examples
Apr 4, 2022