Other answers don't work for me. My question is about Integer.
Integer i1 = new Integer(11);
Integer i2 ;
i2 = i1;
System.out.println(i1+"   "+i2);
i1 = 233;
System.out.println(i1+"   "+i2);
//~ 11    11
//~ 233    11
I want to let i1 and i2 related.
In java java.lang.Integer is immutable. It means that you can't change the value of Integer object (in usual way). You can create new Integer instance with new value.
i1 and i2 contains a reference to the same Integer instance. When you made
i1 = 233;
it means that i1 refers to another instance of Integer class
If you want that i1 and i2 refers to the same instance you can use AtomicInteger, but AtomicInteger was made for different purpose.
AtomicInteger i1 = new AtomicInteger(11);
AtomicInteger i2 ;
i2 = i1;
System.out.println(i1+"   "+i2);
i1.set(233);
System.out.println(i1+"   "+i2);
Or you can make a wrapper
public static class IntegerWrapper {
    private int value;
    public IntegerWrapper(int value) {
        this.value = value;
    }
    public int getValue() {
        return value;
    }
    public IntegerWrapper setValue(int value) {
        this.value = value;
        return this;
    }
}
and code
IntegerWrapper i1 = new IntegerWrapper(11);
IntegerWrapper i2 ;
i2 = i1;
System.out.println(i1.getValue()+"   "+i2.getValue());
i1.setValue(233);
System.out.println(i1.getValue()+"   "+i2.getValue());
                        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