Java
is a strongly typed language. All methods have a return type (including void
, which means return nothing
).
It is not possible to have method returning nothing if its type is not void
and that cannot be changed. This is for a good reason, too: methods that return values are typically used for populating parameters of certain data types.
For example, consider the method
public abstract int calculate();
which is called by an application, for calculating a value, which is saved in a parameter for subsequent use, e.g.
int result = calculate();
What would go into result
, if there was an option to "not return anything" from the calculate()
method?
For this and numerous other reasons, a method must always return a value of a specific data type, or be of type void
and this is enforced by the Java
compiler. If it does return a value, it can be used or ignored, according to the needs of the calling application.
The use of the java.util.Optional
class, introduced in Java 8
and suggested in another answer, is probably not the most suitable approach for use cases like the question above. Having said that, a nice discussion about Optional
can be found in another StackOverlow question.