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.
// File: LengthDemo.java
public class LengthDemo {
public static void main(String[] args) {
String name = "Priya Sharma";
String empty = "";
String spaces = " ";
String special = "Hello, World! 😊";
System.out.println("'" + name + "' length: " + name.length()); // 12
System.out.println("'' length : " + empty.length()); // 0
System.out.println("' ' length : " + spaces.length()); // 3
System.out.println("With emoji length : " + special.length()); // 16 — emoji = 2 code units
// Practical use — validate username length
String username = "rohan_dev";
if (username.length() < 4 || username.length() > 20) {
System.out.println("Username must be 4-20 characters.");
} else {
System.out.println("Username '" + username + "' is valid (" + username.length() + " chars).");
}
// Last character using length()
String path = "/home/user/documents";
System.out.println("Last char: " + path.charAt(path.length() - 1)); // 's'
}
}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().
// File: CharAtDemo.java
public class CharAtDemo {
public static void main(String[] args) {
String word = "DevStackFlow";
// Access individual characters
System.out.println("charAt(0) : " + word.charAt(0)); // D
System.out.println("charAt(3) : " + word.charAt(3)); // S
System.out.println("charAt(11) : " + word.charAt(11)); // w (last char)
System.out.println();
// Count vowels using charAt()
String sentence = "Welcome to India";
int vowelCount = 0;
String vowels = "aeiouAEIOU";
for (int i = 0; i < sentence.length(); i++) {
if (vowels.indexOf(sentence.charAt(i)) != -1) {
vowelCount++;
}
}
System.out.println("Sentence : " + sentence);
System.out.println("Vowels : " + vowelCount);
System.out.println();
// Check if a string is a palindrome using charAt()
String test = "racecar";
boolean isPalindrome = true;
for (int i = 0; i < test.length() / 2; i++) {
if (test.charAt(i) != test.charAt(test.length() - 1 - i)) {
isPalindrome = false;
break;
}
}
System.out.println("'" + test + "' is palindrome: " + isPalindrome);
// Out-of-bounds guard
try {
System.out.println(word.charAt(50));
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
}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.
// File: IndexOfDemo.java
public class IndexOfDemo {
public static void main(String[] args) {
String text = "Java is great. Java is powerful. Java is fun.";
// indexOf — first occurrence
System.out.println("First 'Java' at: " + text.indexOf("Java")); // 0
System.out.println("First '.' at: " + text.indexOf('.')); // 14
System.out.println("'Python' at : " + text.indexOf("Python")); // -1 (not found)
// indexOf with fromIndex — start searching from a position
System.out.println("'Java' from index 5: " + text.indexOf("Java", 5)); // 15
// lastIndexOf — last occurrence
System.out.println("Last 'Java' at: " + text.lastIndexOf("Java")); // 33
System.out.println("Last '.' at: " + text.lastIndexOf('.')); // 44
System.out.println();
// Practical use 1 — extract file extension
String filename = "profile_photo.jpeg";
int dotPos = filename.lastIndexOf('.');
String name = filename.substring(0, dotPos);
String ext = filename.substring(dotPos + 1);
System.out.println("Filename : " + filename);
System.out.println("Name : " + name); // profile_photo
System.out.println("Extension : " + ext); // jpeg
System.out.println();
// Practical use 2 — extract domain from email
String email = "rohan.mehta@razorpay.com";
int atPos = email.indexOf('@');
String username = email.substring(0, atPos);
String domain = email.substring(atPos + 1);
System.out.println("Email : " + email);
System.out.println("Username : " + username); // rohan.mehta
System.out.println("Domain : " + domain); // razorpay.com
System.out.println();
// Count total occurrences of a substring
String source = "banana";
String target = "an";
int count = 0;
int pos = source.indexOf(target);
while (pos != -1) {
count++;
pos = source.indexOf(target, pos + 1);
}
System.out.println("'" + target + "' found " + count + " times in '" + source + "'");
}
}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.
// File: SubstringDemo.java
public class SubstringDemo {
public static void main(String[] args) {
String fullText = "Order ID: ORD-2024-9921 | Status: PLACED";
// substring(start) — from position to end
System.out.println("From index 10 : " + fullText.substring(10)); // ORD-2024-9921 | Status: PLACED
// substring(start, end) — from start (inclusive) to end (exclusive)
System.out.println("Indices 10-23 : " + fullText.substring(10, 23)); // ORD-2024-9921
System.out.println();
// Practical use — extract structured parts
String record = "EMP-042|Priya Sharma|Engineering|85000";
String[] fields = record.split("\\|");
System.out.println("Employee ID : " + fields[0]); // EMP-042
System.out.println("Name : " + fields[1]); // Priya Sharma
System.out.println("Department : " + fields[2]); // Engineering
System.out.println("Salary : " + fields[3]); // 85000
System.out.println();
// Extract first name and last name
String name = "Ananya Krishnan";
int spaceIndex = name.indexOf(' ');
String firstName = name.substring(0, spaceIndex);
String lastName = name.substring(spaceIndex + 1);
System.out.println("First : " + firstName); // Ananya
System.out.println("Last : " + lastName); // Krishnan
System.out.println();
// Truncate a long string for display — show first N chars + "..."
String description = "This wireless keyboard comes with a long-lasting battery and ergonomic design.";
int maxLength = 40;
String truncated = description.length() > maxLength
? description.substring(0, maxLength) + "..."
: description;
System.out.println("Truncated : " + truncated);
}
}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.
// File: ContainsStartsEndsDemo.java
public class ContainsStartsEndsDemo {
public static void main(String[] args) {
String productCode = "ELEC-PHONE-SAMSUNG-S24";
String url = "https://www.meesho.com/product/12345";
String filename = "invoice_2024_01_15.pdf";
// contains() — substring anywhere in the string
System.out.println("Product code checks:");
System.out.println(" contains 'PHONE' : " + productCode.contains("PHONE")); // true
System.out.println(" contains 'LAPTOP' : " + productCode.contains("LAPTOP")); // false
System.out.println();
// startsWith() — beginning of string
System.out.println("URL checks:");
System.out.println(" startsWith 'https': " + url.startsWith("https")); // true
System.out.println(" startsWith 'http' : " + url.startsWith("http")); // true
System.out.println(" startsWith 'ftp' : " + url.startsWith("ftp")); // false
// startsWith with offset — check from a specific position
System.out.println(" 'meesho' at pos 12: " + url.startsWith("meesho", 12)); // true
System.out.println();
// endsWith() — end of string
System.out.println("Filename checks:");
System.out.println(" endsWith '.pdf' : " + filename.endsWith(".pdf")); // true
System.out.println(" endsWith '.xlsx' : " + filename.endsWith(".xlsx")); // false
System.out.println();
// Practical use — file type routing
String[] files = {
"report.pdf", "data.xlsx", "photo.jpg",
"config.json", "app.java"
};
System.out.println("File routing:");
for (String file : files) {
String type;
if (file.endsWith(".pdf")) type = "Document";
else if (file.endsWith(".xlsx")) type = "Spreadsheet";
else if (file.endsWith(".jpg") || file.endsWith(".png")) type = "Image";
else if (file.endsWith(".json")) type = "Config";
else if (file.endsWith(".java")) type = "Source Code";
else type = "Unknown";
System.out.printf(" %-15s → %s%n", file, type);
}
}
}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.
// File: EqualsDemo.java
public class EqualsDemo {
public static void main(String[] args) {
String userInput = "Admin";
String storedRole = "admin";
// equals() — case-sensitive
System.out.println("equals() — case sensitive:");
System.out.println(" 'Admin'.equals('admin') : " + userInput.equals(storedRole)); // false
System.out.println(" 'Admin'.equals('Admin') : " + userInput.equals("Admin")); // true
System.out.println();
// equalsIgnoreCase() — case-insensitive
System.out.println("equalsIgnoreCase():");
System.out.println(" 'Admin' eq-ic 'admin' : " + userInput.equalsIgnoreCase(storedRole)); // true
System.out.println(" 'ADMIN' eq-ic 'admin' : " + "ADMIN".equalsIgnoreCase(storedRole)); // true
System.out.println();
// Safe pattern — known constant on left (no NPE if variable is null)
String input = null;
System.out.println("Null safety:");
System.out.println(" 'admin'.equals(null) : " + "admin".equals(input)); // false — no NPE
// input.equals("admin") would throw NullPointerException
System.out.println();
// Practical use — check user role from form input
String[] roles = {"ADMIN", "Manager", "viewer", "SUPER_ADMIN"};
for (String role : roles) {
if ("admin".equalsIgnoreCase(role)) {
System.out.println(role + " → Full access");
} else if ("manager".equalsIgnoreCase(role)) {
System.out.println(role + " → Reports access");
} else {
System.out.println(role + " → Read-only access");
}
}
}
}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.
// File: CaseConversionDemo.java
public class CaseConversionDemo {
public static void main(String[] args) {
String mixed = "Hello, DevStackFlow!";
String shout = "WHY IS EVERYONE SHOUTING?";
String input = " Mumbai ";
System.out.println("toUpperCase: " + mixed.toUpperCase());
System.out.println("toLowerCase: " + shout.toLowerCase());
System.out.println();
// Normalise before comparison — avoids case sensitivity bugs
String cityInput = " benGaLuRu ";
String citySaved = "BENGALURU";
boolean match = cityInput.trim().equalsIgnoreCase(citySaved);
System.out.println("City match (normalised): " + match); // true
System.out.println();
// Capitalise first letter of each word — title case
String raw = "wireless headphones premium edition";
String[] words = raw.split(" ");
StringBuilder sb = new StringBuilder();
for (String word : words) {
sb.append(Character.toUpperCase(word.charAt(0)));
sb.append(word.substring(1).toLowerCase());
sb.append(" ");
}
System.out.println("Raw : " + raw);
System.out.println("Title case: " + sb.toString().trim());
System.out.println();
// Normalise product codes before saving to database
String[] rawCodes = {"elec-001", "CLOTH-042", "Grocery_101"};
System.out.println("Normalised product codes:");
for (String code : rawCodes) {
System.out.println(" " + code + " → " + code.toUpperCase().replace("-", "_"));
}
}
}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.
// File: TrimStripDemo.java
public class TrimStripDemo {
public static void main(String[] args) {
String padded = " Hello, World! ";
String tabbed = "\t Rohan Mehta \t";
String inner = "Hello World"; // inner spaces NOT removed
System.out.println("Original : '" + padded + "'");
System.out.println("trim() : '" + padded.trim() + "'");
System.out.println("strip() : '" + padded.strip() + "'");
System.out.println();
System.out.println("With tabs : '" + tabbed + "'");
System.out.println("trim() : '" + tabbed.trim() + "'");
System.out.println();
System.out.println("Inner spaces : '" + inner + "'");
System.out.println("trim() : '" + inner.trim() + "'"); // inner unchanged
System.out.println();
// stripLeading() and stripTrailing() — Java 11+
String rightPadded = "Priya ";
String leftPadded = " Sneha";
System.out.println("stripLeading (' Sneha'): '" + leftPadded.stripLeading() + "'");
System.out.println("stripTrailing('Priya '): '" + rightPadded.stripTrailing() + "'");
System.out.println();
// Practical use — clean user input before processing
String[] inputs = {" rohan@meesho.com ", "\tpriya@gmail.com", "sneha@flipkart.com "};
System.out.println("Cleaned emails:");
for (String raw : inputs) {
System.out.println(" '" + raw + "' → '" + raw.strip() + "'");
}
}
}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.
// File: ReplaceDemo.java
public class ReplaceDemo {
public static void main(String[] args) {
String text = "I love Java. Java is great. I use Java every day.";
// replace() — literal string replacement (all occurrences)
System.out.println("Original : " + text);
System.out.println("Replaced : " + text.replace("Java", "Python"));
System.out.println();
// replace() — single character replacement
String phone = "98765-43210";
String cleaned = phone.replace("-", "");
System.out.println("Phone : " + phone);
System.out.println("Cleaned : " + cleaned);
System.out.println();
// replaceAll() — uses regular expressions
String messy = " Too many spaces ";
String neat = messy.trim().replaceAll("\\s+", " "); // one or more spaces → single space
System.out.println("Messy : '" + messy + "'");
System.out.println("Neat : '" + neat + "'");
System.out.println();
// replaceAll() — remove all non-digit characters
String raw = "Phone: (98765) 43-210";
String digits = raw.replaceAll("[^0-9]", ""); // remove everything except digits
System.out.println("Raw : " + raw);
System.out.println("Digits : " + digits);
System.out.println();
// replaceAll() — mask middle digits of card number
String cardNumber = "4111111111114521";
String masked = cardNumber.replaceAll("(\\d{4})(\\d{8})(\\d{4})", "$1 **** **** $3");
System.out.println("Card : " + cardNumber);
System.out.println("Masked : " + masked);
System.out.println();
// replaceFirst() — only the first match
String csv = "name,age,city,name,email";
System.out.println("replaceFirst: " + csv.replaceFirst("name", "REPLACED"));
}
}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.
// File: SplitDemo.java
import java.util.Arrays;
public class SplitDemo {
public static void main(String[] args) {
// Basic split — by comma
String csv = "Priya,28,Bengaluru,Software Engineer";
String[] fields = csv.split(",");
System.out.println("CSV : " + csv);
System.out.println("Parts : " + Arrays.toString(fields));
System.out.println("Name : " + fields[0]);
System.out.println("City : " + fields[2]);
System.out.println();
// Split by whitespace
String sentence = "The quick brown fox";
String[] words = sentence.split("\\s+"); // one or more spaces
System.out.println("Words : " + Arrays.toString(words));
System.out.println();
// Split with limit — maximum number of pieces
String path = "home/user/documents/report.pdf";
String[] parts = path.split("/", 2); // split into at most 2 parts
System.out.println("Full : " + Arrays.toString(path.split("/")));
System.out.println("Limited : " + Arrays.toString(parts)); // [home, user/documents/report.pdf]
System.out.println();
// Split on literal dot — must escape it!
String domain = "mail.google.com";
String[] dotSplit = domain.split("\\."); // escape dot — means literal dot
System.out.println("Domain : " + domain);
System.out.println("Parts : " + Arrays.toString(dotSplit)); // [mail, google, com]
System.out.println();
// Split on pipe character — must escape it!
String record = "ORD-001|Priya|1299.50|PLACED";
String[] cols = record.split("\\|"); // escape pipe — it means OR in regex
System.out.println("Record : " + record);
System.out.println("Columns : " + Arrays.toString(cols));
System.out.println();
// Handling empty trailing fields
String trailing = "A,B,,C,";
System.out.println("Normal split : " + Arrays.toString(trailing.split(",")));
System.out.println("With -1 limit: " + Arrays.toString(trailing.split(",", -1)));
}
}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.
// File: JoinDemo.java
import java.util.List;
public class JoinDemo {
public static void main(String[] args) {
// join with individual strings
String path = String.join("/", "home", "user", "documents");
System.out.println("Path : " + path); // home/user/documents
// join with an array
String[] skills = {"Java", "Spring Boot", "SQL", "Git"};
String skillList = String.join(", ", skills);
System.out.println("Skills : " + skillList); // Java, Spring Boot, SQL, Git
// join with a List
List<String> cities = List.of("Mumbai", "Delhi", "Bengaluru", "Pune");
String cityStr = String.join(" | ", cities);
System.out.println("Cities : " + cityStr); // Mumbai | Delhi | Bengaluru | Pune
System.out.println();
// Practical use — build a CSV row from fields
String[] employee = {"EMP-042", "Priya Sharma", "Engineering", "85000"};
String csvRow = String.join(",", employee);
System.out.println("CSV row : " + csvRow);
System.out.println();
// Build a SQL IN clause
String[] ids = {"101", "205", "330", "412"};
String inClause = "WHERE id IN (" + String.join(", ", ids) + ")";
System.out.println("SQL : " + inClause);
System.out.println();
// Build a display breadcrumb
String[] breadcrumb = {"Home", "Electronics", "Mobile Phones", "Samsung"};
System.out.println("Nav : " + String.join(" > ", breadcrumb));
}
}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).
// File: ValueOfFormatDemo.java
public class ValueOfFormatDemo {
public static void main(String[] args) {
// valueOf() — convert any type to String
int count = 42;
double price = 1299.99;
boolean active = true;
char grade = 'A';
Object nullObj = null;
System.out.println("valueOf(int) : " + String.valueOf(count));
System.out.println("valueOf(double) : " + String.valueOf(price));
System.out.println("valueOf(boolean): " + String.valueOf(active));
System.out.println("valueOf(char) : " + String.valueOf(grade));
System.out.println("valueOf(null) : " + String.valueOf(nullObj)); // "null" — no NPE
System.out.println();
// String.format() — structured formatted output
String name = "Rohan Mehta";
String role = "Developer";
double salary = 75000.50;
int years = 3;
// %s = String, %d = int, %.2f = double with 2 decimals
String profile = String.format(
"Name: %s | Role: %s | Salary: Rs.%.2f | Experience: %d yr(s)",
name, role, salary, years);
System.out.println(profile);
System.out.println();
// Padding and alignment with format()
System.out.println("Formatted table:");
System.out.println(String.format("%-15s %10s %10s", "Product", "Price", "Stock"));
System.out.println("-".repeat(37));
String[][] products = {
{"Laptop", "45999.00", "12"},
{"Mouse", "599.00", "150"},
{"Keyboard", "1299.00", "80"},
{"Monitor", "18500.00", "25"},
};
for (String[] p : products) {
System.out.println(String.format("%-15s %10s %10s", p[0], p[1], p[2]));
}
System.out.println();
// Format numbers with commas (Indian currency format)
double totalSales = 1234567.89;
System.out.println(String.format("Total Sales: Rs.%,.2f", totalSales));
// Pad with leading zeros (e.g. order numbers)
int orderId = 42;
System.out.println("Order ID: " + String.format("ORD-%05d", orderId)); // ORD-00042
}
}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.
// File: IsEmptyBlankDemo.java
public class IsEmptyBlankDemo {
public static void main(String[] args) {
String empty = "";
String spaces = " ";
String tab = "\t";
String text = "hello";
String nullSafe = null;
System.out.println("isEmpty() results:");
System.out.println(" '' isEmpty: " + empty.isEmpty()); // true
System.out.println(" ' ' isEmpty: " + spaces.isEmpty()); // false
System.out.println(" 'hello' isEmpty: " + text.isEmpty()); // false
System.out.println();
System.out.println("isBlank() results:");
System.out.println(" '' isBlank: " + empty.isBlank()); // true
System.out.println(" ' ' isBlank: " + spaces.isBlank()); // true
System.out.println(" '\\t' isBlank: " + tab.isBlank()); // true
System.out.println(" 'hello' isBlank: " + text.isBlank()); // false
System.out.println();
// Practical use — validate user input before processing
String[] inputs = {"Priya Sharma", "", " ", null, " R "};
System.out.println("Input validation:");
for (String input : inputs) {
if (input == null || input.isBlank()) {
System.out.println(" '" + input + "' → INVALID: empty or blank");
} else {
System.out.println(" '" + input.strip() + "' → VALID");
}
}
}
}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[]).
// File: ToCharArrayDemo.java
import java.util.Arrays;
public class ToCharArrayDemo {
public static void main(String[] args) {
String word = "DevStackFlow";
// Convert to char array
char[] chars = word.toCharArray();
System.out.println("String : " + word);
System.out.println("charArray: " + Arrays.toString(chars));
System.out.println("Length : " + chars.length);
System.out.println();
// Sort characters alphabetically
char[] sorted = word.toLowerCase().toCharArray();
Arrays.sort(sorted);
System.out.println("Sorted chars: " + new String(sorted));
System.out.println();
// Count character frequency
String text = "programming";
char[] letters = text.toCharArray();
int[] freq = new int[26]; // a-z
for (char c : letters) {
freq[c - 'a']++;
}
System.out.println("Character frequencies in '" + text + "':");
for (int i = 0; i < 26; i++) {
if (freq[i] > 0) {
System.out.println(" '" + (char)('a' + i) + "' : " + freq[i]);
}
}
System.out.println();
// Reverse a string using char array
String original = "Namaste";
char[] arr = original.toCharArray();
for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
System.out.println("Reversed: " + new String(arr));
}
}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
Basic Example
public class Main {
public static void main(String[] args) {
String raw = " Hello World ";
String trimmed = raw.trim();
System.out.println("Trimmed : '" + trimmed + "'");
System.out.println("Length : " + trimmed.length());
System.out.println("Upper : " + trimmed.toUpperCase());
System.out.println("Contains : " + trimmed.contains("World"));
System.out.println("Replaced : " + trimmed.replace("World", "Java"));
System.out.println("Words : " + trimmed.split(" ").length);
}
}Output
Trimmed : 'Hello World' Length : 11 Upper : HELLO WORLD Contains : true Replaced : Hello Java Words : 2
How it works:
- ›
trim()returns a newStringwith the leading and trailing spaces removed —rawitself is unchanged. - ›
length(),toUpperCase(),contains(), andreplace()are each called ontrimmed, and every one of them returns a fresh result without modifyingtrimmed. - ›
contains("World")scans the characters and returnstruebecause"World"appears inside"Hello World". - ›
split(" ")breaks the string into an array wherever a space appears, so.lengthreports2— one for"Hello"and one for"World".
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
String input = " hello ";
input.trim(); // result discarded — input unchanged
System.out.println(input); // " hello " — still padded
// Correct
input = input.trim();
System.out.println(input); // "hello"Mistake 2 — Using split(".") to Split by Dot
String version = "1.8.0.302";
String[] parts = version.split("."); // . means any character in regex
System.out.println(parts.length); // 0 — every char is a delimiter, nothing left
// Correct — escape the dot
String[] correct = version.split("\\.");
System.out.println(correct.length); // 4 → [1, 8, 0, 302]Mistake 3 — Comparing Strings With ==
String a = new String("hello");
String b = new String("hello");
System.out.println(a == b); // false — different objects in memory
System.out.println(a.equals(b)); // true — same contentMistake 4 — Calling substring(0, 0) Expecting Something Useful
String name = "Priya";
System.out.println(name.substring(0, 0)); // "" — empty string, start == end
System.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
Learn the right way to compare two strings.
Practice Programs
Put this topic into practice — each program has full code, output and a step-by-step explanation you can run online.
Converts every letter in a string to uppercase.
Determines whether one string appears inside another.
Replaces every occurrence of one character with another.
Counts how many non-overlapping times a substring appears in a string.
Removes every space character from a string.
Converts every letter in a string to lowercase.
Splits a string into a char array with toCharArray and shows the array is an independent copy.
Converts a sentence to title case, upper-casing each word's first letter and tidying extra spaces.
Removes every digit character from a string.
Collapses runs of spaces down to a single space and trims the ends.
Show all 16 practice programs ↓Show fewer ↑
Removes every special character from a string, keeping letters, digits, and spaces.
Finds the longest word in a sentence.
Finds the shortest word in a sentence.
Generates every contiguous substring of a string.
Finds the longest contiguous substring that reads the same forwards and backwards.
Sorts the characters of a string into alphabetical order.