Strings are one of the most used data types in Java. Whether you’re working on backend logic, building APIs, or creating user interfaces, you’ll constantly manipulate text. Mastering Java Strings is not just about knowing how to declare them — it’s about using the right methods efficiently.
In this guide, we’ll break down 15 essential String methods in Java.
What Are Java Strings?
In Java, a String
is an object that represents a sequence of characters. Unlike primitive types (like int
or char
), Strings are immutable—once created, they cannot be changed.
For example:
String name = "Java";
Here, "Java"
is a String object. Any operation you perform on it will create a new String instead of modifying the existing one. This immutability ensures safety and consistency but also means you should know which methods to use efficiently.
1. length()
Returns the number of characters in a string.
String text = "Hello World";
System.out.println(text.length()); // Output: 11
Why it matters: You’ll often need to check string sizes for validation, formatting, or loops.
2. charAt(int index)
Returns the character at the given position (index starts from 0).
String word = "Java";
System.out.println(word.charAt(2)); // Output: v
Pro tip: Use it for character-level operations like parsing or encryption.
3. substring(int beginIndex, int endIndex)
Extracts part of a string.
String str = "Mastering Java";
System.out.println(str.substring(0, 9)); // Output: Mastering
Use case: Extract names, IDs, or tokens from a larger text.
4. equals(Object another)
Checks if two strings are exactly equal (case-sensitive).
String a = "Java";
String b = "Java";
System.out.println(a.equals(b)); // Output: true
Tip: Use equalsIgnoreCase()
when case doesn’t matter.
5. compareTo(String another)
Compares two strings lexicographically. Returns:
0
if equal< 0
if first < second> 0
if first > second
System.out.println("apple".compareTo("banana")); // Output: negative value
Why useful: Sorting and ordering strings.
6. contains(CharSequence s)
Checks if a string contains a sequence of characters.
String text = "Learning Java Strings";
System.out.println(text.contains("Java")); // Output: true
7. indexOf(String str)
Finds the first occurrence of a substring.
String sentence = "Java is powerful, Java is popular.";
System.out.println(sentence.indexOf("Java")); // Output: 0
Note: Returns -1
if not found.
8. lastIndexOf(String str)
Finds the last occurrence of a substring. Means, lastIndexOf
gives the starting index of the last occurrence.
System.out.println(sentence.lastIndexOf("Java")); // Output: 18
Great for working with repeated values.
9. toLowerCase()
and toUpperCase()
Convert strings to lower or upper case.
String lang = "Java";
System.out.println(lang.toLowerCase()); // java
System.out.println(lang.toUpperCase()); // JAVA
Perfect for case-insensitive searches or formatting.
10. trim()
Removes leading and trailing spaces.
String messy = " Java Strings ";
System.out.println(messy.trim()); // Output: Java Strings
Pro tip: Always trim user input before processing.
11. replace(CharSequence old, CharSequence new)
Replaces characters or substrings.
String data = "I love Python";
System.out.println(data.replace("Python", "Java")); // Output: I love Java
12. split(String regex)
Splits a string into an array based on a delimiter.
String csv = "apple,banana,grape";
String[] fruits = csv.split(",");
for (String fruit : fruits) {
System.out.println(fruit);
}
Output:
apple
banana
grape
Useful in parsing CSV, logs, or user input.
13. startsWith(String prefix)
/ endsWith(String suffix)
Check if a string begins or ends with a specific sequence.
String file = "report.pdf";
System.out.println(file.endsWith(".pdf")); // true
14. isEmpty()
Checks if a string has no characters.
String empty = "";
System.out.println(empty.isEmpty()); // true
Note: After Java 6, isBlank()
(Java 11+) is even better as it checks whitespace too.
15. valueOf()
Converts other data types into strings.
int num = 100;
String strNum = String.valueOf(num);
System.out.println(strNum + 50); // Output: 10050 ("100" + "50" → "10050")
Why useful: For concatenation and displaying numbers, booleans, or objects.
Best Practices with Java Strings
- Use
StringBuilder
orStringBuffer
for heavy modifications (loops, concatenations). - Always check for
null
before calling string methods. - For large-scale text processing, be mindful of memory since Strings are immutable.
Conclusion
Mastering these Java String methods will make you faster and more confident when handling text in Java applications. Whether you’re validating user input, formatting reports, or parsing data, these 15 methods cover most real-world scenarios.
The key is practice. Start experimenting with these methods in small projects, and you’ll soon find that strings are not just simple text — they’re a powerful tool in every Java developer’s toolkit.