String,String constant pool in java

String grima = “grima”;
String gri = “grima”;
if (grima == gri)
System.out.println(“grima == gri”); // The message is displayed

Both grima,grima references refer to same “grima” in string constant pool.

String pndey = “pandey”;
String pan = “pande”;
pan = pan + “y”; // The value for pan will be resolved during runtime.
if (pndey == pan)
System.out.println(“pndey == pan”); // The 2 references are different

Now in the second case if i change

pan = pan + “y”;this line to –>pan=”pande” +”y”, System.out.println(“pndey == pan”); message will be displayed because the compiler resolves the literal during compilation time itself.

Now as per java docs on string:

•Literal strings within the same class (§8 (Classes)) in the same package (§7 (Packages)) represent references to the same String object (§4.3.1).

•Literal strings within different classes in the same package represent references to the same String object.

•Literal strings within different classes in different packages likewise represent references to the same String object.

•Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.

•Strings computed by concatenation at run time are newly created and therefore distinct.

•The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s