What is a String?
A Java string is a sequence of characters usually written within double quotes. For example, "Java" is a string of length 4. String handling and string manipulation are very important needs of any application program working with data, and therefore proper language support is essential for elegant programming and increased productivity.
Java provides that through its String class and its two more peer classes, StringBuffer and StringBuilder. In Java, a string is an object. It is not a primitive data type like int, long, double, etc., although using the String in Java makes it look like a simple data type called String. String class is immutable, which means once a String object is created, it cannot be changed. If any change is done to the String, a new object is created.
How do we create a string?
In Java, we can create a String in two ways:
a) by assigning a string literal to a String variable like String s1 = " This is a string";
b) by creating a String object with the literal like String s2 = new String(" This is a string");
The main difference lies in memory allocation. Before we discuss this point, let us understand the following concept.
String literal pool
Java maintains a storage space in Java Heap memory to store string literals. This memory area is known as the string literal pool. Each time our application tries to create a new string, literal JVM checks the pool before creating a new String object corresponding to it. If the same literal exists, a reference to the existing object is returned; otherwise, the String literal is placed in the pool, and the object is created. For example,
String varstr1 = "First"; String varstr2 = "Second"; String varstr3 = "First"; String varstr4 = new String("Second");
Two strings, varstr1 and varstr2, are created using the literal "First" and "Second", but when the third String, varstr3 is created with the same literal as the first, JVM returns a reference of varstr1. Memory allocation for the first three is known at compile time, but varstr4 is created at runtime, and even though the existing String literal "Second" is used, a new object is created. We can verify this by comparing varstr1 == varstr3 and varstr2 == varstr4. The first comparison will return true, and the second will return false.
Thus, when we create the string s1, the literal " This is a string" is created in the pool. In the case of s2, the object is created with the same literal but as a new object.