string vs string java code example

Example 1: string literal vs string object

String literal (String str = "abc";)
String Object (String str = new String("abc");)

In String object JVM is forced to
create a new string reference,
even if “abc” is in the reference pool.

String object always takes long time to
execute than String literal because it will
construct new string everytime we run the 
program.

Example 2: string vs new string

String str = new String("");
String str2 = "";

They both immutable and they save in different 
memory location. String objects created without
the use of new keyword are stored in the
String Constant Pool part of the heap.
It doesn't create the same string object
if there is already string constant in the pool.

Tags:

Java Example