Java String Methods:
Strings are one of the most commonly used data types in Java. Whether you're building simple programs or complex applications, working with strings is unavoidable.
📌 What is a String in Java?
A String in Java is a sequence of characters.
String name = "kiran";
👉 Strings in Java are immutable, meaning they cannot be changed once created.
🔑 Important Java String Methods
1️⃣ length()
Returns the number of characters in a string.
String str = "Hello";
System.out.println(str.length()); // 5
2️⃣ toUpperCase() & toLowerCase()
Used to convert string case.
String str = "mapla";
System.out.println(str.toUpperCase()); // MAPLA
System.out.println(str.toLowerCase()); // mapla
3️⃣ charAt()
Returns the character at a specific index.
String str = "Java";
System.out.println(str.charAt(1)); // a
4️⃣ substring()
Extracts a portion of a string.
String str = "Programming";
System.out.println(str.substring(0, 6)); // Progra
5️⃣ equals() vs ==
Important for comparing strings.
String a = "mapla";
String b = "mapla";
System.out.println(a == b); // compares reference
System.out.println(a.equals(b)); // compares content
✅ Always use equals() for accurate comparison.
6️⃣ contains()
Checks if a string contains a specific value.
String str = "Java Programming";
System.out.println(str.contains("Java")); // true
7️⃣ replace()
Replaces characters or words in a string.
String str = "Hello World";
System.out.println(str.replace("World", "Mapla"));
// Hello Mapla
8️⃣ trim()
Removes leading and trailing spaces.
String str = " hello ";
System.out.println(str.trim()); // "hello"
9️⃣ split()
Splits a string into an array.
String str = "apple,banana,mango";
String[] arr = str.split(",");
for(String fruit : arr){
System.out.println(fruit);
}
🔟 indexOf()
Returns the index of a character or substring.
String str = "Hello";
System.out.println(str.indexOf("e")); // 1
🎯 Bonus Methods
🔹 isEmpty()
String str = "";
System.out.println(str.isEmpty()); // true
🔹 startsWith() / endsWith()
String str = "Java";
System.out.println(str.startsWith("J")); // true
System.out.println(str.endsWith("a")); // true
⚡ Real-Time Example
String email = " mapla@gmail.com ";
email = email.trim();
if(email.contains("@gmail.com")){
System.out.println("Valid Gmail");
}
🚨 Important Note: Immutability
Strings are immutable in Java.
String str = "Hello";
str.concat(" World");
System.out.println(str); // Hello (no change)
Correct way:
str = str.concat(" World");
These methods are very important for interviews — especially:
equals()substring()split()
Top comments (0)