JAVA STRING – COMPLETE DETAILED NOTES
1. Introduction to String
String is a non-primitive data type in Java used to store a sequence of characters. It belongs to [Link]
package and is automatically imported. String is implemented as a class in Java.
2. Why String is Special in Java
Strings are heavily used in Java applications. To improve performance, security, and memory efficiency, Java
provides special handling for String objects such as immutability and String Constant Pool.
3. Ways to Create String Objects
Strings can be created using string literals or by using the new keyword. String literals are stored in the String
Constant Pool, while objects created using new are stored in heap memory.
4. String Constant Pool (SCP)
The String Constant Pool is a special memory area inside the heap that stores unique string literals. It avoids
duplicate objects and improves memory utilization.
5. Immutability of String
Once a String object is created, it cannot be changed. Any modification creates a new object. Immutability
ensures security, thread safety, and memory optimization.
6. String Comparison
The == operator compares references, while equals() compares actual content. equalsIgnoreCase() compares
content without considering case.
7. Important String Methods
Common methods include length(), charAt(), concat(), toUpperCase(), toLowerCase(), substring(), replace(),
trim(), split(), contains(), indexOf(), and lastIndexOf().
8. String Concatenation
Strings can be concatenated using + operator, concat() method, or StringBuilder for better performance.
9. StringBuffer
StringBuffer is mutable and thread-safe. It is slower compared to StringBuilder due to synchronization.
10. StringBuilder
StringBuilder is mutable and not thread-safe. It provides better performance and is preferred in
single-threaded environments.
11. Differences Between String, StringBuffer, and StringBuilder
String is immutable, StringBuffer is mutable and thread-safe, and StringBuilder is mutable and
non-thread-safe.
12. String Interning
Interning stores string objects in the String Constant Pool. The intern() method ensures reuse of strings.
13. Why String is Immutable (Interview Point)
Immutability provides security, allows caching of hashcode, supports SCP, and ensures thread safety.
14. Common String Programs
Reverse string, palindrome check, count characters, count vowels, remove spaces, find duplicate characters,
and anagram checking.
15. Real-World Usage of String
Strings are used in user input, file handling, URLs, database queries, APIs, JSON, and configuration data.