M Sach
M Sach

Reputation: 34424

String reference?

we make the following String objects?

String str1 = new String("ABC");
String str2 = new String("ABC");
String str3 = "ABC";
String str4 = "ABC";

Two questions on above :

  1. system.out.println("valof str1 "+str1 ); -- it prints str1 as ABC But when we compare if(str1==str2), it compares the refrences of string object. How does jvm get to differnce?

  2. str1 has differnt reference from str2 and str3 but str3 and str4 have same references so does jvm check if the string we are going to create with equal operator(instead of new) already exists (if it exist it does not create new object just assign the same refernce to new variable i.e str4) but it does not do this verfication in case of new operator?

Upvotes: 3

Views: 453

Answers (2)

searlea
searlea

Reputation: 8378

You're explicitly creating new strings and asking for distinct references when you call new String(...). If you want to get back to a single reference you can call:

str1 = str1.intern();

Upvotes: 3

C. K. Young
C. K. Young

Reputation: 223023

In Java, string literals (bare "ABC" instead of new String("ABC")) are interned. That is, there is only one copy stored in the JVM, and that is always the copy that's used. That's why they compare equal when using ==.

The following comparisons are also always true:

str1.intern() == str2.intern()
str1.intern() == str3
str2.intern() == str3
str1.intern() == str4
str2.intern() == str4

Upvotes: 11

Related Questions