What are other string methods?

QuestionsQuestions8 SkillsProBasic String OperationsNov, 08 2025
072

In Java, there are several useful string methods that you can use to manipulate and work with strings. Here are some commonly used string methods:

  1. length(): Returns the length of the string.

    String str = "Hello";
    int length = str.length(); // 5
  2. charAt(int index): Returns the character at the specified index.

    char ch = str.charAt(1); // 'e'
  3. substring(int beginIndex, int endIndex): Returns a substring from the specified begin index to the end index (exclusive).

    String sub = str.substring(1, 4); // "ell"
  4. indexOf(String str): Returns the index of the first occurrence of the specified substring.

    int index = str.indexOf("l"); // 2
  5. toLowerCase(): Converts all characters in the string to lowercase.

    String lower = str.toLowerCase(); // "hello"
  6. toUpperCase(): Converts all characters in the string to uppercase.

    String upper = str.toUpperCase(); // "HELLO"
  7. trim(): Removes leading and trailing whitespace from the string.

    String trimmed = "  Hello  ".trim(); // "Hello"
  8. replace(char oldChar, char newChar): Replaces all occurrences of a specified character with a new character.

    String replaced = str.replace('l', 'p'); // "Heppo"
  9. split(String regex): Splits the string into an array of substrings based on the specified regular expression.

    String[] parts = str.split("l"); // ["He", "lo"]
  10. equals(Object anObject): Compares the string to the specified object for equality.

    boolean isEqual = str.equals("Hello"); // true

These methods provide a variety of functionalities to handle strings effectively in Java.

0 Comments

no data
Be the first to share your comment!