In Java, the String class provides many built-in methods that help us perform operations like comparison, searching, modification, and formatting.
1.charAt()
This method returns the character at a specific index.
Example:
String s = "Java";
System.out.println(s.charAt(1)); // a
2.length()
Returns the total number of characters in a string.
Example:
String s = "Java";
System.out.println(s.length()); // 4
3.equals()
Compares two strings based on their content.
Example:
String a = "Java";
String b = "Java";
System.out.println(a.equals(b)); // true
4.equalsIgnoreCase()
Compares strings ignoring uppercase and lowercase differences.
Example:
System.out.println("JAVA".equalsIgnoreCase("java")); // true
5.compareTo()
Compares two strings lexicographically.
Example:
System.out.println("apple".compareTo("banana")); // negative
6.substring()
Extracts part of a string.
Example:
String s = "Java";
System.out.println(s.substring(1, 3)); // av
7.contains()
Checks if a string contains a specific value.
Example:
System.out.println("Java Programming".contains("Java")); // true
8.startsWith() and endsWith()
Used to check the beginning and ending of a string.
Example:
String s = "Java";
System.out.println(s.startsWith("Ja")); // true
System.out.println(s.endsWith("va")); // true
9.toUpperCase() and toLowerCase()
Used to change case of characters.
Example:
System.out.println("java".toUpperCase()); // JAVA
System.out.println("JAVA".toLowerCase()); // java
10.trim()
Removes leading and trailing spaces.
Example:
String s = " Java ";
System.out.println(s.trim()); // Java
11.replace()
Replaces characters or strings.
Example:
System.out.println("java".replace('a','o')); // jovo
12.split()
Splits a string into parts.
Example:
String s = "a,b,c";
String[] arr = s.split(",");
System.out.println(arr[0]); // a
13.isEmpty() and isBlank()
Used to check empty strings.
Example:
System.out.println("".isEmpty()); // true
System.out.println(" ".isBlank()); // true
Conclusion
Java String methods are essential for handling text data efficiently. Understanding these methods helps in writing better programs and solving interview problems easily. Practicing these regularly will improve coding skills and confidence.
Top comments (0)