Generally string is a sequence of characters. But in java, string is an object. String class is used to create string object.
There are two ways to create String object:
By string literal
By new keyword
String literal is created by double quote.For Example:
String s="Hello";
String s1="Hello sir";
String s2="Hello sir";
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 returns.
If the string does not exist in the pool, a new String object instantiates, then is placed in the pool.
Note: String objects are stored in a special memory area known as string constant pool inside the Heap memory.
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new String object in normal(nonpool) Heap memory and the literal "Welcome" will be placed in the string constant pool.The variable s will refer to the object in Heap(nonpool).
class Example{
public static void main(String args[]){
String s="Hello";
s.concat(" Sir");//concat() method appends the string at the end
System.out.println(s);//will print Hello because strings are immutable objects
}
}
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 "sachin".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.
There are two ways to create String object:
By string literal
By new keyword
String literal is created by double quote.For Example:
String s="Hello";
String s1="Hello sir";
String s2="Hello sir";
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 returns.
If the string does not exist in the pool, a new String object instantiates, then is placed in the pool.
Note: String objects are stored in a special memory area known as string constant pool inside the Heap memory.
String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new String object in normal(nonpool) Heap memory and the literal "Welcome" will be placed in the string constant pool.The variable s will refer to the object in Heap(nonpool).
class Example{
public static void main(String args[]){
String s="Hello";
s.concat(" Sir");//concat() method appends the string at the end
System.out.println(s);//will print Hello because strings are immutable objects
}
}
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 "sachin".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.
Comments