Java strings are sequence of Unicode characters. In Java we do not have any built in string data type, instead Java libraries contains a class String. So each quoted string in java nothing but an instance of this built in String class.
In Java there are two different ways of creating a String.
- Either using a new operator : String myString = new String("Hello");
- or using string literal : String anotherString = "welcome";
Bellow is the example demonstrating difference between these initialization.
String s1 = new String("abc") ;
String s2 = new String("abc") ;
String s3 = "abc" ;
String s4 = "abc";
Then
s1 == s2 returns false
s1 == s3 returns false
s3 == s4 returns true.
This is because s3 and s4 refers to the same object, and s1 and s2 created using new operator refers to the different objects. The basic difference between them is memory allocation, JVM maintains a special area of memory for storing string literal called "String constant Pool". When you create a string using literal, it checks the pool to see if an identical String already exist, if so then it will direct it's reference to the already existing String object, if not then it will create a new String object in this pool. When you create a String using new operator it will create two objects, one in normal memory (heap) and the literal "abc" will be placed in pool.
In Java String is an immutable object. An immutable object is an object whose attributes values can not be modified. In Java once you create a String object, you can not modify it to some other object or different String. Imagine the concept of StringPool, what if String is not immutable. A String object may have more then one reference variables, so if any of them change it's value others will automatically get affected.
