Reputation: 91193
I know that with the following, a reference is made
public class MyClass
{
public Integer value;
}
public class Main
{
public static void main( String[] args )
{
MyClass john = new MyClass();
john.value = 10;
MyClass bob = john;
bob.value = 20;
System.out.println(Integer.toString(john.value)); // Should print value of "20"
}
}
But how do you do similar referencing with primitive data-types?
public class Main
{
public static void main( String[] args )
{
Integer x = 30;
Integer y = x;
y = 40;
System.out.println(Integer.toString(x)); // Prints "30". I want it to print "40"
}
}
Upvotes: 2
Views: 487
Reputation: 18218
You cannot. While Integer
is not a primitive datatype but a wrapper class around the int
primitive type, your code is equivalent to:
Integer y = x;
y = new Integer(40);
So you are actually changing the object y
points to. This mechanism is called auto-boxing. There's a simple rule of thumb: in order to change the state of an object, rather than to replace the whole object, you have to call one of your object's methods. It's quite common for classes representing values, such as numbers, not to provide such methods, but to require that the object be replaced by a new one representing the new value.
Upvotes: 1
Reputation: 11999
What happens in your second code block is that 30
gets boxed into an Integer and assigned to x
. Then you assign that same Integer to y
. x and y are now pointing to the same object. But when you do y = 40
, that 40 is boxed into a new Integer object and gets assigned to y. The Integer class is immutable, you won't be able to change its value after creation.
Upvotes: 0
Reputation: 88707
Simple answer: you don't. Primitive values are always passed by value (i.e. they are copied).
Wrapper objects like Integer
are also immutable, i.e. y = 40
will create a new Integer
object with the value 40 and assign it to y
.
To achieve what you want you need a container object whose value you can change.
You could, for example, use AtomicInteger
:
AtomicInteger x = new AtomicInteger(30);
AtomicInteger y = x;
y.set( 40 );
System.out.println(x.get());
Upvotes: 3