What is a String:
- A string is a sequence of characters.
- String is an immutable object, and it is in java.lang.String package.
- It implements interfaces like Serializable, Comparable, and CharSequence interfaces.
- CharSequence is the parent interface of String. It is also implemented by StringBuffer and StringBuilder.
String is an Immutable Object:
- String is an immutable object, which means it is constant and cannot be changed
- It is stored in a special memory area called the String Constant Pool (SCP)
- The String Constant Pool (SCP) is a special memory area inside the heap.
Ways of creating a string in Java:
- String literal (Static Memory)
- Using new keyword (Heap Memory)
How to create a string literal:
String s1="Java";
When you create a string using a literal, Java first checks:
-If the same string already exists in SCP → it reuses it
Otherwise → it creates a new object
String s1 = "Java";
String s2 = "Java";
->Both s1 and s2 point to the same memory location in the String Pool.
public static void main(String[] args)
{
String s = "Test";
// concat() method appends the string at the end
s.concat(" Automation");
// This will print Test because strings are immutable objects
System.out.println(s);
}
O/P: Test
As we can see in the given figure, two objects are created, but the reference variable still refers to "Test" and not to "Automation". But if we explicitly assign it to the reference variable, it will refer to the "Test Automation" object.
public static void main(String[] args)
{
String name = "Test";
name = name.concat(" Automation");
System.out.println(name);
}
O/P: Test Automation
How to create a String using new Keyword:
String s = new String("Welcome");
A String object is explicitly created in Heap memory, even if the same value already exists in the String Constant Pool.
Top comments (0)