I have these two situations:
String s = "aa";
s = s + " aa";
System.out.println(s);
//......
that work fine! It prints aa aa.
But there is a problem:
String s = "aa";
this.addStringToStatement(s, " aa");
System.out.println(s);
//...
private void addStringToStatement(String statement, Object value) {
statement += value;
}
It prints: aa.
What is the reason??
Thanks!
There are two issues to understand here.
The String append operator will create a new immutable String object. The expression
s + valueis a different object in memory froms.In your function
addStringToStatementwhen you execute statement += value;you aren’t changing the value of the variables, rather you are reassigning the local pointerstatementto a new String instance.EDIT: Fixed usual noob mistake: In Java, object references are passed, not the objects themselves.