Question

Have a look at this code

Integer x = 5;
Integer y = 2;
Integer xy = x+y;
System.out.println("xy = " + xy); // outputs: 7
System.out.println("xy2 = " + xy2); // outputs: 7

x++;

System.out.println("xy = " + xy); // outputs: 7
System.out.println("xy2 = " + xy2); // outputs: 7

How can I get the code to output 8 without using a method that calculates it for you?

Was it helpful?

Solution

An Integer in Java is immutable. You can not change its value. In addition, it's a special autoboxing type to provide an Object wrapper for the int primitive.

In your code, for example, x++ does not modify the Integer object x is referencing. It un-autoboxes it to a primitive int, post-increments it, re-autoboxes it returning a new Integer object and assigns that Integer to x.

Edit to add for completeness: Autoboxing is one of those special things in Java that can cause confusion. There's even more going on behind the scenes when talking about memory / objects. The Integer type also implements the flyweight pattern when autoboxing. Values from -128 to 127 are cached. You should always use the .equals() method when comparing Integer objects.

Integer x = 5;
Integer y = 5;
if (x == y) // == compares the *reference (pointer) value* not the contained int value 
{
    System.out.println("They point to the same object");
}

x = 500;
y = 500;
if (x != y)
{
    System.out.println("They don't point to the same object");
    if (x.equals(y)) // Compares the contained int value
    {
        System.out.println("But they have the same value!");
    }
} 

See: Why aren't Integers cached in Java? for more info (and of course the JLS)

OTHER TIPS

You need to update xy after modifying x. So:

x++;
xy = x + y;
xy2 = x + y;

In Java you'll need to update a variable yourself if you want the value to change. It's not like other languages where you express a relationship between two variables and this relationship is maintained whenever a variable changes.

The expression: xy = x + y doesn't mean that now xy is depends on the values of x and y (if they changed, xy is changed too). You can see it as follows: the value of the expression x + y is inserted into xy.

Therefore, you must increase the value of x (by x++), before your set the value of xy.

I'm new to java, and I'm not really sure of the context for this question, but if all you want to do is output 8, you can just make it xy++ instead of x++.

Integer x = 5;
Integer y = 2;
Integer xy = x+y;
int xy2 = x+y; // just testing to see if it makes a difference
System.out.println("xy = " + xy); // outputs: 7
System.out.println("xy2 = " + xy2); // outputs: 7

**xy++;**
System.out.println("xy = " + xy); // **outputs: 8**
System.out.println("xy2 = " + xy2); // outputs: 7
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top