I am testing the behavior of Object#clone method and I don't understand why the following code prints true, Diego, Diego, I was expecting it to print true, Diego, Armando since p.getName() == p2.getName() prints true. Could please anyone explain why p2.setName("Armando") is not modifying the p Object if they point to the same String? Thank you.
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.setName("Diego");
Person p2 = null;
try {
p2 = (Person) p.clonar();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
System.out.println(p.getName() == p2.getName());
System.out.println(p.getName());
p2.setName("Armando");
System.out.println(p.getName());
}
}
class Person implements Cloneable {
private String name;
public Object clonar() throws CloneNotSupportedException {
return this.clone();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}