Strings: Methods & Comparison
String methods and comparison techniques
1. Basic String Operations
Every Java developer should master these fundamental string operations for effective text processing.
Length and Character Access
Core String Properties
String text = "Java Programming";
// Get string length
int length = text.length(); // 16
// Access individual characters
char firstChar = text.charAt(0); // 'J'
char lastChar = text.charAt(length - 1); // 'g'
char spaceChar = text.charAt(4); // ' '
// Check for empty strings
String empty = "";
String whitespace = " ";
boolean isEmpty1 = empty.isEmpty(); // true
boolean isEmpty2 = text.isEmpty(); // false
boolean isBlank1 = whitespace.isBlank(); // true (Java 11+)
boolean isBlank2 = text.isBlank(); // false
Substring Operations
Extracting Substrings
String sentence = "Learn Java Programming";
// Extract from index to end
String fromIndex = sentence.substring(6); // "Java Programming"
// Extract range (start inclusive, end exclusive)
String range = sentence.substring(6, 10); // "Java"
String word = sentence.substring(0, 5); // "Learn"
// Convert to character array
char[] charArray = sentence.toCharArray();
// ['L','e','a','r','n',' ','J','a','v','a',' ','P','r','o','g','r','a','m','m','i','n','g']
// Safe substring with bounds checking
public static String safeSubstring(String str, int start, int end) {
if (str == null || start < 0 || end > str.length() || start > end) {
return "";
}
return str.substring(start, end);
}
Index Bounds
Always validate indices before calling charAt() or substring() to avoid StringIndexOutOfBoundsException. String indices are 0-based.
2. Search & Find Methods
String searching is essential for text processing, validation, and data extraction.
Index-Based Searching
Finding Characters and Substrings
String text = "Java is awesome and Java is powerful";
// Find substring positions
int firstJava = text.indexOf("Java"); // 0 (first occurrence)
int lastJava = text.lastIndexOf("Java"); // 20 (last occurrence)
int fromPos = text.indexOf("Java", 5); // 20 (search from index 5)
// Find individual characters
int firstA = text.indexOf('a'); // 1 (first 'a')
int lastA = text.lastIndexOf('a'); // 34 (last 'a')
// Case-sensitive search
int upperA = text.indexOf('A'); // -1 (not found)
int notFound = text.indexOf("Python"); // -1 (not found)
// Practical search example
String email = "user@example.com";
int atPos = email.indexOf('@');
int dotPos = email.lastIndexOf('.');
if (atPos > 0 && dotPos > atPos) {
String username = email.substring(0, atPos); // "user"
String domain = email.substring(atPos + 1); // "example.com"
}
Boolean Search Methods
Quick Existence Checks
String filename = "document.pdf";
String url = "https://www.example.com/page";
String code = "public class Main";
// Check if string contains substring
boolean hasPdf = filename.contains(".pdf"); // true
boolean hasJava = code.contains("Java"); // false (case-sensitive)
// Check string prefixes
boolean isHttps = url.startsWith("https://"); // true
boolean isPublic = code.startsWith("public"); // true
// Check string suffixes
boolean isPdf = filename.endsWith(".pdf"); // true
boolean isHtml = filename.endsWith(".html"); // false
// Practical file extension check
public static boolean isImageFile(String filename) {
String lower = filename.toLowerCase();
return lower.endsWith(".jpg") || lower.endsWith(".png") ||
lower.endsWith(".gif") || lower.endsWith(".bmp");
}
3. String Transformation
String transformation methods create new strings with modified content while preserving the original immutable string.
Case Conversion
Changing Case
String mixed = "Hello World";
// Case conversion
String upper = mixed.toUpperCase(); // "HELLO WORLD"
String lower = mixed.toLowerCase(); // "hello world"
// Original string unchanged
System.out.println(mixed); // "Hello World"
// Practical case-insensitive comparison
public static boolean equalsIgnoreCase(String str1, String str2) {
if (str1 == str2) return true;
if (str1 == null || str2 == null) return false;
return str1.toLowerCase().equals(str2.toLowerCase());
}
// Title case utility
public static String toTitleCase(String input) {
if (input == null || input.isEmpty()) return input;
return Character.toUpperCase(input.charAt(0)) +
input.substring(1).toLowerCase();
}
Whitespace Handling
Managing Whitespace
String messy = " Hello World ";
// Remove leading and trailing whitespace
String trimmed = messy.trim(); // "Hello World"
// Java 11+ enhanced whitespace methods
String stripped = messy.strip(); // "Hello World" (Unicode-aware)
String stripLeading = messy.stripLeading(); // "Hello World "
String stripTrailing = messy.stripTrailing(); // " Hello World"
// Normalize internal whitespace
String normalized = messy.trim().replaceAll("\\s+", " ");
// "Hello World"
// Check for blank strings
String onlySpaces = " ";
boolean isEmpty = onlySpaces.isEmpty(); // false
boolean isBlank = onlySpaces.isBlank(); // true (Java 11+)
boolean isTrimEmpty = onlySpaces.trim().isEmpty(); // true
String Replacement
Replace Operations
String text = "Hello World Hello";
// Replace all occurrences
String replaced1 = text.replace('l', 'x'); // "Hexxo Worxd Hexxo"
String replaced2 = text.replace("Hello", "Hi"); // "Hi World Hi"
// Replace only first occurrence
String replaceFirst = text.replaceFirst("Hello", "Hi"); // "Hi World Hello"
// Regex-based replacement
String numbers = "abc123def456ghi";
String noNumbers = numbers.replaceAll("\\d+", "-"); // "abc-def-ghi"
// Practical example: Clean user input
public static String cleanInput(String input) {
if (input == null) return "";
return input.trim()
.replaceAll("\\s+", " ") // Normalize spaces
.replaceAll("[^a-zA-Z0-9\\s]", ""); // Remove special chars
}
String Splitting and Joining
Split and Join Operations
// Splitting strings
String csv = "Java,Python,JavaScript,C++";
String[] languages = csv.split(",");
// ["Java", "Python", "JavaScript", "C++"]
// Split with limit
String data = "name:John:Doe:Developer";
String[] parts = data.split(":", 3); // ["name", "John", "Doe:Developer"]
// Split on whitespace
String sentence = "Hello World Java";
String[] words = sentence.trim().split("\\s+");
// ["Hello", "World", "Java"]
// Joining strings (Java 8+)
String[] fruits = {"Apple", "Banana", "Orange"};
String joined = String.join(", ", fruits); // "Apple, Banana, Orange"
String pathJoined = String.join("/", "home", "user", "documents");
// "home/user/documents"
// Repeat strings (Java 11+)
String dashes = "-".repeat(20); // "--------------------"
String padding = " ".repeat(5); // " "
4. String Comparison
Proper string comparison is critical for correctness. Understanding the different comparison methods prevents common bugs.
Content vs Reference Comparison
equals() vs == Operator
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
String str4 = "Hel" + "lo";
// Content comparison with equals()
System.out.println(str1.equals(str2)); // true
System.out.println(str1.equals(str3)); // true
System.out.println(str1.equals(str4)); // true
// Reference comparison with ==
System.out.println(str1 == str2); // true (string pool)
System.out.println(str1 == str3); // false (different objects)
System.out.println(str1 == str4); // true (compile-time optimization)
// Case-sensitive vs case-insensitive
String upper = "HELLO";
System.out.println(str1.equals(upper)); // false
System.out.println(str1.equalsIgnoreCase(upper)); // true
Null-Safe Comparison
Handling Null Values Safely
import java.util.Objects;
String str1 = "Hello";
String str2 = null;
String str3 = "Hello";
// DANGEROUS: Can throw NullPointerException
// boolean result = str2.equals(str1); // NPE!
// SAFE: Use Objects.equals() for null safety
boolean safe1 = Objects.equals(str1, str2); // false
boolean safe2 = Objects.equals(str1, str3); // true
boolean safe3 = Objects.equals(null, null); // true
// SAFE: Literal-first pattern (defensive programming)
boolean literalFirst = "Hello".equals(str2); // false (no NPE)
// SAFE: Explicit null check
boolean explicit = (str2 != null && str2.equals(str1)); // false
// Utility method for safe comparison
public static boolean safeEquals(String s1, String s2) {
return Objects.equals(s1, s2);
}
Lexicographic Ordering
Dictionary-Style Comparison
String str1 = "Apple";
String str2 = "Banana";
String str3 = "apple";
// compareTo returns int: negative, zero, or positive
int result1 = str1.compareTo(str2); // Negative (Apple < Banana)
int result2 = str2.compareTo(str1); // Positive (Banana > Apple)
int result3 = str1.compareTo(str1); // 0 (equal)
int result4 = str1.compareTo(str3); // Negative (uppercase < lowercase)
// Case-insensitive comparison
int ignoreCase = str1.compareToIgnoreCase(str3); // 0 (equal)
// Sorting usage example
public static int compareNames(String name1, String name2) {
if (name1 == null && name2 == null) return 0;
if (name1 == null) return -1;
if (name2 == null) return 1;
return name1.compareToIgnoreCase(name2);
}
// Practical sorting example
Arrays.sort(names, String::compareToIgnoreCase);
Part 1B Summary
Part 1B covered essential string methods and comparison techniques that form the core of string manipulation in Java.
Key Takeaways
- String Methods: Master basic operations like length(), charAt(), substring()
- Search Operations: Use indexOf(), contains(), startsWith(), endsWith() for finding text
- Transformations: Apply trim(), replace(), split() for text processing
- Safe Comparison: Always use equals() for content, Objects.equals() for null safety
- Case Handling: Remember that most string operations are case-sensitive
Practice Exercises
Try implementing these methods to reinforce your learning:
- Create a method to count word occurrences in a text
- Write a function to validate email format using string methods
- Implement a case-insensitive string search method
- Build a utility to extract file name and extension from a path