0

If someone could help me understand the following problem:

As I understand double is primitive data type in Java and Double is immutable class. Every parameter is passed by value. If it is primitive type (int, double, byte), then it is the actual value that is passed; and if it is an object type, then it is the address to that object that is copied.

If that is so, why this parameter that is of type Double is not changed?

...
    public static void main(String[] args) {
        Double value = new Double(0);

        SomeObj so = new SomeObj();
        so.setNewValue(value);

        System.out.println(value);
    }
...

public class SomeObj {
    public void setNewValue(Double changeMe)
    {
        changeMe = new Double(10.0);
    }
}
Andrei Nicusan
  • 4,555
  • 1
  • 23
  • 36
TeslaS
  • 33
  • 2
  • 6
  • "and if it is an object type" The key is that there is no such thing as an "object type". The only types in Java are primitive types and reference types. – newacct Dec 12 '13 at 23:27

1 Answers1

6

It is the reference to the object that is passed by value. In the setNewValue method, you change the reference, so the changeMe variable points to something else. The (reference to the) original value object in the main method is not changed.

see also Is Java "pass-by-reference" or "pass-by-value"?

Community
  • 1
  • 1
Fortega
  • 19,463
  • 14
  • 75
  • 113
  • 1
    It would be worth to mention that the only way to be able to change the reference would be passing a array or encapsulate the type in a new class. – Bruno Costa Dec 12 '13 at 15:28
  • My god! The feeling when youre stuck in your own world of thoughts. I didnt understand what you wrote at first. Thank you! Bruno Costa i now about that, thank to you too! Just to add if the Double was mutable than i could change it using setter outside of main method and the change would reflect.. – TeslaS Dec 12 '13 at 15:47