简体   繁体   中英

String comparison and interning

The following code (from an interview) produces an output of false , but I believe it should be true .

public static void main(String[] args) {    
    String a = "hello";
    String b = a + "world";
    String c = "helloworld";
    System.out.println(b==c);
}

I thought that constant String expressions were interned, and a + "world" is a constant, so it should intern "hello world" .

Can someone explain why the output is false ?

Java interns all Strings that are compile time constants . However, only Strings declared by concatenating String literals are considered a compile time constant and so be interned.

This is because the compiler looks only at the line being compiled, so it has no idea if a if a is a constant or not. For example, a could be declared as:

String a = new Date().toString();

Hence, c is a different instance of String than b .

When you do this,

String b=a+"world";

The compiler chooses a StringBuilder based concatenation of String objects like so,

StringBuilder sb = new StringBuilder(a);
sb.append("world"); 
String b = sb.toString();

This yields a different reference, hence returning false as in your case.

But if you use this,

String b="hello"+"world";

Then the compiler identifies it as a constant, and both the b and c variables reference the same literal in the constant pool. Hence it returns true .

When you assign strings like in your example, a , b , and c are separate String objects. So when you compare them you get false because they are not the same object . == in Java does not do a character-by-character comparison of the string. That's what String.equals() is for.

This is a solid summary to read to understand: How do I compare strings in Java?

The code you are looking at does an equality comparison between two variables that point to two different string instances, which are diferent objects stored in different places in memory (among other things) and are therefore different even though the string they represent is the same.

To do a string comparison you would need to use

stringInstance.equals(anotherStringInstance)

If you did something like this

String a = "abcde";
String b = a;

Then you would get a == b to be true as both variables point to the same object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM