The String in Java is a sequence of characters used to store and manipulate text.It is one of the most used classes in Java.
- Each character in a string is stored using 16-bit Unicode (UTF-16) encoding.
- Strings are immutable, meaning their value cannot be changed after creation.
Example
String str = "Hello";
str.concat(" World");
System.out.println(str);
Output
Hello
- Because concat() creates a new string instead of modifying the old one.
Ways to Create String
1. String Literal
Example:1
public class Demo {
public static void main(String[] args) {
String name = "Harini";
System.out.println(name);
}
}
Output
Harini
Why is this called String Literal?
String name = "Harini";
- "Harini" β String literal
- It is directly written inside double quotes.
- Java stores it inside the String Constant Pool.
Example: 2
public class Test {
public static void main(String[] args) {
String a = "Java";
String b = "Java";
System.out.println(a == b);
}
}
Output:
true
- Because both a and b point to the same object in the String pool.
String Pool
- Java stores string literals in a special memory area called the String Constant Pool.
2. Using new Keyword
Example
public class Demo {
public static void main(String[] args) {
String s1 = new String("Java");
String s2 = new String("Java");
System.out.println(s1);
System.out.println(s2);
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
}
}
Output
Java
Java
false
true
Creating String using new
String s1 = new String("Java");
- new keyword creates a new object
- Object is created in heap memory
- Even if "Java" already exists, Java creates another new object
Same for:
String s2 = new String("Java");
So s1 and s2 are different objects.
Why s1 == s2 is false?
System.out.println(s1 == s2);
Output:
false
Because:
- == compares memory address/reference
- s1 and s2 are different objects in memory
Why s1.equals(s2) is true?
System.out.println(s1.equals(s2));
Output:
true
Because:
- equals() compares actual content
- Both strings contain "Java"
Memory Representation
- String s1 = new String("Java");
- String s2 = new String("Java");
Heap Memory
s1 ---> "Java" (Object 1)
s2 ---> "Java" (Object 2)
Two separate objects are created.
Top comments (1)
From high-level view to small details, all things are covered well!
Well written!