Example & Tutorial understanding programming in easy ways.

What is the difference between creating string as new and literal in java?

When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool.

eg. String str = new String("Test");

Does not put the object str in String pool , we need to call String.intern() method which is used to put them into String pool explicitly. its only when you create String object as String literal.

String literal is a value of type String.
eg. String s1 = "test";

it is immutable. means the value referred by s1 will not changed. new value with change will be created and s1 will refer to it. Java automatically put that into String pool. By the way there is a catch here, Since we are passing arguments as "Test", which is a String literal, it will also create another object as "Test" on string pool.
  

Read More →