I am preparing myself to the Java certification and confused with object references in this case. In this piece of code I can't understand why ArrayList's and arrays's elements aren't affected when we assign a new object to them?
ArrayList<StringBuilder> myArrList = new ArrayList<StringBuilder>();
StringBuilder sb1 = new StringBuilder("Jan");
StringBuilder sb2 = new StringBuilder("Feb");
myArrList.add(sb1);
myArrList.add(sb2);
StringBuilder[] array = myArrList.toArray(new StringBuilder[2]);
for(StringBuilder val : array) {
System.out.println(val);
}
StringBuilder sb3 = new StringBuilder("NNN");
sb2 = sb3;
for(StringBuilder val : array) {
System.out.println(val);
}
for(StringBuilder val : myArrList) {
System.out.println(val);
}
Output:
Jan
Feb
Jan
Feb
Jan
Feb
I will be grateful if you could provide simple explanation. Thank you.