String in Java IV: Important String Methods

String methods are what makes Java Strings so powerful. A Java String comprises of the underlying data and methods that can operate on the data. In a language such as C where a string is a char[] , the developer is responsible for manipulating the data. String methods are very powerful and provide most frequently used string manipulation algorithms out of the box. There is no need to reinvent the well. In this lesson we will learn most important String methods with examples. Bear in mind that Strings are immutable. Some methods may appear to be changing the String, but in fact they return a new String.

The charAt method

The charAt method returns the character located at a particular index. Strings, like arrays, start at 0th index. The signature of charAt is

The following short code snippet demonstrates how to use charAt

If you venture beyond the length of String and try to access a character beyond the range of string you will get the following exception –

The substring method

Creating a substring from a string is one of the most common operations. String class has following two overloaded variants of the substring method. Both of these methods splice a given string and return a substring

  1.  String substring ( begin, end) – returns a substring beginning at index begin and ending at end – 1.
  2. String substring (begin) – returns  a substring starting at index begin upto the end of string

The following code demonstrates usage of both these methods

The output of the above code is

The length() and isEmpty() methods

One of the most important reasons that Java Strings are superior to strings in non-object oriented language such as C is that Java Strings are aware of their length. They also know if they don’t yet hold a value in them. The code below demonstrates the usage pattern of the two methods that deal with length of strings.

The output of the above program is

Also note that isEmpty() is just a code sweetner. It was introduced in Java 6. This method depends on length() . If a string is non-null and has zero length,  isEmpty returns true. Before this method was introduced, Java programmers would repeatedly do these checks themselves. Checking for emptiness of a string is a fairly common operation, and if not done properly can give you NullPointerException.

The contains() method

The contains method checks if the parameter passed to it is contained in the current substring or not.

The output of the above program is

startsWith and endsWith methods

These two methods check if there is a substring match at either beginning or end of a string. Whereas the contains() method searches the entire string, these methods search at the two extremities.

The output of this program is

We have looked at a few String methods here. In the next lesson we will look at a few more important String methods.

Leave a comment

Your email address will not be published.