stefanie lsy
stefanie lsy

Reputation: 49

String compare to literal java == interned string

public static void main(String[] args) {
    String m1 = args[0];
    System.out.println(m1.hashCode());
    System.out.println(args[0].hashCode());
    System.out.println("2345".hashCode());
    System.out.println(m1 == "2345");
}

If args[0] is "2345". The output is 1540226 1540226 1540226 false. Why false? Interned string can be compared with ==, right?

Upvotes: 1

Views: 146

Answers (5)

Vishal
Vishal

Reputation: 2173

By "==" you are checking and comparing "reference" values of the String. Using "equals" works to compare the "contents" of two given strings.

hashCode returns similar values for m1, args[0], and "2345" because as interned strings, these have similar reference values as shown in your SOPs. Using a code example, this is how it is initializing:

String someString = "string_info"  
//Interning. Constant pool is checked for "string_info" and the reference is assigned to someString variable if "string_info" is found in constant pool.

However, when string is being passed as an argument, this is actually being created as a new string object. The new object is created in memory and hence your code m1 == "2345" returns false. Using example, this is how it is initializing:

String someString = new String("string_info") //a new String object is first created in memory and then assignment of "string_info" is referenced using constant pool look up.

Upvotes: 0

yshavit
yshavit

Reputation: 43391

Just because one instance of a string is interned, doesn't mean that others are. In this case, "2345" is a string constant and is thus automatically interned, but there's nothing that requires the JVM to automatically intern the arguments to main. To my knowledge, there's nothing that explicitly prohibits the JVM from doing that, but it doesn't seem to be happening.

Upvotes: 1

ControlAltDel
ControlAltDel

Reputation: 35096

Interned strings can only be compared using == to other interned strings, and will only return true if the interned string value is the same, ie

String a = "a";
String b = "b";
String a2 = "a";
String c = a;
String d = a;


a == a2; //true
a == "a"; //true
a == new String("a"); //false
c == d; // true;
(a + a) == "aa"; // false

Upvotes: 2

Severage
Severage

Reputation: 33

A String is an object, so when you use ==, you're not checking for value equivalency, you're checking if one String object is in the same memory location as another.

Use .equals() when you want to test for value equivalency between objects

Upvotes: 1

Raghu K Nair
Raghu K Nair

Reputation: 3942

You are checking a reference with value ? "2345".equals(m1) is right.

Upvotes: 1

Related Questions