Strings
1. What is a String in Java?โ
In Java, a String is a sequence of characters. Strings are immutable objects, meaning once created, their values cannot be changed.
Strings are represented by the java.lang.String class.
Key Characteristicsโ
- Immutable (cannot be changed after creation)
- Stored in String Constant Pool (for literals)
- Final class (cannot be extended)
- Thread-safe due to immutability
- Implements Serializable, Comparable, CharSequence
String s = "Hello World";
2. Why String is Immutableโ
Once created, the internal value cannot change.
Reasonsโ
โ Security (URLs, file paths, credentials)
โ Thread safety
โ HashCode caching (important for HashMap)
โ String Pool optimization
Exampleโ
String s = "Hello";
s.concat(" Java");
System.out.println(s); // Hello
Correct:
s = s.concat(" Java");
3. String Constant Pool (SCP)โ
A special memory area inside heap where unique string literals are stored.
- Java maintains a String Pool to store unique string literals.
- Helps in saving memory by avoiding duplicate String objects.
Benefitsโ
- Memory efficiency
- Faster comparisons
- Reuse of objects
Exampleโ
String a = "Test";
String b = "Test";
System.out.println(a == b); // true (same reference)
Using new:
String a = new String("Test");
String b = new String("Test");
System.out.println(a == b); // false
4. Creating Stringsโ
4.1 Literal (Recommended)โ
String s = "Java";
Stored in SCP.
4.2 Using newโ
String s = new String("Java");
Creates new object in heap.
5. Important String Methodsโ
| Method | Description |
|---|---|
length() | Returns the number of characters |
charAt(int index) | Returns character at given index |
substring(int begin) | Returns substring from index |
substring(int, int) | Returns substring between two indexes |
toLowerCase() | Converts to lowercase |
toUpperCase() | Converts to uppercase |
trim() | Removes leading and trailing spaces |
equals(String) | Compares content (case-sensitive) |
equalsIgnoreCase(String) | Compares ignoring case |
compareTo(String) | Lexicographically compares strings |
contains(String) | Checks if substring is present |
replace(old, new) | Replaces characters or words |
split(String regex) | Splits string into array |
startsWith(prefix) | Checks start of the string |
endsWith(suffix) | Checks end of the string |
Examples:
length()โ
Returns number of characters.
String s = "Automation";
System.out.println(s.length()); // 10
charAt()โ
Returns character at index.
System.out.println(s.charAt(2)); // t
substring()โ
Extracts part of string.
System.out.println(s.substring(3)); // omation
System.out.println(s.substring(3, 6)); // oma
equals() vs ==โ
==โ reference comparisonequals()โ content comparison
String x = "Java";
String y = new String("Java");
System.out.println(x == y); // false
System.out.println(x.equals(y)); // true
compareTo()โ
Lexicographical comparison means it will compare char by char. It will compare unicode values of both strings.
String a = "Java";
String b = "java";
a.compareTo(b); // -32
contains()โ
Checks if substring exists.
System.out.println("Hello Java".contains("Java")); // true
replace()โ
Replaces characters or words.
System.out.println("banana".replace('a', 'o')); // bonono
split()โ
Splits string using regex delimiter.
String data = "A,B,C";
String[] arr = data.split(",");
trim()โ
Removes leading/trailing spaces.
String s = " Java ";
System.out.println(s.trim()); // "Java"
Case Conversionโ
"Java".toUpperCase();
"JAVA".toLowerCase();
6. String Concatenation and Performanceโ
Using + repeatedly creates many temporary objects.
String result = "";
for (int i = 0; i < 5; i++) {
result += i;
}
Better approach โ StringBuilder.
7. StringBuilder (Mutable, Not Thread-Safe)โ
What is StringBuilder?โ
A mutable sequence of characters introduced in Java 5.
Characteristicsโ
- Mutable (can modify without creating new object)
- Not synchronized โ not thread-safe
- High performance
- Ideal for single-thread scenarios
StringBuilder sb = new StringBuilder("Hello");
sb.append(" Java");
Important Methodsโ
append()โ
Adds data at end.
sb.append(" World");
insert()โ
Adds data at specific index.
sb.insert(5, " Amazing");
delete()โ
Removes characters between indices.
sb.delete(5, 13);
replace()โ
Replaces characters in range.
sb.replace(0, 5, "Hi");
reverse()โ
Reverses sequence.
sb.reverse();
capacity()โ
Returns current capacity.
System.out.println(sb.capacity());
ensureCapacity()โ
Ensures minimum capacity.
sb.ensureCapacity(100);
Complete Exampleโ
public class BuilderDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Java");
sb.append(" Programming");
sb.insert(4, " Language");
sb.replace(0, 4, "Core");
sb.delete(4, 13);
sb.reverse();
System.out.println(sb);
}
}
8. StringBuffer (Mutable, Thread-Safe)โ
What is StringBuffer?โ
A mutable sequence of characters similar to StringBuilder but synchronized.
Characteristicsโ
- Mutable
- Thread-safe (synchronized)
- Slower than StringBuilder
- Used in multi-threaded environments
StringBuffer sb = new StringBuffer("Hello");
sb.append(" Java");
Methodsโ
Same as StringBuilder:
- append()
- insert()
- delete()
- replace()
- reverse()
- capacity()
- ensureCapacity()
Exampleโ
public class BufferDemo {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Multi");
sb.append(" Thread");
sb.insert(5, " Safe");
sb.delete(5, 10);
sb.reverse();
System.out.println(sb);
}
}
9. String vs StringBuilder vs StringBufferโ
| Feature | String | StringBuilder | StringBuffer |
|---|---|---|---|
| Mutable | No | Yes | Yes |
| Thread-safe | Yes | No | Yes |
| Performance | Slow | Fast | Medium |
10. String Interningโ
Interning ensures that all identical strings point to the same memory location in the pool.
String a = new String("Test");
String b = a.intern(); // refers to "Test" in the pool
System.out.println(s2 == "Test"); // true
11. Conversionsโ
String โ intโ
int num = Integer.parseInt("123");
int โ Stringโ
String s = String.valueOf(123);
String โ char[]โ
char[] arr = str.toCharArray();
12. Practical Programsโ
Reverse Stringโ
String input = "Automation";
String rev = new StringBuilder(input).reverse().toString();
Palindrome Checkโ
String s = "madam";
boolean isPal = s.equals(
new StringBuilder(s).reverse().toString()
);
Count Vowelsโ
String s = "Automation";
int count = 0;
for (char c : s.toLowerCase().toCharArray()) {
if ("aeiou".indexOf(c) != -1) count++;
}
13. When to Use Whatโ
Use String when:
- Data is constant
- Few modifications
Use StringBuilder when:
- Frequent modifications
- Single-threaded programs
Use StringBuffer when:
- Multi-threaded modifications
- Need synchronization
๐ก Best Practicesโ
- Use
StringBuilderfor string manipulation inside loops. - Use
.equals()instead of==for comparison. - Avoid creating strings with
newunnecessarily.
๐งช Interview Tipsโ
- Understand String Pool and immutability
- Practice questions on
substring,replace,split - Know differences between
String,StringBuilder, andStringBuffer