Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How + internally works on Strings in JAVA

Tags:

java

string

I read from the blogs that internally java use StringBuilder to concat the String when we use + operator. I was just checking it and found some strange outputs.

public class StringDemo {

    public static void main(String[] args) {

        String a = "Hello World";
        String b = "Hello World";
        String c = "Hello";
        String d =  c + " World".intern();
        String e =  new StringBuilder().append(String.valueOf(c)).append(" World").toString().intern() ;
        String f =  new StringBuilder(String.valueOf(c)).append(" World").toString().intern();

        System.out.println(a == b);   // Line 1 Expected output true
        System.out.println(a == d);   // Line 2 Output is false
        System.out.println(a == e);   // Line 3 Output is true
        System.out.println(a == f);   // Line 4 Output is true

    }
}

So i am using + operator to concat two strings c & " World" and then use intern() method to move String in the pool for String d.

As per my understanding java use StringBuilder, so now I use StringBuilder to concat the String and use intern() method for Strings e and f. So if both the equivalent then address of both the String must be same but the output of Line 2 not matching with Line 4 & 5.

Thanks in advance for your valuable feedback.

like image 892
Kick Avatar asked Oct 15 '15 06:10

Kick


1 Answers

How + internally works in JAVA

Here is my post on the same, give a read Compiler version : How String concatenation works in java.

And coming to your code inside

System.out.println(a == d); 

That should be false only.

As per your understanding you are expecting true. No. Your understanding is wrong. There is a clear difference between

    String d =  c + " World".intern();

And

    String d =  (c + " World").intern();

In first line only "World" got interned and the second line "Hello World" got interned

When you do (c + " World").intern(), you'll see the output true.

like image 168
Suresh Atta Avatar answered Sep 20 '22 08:09

Suresh Atta