Java String Methods
Java String Methods
The String class in Java comes with over 60 built-in methods. You do not need all of them — but roughly 20 show up in almost every real project. This article covers each of those 20 with a clear explanation of what it does, how it behaves on edge cases, and where it genuinely appears in production code.
Every method here returns a new String or a computed value — none of them modify the original. That is the immutability rule, and it applies to every method on this page without exception.
Quick Reference — All Methods Covered
| Method | Returns | What It Does |
|---|---|---|
length() | int | Number of characters in the string |
charAt(i) | char | Character at index i |
indexOf(str) | int | First position of substring (-1 if not found) |
lastIndexOf(str) | int | Last position of substring |
substring(start) | String | Everything from start to end |
substring(start, end) | String | Characters from start (inclusive) to end (exclusive) |
contains(str) | boolean | Whether the string contains a substring |
startsWith(str) | boolean | Whether the string begins with the given prefix |
endsWith(str) | boolean | Whether the string ends with the given suffix |
equals(str) | boolean | Content equality, case-sensitive |
equalsIgnoreCase(str) | boolean | Content equality, case-insensitive |
compareTo(str) | int | Lexicographic order comparison |
toUpperCase() | String | Converts all characters to uppercase |
toLowerCase() | String | Converts all characters to lowercase |
trim() | String | Removes leading and trailing whitespace |
strip() | String | Same as trim but Unicode-aware (Java 11+) |
replace(old, new) | String | Replaces all occurrences of a character or substring |
replaceAll(regex, str) | String | Replaces all matches of a regular expression |
split(regex) | String[] | Splits string at each regex match |
join(sep, parts) | String | Joins multiple strings with a separator |
valueOf(val) | String | Converts any type to its String representation |
format(template, args) | String | Creates a formatted string using placeholders |
isEmpty() | boolean | True only if length is 0 |
isBlank() | boolean | True if empty or contains only whitespace (Java 11+) |
toCharArray() | char[] | Converts string to character array |
intern() | String | Returns the pooled version of the string |
1 — length()
Returns the total number of characters in the string, including spaces and punctuation. Indexing in Java is zero-based, so the last valid index is always length() - 1.
1// File: LengthDemo.java
2
3public class LengthDemo {
4
5 public static void main(String[] args) {
6
7 String name = "Priya Sharma";
8 String empty = "";
9 String spaces = " ";
10 String special = "Hello, World! 😊";
11
12 System.out.println("'" + name + "' length: " + name.length()); // 12
13 System.out.println("'' length : " + empty.length()); // 0
14 System.out.println("' ' length : " + spaces.length()); // 3
15 System.out.println("With emoji length : " + special.length()); // 16 — emoji = 2 code units
16
17 // Practical use — validate username length
18 String username = "rohan_dev";
19 if (username.length() < 4 || username.length() > 20) {
20 System.out.println("Username must be 4-20 characters.");
21 } else {
22 System.out.println("Username '" + username + "' is valid (" + username.length() + " chars).");
23 }
24
25 // Last character using length()
26 String path = "/home/user/documents";
27 System.out.println("Last char: " + path.charAt(path.length() - 1)); // 's'
28 }
29}Output:
'Priya Sharma' length: 12
'' length : 0
' ' length : 3
With emoji length : 16
Username 'rohan_dev' is valid (9 chars).
Last char: s
Note: length without parentheses is for arrays (arr.length). For strings, you always need parentheses — str.length().
2 — charAt(index)
Returns the char at the specified zero-based index. Throws StringIndexOutOfBoundsException if the index is negative or greater than or equal to length().
1// File: CharAtDemo.java
2
3public class CharAtDemo {
4
5 public static void main(String[] args) {
6
7 String word = "DevStackFlow";
8
9 // Access individual characters
10 System.out.println("charAt(0) : " + word.charAt(0)); // D
11 System.out.println("charAt(3) : " + word.charAt(3)); // S
12 System.out.println("charAt(11) : " + word.charAt(11)); // w (last char)
13
14 System.out.println();
15
16 // Count vowels using charAt()
17 String sentence = "Welcome to India";
18 int vowelCount = 0;
19 String vowels = "aeiouAEIOU";
20
21 for (int i = 0; i < sentence.length(); i++) {
22 if (vowels.indexOf(sentence.charAt(i)) != -1) {
23 vowelCount++;
24 }
25 }
26 System.out.println("Sentence : " + sentence);
27 System.out.println("Vowels : " + vowelCount);
28
29 System.out.println();
30
31 // Check if a string is a palindrome using charAt()
32 String test = "racecar";
33 boolean isPalindrome = true;
34 for (int i = 0; i < test.length() / 2; i++) {
35 if (test.charAt(i) != test.charAt(test.length() - 1 - i)) {
36 isPalindrome = false;
37 break;
38 }
39 }
40 System.out.println("'" + test + "' is palindrome: " + isPalindrome);
41
42 // Out-of-bounds guard
43 try {
44 System.out.println(word.charAt(50));
45 } catch (StringIndexOutOfBoundsException e) {
46 System.out.println("Error: " + e.getMessage());
47 }
48 }
49}Output:
charAt(0) : D
charAt(3) : S
charAt(11) : w
Sentence : Welcome to India
Vowels : 6
'racecar' is palindrome: true
Error: String index out of range: 50
3 — indexOf() and lastIndexOf()
indexOf(str) returns the starting index of the first occurrence of a substring. Returns -1 if not found. lastIndexOf(str) returns the last occurrence. Both have overloads that accept a starting position for the search.
1// File: IndexOfDemo.java
2
3public class IndexOfDemo {
4
5 public static void main(String[] args) {
6
7 String text = "Java is great. Java is powerful. Java is fun.";
8
9 // indexOf — first occurrence
10 System.out.println("First 'Java' at: " + text.indexOf("Java")); // 0
11 System.out.println("First '.' at: " + text.indexOf('.')); // 14
12 System.out.println("'Python' at : " + text.indexOf("Python")); // -1 (not found)
13
14 // indexOf with fromIndex — start searching from a position
15 System.out.println("'Java' from index 5: " + text.indexOf("Java", 5)); // 15
16
17 // lastIndexOf — last occurrence
18 System.out.println("Last 'Java' at: " + text.lastIndexOf("Java")); // 33
19 System.out.println("Last '.' at: " + text.lastIndexOf('.')); // 44
20
21 System.out.println();
22
23 // Practical use 1 — extract file extension
24 String filename = "profile_photo.jpeg";
25 int dotPos = filename.lastIndexOf('.');
26 String name = filename.substring(0, dotPos);
27 String ext = filename.substring(dotPos + 1);
28 System.out.println("Filename : " + filename);
29 System.out.println("Name : " + name); // profile_photo
30 System.out.println("Extension : " + ext); // jpeg
31
32 System.out.println();
33
34 // Practical use 2 — extract domain from email
35 String email = "rohan.mehta@razorpay.com";
36 int atPos = email.indexOf('@');
37 String username = email.substring(0, atPos);
38 String domain = email.substring(atPos + 1);
39 System.out.println("Email : " + email);
40 System.out.println("Username : " + username); // rohan.mehta
41 System.out.println("Domain : " + domain); // razorpay.com
42
43 System.out.println();
44
45 // Count total occurrences of a substring
46 String source = "banana";
47 String target = "an";
48 int count = 0;
49 int pos = source.indexOf(target);
50 while (pos != -1) {
51 count++;
52 pos = source.indexOf(target, pos + 1);
53 }
54 System.out.println("'" + target + "' found " + count + " times in '" + source + "'");
55 }
56}Output:
First 'Java' at: 0
First '.' at: 14
'Python' at : -1
'Java' from index 5: 15
Last 'Java' at: 33
Last '.' at: 44
Filename : profile_photo.jpeg
Name : profile_photo
Extension : jpeg
Email : rohan.mehta@razorpay.com
Username : rohan.mehta
Domain : razorpay.com
'an' found 2 times in 'banana'
Always check for -1 before using the index in substring(). If indexOf returns -1 and you pass that to substring(), you get a StringIndexOutOfBoundsException.
4 — substring(start) and substring(start, end)
substring(start) returns everything from start index to the end. substring(start, end) returns characters from start (inclusive) to end (exclusive). The length of the result is always end - start.
1// File: SubstringDemo.java
2
3public class SubstringDemo {
4
5 public static void main(String[] args) {
6
7 String fullText = "Order ID: ORD-2024-9921 | Status: PLACED";
8
9 // substring(start) — from position to end
10 System.out.println("From index 10 : " + fullText.substring(10)); // ORD-2024-9921 | Status: PLACED
11
12 // substring(start, end) — from start (inclusive) to end (exclusive)
13 System.out.println("Indices 10-23 : " + fullText.substring(10, 23)); // ORD-2024-9921
14
15 System.out.println();
16
17 // Practical use — extract structured parts
18 String record = "EMP-042|Priya Sharma|Engineering|85000";
19 String[] fields = record.split("\\|");
20 System.out.println("Employee ID : " + fields[0]); // EMP-042
21 System.out.println("Name : " + fields[1]); // Priya Sharma
22 System.out.println("Department : " + fields[2]); // Engineering
23 System.out.println("Salary : " + fields[3]); // 85000
24
25 System.out.println();
26
27 // Extract first name and last name
28 String name = "Ananya Krishnan";
29 int spaceIndex = name.indexOf(' ');
30 String firstName = name.substring(0, spaceIndex);
31 String lastName = name.substring(spaceIndex + 1);
32 System.out.println("First : " + firstName); // Ananya
33 System.out.println("Last : " + lastName); // Krishnan
34
35 System.out.println();
36
37 // Truncate a long string for display — show first N chars + "..."
38 String description = "This wireless keyboard comes with a long-lasting battery and ergonomic design.";
39 int maxLength = 40;
40 String truncated = description.length() > maxLength
41 ? description.substring(0, maxLength) + "..."
42 : description;
43 System.out.println("Truncated : " + truncated);
44 }
45}Output:
From index 10 : ORD-2024-9921 | Status: PLACED
Indices 10-23 : ORD-2024-9921
Employee ID : EMP-042
Name : Priya Sharma
Department : Engineering
Salary : 85000
First : Ananya
Last : Krishnan
Truncated : This wireless keyboard comes with a long...
substring(start, end) — end is exclusive. "Hello".substring(0, 3) is "Hel" — positions 0, 1, 2, not 3. A common interview question is: what does "Hello".substring(2, 2) return? Answer: an empty string "" — start equals end, so zero characters.
5 — contains(), startsWith(), endsWith()
Three methods that check whether a string contains or begins/ends with a given value. All return boolean.
1// File: ContainsStartsEndsDemo.java
2
3public class ContainsStartsEndsDemo {
4
5 public static void main(String[] args) {
6
7 String productCode = "ELEC-PHONE-SAMSUNG-S24";
8 String url = "https://www.meesho.com/product/12345";
9 String filename = "invoice_2024_01_15.pdf";
10
11 // contains() — substring anywhere in the string
12 System.out.println("Product code checks:");
13 System.out.println(" contains 'PHONE' : " + productCode.contains("PHONE")); // true
14 System.out.println(" contains 'LAPTOP' : " + productCode.contains("LAPTOP")); // false
15
16 System.out.println();
17
18 // startsWith() — beginning of string
19 System.out.println("URL checks:");
20 System.out.println(" startsWith 'https': " + url.startsWith("https")); // true
21 System.out.println(" startsWith 'http' : " + url.startsWith("http")); // true
22 System.out.println(" startsWith 'ftp' : " + url.startsWith("ftp")); // false
23
24 // startsWith with offset — check from a specific position
25 System.out.println(" 'meesho' at pos 12: " + url.startsWith("meesho", 12)); // true
26
27 System.out.println();
28
29 // endsWith() — end of string
30 System.out.println("Filename checks:");
31 System.out.println(" endsWith '.pdf' : " + filename.endsWith(".pdf")); // true
32 System.out.println(" endsWith '.xlsx' : " + filename.endsWith(".xlsx")); // false
33
34 System.out.println();
35
36 // Practical use — file type routing
37 String[] files = {
38 "report.pdf", "data.xlsx", "photo.jpg",
39 "config.json", "app.java"
40 };
41
42 System.out.println("File routing:");
43 for (String file : files) {
44 String type;
45 if (file.endsWith(".pdf")) type = "Document";
46 else if (file.endsWith(".xlsx")) type = "Spreadsheet";
47 else if (file.endsWith(".jpg") || file.endsWith(".png")) type = "Image";
48 else if (file.endsWith(".json")) type = "Config";
49 else if (file.endsWith(".java")) type = "Source Code";
50 else type = "Unknown";
51 System.out.printf(" %-15s → %s%n", file, type);
52 }
53 }
54}Output:
Product code checks:
contains 'PHONE' : true
contains 'LAPTOP' : false
URL checks:
startsWith 'https': true
startsWith 'http' : true
startsWith 'ftp' : false
'meesho' at pos 12: true
Filename checks:
endsWith '.pdf' : true
endsWith '.xlsx' : false
File routing:
report.pdf → Document
data.xlsx → Spreadsheet
photo.jpg → Image
config.json → Config
app.java → Source Code
6 — equals() and equalsIgnoreCase()
equals() compares content exactly — case-sensitive. equalsIgnoreCase() compares content while ignoring upper/lower case differences. Neither modifies either string.
1// File: EqualsDemo.java
2
3public class EqualsDemo {
4
5 public static void main(String[] args) {
6
7 String userInput = "Admin";
8 String storedRole = "admin";
9
10 // equals() — case-sensitive
11 System.out.println("equals() — case sensitive:");
12 System.out.println(" 'Admin'.equals('admin') : " + userInput.equals(storedRole)); // false
13 System.out.println(" 'Admin'.equals('Admin') : " + userInput.equals("Admin")); // true
14
15 System.out.println();
16
17 // equalsIgnoreCase() — case-insensitive
18 System.out.println("equalsIgnoreCase():");
19 System.out.println(" 'Admin' eq-ic 'admin' : " + userInput.equalsIgnoreCase(storedRole)); // true
20 System.out.println(" 'ADMIN' eq-ic 'admin' : " + "ADMIN".equalsIgnoreCase(storedRole)); // true
21
22 System.out.println();
23
24 // Safe pattern — known constant on left (no NPE if variable is null)
25 String input = null;
26 System.out.println("Null safety:");
27 System.out.println(" 'admin'.equals(null) : " + "admin".equals(input)); // false — no NPE
28 // input.equals("admin") would throw NullPointerException
29
30 System.out.println();
31
32 // Practical use — check user role from form input
33 String[] roles = {"ADMIN", "Manager", "viewer", "SUPER_ADMIN"};
34 for (String role : roles) {
35 if ("admin".equalsIgnoreCase(role)) {
36 System.out.println(role + " → Full access");
37 } else if ("manager".equalsIgnoreCase(role)) {
38 System.out.println(role + " → Reports access");
39 } else {
40 System.out.println(role + " → Read-only access");
41 }
42 }
43 }
44}Output:
equals() — case sensitive:
'Admin'.equals('admin') : false
'Admin'.equals('Admin') : true
equalsIgnoreCase():
'Admin' eq-ic 'admin' : true
'ADMIN' eq-ic 'admin' : true
Null safety:
'admin'.equals(null) : false
ADMIN → Full access
Manager → Reports access
viewer → Read-only access
SUPER_ADMIN → Read-only access
7 — toUpperCase() and toLowerCase()
Convert all characters to uppercase or lowercase respectively. Useful for normalising user input before storage or comparison.
1// File: CaseConversionDemo.java
2
3public class CaseConversionDemo {
4
5 public static void main(String[] args) {
6
7 String mixed = "Hello, DevStackFlow!";
8 String shout = "WHY IS EVERYONE SHOUTING?";
9 String input = " Mumbai ";
10
11 System.out.println("toUpperCase: " + mixed.toUpperCase());
12 System.out.println("toLowerCase: " + shout.toLowerCase());
13
14 System.out.println();
15
16 // Normalise before comparison — avoids case sensitivity bugs
17 String cityInput = " benGaLuRu ";
18 String citySaved = "BENGALURU";
19
20 boolean match = cityInput.trim().equalsIgnoreCase(citySaved);
21 System.out.println("City match (normalised): " + match); // true
22
23 System.out.println();
24
25 // Capitalise first letter of each word — title case
26 String raw = "wireless headphones premium edition";
27 String[] words = raw.split(" ");
28 StringBuilder sb = new StringBuilder();
29
30 for (String word : words) {
31 sb.append(Character.toUpperCase(word.charAt(0)));
32 sb.append(word.substring(1).toLowerCase());
33 sb.append(" ");
34 }
35
36 System.out.println("Raw : " + raw);
37 System.out.println("Title case: " + sb.toString().trim());
38
39 System.out.println();
40
41 // Normalise product codes before saving to database
42 String[] rawCodes = {"elec-001", "CLOTH-042", "Grocery_101"};
43 System.out.println("Normalised product codes:");
44 for (String code : rawCodes) {
45 System.out.println(" " + code + " → " + code.toUpperCase().replace("-", "_"));
46 }
47 }
48}Output:
toUpperCase: HELLO, DEVSTACKFLOW!
toLowerCase: why is everyone shouting?
City match (normalised): true
Raw : wireless headphones premium edition
Title case: Wireless Headphones Premium Edition
Normalised product codes:
elec-001 → ELEC_001
CLOTH-042 → CLOTH_042
Grocery_101 → GROCERY_101
8 — trim() and strip()
Both remove leading and trailing whitespace. strip() (Java 11+) is the modern version — it handles Unicode whitespace correctly, while trim() only handles characters with ASCII value ≤ 32.
1// File: TrimStripDemo.java
2
3public class TrimStripDemo {
4
5 public static void main(String[] args) {
6
7 String padded = " Hello, World! ";
8 String tabbed = "\t Rohan Mehta \t";
9 String inner = "Hello World"; // inner spaces NOT removed
10
11 System.out.println("Original : '" + padded + "'");
12 System.out.println("trim() : '" + padded.trim() + "'");
13 System.out.println("strip() : '" + padded.strip() + "'");
14
15 System.out.println();
16
17 System.out.println("With tabs : '" + tabbed + "'");
18 System.out.println("trim() : '" + tabbed.trim() + "'");
19
20 System.out.println();
21
22 System.out.println("Inner spaces : '" + inner + "'");
23 System.out.println("trim() : '" + inner.trim() + "'"); // inner unchanged
24
25 System.out.println();
26
27 // stripLeading() and stripTrailing() — Java 11+
28 String rightPadded = "Priya ";
29 String leftPadded = " Sneha";
30
31 System.out.println("stripLeading (' Sneha'): '" + leftPadded.stripLeading() + "'");
32 System.out.println("stripTrailing('Priya '): '" + rightPadded.stripTrailing() + "'");
33
34 System.out.println();
35
36 // Practical use — clean user input before processing
37 String[] inputs = {" rohan@meesho.com ", "\tpriya@gmail.com", "sneha@flipkart.com "};
38 System.out.println("Cleaned emails:");
39 for (String raw : inputs) {
40 System.out.println(" '" + raw + "' → '" + raw.strip() + "'");
41 }
42 }
43}Output:
Original : ' Hello, World! '
trim() : 'Hello, World!'
strip() : 'Hello, World!'
With tabs : ' Rohan Mehta '
trim() : 'Rohan Mehta'
Inner spaces : 'Hello World'
trim() : 'Hello World'
stripLeading (' Sneha'): 'Sneha'
stripTrailing('Priya '): 'Priya'
Cleaned emails:
' rohan@meesho.com ' → 'rohan@meesho.com'
' priya@gmail.com' → 'priya@gmail.com'
'sneha@flipkart.com ' → 'sneha@flipkart.com'
Neither trim() nor strip() removes spaces from the middle of a string. To remove all spaces, use replace(" ", "") or replaceAll("\\s+", "").
9 — replace() and replaceAll()
replace(old, new) replaces every occurrence of a character or literal substring. replaceAll(regex, replacement) replaces every match of a regular expression. Both return a new string with all replacements applied.
1// File: ReplaceDemo.java
2
3public class ReplaceDemo {
4
5 public static void main(String[] args) {
6
7 String text = "I love Java. Java is great. I use Java every day.";
8
9 // replace() — literal string replacement (all occurrences)
10 System.out.println("Original : " + text);
11 System.out.println("Replaced : " + text.replace("Java", "Python"));
12
13 System.out.println();
14
15 // replace() — single character replacement
16 String phone = "98765-43210";
17 String cleaned = phone.replace("-", "");
18 System.out.println("Phone : " + phone);
19 System.out.println("Cleaned : " + cleaned);
20
21 System.out.println();
22
23 // replaceAll() — uses regular expressions
24 String messy = " Too many spaces ";
25 String neat = messy.trim().replaceAll("\\s+", " "); // one or more spaces → single space
26 System.out.println("Messy : '" + messy + "'");
27 System.out.println("Neat : '" + neat + "'");
28
29 System.out.println();
30
31 // replaceAll() — remove all non-digit characters
32 String raw = "Phone: (98765) 43-210";
33 String digits = raw.replaceAll("[^0-9]", ""); // remove everything except digits
34 System.out.println("Raw : " + raw);
35 System.out.println("Digits : " + digits);
36
37 System.out.println();
38
39 // replaceAll() — mask middle digits of card number
40 String cardNumber = "4111111111114521";
41 String masked = cardNumber.replaceAll("(\\d{4})(\\d{8})(\\d{4})", "$1 **** **** $3");
42 System.out.println("Card : " + cardNumber);
43 System.out.println("Masked : " + masked);
44
45 System.out.println();
46
47 // replaceFirst() — only the first match
48 String csv = "name,age,city,name,email";
49 System.out.println("replaceFirst: " + csv.replaceFirst("name", "REPLACED"));
50 }
51}Output:
Original : I love Java. Java is great. I use Java every day.
Replaced : I love Python. Python is great. I use Python every day.
Phone : 98765-43210
Cleaned : 9876543210
Messy : ' Too many spaces '
Neat : 'Too many spaces'
Raw : Phone: (98765) 43-210
Digits : 9876543210
Card : 4111111111114521
Masked : 4111 **** **** 4521
replaceFirst: REPLACED,age,city,name,email
replace() with a String argument replaces literal text. replaceAll() interprets the first argument as a regex — special characters like ., *, +, ?, (, ) must be escaped with \\ if you want them treated literally.
10 — split()
Splits a string at every match of a regular expression and returns a String[]. The delimiter itself is not included in the result.
1// File: SplitDemo.java
2
3import java.util.Arrays;
4
5public class SplitDemo {
6
7 public static void main(String[] args) {
8
9 // Basic split — by comma
10 String csv = "Priya,28,Bengaluru,Software Engineer";
11 String[] fields = csv.split(",");
12
13 System.out.println("CSV : " + csv);
14 System.out.println("Parts : " + Arrays.toString(fields));
15 System.out.println("Name : " + fields[0]);
16 System.out.println("City : " + fields[2]);
17
18 System.out.println();
19
20 // Split by whitespace
21 String sentence = "The quick brown fox";
22 String[] words = sentence.split("\\s+"); // one or more spaces
23 System.out.println("Words : " + Arrays.toString(words));
24
25 System.out.println();
26
27 // Split with limit — maximum number of pieces
28 String path = "home/user/documents/report.pdf";
29 String[] parts = path.split("/", 2); // split into at most 2 parts
30 System.out.println("Full : " + Arrays.toString(path.split("/")));
31 System.out.println("Limited : " + Arrays.toString(parts)); // [home, user/documents/report.pdf]
32
33 System.out.println();
34
35 // Split on literal dot — must escape it!
36 String domain = "mail.google.com";
37 String[] dotSplit = domain.split("\\."); // escape dot — means literal dot
38 System.out.println("Domain : " + domain);
39 System.out.println("Parts : " + Arrays.toString(dotSplit)); // [mail, google, com]
40
41 System.out.println();
42
43 // Split on pipe character — must escape it!
44 String record = "ORD-001|Priya|1299.50|PLACED";
45 String[] cols = record.split("\\|"); // escape pipe — it means OR in regex
46 System.out.println("Record : " + record);
47 System.out.println("Columns : " + Arrays.toString(cols));
48
49 System.out.println();
50
51 // Handling empty trailing fields
52 String trailing = "A,B,,C,";
53 System.out.println("Normal split : " + Arrays.toString(trailing.split(",")));
54 System.out.println("With -1 limit: " + Arrays.toString(trailing.split(",", -1)));
55 }
56}Output:
CSV : Priya,28,Bengaluru,Software Engineer
Parts : [Priya, 28, Bengaluru, Software Engineer]
Name : Priya
City : Bengaluru
Words : [The, quick, brown, fox]
Full : [home, user, documents, report.pdf]
Limited : [home, user/documents/report.pdf]
Domain : mail.google.com
Parts : [mail, google, com]
Record : ORD-001|Priya|1299.50|PLACED
Columns : [ORD-001, Priya, 1299.50, PLACED]
Normal split : [A, B, , C]
With -1 limit: [A, B, , C, ]
Common traps with split(): . means "any character" in regex — use "\\." for literal dot. | means OR — use "\\|" for literal pipe. By default, trailing empty strings are discarded — use split(delimiter, -1) to preserve them.
11 — String.join()
String.join(separator, parts...) joins multiple strings or an array/list with a separator between each element. This is cleaner than building the joined string manually in a loop.
1// File: JoinDemo.java
2
3import java.util.List;
4
5public class JoinDemo {
6
7 public static void main(String[] args) {
8
9 // join with individual strings
10 String path = String.join("/", "home", "user", "documents");
11 System.out.println("Path : " + path); // home/user/documents
12
13 // join with an array
14 String[] skills = {"Java", "Spring Boot", "SQL", "Git"};
15 String skillList = String.join(", ", skills);
16 System.out.println("Skills : " + skillList); // Java, Spring Boot, SQL, Git
17
18 // join with a List
19 List<String> cities = List.of("Mumbai", "Delhi", "Bengaluru", "Pune");
20 String cityStr = String.join(" | ", cities);
21 System.out.println("Cities : " + cityStr); // Mumbai | Delhi | Bengaluru | Pune
22
23 System.out.println();
24
25 // Practical use — build a CSV row from fields
26 String[] employee = {"EMP-042", "Priya Sharma", "Engineering", "85000"};
27 String csvRow = String.join(",", employee);
28 System.out.println("CSV row : " + csvRow);
29
30 System.out.println();
31
32 // Build a SQL IN clause
33 String[] ids = {"101", "205", "330", "412"};
34 String inClause = "WHERE id IN (" + String.join(", ", ids) + ")";
35 System.out.println("SQL : " + inClause);
36
37 System.out.println();
38
39 // Build a display breadcrumb
40 String[] breadcrumb = {"Home", "Electronics", "Mobile Phones", "Samsung"};
41 System.out.println("Nav : " + String.join(" > ", breadcrumb));
42 }
43}Output:
Path : home/user/documents
Skills : Java, Spring Boot, SQL, Git
Cities : Mumbai | Delhi | Bengaluru | Pune
CSV row : EMP-042,Priya Sharma,Engineering,85000
SQL : WHERE id IN (101, 205, 330, 412)
Nav : Home > Electronics > Mobile Phones > Samsung
12 — String.valueOf() and String.format()
String.valueOf(x) converts any type — int, double, boolean, char, object — to its String representation. It handles null safely, returning "null".
String.format(template, args) builds a formatted string using placeholders like %s (string), %d (integer), %f (decimal), %n (newline).
1// File: ValueOfFormatDemo.java
2
3public class ValueOfFormatDemo {
4
5 public static void main(String[] args) {
6
7 // valueOf() — convert any type to String
8 int count = 42;
9 double price = 1299.99;
10 boolean active = true;
11 char grade = 'A';
12 Object nullObj = null;
13
14 System.out.println("valueOf(int) : " + String.valueOf(count));
15 System.out.println("valueOf(double) : " + String.valueOf(price));
16 System.out.println("valueOf(boolean): " + String.valueOf(active));
17 System.out.println("valueOf(char) : " + String.valueOf(grade));
18 System.out.println("valueOf(null) : " + String.valueOf(nullObj)); // "null" — no NPE
19
20 System.out.println();
21
22 // String.format() — structured formatted output
23 String name = "Rohan Mehta";
24 String role = "Developer";
25 double salary = 75000.50;
26 int years = 3;
27
28 // %s = String, %d = int, %.2f = double with 2 decimals
29 String profile = String.format(
30 "Name: %s | Role: %s | Salary: Rs.%.2f | Experience: %d yr(s)",
31 name, role, salary, years);
32 System.out.println(profile);
33
34 System.out.println();
35
36 // Padding and alignment with format()
37 System.out.println("Formatted table:");
38 System.out.println(String.format("%-15s %10s %10s", "Product", "Price", "Stock"));
39 System.out.println("-".repeat(37));
40
41 String[][] products = {
42 {"Laptop", "45999.00", "12"},
43 {"Mouse", "599.00", "150"},
44 {"Keyboard", "1299.00", "80"},
45 {"Monitor", "18500.00", "25"},
46 };
47
48 for (String[] p : products) {
49 System.out.println(String.format("%-15s %10s %10s", p[0], p[1], p[2]));
50 }
51
52 System.out.println();
53
54 // Format numbers with commas (Indian currency format)
55 double totalSales = 1234567.89;
56 System.out.println(String.format("Total Sales: Rs.%,.2f", totalSales));
57
58 // Pad with leading zeros (e.g. order numbers)
59 int orderId = 42;
60 System.out.println("Order ID: " + String.format("ORD-%05d", orderId)); // ORD-00042
61 }
62}Output:
valueOf(int) : 42
valueOf(double) : 1299.99
valueOf(boolean): true
valueOf(char) : A
valueOf(null) : null
Name: Rohan Mehta | Role: Developer | Salary: Rs.75000.50 | Experience: 3 yr(s)
Formatted table:
Product Price Stock
-------------------------------------
Laptop 45999.00 12
Mouse 599.00 150
Keyboard 1299.00 80
Monitor 18500.00 25
Total Sales: Rs.1,234,567.89
Order ID: ORD-00042
13 — isEmpty() and isBlank()
isEmpty() — true only when length() is 0. A string of spaces has length > 0 so it is not empty.
isBlank() (Java 11+) — true when the string is empty OR contains only whitespace. Better for user input validation.
1// File: IsEmptyBlankDemo.java
2
3public class IsEmptyBlankDemo {
4
5 public static void main(String[] args) {
6
7 String empty = "";
8 String spaces = " ";
9 String tab = "\t";
10 String text = "hello";
11 String nullSafe = null;
12
13 System.out.println("isEmpty() results:");
14 System.out.println(" '' isEmpty: " + empty.isEmpty()); // true
15 System.out.println(" ' ' isEmpty: " + spaces.isEmpty()); // false
16 System.out.println(" 'hello' isEmpty: " + text.isEmpty()); // false
17
18 System.out.println();
19
20 System.out.println("isBlank() results:");
21 System.out.println(" '' isBlank: " + empty.isBlank()); // true
22 System.out.println(" ' ' isBlank: " + spaces.isBlank()); // true
23 System.out.println(" '\\t' isBlank: " + tab.isBlank()); // true
24 System.out.println(" 'hello' isBlank: " + text.isBlank()); // false
25
26 System.out.println();
27
28 // Practical use — validate user input before processing
29 String[] inputs = {"Priya Sharma", "", " ", null, " R "};
30 System.out.println("Input validation:");
31 for (String input : inputs) {
32 if (input == null || input.isBlank()) {
33 System.out.println(" '" + input + "' → INVALID: empty or blank");
34 } else {
35 System.out.println(" '" + input.strip() + "' → VALID");
36 }
37 }
38 }
39}Output:
isEmpty() results:
'' isEmpty: true
' ' isEmpty: false
'hello' isEmpty: false
isBlank() results:
'' isBlank: true
' ' isBlank: true
'\t' isBlank: true
'hello' isBlank: false
Input validation:
'Priya Sharma' → VALID
'' → INVALID: empty or blank
' ' → INVALID: empty or blank
'null' → INVALID: empty or blank
'R' → VALID
14 — toCharArray()
Converts the String into a char[]. Useful for character-level operations: sorting characters, frequency counting, manual parsing, or when you need to modify characters (remember, String is immutable — you cannot modify a String's characters in place, but you can modify a char[]).
1// File: ToCharArrayDemo.java
2
3import java.util.Arrays;
4
5public class ToCharArrayDemo {
6
7 public static void main(String[] args) {
8
9 String word = "DevStackFlow";
10
11 // Convert to char array
12 char[] chars = word.toCharArray();
13 System.out.println("String : " + word);
14 System.out.println("charArray: " + Arrays.toString(chars));
15 System.out.println("Length : " + chars.length);
16
17 System.out.println();
18
19 // Sort characters alphabetically
20 char[] sorted = word.toLowerCase().toCharArray();
21 Arrays.sort(sorted);
22 System.out.println("Sorted chars: " + new String(sorted));
23
24 System.out.println();
25
26 // Count character frequency
27 String text = "programming";
28 char[] letters = text.toCharArray();
29 int[] freq = new int[26]; // a-z
30
31 for (char c : letters) {
32 freq[c - 'a']++;
33 }
34
35 System.out.println("Character frequencies in '" + text + "':");
36 for (int i = 0; i < 26; i++) {
37 if (freq[i] > 0) {
38 System.out.println(" '" + (char)('a' + i) + "' : " + freq[i]);
39 }
40 }
41
42 System.out.println();
43
44 // Reverse a string using char array
45 String original = "Namaste";
46 char[] arr = original.toCharArray();
47
48 for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
49 char temp = arr[i];
50 arr[i] = arr[j];
51 arr[j] = temp;
52 }
53 System.out.println("Reversed: " + new String(arr));
54 }
55}Output:
String : DevStackFlow
charArray: [D, e, v, S, t, a, c, k, F, l, o, w]
Length : 12
Sorted chars: acdefklovstw
Character frequencies in 'programming':
'a' : 1
'g' : 2
'i' : 1
'm' : 2
'n' : 1
'o' : 1
'p' : 1
'r' : 2
Reversed: etsamaN
Real-World Example — Complete Profile Processing Pipeline
The Business Problem
A user profile management system at a company like Meesho or Flipkart receives raw profile data from multiple sources — mobile apps, web forms, import files. The data is inconsistent: mixed case, extra spaces, partially formatted phone numbers, varied email formats. The pipeline below uses string methods at every step to clean, validate, and format the data into a consistent structure before saving it.
1// File: ProfileData.java
2
3public class ProfileData {
4 public String rawName;
5 public String rawEmail;
6 public String rawPhone;
7 public String rawCity;
8
9 public ProfileData(String name, String email, String phone, String city) {
10 this.rawName = name;
11 this.rawEmail = email;
12 this.rawPhone = phone;
13 this.rawCity = city;
14 }
15}1// File: ProfileProcessor.java
2
3public class ProfileProcessor {
4
5 // Formats name — trim, title case, validate
6 public static String processName(String raw) {
7 if (raw == null || raw.isBlank()) return null;
8
9 String[] words = raw.trim().toLowerCase().split("\\s+");
10 StringBuilder result = new StringBuilder();
11
12 for (String word : words) {
13 if (!word.isEmpty()) {
14 result.append(Character.toUpperCase(word.charAt(0)));
15 result.append(word.substring(1));
16 result.append(" ");
17 }
18 }
19 return result.toString().trim();
20 }
21
22 // Normalises email — trim, lowercase, validate format
23 public static String processEmail(String raw) {
24 if (raw == null || raw.isBlank()) return null;
25
26 String email = raw.trim().toLowerCase();
27
28 if (!email.contains("@")) return null;
29
30 int atIdx = email.indexOf('@');
31 if (atIdx == 0) return null; // nothing before @
32
33 String domain = email.substring(atIdx + 1);
34 if (!domain.contains(".") || domain.startsWith(".")) return null;
35
36 return email;
37 }
38
39 // Normalises phone — strip non-digits, validate 10 digits
40 public static String processPhone(String raw) {
41 if (raw == null || raw.isBlank()) return null;
42
43 // Remove spaces, dashes, parentheses, country code prefix
44 String digits = raw.replaceAll("[^0-9]", "");
45
46 // Remove leading 91 if Indian country code is included
47 if (digits.length() == 12 && digits.startsWith("91")) {
48 digits = digits.substring(2);
49 }
50
51 if (digits.length() != 10) return null;
52
53 // Format as XXXXX-XXXXX
54 return digits.substring(0, 5) + "-" + digits.substring(5);
55 }
56
57 // Normalises city — trim, title case
58 public static String processCity(String raw) {
59 if (raw == null || raw.isBlank()) return null;
60 return processName(raw); // same title-case logic
61 }
62
63 // Builds a display summary from processed data
64 public static String buildSummary(String name, String email,
65 String phone, String city) {
66 StringBuilder sb = new StringBuilder();
67 sb.append(String.format("%-10s : %s%n", "Name", name != null ? name : "MISSING"));
68 sb.append(String.format("%-10s : %s%n", "Email", email != null ? email : "MISSING"));
69 sb.append(String.format("%-10s : %s%n", "Phone", phone != null ? phone : "MISSING"));
70 sb.append(String.format("%-10s : %s%n", "City", city != null ? city : "MISSING"));
71 return sb.toString();
72 }
73}1// File: ProfilePipelineDemo.java
2
3public class ProfilePipelineDemo {
4
5 public static void main(String[] args) {
6
7 ProfileData[] profiles = {
8 new ProfileData(" priya SHARMA ", "PRIYA@MEESHO.COM ", "98765 43210", " bengaluru "),
9 new ProfileData("rohan mehta", "rohan@flipkart.in", "+91-9876543210", "Mumbai"),
10 new ProfileData("SNEHA RAO", "sneha.rao", "9123456789", "CHENNAI"),
11 new ProfileData("", "karan@gmail.com", "12345", "Delhi"),
12 };
13
14 System.out.println("╔══════════════════════════════════════════╗");
15 System.out.println("║ PROFILE PROCESSING PIPELINE ║");
16 System.out.println("╚══════════════════════════════════════════╝\n");
17
18 for (int i = 0; i < profiles.length; i++) {
19 ProfileData raw = profiles[i];
20
21 System.out.println("── Profile " + (i + 1) + " ──────────────────────────────");
22 System.out.println("RAW INPUT:");
23 System.out.println(" name : '" + raw.rawName + "'");
24 System.out.println(" email : '" + raw.rawEmail + "'");
25 System.out.println(" phone : '" + raw.rawPhone + "'");
26 System.out.println(" city : '" + raw.rawCity + "'");
27
28 String name = ProfileProcessor.processName(raw.rawName);
29 String email = ProfileProcessor.processEmail(raw.rawEmail);
30 String phone = ProfileProcessor.processPhone(raw.rawPhone);
31 String city = ProfileProcessor.processCity(raw.rawCity);
32
33 System.out.println("\nPROCESSED:");
34 System.out.print(ProfileProcessor.buildSummary(name, email, phone, city));
35 System.out.println();
36 }
37 }
38}Output:
╔══════════════════════════════════════════╗
║ PROFILE PROCESSING PIPELINE ║
╚══════════════════════════════════════════╝
── Profile 1 ──────────────────────────────
RAW INPUT:
name : ' priya SHARMA '
email : 'PRIYA@MEESHO.COM '
phone : '98765 43210'
city : ' bengaluru '
PROCESSED:
Name : Priya Sharma
Email : priya@meesho.com
Phone : 98765-43210
City : Bengaluru
── Profile 2 ──────────────────────────────
RAW INPUT:
name : 'rohan mehta'
email : 'rohan@flipkart.in'
phone : '+91-9876543210'
city : 'Mumbai'
PROCESSED:
Name : Rohan Mehta
Email : rohan@flipkart.in
Phone : 98765-43210
City : Mumbai
── Profile 3 ──────────────────────────────
RAW INPUT:
name : 'SNEHA RAO'
email : 'sneha.rao'
phone : '9123456789'
city : 'CHENNAI'
PROCESSED:
Name : Sneha Rao
Email : MISSING
Phone : 91234-56789
City : Chennai
── Profile 4 ──────────────────────────────
RAW INPUT:
name : ''
email : 'karan@gmail.com'
phone : '12345'
city : 'Delhi'
PROCESSED:
Name : MISSING
Email : karan@gmail.com
Phone : MISSING
City : Delhi
All 14 methods appear across the pipeline: isBlank, trim, strip, toLowerCase, toUpperCase, split, charAt, substring, contains, indexOf, startsWith, replaceAll, format, toCharArray.
Best Practices
Always check for null before calling any String method. A null String reference throws NullPointerException on any method call. The safe pattern: if (input != null && !input.isBlank()). For comparison, put the known non-null constant on the left: "expected".equals(input).
Prefer isBlank() over isEmpty() for user input validation. A user typing only spaces has not provided a value. isEmpty() misses this. isBlank() correctly rejects whitespace-only strings. This distinction prevents silent bugs in form validation logic.
Use String.format() for multi-value messages. Building a message with several variables using + produces code that is hard to read as the number of parts grows. String.format("Rs.%.2f for order %s", amount, id) is readable, maintainable, and auto-formats numbers.
Escape regex special characters in split() and replaceAll(). Common characters that must be escaped: . (dot), | (pipe), *, +, ?, (, ), [, ]. Use "\\." for a literal dot, "\\|" for a literal pipe. Forgetting this is the most common mistake with both methods.
Common Mistakes
Mistake 1 — Ignoring the Return Value
1String input = " hello ";
2input.trim(); // result discarded — input unchanged
3System.out.println(input); // " hello " — still padded
4
5// Correct
6input = input.trim();
7System.out.println(input); // "hello"Mistake 2 — Using split(".") to Split by Dot
1String version = "1.8.0.302";
2String[] parts = version.split("."); // . means any character in regex
3System.out.println(parts.length); // 0 — every char is a delimiter, nothing left
4
5// Correct — escape the dot
6String[] correct = version.split("\\.");
7System.out.println(correct.length); // 4 → [1, 8, 0, 302]Mistake 3 — Comparing Strings With ==
1String a = new String("hello");
2String b = new String("hello");
3
4System.out.println(a == b); // false — different objects in memory
5System.out.println(a.equals(b)); // true — same contentMistake 4 — Calling substring(0, 0) Expecting Something Useful
1String name = "Priya";
2System.out.println(name.substring(0, 0)); // "" — empty string, start == end
3System.out.println(name.substring(0, 1)); // "P" — just the first charactersubstring(start, end) where start == end returns an empty string, not a single character. To get the first character as a String: name.substring(0, 1) or String.valueOf(name.charAt(0)).
Interview Questions
Q1. What is the difference between str.replace() and str.replaceAll() in Java?
replace(old, new) replaces all occurrences of a literal character or literal string. It does not interpret the first argument as a regular expression. replaceAll(regex, replacement) interprets the first argument as a regular expression and replaces every match. Use replace() for straightforward text substitution. Use replaceAll() when you need pattern matching — removing all digits, collapsing multiple spaces, or extracting specific formats. Because replaceAll() compiles the regex each call, replace() is slightly faster for literal substitution.
Q2. What does split(".") return when called on a String?
An empty array — not the parts separated by dots. The . in regex means "match any single character". So every character in the string is treated as a delimiter, leaving no content between delimiters. To split on a literal dot, escape it: split("\\."). This is one of the most common beginner traps and appears frequently in interview screening tests.
Q3. What is the difference between trim() and strip() in Java?
Both remove leading and trailing whitespace, but they differ in which characters they consider whitespace. trim() removes characters with ASCII value ≤ 32 — the standard ASCII whitespace. strip() (Java 11+) removes Unicode whitespace — it recognises non-breaking spaces, ideographic spaces, and other Unicode whitespace characters that trim() would leave behind. For modern Java, strip() is the preferred choice. stripLeading() and stripTrailing() are also available for one-sided trimming.
Q4. What is the difference between isEmpty() and isBlank()?
isEmpty() returns true only when length() is 0 — a string with just spaces like " " is not empty. isBlank() (Java 11+) returns true when the string is either empty or contains only whitespace characters. For validating user input, isBlank() is almost always the correct choice — a user who types only spaces has not provided a value, and isEmpty() would incorrectly accept it.
Q5. How does String.format() work and what are the main format specifiers?
String.format(template, args...) builds a formatted string by replacing placeholders in the template with the provided arguments. The main specifiers: %s for any object (calls toString()), %d for integers, %f for floating-point (use %.2f for 2 decimal places), %c for a single character, %b for boolean, %n for a newline, and %, for thousand separators. Width and alignment are controlled by numbers — %-20s left-aligns in a 20-character field, %10d right-aligns an integer in 10 characters.
Q6. What does indexOf() return when the substring is not found, and why does this matter?
indexOf() returns -1 when the target substring is not present. The return value of -1 matters because it is a common source of bugs: if you pass -1 directly to substring() — for example, str.substring(0, str.indexOf("@")) when there is no @ — you get StringIndexOutOfBoundsException. Always check if indexOf returned -1 before using the result: int idx = str.indexOf("@"); if (idx != -1) { ... }.
FAQs
Are String methods case-sensitive by default?
Yes. contains(), startsWith(), endsWith(), equals(), indexOf(), and replace() are all case-sensitive. "Hello".contains("hello") returns false. Use toLowerCase() on both sides before comparing, or use the IgnoreCase variants where they exist: equalsIgnoreCase(), compareToIgnoreCase(), regionMatches() with ignoreCase=true.
Can String methods be chained?
Yes. Since every String method returns a new String, you can chain calls directly: input.trim().toLowerCase().replace(",", "").split(" "). Each method is called on the result of the previous one. Chaining is readable for two or three operations. For longer chains, assigning intermediate results to named variables improves readability and makes debugging easier.
What is the difference between compareTo() and equals()?
equals() returns a boolean — just true or false, same content or not. compareTo() returns an integer — zero means equal, negative means the first string comes before the second lexicographically (dictionary order), positive means the first comes after. compareTo() is used for sorting strings. equals() is used for equality checks. compareToIgnoreCase() is the case-insensitive version.
Why does substring() use exclusive end index?
The exclusive end index is a convention used throughout Java's standard library — Arrays.copyOfRange, List.subList, String.substring all use (from, to) where from is inclusive and to is exclusive. This makes it easy to compute the length: the result always has to - from elements. It also makes adjacent slices simple — substring(0, 5) and substring(5, 10) together cover positions 0-9 with no overlap and no gap.
Does replace() modify the original string?
No. String is immutable. replace() returns a new String with the replacements applied — the original string is unchanged. If you write str.replace("a", "b") without capturing the result, nothing changes. Always assign the return value: str = str.replace("a", "b") or String newStr = str.replace("a", "b").
Summary
The twenty String methods covered here handle the vast majority of text processing needs in real Java development. The most critical to master: trim() and strip() for cleaning input, equals() and equalsIgnoreCase() for comparison, contains() / startsWith() / endsWith() for presence checks, indexOf() and substring() for extraction, replace() and replaceAll() for substitution, split() for parsing, and String.format() for structured output.
The one rule that ties all of them together: String is immutable. Every method returns a new String. Always capture the result.
What to Read Next
| Topic | Link |
|---|---|
| How StringBuilder works for efficient mutable string building | Java StringBuilder and StringBuffer → |
| How String comparison works with equals and hashCode in collections | Java String Class → |
| How split and replaceAll use regular expressions internally | Java Arrays Class Methods → |
| How String immutability connects to the String pool in JVM memory | Java Immutable Class → |
| How format specifiers work in Java 21 text blocks and records | Java Modern Java (8–21) → |