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)