String is a sequence of characters. In java, a string is an object of String class that represents a sequence of characters.
Even though, String is a class, it is used often in the form of a data type.
For example: String s = “Basicofy”;
There are two ways to create string
String s = “Hello”;
In this case, JVM creates an object and stores the string “Hello” in that object. Remember, creating object means allotting memory for storing data.
2.Using new operator
We can create an object to String class by allocating memory using new operator. This is just like creating an object to any class, as:
String s = new String(“Hello”);
Explain the difference between ‘String s = “Hello”;’ and ‘String s = new String(“Hello”);’
In the first statement, assignment operator is used to assign the string literal to the String variable s. In this case JVM first of all checks whether the same object is already available in the string constant pool. If it is available, then it creates another reference to it. If the same object is not available, then it creates another object with the content “Hello” and store it into the string constant pool.
In the second statement, new operator is used to creates the string object. In this case, JVM always creates a new object without looking in the string constant pool.