String Library Functions in Java
In Java, String is one of the most widely used classes. Java provides a rich set of built-in string library functions that make string manipulation simple, readable, and efficient.
Understanding these methods is essential for beginners, interview preparation, and real-world application development.
1. length()
Returns the number of characters in a string.
String s = "Java";
System.out.println(s.length()); // 4
2. charAt(int index)
Returns the character at a specific index.
String s = "Hello";
System.out.println(s.charAt(1)); // e
3. toUpperCase()
Converts all characters to uppercase.
String s = "java";
System.out.println(s.toUpperCase()); // JAVA
4. toLowerCase()
Converts all characters to lowercase.
String s = "JAVA";
System.out.println(s.toLowerCase()); // java
5. equals()
Compares the content of two strings.
String a = "Java";
String b = "Java";
System.out.println(a.equals(b)); // true
6. equalsIgnoreCase()
Compares two strings ignoring case.
System.out.println("Java".equalsIgnoreCase("java")); // true
7. compareTo()
Compares strings lexicographically.
System.out.println("apple".compareTo("banana")); // negative value
8. contains()
Checks if a string contains another sequence.
String s = "programming";
System.out.println(s.contains("gram")); // true
9. startsWith()
Checks if a string starts with a given prefix.
System.out.println("JavaScript".startsWith("Java")); // true
10. endsWith()
Checks if a string ends with a given suffix.
System.out.println("file.txt".endsWith(".txt")); // true
11. substring()
Extracts part of a string.
String s = "Programming";
System.out.println(s.substring(0, 7)); // Program
12. indexOf()
Returns the first occurrence index of a character or substring.
String s = "banana";
System.out.println(s.indexOf('a')); // 1
13. lastIndexOf()
Returns the last occurrence index.
System.out.println("banana".lastIndexOf('a')); // 5
14. replace()
Replaces characters or substrings.
String s = "Java is fun";
System.out.println(s.replace("fun", "powerful"));
15. trim()
Removes leading and trailing spaces.
String s = " hello ";
System.out.println(s.trim());
16. split()
Splits a string into an array.
String s = "Java is awesome";
String[] words = s.split(" ");
Important Notes
- Strings in Java are immutable.
- Most methods return a new string.
- Understanding these functions reduces manual logic.
Practice Challenges
- Reverse a string using library methods only.
- Check palindrome using built-in functions.
- Count words using split().
Mastering string library functions is a must for writing clean, efficient, and professional Java code.