Home/Java/String Methods in Java

String Methods in Java

Learn all the powerful tools you can use with Strings

💡 Think of String methods like tools in a toolbox! Just like you have different tools for different jobs (hammer, screwdriver, wrench), Java has different String methods for different text tasks. Need to make text uppercase? There's a tool for that! Need to find something in your text? There's a tool for that too!

🛠️ What are String Methods?

String methods are built-in functions that help you manipulate and work with text. They make it easy to do common tasks like changing case, finding characters, splitting text, and much more!

StringMethodsIntro.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class StringMethodsIntro {
public static void main(String[] args) {
String message = "Hello World";
// Call different methods on the string
System.out.println("Original: " + message);
System.out.println("Length: " + message.length());
System.out.println("Uppercase: " + message.toUpperCase());
System.out.println("Lowercase: " + message.toLowerCase());
System.out.println("First char: " + message.charAt(0));
System.out.println("Contains 'World': " + message.contains("World"));
// Notice: original string is unchanged!
System.out.println("Still: " + message);
}
}

📏 Getting Information About Strings

These methods help you learn about your string's size and contents:

LengthAndInfo.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class LengthAndInfo {
public static void main(String[] args) {
String text = "Java Programming";
// length() - returns the number of characters
int len = text.length();
System.out.println("Length: " + len); // 16
// charAt(index) - returns character at position
char firstChar = text.charAt(0); // 'J'
char lastChar = text.charAt(len - 1); // 'g'
System.out.println("First: " + firstChar + ", Last: " + lastChar);
// isEmpty() - checks if string is empty
String empty = "";
String notEmpty = "Hello";
System.out.println("Is empty? " + empty.isEmpty()); // true
System.out.println("Is notEmpty? " + notEmpty.isEmpty()); // false
// isBlank() - checks if string is empty or only whitespace (Java 11+)
String blank = " ";
System.out.println("Is blank? " + blank.isBlank()); // true
System.out.println("Is empty? " + blank.isEmpty()); // false
}
}

✂️ Changing and Manipulating Strings

These methods help you modify strings (remember: they create NEW strings because Strings are immutable!):

ManipulationMethods.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class ManipulationMethods {
public static void main(String[] args) {
String text = " Hello World ";
// toUpperCase() / toLowerCase()
System.out.println(text.toUpperCase()); // " HELLO WORLD "
System.out.println(text.toLowerCase()); // " hello world "
// trim() - removes leading and trailing whitespace
String trimmed = text.trim();
System.out.println("[" + trimmed + "]"); // "[Hello World]"
// replace(old, new) - replaces all occurrences
String replaced = text.replace("World", "Java");
System.out.println(replaced); // " Hello Java "
// replaceAll(regex, replacement) - using regex patterns
String noSpaces = text.replaceAll("\\s+", "-");
System.out.println(noSpaces); // "-Hello-World-"
// substring(start) - from start to end
String sub1 = "Programming".substring(3);
System.out.println(sub1); // "gramming"
// substring(start, end) - from start to end-1
String sub2 = "Programming".substring(3, 7);
System.out.println(sub2); // "gram"
// concat() - joins strings (can also use +)
String greeting = "Hello".concat(" ").concat("World");
System.out.println(greeting); // "Hello World"
}
}

🔍 Searching and Finding in Strings

These methods help you find things inside your strings:

SearchingMethods.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class SearchingMethods {
public static void main(String[] args) {
String text = "Java is awesome and Java is fun";
// contains(substring) - checks if substring exists
boolean hasJava = text.contains("Java");
System.out.println("Contains 'Java': " + hasJava); // true
// indexOf(substring) - finds first occurrence (returns -1 if not found)
int firstJava = text.indexOf("Java");
System.out.println("First 'Java' at: " + firstJava); // 0
// indexOf(substring, fromIndex) - search from position
int secondJava = text.indexOf("Java", firstJava + 1);
System.out.println("Second 'Java' at: " + secondJava); // 20
// lastIndexOf(substring) - finds last occurrence
int lastJava = text.lastIndexOf("Java");
System.out.println("Last 'Java' at: " + lastJava); // 20
// startsWith(prefix) - checks if starts with
boolean startsWithJava = text.startsWith("Java");
System.out.println("Starts with 'Java': " + startsWithJava); // true
// endsWith(suffix) - checks if ends with
boolean endsWithFun = text.endsWith("fun");
System.out.println("Ends with 'fun': " + endsWithFun); // true
// Example: checking if substring not found
int notFound = text.indexOf("Python");
if (notFound == -1) {
System.out.println("'Python' not found in text");
}
}
}

⚖️ Comparing Strings

These methods help you compare strings to see if they're equal or which comes first:

ComparisonMethods.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class ComparisonMethods {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
String str3 = "hello";
String str4 = "World";
// equals(other) - checks if content is exactly the same
System.out.println(str1.equals(str2)); // true
System.out.println(str1.equals(str3)); // false (case matters!)
// equalsIgnoreCase(other) - ignores case differences
System.out.println(str1.equalsIgnoreCase(str3)); // true
// compareTo(other) - lexicographic comparison
// Returns: 0 if equal, negative if this < other, positive if this > other
System.out.println(str1.compareTo(str2)); // 0 (equal)
System.out.println(str1.compareTo(str4)); // negative (H comes before W)
System.out.println(str4.compareTo(str1)); // positive (W comes after H)
// compareToIgnoreCase(other) - case-insensitive comparison
System.out.println(str1.compareToIgnoreCase(str3)); // 0
// IMPORTANT: Never use == for string comparison!
String a = new String("Test");
String b = new String("Test");
System.out.println(a == b); // false (different objects)
System.out.println(a.equals(b)); // true (same content)
}
}

🔪 Splitting Strings

SplitMethod.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class SplitMethod {
public static void main(String[] args) {
// split(delimiter) - breaks string into array
String fruits = "apple,banana,orange,grape";
String[] fruitArray = fruits.split(",");
System.out.println("Number of fruits: " + fruitArray.length);
for (String fruit : fruitArray) {
System.out.println("- " + fruit);
}
// Split by spaces
String sentence = "Java is awesome";
String[] words = sentence.split(" ");
System.out.println("\nWords: " + words.length);
for (String word : words) {
System.out.println(word);
}
// Split with limit
String data = "name:age:city:country";
String[] parts = data.split(":", 2);
System.out.println("\nFirst part: " + parts[0]); // name
System.out.println("Rest: " + parts[1]); // age:city:country
// Split with regex
String mixed = "one1two2three3four";
String[] pieces = mixed.split("\\d+"); // split by digits
System.out.println("\nPieces:");
for (String piece : pieces) {
System.out.println(piece);
}
}
}

🌟 Real-World Example: Email Validator

EmailValidator.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public class EmailValidator {
public static boolean isValidEmail(String email) {
// Check if email is null or empty
if (email == null || email.isEmpty()) {
return false;
}
// Trim whitespace
email = email.trim();
// Check if contains @ symbol
if (!email.contains("@")) {
return false;
}
// Split by @ to get username and domain
String[] parts = email.split("@");
if (parts.length != 2) {
return false;
}
String username = parts[0];
String domain = parts[1];
// Validate username (not empty)
if (username.isEmpty()) {
return false;
}
// Validate domain (must contain .)
if (!domain.contains(".")) {
return false;
}
// Check domain doesn't start or end with .
if (domain.startsWith(".") || domain.endsWith(".")) {
return false;
}
return true;
}
public static void main(String[] args) {
String[] emails = {
"user@example.com",
"invalid.email",
"@nodomain.com",
"noatsign.com",
"user@.com",
"user@domain.",
" valid@email.com "
};
for (String email : emails) {
boolean valid = isValidEmail(email);
System.out.println(email + " -> " + (valid ? "VALID" : "INVALID"));
}
}
}

🔑 Key Concepts

Method Chaining

You can call multiple methods one after another

text.trim().toLowerCase().replace(' ', '_')

Index Starts at 0

The first character is at position 0, not 1

'Hello'.charAt(0) returns 'H'

Strings Are Immutable

Methods return NEW strings; they don't change the original

String upper = text.toUpperCase() // creates new string

Case Sensitivity

Java treats uppercase and lowercase as different

'Hello'.equals('hello') is false

Best Practices

  • Use equals() to compare strings, not == (== compares references, not content)
  • Check for null before calling string methods to avoid NullPointerException
  • Use StringBuilder for multiple string concatenations in loops
  • Consider using equalsIgnoreCase() when case doesn't matter
  • Always validate string indices before using charAt() or substring()

⚠️ Common Mistakes

  • Using == instead of equals() to compare strings
  • Forgetting that strings are immutable (str.toLowerCase() doesn't change str)
  • Not checking string bounds before accessing characters
  • Assuming indexOf() will never return -1 (it returns -1 when not found)
  • Forgetting to handle empty strings or null values

💼 Interview Tips

  • Know the difference between equals() and ==
  • Remember that indexOf() returns -1 when the substring is not found
  • Understand that substring(start, end) goes from start (inclusive) to end (exclusive)
  • Be aware of String immutability and how it affects method behavior
  • Know that split() returns an array of strings
  • Understand the performance implications of string concatenation in loops