1

We can create Strings using explicit or implicit constructions.

Implicit construction example:

String str1 = "hello";
String str2 = "hello";
str1==str2 // returns true, both str1 and str2 points to the same String object in string pool

Explicit construction example

String str3 = new String("hello");
String str4 = new String("hello")
str3==str4 // returns false because str3 and str4 points to different String object

Since it's preferred (memory save) to use implicit construction why we shouldn't use == operator? As far as I know the only one reason to not use == operator is that we can forget about not using explicit constructions and try to do something like

str1==str3
str3==str4 // and so forth
user123454321
  • 1,028
  • 8
  • 26
  • 3
    Try for example with `String str2 = "hhello".substring(1);` and you'll see why you shouldn't use `==`. – Alexis C. Apr 28 '15 at 17:53
  • 1
    Why do you think that every used string is a predefined one? What about strings from an user input? Or from a json object, or a file, or...? – Tom Apr 28 '15 at 18:10

1 Answers1

8

Literal strings, coming from your code, are interned. That's why they're the same object in your example.

But not all strings in your program come from your code, some come from various inputs (for example a user input, or a file) or from operations you do to build them, and those strings aren't interned (unless you ask for it). Those strings aren't usually == even when they're equal.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758