Does Java allow nullable types? - java

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?

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

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;

No, in java primitives cannot have null value, if you want this feature, you might want to use Boolean instead.

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

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.

In Java, primitive types can't be null. However, you could use Boolean and friends.

No but you may use Boolean class instead of primitive boolean type to put null

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

Related

How to compare object type with boolean

import java.util.HashMap;
public class file{
public static void main(String args[]){
Object a;
a = true;
if (a == true){
System.out.println("Yes");
}
}
}
I get the error error: incomparable types: Object and boolean
I was to compare object a which stores a boolean value with an actual boolean type. How do I do that?
This happens because boolean primitive true is boxed for conversion to Object. You need to compare it to another boxed object, like this
if (a == Boolean.TRUE) {
...
}
or like this
if (a.equals(true)) {
...
}
You are comparing an Object reference to a primitive boolean - the types are not compatible for the equality operator (==). You should generally avoid using == with objects unless you really want to check if it is the same reference.
Prefer the equals method to compare objects.
if (Boolean.TRUE.equals(a)) { ... do stuff ... }
Note that we are invoking the method on a statically defined instance and passing the variable to be tested as the argument. The method will handle null arguments and incorrect type arguments (it will return false) so you don't have to.
Try this -
if (Boolean.TRUE.equals(a)) { ... }

Constructing a Java method that returns a primitive data type that is decided by the input?

I would like a method to read a string, and return it's value in the implied (best fitting) data type. I would like to avoid doing the string to data type conversion in "main", as the code is likely to create clutter. Is this possible? Can I create a method that returns different types? What does the constructor look like?
It's not possible to return different primitive types. What you can do is declare the method as returning Object, and at runtime return boxed primitives: instances of Integer, Double, Boolean, etc.
You could explore an enum type as a way to classify the type you end up with. You don't say what you want to use it for, so this may not be best, but it could be done in a way that handles the requirements you do give.
public class ClassifiedType
{
public enum ClassifiedTypeType { INTEGER, FLOAT, STRING, BOOLEAN };
ClassifiedTypeType typeType = null;
int integerValue;
float floatValue;
String stringValue;
boolean booleanValue;
public ClassifiedType(int i) { integerValue = i; typeType = ClassifiedTypeType.INTEGER; }
public ClassifiedType(float f) { floatValue = f; typeType = ClassifiedTypeType.FLOAT; }
// etc.
public int getIntegerValue()
{
if (typeType != ClassifiedTypeType.INTEGER)
{
throw new IllegalArgumentException("Attempting getInteger on type of " + this.toString());
}
else
{
return integerValue;
}
}
// do gets for other types similarly.
public static ClassifiedType getClassifiedType(String string)
{
// parse the string, determine which type you want,
// instantiate a ClassifiedType with its value and
// and type, and return it.
}
}
Other classes can use the ClassifiedTypeType (hopefully with a better name) to determine what kind of value to get from it, to the extent they need that.
Anyway, it beats returning Object and then having to use instanceof all over the place to figure out what you're dealing with, and this extends to non-primitives if you ever need that.
A single Java method cannot return multiple types. This is because Java is a strongly typed language.
There are a few different ways to accomplish this. If you'd like to go the constructor route as mentioned in the OP, it would look something like this:
public class Demo(){
Demo(String str){
// Do something...
}
Demo(int newInt){
// Do something...
}
// Other constructors for other types here
}

incomparable types boolean and nulltype

When I compile my code this way, I get the mentioned error:
public class SymTree{
public static boolean isSym(BT bt)
{
return(IsMirror(bt.left, bt.right));
}
private static boolean IsMirror(BT lr,BT rr)
{
if(lr==rr==null) (((ERROR HERE)))
return true;
.....
However when I compile like this
private static boolean IsMirror(BT lr,BT rr)
{
if(lr==rr)&&(lr==null))
return true;
.......
I get no error. The error is uncomparable types with nulltype and boolean, however non of my compared objects are boolean- they are both objects from a BT(Binary Tree) class, which has been defined elsewhere.
Thank you!
Examine (lr==rr==null). lr==rr is a boolean. It is primitive and can not be compared to null.
The reason it's giving you that error is because when you write this:
if (lr==rr==null)
The compiler interprets it similar to one of the following:
if ((lr==rr) == null)
if (lr == (rr==null))
Basically, you're comparing a boolean condition (either lr==rr or rr==null) to a nullable type, which doesn't make sense since booleans are value types and can never be null.
It is because in if(lr==rr==null), lr==rr is a boolean comparison which you are comparing with a null by doing ==null.
For Example, if suppose lr is equal to rr then lr==rr will return true next you are comparing whether true==null. Here you get error because boolean and null are not comparable.

Apache Thrift, Java: Object Data Types

i'm stuck with Thrift about data types.
Now when i map and Integer value to a thrift generated bean, i'm using i32 type in the idl definition.
class MyBean {
Integer i = null;
}
struct TMyBean {
1: i32 i;
}
The problem is that in TMyBean generated bean, the i var is an int primitive type, than it's putting 0 as the default value, and for me 0 it's a valid value.
I've tried to put the optional keyword in the idl file, but things are not changing, it's always int.
How i've to handle this situation? i need i to accept a null value in TMyBean i var.
Thanks, Phaedra..
The optional keyword was the right choice.
To test, whether or not a particular optional field is set or not, use the isset flags:
struct MyBean {
1: i32 IntValue
}
gives
public class MyBean implements org.apache.thrift.TBase<MyBean, MyBean._Fields>, java.io.Serializable, Cloneable, Comparable<MyBean> {
// ... lots of other code omitted ...
// isset id assignments
private static final int __INTVALUE_ISSET_ID = 0;
private byte __isset_bitfield = 0;
// ... lots of other code omitted ...
/** Returns true if field IntValue is set (has been assigned a value) and false otherwise */
public boolean isSetIntValue() {
return EncodingUtils.testBit(__isset_bitfield, __INTVALUE_ISSET_ID);
}
public void setIntValueIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __INTVALUE_ISSET_ID, value);
}
// ... even more code omitted ...
}
Each generated java class (from a thrift struct) has methods to check if the primitives are set. It's more cumbersome than autoboxing but works.
Example: for a thrift struct TMyBean that has a property myValue, the following generated Java method would help to check if it's null:
isSetMyValue()
If you want to nullify the primitive, use:
setMyValueIsSet(false).
* I don't understand why Thrift decided not to use optional primitives as objects in Java and let autoboxing do it's magic. Perhaps because of large collections? Anyhow, sounds like another priority issue of preferring performance over simplicity.
Integer in java is a class, not a primitive. Thrift will only allow you to use defined primitives i16, i32, i64, double for numbers. i32 i is equivalent to int i; in Java; an int always defaults to 0 in Java if it is not set. If you want to use a class, then you have to have a Thrift definition for that class that you can reference.

How to cast Object to boolean?

How can I cast a Java object into a boolean primitive
I tried like below but it doesn't work
boolean di = new Boolean(someObject).booleanValue();
The constructor Boolean(Object) is undefined
Please advise.
If the object is actually a Boolean instance, then just cast it:
boolean di = (Boolean) someObject;
The explicit cast will do the conversion to Boolean, and then there's the auto-unboxing to the primitive value. Or you can do that explicitly:
boolean di = ((Boolean) someObject).booleanValue();
If someObject doesn't refer to a Boolean value though, what do you want the code to do?
Assuming that yourObject.toString() returns "true" or "false", you can try
boolean b = Boolean.valueOf(yourObject.toString())
use the conditional operator "?" like this below:
int a = 1; //in case you want to type 1 or 0 values in the constructor call
Boolean b; //class var.
b=(a>0?true:false); //set it in the constructor body

Categories