Let's say I have a class as follows:
class Apple {
String apple;
Apple(String apple) {
this.apple = apple;
}
}
What makes the following code true?
public boolean result() {
Apple a = new Apple("apple");
Apple b = new Apple("apple");
return a.apple == b.apple;
}
Does Java automatically intern Strings set within instances of my objects?
Is the only time that Java doesn't intern Strings is when they're created using new String("...")
?
EDIT:
Thanks for the answers, an extension to this question would then be to say
Apple a = new Apple(new String("apple"));
Apple b = new Apple(new String("apple"));
returns false with the same test.
This is because I am passing an instance of String into the constructor as opposed to a String literal.