String are constant (immutable), their values cannot be changed after they are created.
String buffers support mutable strings.
String can be shared because string object are immutable.
String represent a string in the UTF-16 format.
Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new string instance is created and placed in the pool. For example:
String s1="something";
String s2="something";//will not create new instance
In the above example only one object will be created. Firstly JVM will not find any string object with the value "something" in string constant pool, so it will create a new object. After that it will find the string with the value "something" in the pool, it will not create new object but will return the reference to the same instance.
Java uses concept of string literal to make Java more memory efficient (because no new objects are created if it exists already in string constant pool).
String s=new String("something");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "something" will be placed in the string constant pool. The variable s will refer to the object in heap(non pool).
Why string objects are immutable in java? Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "abc".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.
After a string literal, all the + will be treated as string concatenation operator.
String Index starts from 0
Java StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously. So it is safe and will result in an order.
The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized.
String Vs StringBuffer
How can we make immutable class