Java String Literal vs String Object

12/26/2016 code-examplejavastrings

Most asked question during your interviews, different between

String s1 = "abc";
String s2 = new String("abc");
1
2

Here s1 string is called as Java String Literal which is created in Heap Space and maintained in a shared memory pool, whereas s2 string is regular Java String Object created in Heap memory and has nothing to do with shared memory.

In the above scenario, s1 is literal string and hence if there are same literals available in shared memory pool, then the same is preferred and no new instance is created unlike string s2 since its an object, so everytime you create the same string object, it will always create a new String Object in memory making in less memory efficient. Refer to below diagram to understand in depth.

String Literals vs String Objects Diagram Representation