DEV Community

Cover image for String_Methods
Ajay Raja
Ajay Raja

Posted on

String_Methods

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
Enter fullscreen mode Exit fullscreen mode

2.length()

Returns the total number of characters in a string.

Example:

String s = "Java";
System.out.println(s.length()); // 4
Enter fullscreen mode Exit fullscreen mode

3.equals()

Compares two strings based on their content.

Example:

String a = "Java";
String b = "Java";
System.out.println(a.equals(b)); // true
Enter fullscreen mode Exit fullscreen mode

4.equalsIgnoreCase()

Compares strings ignoring uppercase and lowercase differences.

Example:

System.out.println("JAVA".equalsIgnoreCase("java")); // true
Enter fullscreen mode Exit fullscreen mode

5.compareTo()

Compares two strings lexicographically.

Example:

System.out.println("apple".compareTo("banana")); // negative
Enter fullscreen mode Exit fullscreen mode

6.substring()

Extracts part of a string.

Example:

String s = "Java";
System.out.println(s.substring(1, 3)); // av
Enter fullscreen mode Exit fullscreen mode

7.contains()

Checks if a string contains a specific value.

Example:

System.out.println("Java Programming".contains("Java")); // true
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

9.toUpperCase() and toLowerCase()

Used to change case of characters.

Example:

System.out.println("java".toUpperCase()); // JAVA
System.out.println("JAVA".toLowerCase()); // java
Enter fullscreen mode Exit fullscreen mode

10.trim()

Removes leading and trailing spaces.

Example:

String s = "  Java  ";
System.out.println(s.trim()); // Java
Enter fullscreen mode Exit fullscreen mode

11.replace()

Replaces characters or strings.

Example:

System.out.println("java".replace('a','o')); // jovo
Enter fullscreen mode Exit fullscreen mode

12.split()

Splits a string into parts.

Example:

String s = "a,b,c";
String[] arr = s.split(",");
System.out.println(arr[0]); // a
Enter fullscreen mode Exit fullscreen mode

13.isEmpty() and isBlank()

Used to check empty strings.

Example:

System.out.println("".isEmpty());   // true
System.out.println("   ".isBlank()); // true
Enter fullscreen mode Exit fullscreen mode

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)