Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Nullables types in java

Tags:

java

nullable

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

like image 757
RC1140 Avatar asked Jul 14 '09 05:07

RC1140


People also ask

How do you make a nullable in Java?

you can use : Boolean b = null; that is, the java. lang.

How do you make a type nullable?

You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.

What is nullable in Java?

@Nullable The @Nullable annotation helps you detect: Method calls that can return null. Variables (fields, local variables, and parameters), that can be null.

What is a nullable data type?

The Nullable type allows you to assign a null value to a variable. Nullable types introduced in C#2.0 can only work with Value Type, not with Reference Type. The nullable types for Reference Type is introduced later in C# 8.0 in 2019 so that we can explicitly define if a reference type can or can not hold a null value.


2 Answers

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.

like image 82
Henrik Paul Avatar answered Sep 19 '22 10:09

Henrik Paul


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: How to present the nullable primitive type int in Java?)

like image 37
Peter Recore Avatar answered Sep 22 '22 10:09

Peter Recore