Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java allow nullable types?

Tags:

java

syntax

null

In C# I can a variable to allow nulls with the question mark. I want to have a true/false/null result. I want to have it set to null by default. The boolean will be set to true/false by a test result, but sometimes the test is not run and a boolean is default to false in java, so 3rd option to test against would be nice.

c# example:

bool? bPassed = null; 

Does java have anything similar to this?

like image 318
Green Avatar asked Sep 21 '11 17:09

Green


People also ask

Can you do null in Java?

null is Case sensitive: null is literal in Java and because keywords are case-sensitive in java, we can't write NULL or 0 as in C language.

Can a Java int be null?

Java primitive types (such as int , double , or float ) cannot have null values, which you must consider in choosing your result expression and host expression types.

Is Java long nullable?

You will never get null value for Long.


2 Answers

No.

Instead, you can use the boxed Boolean class (which is an ordinary class rather a primitive type), or a three-valued enum.

like image 147
SLaks Avatar answered Oct 05 '22 13:10

SLaks


you can use :

Boolean b = null;

that is, the java.lang.Boolean object in Java.

And then also set true or false by a simple assignment:

Boolean b = true; or Boolean b = false;

like image 33
Saket Avatar answered Oct 05 '22 12:10

Saket