0

My idea was to create two objects in such a way that when I modified the second object the first one would also be modified. I read that when ussing the assing operator between objects the value of the reference of obj2 is assigned to obj1. I suppose my code doesn't work because it just create a copy of the reference, but I would like to know if there is another way I can do that or if it is impossible.

CODE:

public class Try{
    public static void main(String args[]){
        Integer a=Integer.valueOf(2);
        Integer b;
        b=a;
        System.out.println(b);
        Integer c=Integer.valueOf(3);
        a=c;
        System.out.println(b);
    }
}

Output: 2 2

Desired output: 2 3

parse5214
  • 27
  • 1
  • 8
  • 1
    *"when I modified the second object the first one would also be modified"* ... where do you ___modify___ an object in your code? – Tom Apr 19 '22 at 10:12
  • a=c. Sorry if the terminology is not correct, I would make a correction if that's the case. – parse5214 Apr 19 '22 at 10:13
  • you are assigning an object c to an a object. You are not modifying any object – Morph21 Apr 19 '22 at 10:14
  • 1
    See the duplicate for the difference between assigning variables and modifying objects and what you want to do is not possible in Java (when you stick just assigning variables instead of actually modifying an object). – Tom Apr 19 '22 at 10:18
  • 1
    `Integer` is immutable, it cannot be changed - `a = c` is changing the variable, not the instance that was referenced by `a` (`a.setSomething()` would eventually change the instance, but does not work with `Integer` - it is immutable) – user16320675 Apr 19 '22 at 10:19
  • 2
    Before reading duplicate you may want to familiarize yourself with: [What is the difference between a variable, object, and reference?](https://stackoverflow.com/q/32010172) – Pshemo Apr 19 '22 at 10:20
  • 1
    In the first three lines of code, you create a value `2` that has a certain memory address. You assign `a` to that memory address, and then you assign `b` to the memory address of `a` (so they both print the same value). Then, you create another value `3` which will have another memory address. You assign that memory address to `c` and then you assign to `a` the memory address of `c`. The memory address of `b` however, it hasn't changed. Hence, it still points to the memory address of the value `2`, and that's why it prints `2` and not `3` as you were expecting. – Matteo NNZ Apr 19 '22 at 10:22

0 Answers0