What is the need for the intValue () method if wrappers use unpacking?

For example, look at this code:

Integer myInt = new Integer(5);
int i1 = myInt.intValue();
int i2 = myInt;

System.out.println(i1);
System.out.println(i2);

As you can see, I have two ways to copy my integer value from a wrapper to a primitive:

I can use unboxing

OR

I can use intValue () method

So ... what you need to have a method when it is already unpacked?

+5
source share
2 answers

Unboxing was introduced in Java 5. Wrappers (including this method) have been there since release.

Link to Javadoc

At that time (1996), we need a method intValue(), and since Oracle guarantees backward compatibility ... to a certain level (this is not always 100% of major releases).

The method should remain.

+9

, , - intValue() .

, , Integer int:

 Integer i1 = new Integer(5);
 Integer i2 = new Integer(5);

 //This would be the way if they were int
 System.out.println(i1 == i2); //Returns false

 //This is the way for Integers
 System.out.println(i1.intValue()==i2.intValue()); //Returns true
 System.out.println(i1.equals(i2)); //Returns true

false
true
true
+7

All Articles