Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On Void return type

Tags:

java

void

If one needs return a Void type, which Javadoc describes as

A class that is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

Why does the following still require null to be returned?

public Void blah() {
    return null; // It seems to always want null
}
like image 694
James Raitsev Avatar asked Jan 10 '12 16:01

James Raitsev


People also ask

What is the return type of void?

The void type, in several programming languages derived from C and Algol68, is the return type of a function that returns normally, but does not provide a result value to its caller. Usually such functions are called for their side effects, such as performing some task or writing to their output parameters.

Do void methods have a return type?

Any method declared void doesn't return a value.

Why void has no return type?

Return from void functions in C++ The void functions are called void because they do not return anything. “A void function cannot return anything” this statement is not always true. From a void function, we cannot return any values, but we can return something other than values.

What does return void mean?

void represents the return value of functions which don't return a value. Whenever you see a function returning void , you are explicitly told there is no return value. All functions with no return value have an inferred return type of void . This should not be confused with a function returning undefined or null .


1 Answers

Void is a class like any other, so a function returning Void has to return a reference (such as null). In fact, Void is final and uninstantiable, which means that null is the only thing that a function returning Void could return.

Of course public void blah() {...} (with a lowercase v) doesn't have to return anything.

If you're wondering about possible uses for Void, see Uses for the Java Void Reference Type?

like image 161
NPE Avatar answered Oct 07 '22 04:10

NPE