2

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"
  }
}
Jake Wilson
  • 88,616
  • 93
  • 252
  • 370

3 Answers3

3

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());
Thomas
  • 87,414
  • 12
  • 119
  • 157
1

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.

Nicola Musatti
  • 17,834
  • 2
  • 46
  • 55
0

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.

G_H
  • 11,739
  • 3
  • 38
  • 82