tags:

views:

393

answers:

3

I am trying to create a nullalble object in Java but no idea how to do this , in C# this would be done like this

int? someTestInt;

This allows me to check for for null , while in certain cases i can use a 0 value ,this isnt always possible since certain execution paths allow 0 values

+7  A: 

I'm not entirely sure what you want, but if you want to have an integer value that also can be declared null, you probably want to use the Integer class:

Integer nullableInteger = 1;
nullableInteger = null;
System.out.println(nullableInteger); // "null"

There are corresponding classes for each primitive: Character, Long, Double, Byte, etc. The 'standard library' numeric classes all extend the Number class.

Note that Java autoboxes these objects automatically since JDK 1.5, so you can use and declare them just like the primitives (no need for e.g. "new Integer(1)"). So, although they are technically objects (and, therefore, extend the Object class, which the primitive int type does not), you can do basic arithmetics with them. They are converted to object operations at compile time.

Henrik Paul
Oh, great...you will get all the credit because you decided to go all out with code sample and everything... ;)I'll give you +1 anyway.
mkmurray
In the west, it pays off to be fast with your draw :)
Henrik Paul
I dont need to use the nullable type for integers only ,will use the corresponding classes instead of the primitives , thanks for the info
RC1140
+1  A: 

Perhaps try the Integer type in Java.

mkmurray
+2  A: 

Java does not support nullable primitives. You can use the Integer type if you want the ability to store nulls.

(This is a duplicate of this post: http://stackoverflow.com/questions/985151/how-to-present-the-nullable-primitive-type-int-in-java)

Peter Recore