Java String Methods
In Java, the String class is used to work with text.
Strings are objects in Java and come with many built-in methods that help you
manipulate and process text easily. Understanding string methods is very important
because strings are used in almost every Java program.
Below are the most commonly used Java String methods with simple explanations and examples.
1. length()
The length() method returns the number of characters in a string.
String text = "Java Programming";
System.out.println(text.length());
2. toUpperCase() and toLowerCase()
These methods convert the string to uppercase or lowercase.
String name = "Java";
System.out.println(name.toUpperCase());
System.out.println(name.toLowerCase());
3. charAt()
The charAt(index) method returns the character at a specific index.
Index always starts from 0.
String word = "Hello";
System.out.println(word.charAt(1));
4. indexOf()
The indexOf() method returns the position of the first occurrence
of a specified character or string.
String text = "Java Programming";
System.out.println(text.indexOf("Program"));
5. equals() and equalsIgnoreCase()
These methods compare two strings. The equals() method
checks exact match, while equalsIgnoreCase() ignores case differences.
String a = "Java";
String b = "java";
System.out.println(a.equals(b));
System.out.println(a.equalsIgnoreCase(b));
6. contains()
The contains() method checks if a string contains
a specific sequence of characters.
String sentence = "Welcome to Java";
System.out.println(sentence.contains("Java"));
7. replace()
The replace() method replaces a character or substring
with another value.
String text = "Java";
System.out.println(text.replace("a", "o"));
8. substring()
The substring() method extracts part of a string.
String text = "Java Programming";
System.out.println(text.substring(5));
System.out.println(text.substring(0, 4));
9. trim()
The trim() method removes extra spaces from the beginning
and end of a string.
String text = " Java ";
System.out.println(text.trim());
10. split()
The split() method divides a string into an array
based on a specified delimiter.
String text = "Java,Python,C++";
String[] languages = text.split(",");
for(String lang : languages){
System.out.println(lang);
}
11. startsWith() and endsWith()
These methods check whether a string starts or ends with a specific value.
String text = "Java Programming";
System.out.println(text.startsWith("Java"));
System.out.println(text.endsWith("ing"));
Why Java String Methods Are Important?
- Used in almost every Java application
- Essential for text processing
- Important for form validation
- Frequently asked in interviews
- Help in data manipulation and formatting
Helpful Tip: Practice combining multiple string methods
in one program. For example, use trim() with
toLowerCase() and contains()
to validate user input.