String Methods

Understanding String Methods

  • String methods allow manipulation and interaction within String objects in Java.
  • In Java, String is an object that represents a sequence of characters.
  • The java.lang.String class provides many methods to perform operations on strings such as comparing strings, finding substring, concatenating strings, replacing characters, splitting strings, determining string length, etc.

Commonly Used String Methods

  • char charAt(int index) : This method returns the character located at the specified index of the string. The index starts from 0.
  • int length() : The length() method returns the length (character count) of a string.
  • boolean equals(Object another) : The equals() method compares two strings and returns true if the strings are equal, false otherwise.
  • String substring(int beginIndex, int endIndex) : The substring() method returns a new string that starts from beginIndex and ends at endIndex.
  • int indexOf(int ch, int fromIndex) : The indexOf() method returns the index within this string of the first occurrence of the specified character or -1, if the character does not occur.

Defining Strings and Utilising Methods

  • A String can be defined as: String myString = "Hello, world!";
  • You can then use String methods on that string, like so: int stringLength = myString.length();

String Comparison

  • Strings can be compared using the equals(), equalsIgnoreCase(), compareTo() and compareToIgnoreCase() methods.
  • equals() checks for exact matches, case-sensitive. Thus, “hello” and “Hello” are not equal.

String Modification

  • Strings are immutable in Java, meaning once created, they cannot be changed.
  • However, methods like toLowerCase(), toUpperCase(), trim(), replace(), substring() seem to modify strings, but they actually return a new string with the modifications—the original string remains unaltered.

Using String Methods

  • String methods can help in processing and manipulating textual data, changing case, comparing strings, find sub-strings or characters, and more.
  • They make handling and manipulating the data carried by your String variables more accessible and provide versatile solutions for a wide range of scenarios.

Wrapping Up

  • Mastery of String methods is essential, as they are frequently used in Java programming. These methods make the handling, manipulation, and operation of String objects easier, more efficient, and intuitive.