Introduction
A String is a sequence of characters. In Java, strings are objects of the String class. Unlike primitive types, String is a reference type used to represent text.
Creating Strings
1. String Literal:
String name = "John";
String greeting = "Hello, World!";
String empty = "";
2. Using new Keyword:
String name = new String("John");
String greeting = new String("Hello");
3. From Character Array:
char[] chars = {'H', 'e', 'l', 'l', 'o'};
String str = new String(chars);
System.out.println(str); // "Hello"
4. From Byte Array:
byte[] bytes = {72, 101, 108, 108, 111};
String str = new String(bytes);
System.out.println(str); // "Hello"
String Characteristics
1. Immutable
Once created, String content cannot be changed.
String str = "Hello";
str = str + " World"; // Creates new String object
// Original "Hello" remains unchanged in memory
String original = "Java";
String modified = original.concat(" Programming");
System.out.println(original); // "Java" (unchanged)
System.out.println(modified); // "Java Programming" (new object)
Why Immutable?
- Security: Strings used in network connections, file paths
- Thread-safe: Can be shared across threads
- Caching: String pool optimization
- HashCode: Can be cached
2. String Pool
Java maintains a pool of string literals for memory efficiency.
String s1 = "Hello"; // Created in string pool
String s2 = "Hello"; // Refers to same object in pool
String s3 = new String("Hello"); // Created in heap (new object)
System.out.println(s1 == s2); // true (same reference)
System.out.println(s1 == s3); // false (different references)
System.out.println(s1.equals(s3)); // true (same content)
Visual:
String Pool: Heap:
["Hello"] ← s1, s2
["Hello"] ← s3
String Methods
1. Length and Character Access
length() - Returns string length:
String str = "Hello";
int len = str.length();
System.out.println(len); // 5
String empty = "";
System.out.println(empty.length()); // 0
charAt(index) - Returns character at index:
String str = "Hello";
char ch = str.charAt(0); // 'H'
System.out.println(ch);
char last = str.charAt(str.length() - 1); // 'o'
System.out.println(last);
// Out of bounds
char invalid = str.charAt(10); // ❌ StringIndexOutOfBoundsException
2. Comparison Methods
equals(String) - Compares content:
String s1 = "Hello";
String s2 = "Hello";
String s3 = "hello";
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // false (case-sensitive)
equalsIgnoreCase(String) - Ignores case:
String s1 = "Hello";
String s2 = "hello";
String s3 = "HELLO";
System.out.println(s1.equalsIgnoreCase(s2)); // true
System.out.println(s1.equalsIgnoreCase(s3)); // true
compareTo(String) - Lexicographic comparison:
String s1 = "Apple";
String s2 = "Banana";
String s3 = "Apple";
System.out.println(s1.compareTo(s2)); // Negative (Apple < Banana)
System.out.println(s2.compareTo(s1)); // Positive (Banana > Apple)
System.out.println(s1.compareTo(s3)); // 0 (equal)
compareToIgnoreCase(String) - Case-insensitive comparison:
String s1 = "apple";
String s2 = "APPLE";
System.out.println(s1.compareToIgnoreCase(s2)); // 0
3. Searching Methods
contains(CharSequence) - Checks if substring exists:
String str = "Hello World";
System.out.println(str.contains("World")); // true
System.out.println(str.contains("Java")); // false
startsWith(String) - Checks prefix:
String str = "Hello World";
System.out.println(str.startsWith("Hello")); // true
System.out.println(str.startsWith("World")); // false
endsWith(String) - Checks suffix:
String str = "HelloWorld.java";
System.out.println(str.endsWith(".java")); // true
System.out.println(str.endsWith(".txt")); // false
indexOf(String) - Returns first occurrence index:
String str = "Hello World Hello";
System.out.println(str.indexOf("Hello")); // 0
System.out.println(str.indexOf("World")); // 6
System.out.println(str.indexOf("Java")); // -1 (not found)
System.out.println(str.indexOf('o')); // 4
lastIndexOf(String) - Returns last occurrence index:
String str = "Hello World Hello";
System.out.println(str.lastIndexOf("Hello")); // 12
System.out.println(str.lastIndexOf('o')); // 16
4. Extraction Methods
substring(int beginIndex) - Extract from index to end:
String str = "Hello World";
String sub = str.substring(6);
System.out.println(sub); // "World"
substring(int beginIndex, int endIndex) - Extract range:
String str = "Hello World";
String sub = str.substring(0, 5); // End index is exclusive
System.out.println(sub); // "Hello"
String sub2 = str.substring(6, 11);
System.out.println(sub2); // "World"
5. Modification Methods (Return New String)
concat(String) - Concatenate strings:
String s1 = "Hello";
String s2 = " World";
String result = s1.concat(s2);
System.out.println(result); // "Hello World"
System.out.println(s1); // "Hello" (unchanged)
replace(char old, char new) - Replace characters:
String str = "Hello World";
String result = str.replace('o', 'a');
System.out.println(result); // "Hella Warld"
replace(String old, String new) - Replace substring:
String str = "Java is fun";
String result = str.replace("fun", "awesome");
System.out.println(result); // "Java is awesome"
replaceAll(regex, replacement) - Replace with regex:
String str = "Hello123World456";
String result = str.replaceAll("\\d+", ""); // Remove digits
System.out.println(result); // "HelloWorld"
toLowerCase() - Convert to lowercase:
String str = "HELLO World";
String lower = str.toLowerCase();
System.out.println(lower); // "hello world"
toUpperCase() - Convert to uppercase:
String str = "hello World";
String upper = str.toUpperCase();
System.out.println(upper); // "HELLO WORLD"
trim() - Remove leading/trailing whitespace:
String str = " Hello World ";
String trimmed = str.trim();
System.out.println(trimmed); // "Hello World"
System.out.println(str.length()); // 15
System.out.println(trimmed.length()); // 11
strip() - Remove whitespace (Java 11+):
String str = " Hello World ";
String stripped = str.strip(); // Similar to trim()
System.out.println(stripped); // "Hello World"
6. Splitting and Joining
split(String regex) - Split into array:
String str = "Apple,Banana,Cherry";
String[] fruits = str.split(",");
for (String fruit : fruits) {
System.out.println(fruit);
}
// Output:
// Apple
// Banana
// Cherry
String sentence = "Hello World Java";
String[] words = sentence.split(" ");
for (String word : words) {
System.out.println(word);
}
join(delimiter, elements) - Join strings (Java 8+):
String result = String.join(", ", "Apple", "Banana", "Cherry");
System.out.println(result); // "Apple, Banana, Cherry"
String[] words = {"Hello", "World", "Java"};
String sentence = String.join(" ", words);
System.out.println(sentence); // "Hello World Java"
7. Checking Methods
isEmpty() - Checks if length is 0:
String str1 = "";
String str2 = "Hello";
System.out.println(str1.isEmpty()); // true
System.out.println(str2.isEmpty()); // false
isBlank() - Checks if empty or only whitespace (Java 11+):
String str1 = "";
String str2 = " ";
String str3 = "Hello";
System.out.println(str1.isBlank()); // true
System.out.println(str2.isBlank()); // true
System.out.println(str3.isBlank()); // false
8. Conversion Methods
valueOf() - Convert to String:
int num = 100;
String str = String.valueOf(num); // "100"
double d = 99.99;
String str2 = String.valueOf(d); // "99.99"
boolean flag = true;
String str3 = String.valueOf(flag); // "true"
toCharArray() - Convert to char array:
String str = "Hello";
char[] chars = str.toCharArray();
for (char c : chars) {
System.out.println(c);
}
// Output: H e l l o
getBytes() - Convert to byte array:
String str = "Hello";
byte[] bytes = str.getBytes();
for (byte b : bytes) {
System.out.print(b + " ");
}
// Output: 72 101 108 108 111
String Concatenation
1. Using + Operator:
String s1 = "Hello";
String s2 = "World";
String result = s1 + " " + s2;
System.out.println(result); // "Hello World"
// With other types
int age = 25;
String msg = "Age: " + age;
System.out.println(msg); // "Age: 25"
2. Using concat():
String s1 = "Hello";
String s2 = " World";
String result = s1.concat(s2);
System.out.println(result); // "Hello World"
3. Using StringBuilder (Efficient):
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String result = sb.toString();
System.out.println(result); // "Hello World"
String vs StringBuilder vs StringBuffer
String:
- Immutable: Cannot be changed
- Thread-safe: By nature (immutable)
- Performance: Slow for multiple concatenations
- Use: When string rarely changes
StringBuilder:
- Mutable: Can be changed
- Not thread-safe: Faster
- Performance: Fast for multiple operations
- Use: When string changes frequently (single-threaded)
StringBuffer:
- Mutable: Can be changed
- Thread-safe: Synchronized
- Performance: Slower than StringBuilder
- Use: When string changes frequently (multi-threaded)
Example:
// String - Creates many objects
String str = "Hello";
str = str + " World"; // New object
str = str + " Java"; // New object
// StringBuilder - Modifies same object
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World"); // Same object
sb.append(" Java"); // Same object
String result = sb.toString();
String Formatting
Using format():
// Basic formatting
String name = "John";
int age = 25;
String formatted = String.format("Name: %s, Age: %d", name, age);
System.out.println(formatted); // "Name: John, Age: 25"
// Numbers
String.format("%d", 100); // "100"
String.format("%f", 10.5); // "10.500000"
String.format("%.2f", 10.567); // "10.57"
String.format("%,d", 1000000); // "1,000,000"
// Padding
String.format("%10s", "Hello"); // " Hello"
String.format("%-10s", "Hello"); // "Hello "
String.format("%05d", 42); // "00042"
Format Specifiers:
| Specifier | Description | Example |
|---|---|---|
%s | String | ”Hello” |
%d | Integer | 123 |
%f | Float/Double | 10.5 |
%c | Character | ’A’ |
%b | Boolean | true |
%n | Newline | \n |
Common String Operations
1. Reverse a String:
String str = "Hello";
StringBuilder sb = new StringBuilder(str);
String reversed = sb.reverse().toString();
System.out.println(reversed); // "olleH"
2. Check Palindrome:
String str = "madam";
String reversed = new StringBuilder(str).reverse().toString();
boolean isPalindrome = str.equals(reversed);
System.out.println(isPalindrome); // true
3. Count Characters:
String str = "Hello World";
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'o') {
count++;
}
}
System.out.println(count); // 2
4. Remove Spaces:
String str = "Hello World Java";
String noSpaces = str.replace(" ", "");
System.out.println(noSpaces); // "HelloWorldJava"
Escape Sequences
String s1 = "Hello\nWorld"; // Newline
String s2 = "Hello\tWorld"; // Tab
String s3 = "She said \"Hi\""; // Double quote
String s4 = "C:\\Users\\Java"; // Backslash
String s5 = "It\'s here"; // Single quote
Important String Methods Summary
| Method | Description | Example |
|---|---|---|
length() | String length | "Hello".length() → 5 |
charAt(i) | Character at index | "Hello".charAt(0) → ‘H’ |
equals(s) | Compare content | s1.equals(s2) |
substring(i, j) | Extract substring | "Hello".substring(0,3) → “Hel” |
indexOf(s) | Find index | "Hello".indexOf('e') → 1 |
replace(old, new) | Replace | "Hello".replace('l', 'p') |
toLowerCase() | Convert to lower | "HELLO".toLowerCase() → “hello” |
toUpperCase() | Convert to upper | "hello".toUpperCase() → “HELLO” |
trim() | Remove whitespace | " Hi ".trim() → “Hi” |
split(regex) | Split to array | "a,b,c".split(",") |
concat(s) | Concatenate | "Hello".concat(" World") |
contains(s) | Check substring | "Hello".contains("ell") → true |
Exam Tips
Remember:
- Immutable: Strings cannot be changed
- String Pool: Literals stored in pool
- equals() vs ==: Use equals() for content comparison
- Index: Starts from 0
- substring(i, j): j is exclusive
- Methods return new String: Original unchanged
- Empty string:
""has length 0 - null vs empty: null is no object, "" is empty string
Common Questions:
- What is String immutability?
- Difference between == and equals()
- String vs StringBuilder
- What is String pool?
- How to compare strings?
- How to reverse a string?
- Common String methods
- String concatenation methods