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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With