3

In Java, we can use the wrapper classes for declaring a variables. For example

    Integer x=5;

This means that there is a reference 'x' that points to a value of 5.

Then I declared another reference called y that points to the same value

    Integer y=x;  //now y should point to the number "5"

then I changed the value which y points to

     y=20;

Doesn't this make both x and y point to 20 ? because when I print x , I still get 5

1
  • 1
    Forget about pointers - no such thing in Java! y=20 is the same as y = Integer.valueOf(20), so y references a different object afterwards. Commented Sep 23, 2013 at 13:19

4 Answers 4

3

The following:

y=20;

rebinds y to point to a different Integer object.

It does not touch x, so its value does not change.

Sign up to request clarification or add additional context in comments.

2 Comments

so java always rebinds to different object ? and is there anyway to go around this ?
@fadytaher: Have many references to the same instance of a mutable class.
1

Everytime you see code in the form

Integer x = 5;

the compiler replaces it by something like

Integer x = Integer.valueOf(5);

which is almost similar to

Integer x = new Integer(5);

So in fact, y = 20 is nothing else than y = new Integer(20), so the y-pointer is relocated to point to a newly created Integer object.

Comments

1

In the first line Integer x=5; x is a reference to an Integer object with the value of 5. Then Integer y=x; creates another reference for the same object, so x and y refer the same object. Finally, y=20; makes the reference y to point to a different object, an Integer of value 20.

From "The Java Programming Language, 4th edition" by Ken Arnold, James Gosling and David Holmes:

The Java programming language does not pass objects by reference; it passes object references by value. Because two copies of the same reference refer to the same actual object, changes made through one reference variable are visible through the other.

But in your case, you don't actually modify the initial object, but change one of its references to point to a different object.

Comments

0

Integer x = 5

The above statement allocates a memory space which holds value 5 and is referenced by x;

Integer y = x

The above statement points reference y to the same memory location as x.

When you assign the value to y = 20. This creates a new memory space that holds the value 20 and is referenced by y. So at this moment both x and y point to different memory locations.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.