I know this is a basic Java question yet I have never seen a full solution to this problem. Basically, I want to copy another variable's value into another variable and then have the newly created variable preserve that value.
Here is my code :
private void someMethod() {
String tmpCommand = commandName;
commandName = modelItem.getName();
}
Here, tmpCommand
's value will change to modelItem.getName()
value since it references commandName
. However, what if I want tmpCommand
to not change value whenever commandName
value is changed? Would I have to create a new object tmpCommand
?
Here, if
tmpCommand
's value will change tomodelItem.getName()
value since it referencescommandName
.
No, it won't. The value of tmpCommand
is just the value of commandName
at the time of the assignment.
That's really simple to demonstrate:
String original = "foo";
String test = original;
original = "bar";
System.out.println(test); // Prints foo
Note that changing the value of original
is not the same as changing the data within the object that the value of original
refers to. Let's do a different example with a mutable type - StringBuilder
:
StringBuilder original = new StringBuilder("foo");
String test = original;
original.append("bar");
System.out.println(test); // Prints foobar
Here, both test
and original
still have the same value: that value is a reference to a StringBuilder
object. The call to append
doesn't change that reference at all... it changes the data in the object that the reference refers to. It's really important to differentiate between variables, references and objects.
So if you want to avoid that, you'll need to create a new object with the same content - some classes provide a way of doing that; others don't. For example, you could use:
StringBuilder original = new StringBuilder("foo");
String test = new StringBuilder(original);
original.append("bar");
System.out.println(test); // Prints foo
When a clone()
method is provided, that could be used too. But basically the idea is that sometimes you want two variables to hold references to independent objects.
See more on this question at Stackoverflow