3

In this circumstance what is the value of variable y after the first two statements? I'm assuming it's Integer 7 but my book says automatic unboxing of objects only occurs with relational operators < >". I'm a little confused how variable Integer y gets it's value. Does any unboxing occur in newInteger(x)?

Integer x = 7;
Integer y = new Integer(x); 

println( "x == y" + " is " +  (x == y))
Ian
  • 57
  • 1
  • 7
  • possible duplicate of [What exactly does comparing Integers with == do?](http://stackoverflow.com/questions/3689745/what-exactly-does-comparing-integers-with-do) – Abimaran Kugathasan Jul 13 '15 at 10:32
  • @AbimaranKugathasan i understand what happens when == compares two objects but I don't understand how `y` gets its value. – Ian Jul 13 '15 at 10:34
  • 2
    Note that `"x == y" + " is " + x == y` means: `("x == y" + " is " + x) == y`, which is not what you want. Use parentheses: `"x == y" + " is " + (x == y)` – Jesper Jul 13 '15 at 10:35
  • @Jesper i didn't even notice that mistake. Thanks. – Ian Jul 13 '15 at 10:38

2 Answers2

3

Unboxing happens when the compiler is certain that you wish to compare values. Using == can compare the Objects and therefore give false because == is a valid operation between objects. With < and > there is no concept of Object < OtherObject so it is certain that you mean numerically.

public void test() {
    Integer x = 7;
    Integer y = new Integer(x) + 1;

    System.out.println("x == y" + " is " + (x == y));
    System.out.println("x.intValue() == y.intValue()" + " is " + (x.intValue() == y.intValue()));
    System.out.println("x < y" + " is " + (x < y));
    System.out.println("x.intValue() < y.intValue()" + " is " + (x.intValue() < y.intValue()));
}

x == y is false

x.intValue() == y.intValue() is true

x < y is true

x.intValue() < y.intValue() is true


In this circumstance what is the value of variable y after the first two statements?

The value of the variable y is a reference to an Integer object containing the value 7.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
2
Integer x = 7;

In this case, the int literal 7 is automatically boxed into the Integer variable x.

Integer y = new Integer(x);

This involves an automatic unboxing of the Integer variable x into an int (temporary) variable, which is passed to the Integer constructor. In other words, it is equivalent to:

Integer y = new Integer(x.intValue());

After this statement, y points to a new object that is different than x but containing the same int wrapped value.

M A
  • 71,713
  • 13
  • 134
  • 174
  • So x in `new Integer(x)` is temporarily unboxed to value type `int` so the integer constructor for variable y could take effect. The sequence of boxing and unboxing was a little confusing to me at first. Now it makes sense. Thanks. – Ian Jul 13 '15 at 10:50
  • @Ian Yes it does unboxing because the constructor takes a primitive `int`, not the `Integer`. – M A Jul 13 '15 at 11:08