Strings are a sequence of characters. In the Java programming language, strings are objects. A Java String represents an immutable sequence of characters and cannot be changed once created. Strings are of type java.lang.String class.
There are two ways to create a String in Java.
java.lang.String
type. ExampleString str = "hello";
String message = "Hello World";
String literals are stored in String pool, a special memory area created by JVM. There can be only one instance of one String. Any second String with same character sequence will have the reference of first string stored in string pool. It makes efficient to work with Strings and saves lots of physical memory in runtime.
Memory management is the most important aspect of any programming language. Memory management in case of string in Java is a little bit different than any other class. To make Java more memory efficient, JVM introduced a special memory area for the string called String Constant Pool.
String name1 = "hello World";
String name2 = "hello World";
String name3 = "hello World";
in above example, we created 3 string literals with same char sequence. Inside JVM, there will be only one instance of String inside string pool. All rest 2 instances will share the reference of string literal created for first literal.
2.String object we can create separate instance for each separate string in memory. We can create one string object per string value using new keyword.
String objects created using new keyword – are stored in heap memory.
Example
String name1 = new String("javaoops.com");
String name2 = new String("javaoops.com");
String name3 = new String("javaoops.com");
In above example, there will be 3 separate instances of String with same value in heap memory.
The string is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client's action would affect all another client. For example, if one client changes the value of String "Test" to "TEST", all other clients will also see that value as explained in the first example. Since caching of String objects was important from performance reason this risk was avoided by making String class Immutable. At the same time, String was made final so that no one can compromise invariant of String class e.g. Immutability, Caching hashcode calculation etc by extending and overriding behaviors.
String final in Java
The string is final by design in Java, some of the points which make sense. String is final for Security, optimization and to maintain a pool of String. String pool facility without making string immutable , its not possible at all because in case of string pool one string object/literal. it is thread-safe and it can be shared between multiple threads without external synchronization. String is not immutable, this would lead serious security threat