Sultan Khan
Sultan Khan

Reputation: 21

assigned a null value to object and then try to do unboxing

If I have assigned a null value to an Object like

Integer t=new Integer(null);

How can I change this Object to Int primitive data type now (Unboxing) ?

Upvotes: 0

Views: 778

Answers (4)

Boris the Spider
Boris the Spider

Reputation: 61158

I think you will find that this throws a NumberFormatException:

public static void main(String[] args) throws Exception {
    final Integer i = new Integer(null);
}

Output:

Exception in thread "main" java.lang.NumberFormatException: null

So, to answer your question, you cannot as your Integer is never created. I.e. the first statement in your question is false: If I have assigned a null value to an Object. You have not.

You might mean something different:

public static void main(String[] args) throws Exception {
    final Integer i = null;
    final int ii = i;
}

This throws a NullPointerException, output:

Exception in thread "main" java.lang.NullPointerException

As int cannot be null, when the unboxing happens (essentially a call to i.intValue()) an NPE is thrown.

Upvotes: 7

Deepak Bhatia
Deepak Bhatia

Reputation: 6276

This code wont work and it will throw java.lang.NumberFormatException: at the line Integer t=new Integer(null);.
Exception is,

Exception in thread "main" java.lang.NumberFormatException: null

You asked

How can I change this Object to Int primitive data type now (Unboxing)?

A safe method to unbox null Integer objects i.e. changing this Object to Int primitive data try this,

Integer t=new Integer(null);
int a= (int)( t == null ? 0 : t) ;

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328624

Integer t=new Integer(null); throws a NumberFormatException since this constructor expects a non-null String as input.

If you need to create an Integer from something that can be null, use this code:

 Integer t = new Integer( null == input ? "0" : input );

Unboxing this is then always safe.

If you have an Integer which can be null, then you need to use this code:

int value = ( null == t ? 0 : t.intValue() );

as auto-unboxing will not work in this case.

Upvotes: 0

Scary Wombat
Scary Wombat

Reputation: 44844

How about

Object obj = null; // maybe not null??
Integer t=new Integer(null ? 0 : obj);

Upvotes: 1

Related Questions