4

In C++ I might do something like:

sometype var = somevalue;
mutate(var);
// var is now someothervalue

void mutate(sometype &a) {
    a = someothervalue;
}

Is there an equivalent thing in Java?

I am trying to accomplish something like:

Customer a;

public static void main(String[] args) {
    a = newCustomer("Charles");
    Customer b = null;
    mutate(b);
    System.out.println(b.getName()); // NullPointerException, expected "Charles"
}

void mutate(Customer c) {
    c = a;
}

If Customer is mutable, why does this yield NullPointerException?

gator
  • 3,465
  • 8
  • 36
  • 76

1 Answers1

5

Looks like you are confused with Mutability. Mutability is just changing the object state. What you are showing in the example is not just mutability. You are completely changing the instance by referring that to some other instance (=).

sometype var = somevalue;
mutate(var);

void mutate(sometype a) {
    a = someothervalue; // changing a to someothervalue.
}

What mutability is

sometype var = somevalue;
mutate(var);
var.getChangeState() // just gives you the latest value you done in mutate method

    void mutate(sometype a) {
        varType someParamForA= valueX;
        a.changeState(someParamForA); // changing a param inside object a.
    }

Yes, in case mutable objects that is completely valid in Java. You can see the changes after you called the mutate method.

case of primitives ::

Remember that you cannot do that with Java in case of primitives. All the primitive variables are immutable.

If you want to acheive the same with Java for primitives, you can try something like this

int var = 0;
var = mutate(var);

int mutate(int a) {
    a = a + 1;
    return a;
}
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • The example does not demonstrate mutability. both simply describe overwriting a reference/value with another reference/value. Also since Java is call-by-value, the reference (think of it as a pointer, since a Java reference is not the same as a c++ reference) will be copied in the function. Unless you do something like `a = ` (like `a.setValue(7)` or for public members `a.member = 7`) the state of sometype does not change. – patrik Mar 17 '17 at 06:03
  • @patrik Agreed with you. Cleared up my answer :) – Suresh Atta Mar 17 '17 at 06:16