Reputation: 1465
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?
Upvotes: 47
Views: 48954
Reputation: 7321
Sure you can go with Boolean, but to make it more obvious that your type can have "value" or "no value", it's very easy to make a wrapper class that does more or less what ?
types do in C#:
public class Nullable<T> {
private T value;
public Nullable() { value = null; }
public Nullable(T init) { value = init; }
public void set(T v) { value = v; }
public boolean hasValue() { return value != null; }
public T value() { return value; }
public T valueOrDefault(T defaultValue) { return value == null ? defaultValue : value; }
}
Then you can use it like this:
private Nullable<Integer> myInt = new Nullable<>();
...
myInt.set(5);
...
if (myInt.hasValue())
....
int foo = myInt.valueOrDefault(10);
Note that something like this is standard since Java8: the Optional
class.
https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
Upvotes: 10
Reputation: 1068
If you are using object, it allows null
If you are using Primitive Data Types, it does not allow null
That the reason Java has Wrapper Class
Upvotes: 3
Reputation: 1212
Yes you can.
To do this sort of thing, java has a wrapper class for every primitive type. If you make your variable an instance of the wrapper class, it can be assigned null
just like any normal variable.
Instead of:
boolean myval;
... you can use:
Boolean myval = null;
You can assign it like this:
myval = new Boolean(true);
... And get its primitive value out like this:
if (myval.booleanValue() == false) {
// ...
}
Every primitive type (int
, boolean
, float
, ...) has a corresponding wrapper type (Integer
, Boolean
, Float
, ...).
Java's autoboxing feature allows the compiler to sometimes automatically coerce the wrapper type into its primitive value and vice versa. But, you can always do it manually if the compiler can't figure it out.
Upvotes: 7
Reputation: 2388
No but you may use Boolean
class instead of primitive boolean
type to put null
Upvotes: 2
Reputation: 887433
No.
Instead, you can use the boxed Boolean
class (which is an ordinary class rather a primitive type), or a three-valued enum
.
Upvotes: 49
Reputation: 500327
In Java, primitive types can't be null. However, you could use Boolean
and friends.
Upvotes: 5
Reputation: 46137
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;
Upvotes: 22
Reputation: 178441
No, in java primitives cannot have null value, if you want this feature, you might want to use Boolean instead.
Upvotes: 11