Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples

September 26, 2015 Categories: Core Java Basics. No Comments on Strings in Java

This article explains about handling strings in Java programs. It is common in Java programs to work with strings to solve different problems. So, let’s see how to work with strings in Java.

Strings in Java: Classes

A string is a collection of characters. In Java, strings can be created using three predefined classes namely String, StringBuffer and StringBuilder which are available in java.lang package. Why did Java designers provide three classes for creating strings?

 

Each of the above three string classes has their own advantages and disadvantages. If you want to create an immutable (whose content cannot be changed once created) string, String class is the best choice. Strings created using StringBuffer and StringBuilder classes are mutable (content can be changed after they are created).

 

Among StringBuffer and StringBuilder classes, strings created using StringBuffer are thread safe whereas strings created using StringBuilder are non-thread safe. I will explain about threads in future articles.

 

Differences between all string classes: String, StringBuffer and StringBuilder are summarized in the below table:

Strings in Java

 

Now let’s look at each class in detail…

 

String Class

A string can be created in Java using the following alternatives:

 

 

In line 2, we are using a String constructor along with the new operator to create the string explicitly. In line 1, the whole process (creation of string) is done implicitly by JVM.

 

If the content of the newly created string matches with the existing string (already available in memory), then a reference to the existing string in the memory is returned instead of allocating new memory. Since strings created using String are shared, hence they are immutable as changing the string content using one reference might effect the others.

 

There are several other ways of creating strings which can be found in the official Java documentation of String class available here.

 

String Manipulation

As we already know that strings created using String class are immutable, how to manipulate them? Let us concatenate (join) two strings as shown below:

 

 

From the above two lines of code, content in str is “helloworld”. How is this possible if strings created using String class are immutable. Actually what JVM has done implicitly (automatically) is this:

 

 

Since concatenation is a manipulation, a new StringBuffer object is created and the content of str which is “hello” is appended to the buffer by using append method and then “world” is concatenated to “hello” making it “helloworld”. Finally the StringBuffer object is converted to a String object using the toString. All this process is done automatically by JVM whenever we try to concatenate two or more String objects.

 

Now we will look at various methods supported by String class for working with strings.

 

String Methods

The length method can be used to find the length of given string. Syntax of this method is given below:

int length()

An example of using length method is given below:

The above code prints 5.

 

The equals method can be used to compare whether two strings are having the same content or not. If both the strings are same, this method returns true, otherwise, false. Syntax of this method is given below:

boolean equals(String str)

An example of using equals method is given below:

The above code prints true.

 

The compareTo method can be used to compare whether two strings are having the same content or not. Syntax of this method is given below:

int compareTo(String str)

This method returns 0 when both strings are same, returns -ve number when the invoking string is less than the argument string, and +ve number when the invoking string is greater than the argument string.

An example of using compareTo method is given below:

Above example prints 0 as both strings are equal (same content).

Another example of compareTo method is given below:

Above example prints -4 as the difference between ‘a’ in “hallo” and ‘e’ in “hello” is 4 and “hallo” is the invoking string.

 

The indexOf method is used to find the position (number) of a specified character in the invoking string. Syntax of this method is given below:

int indexOf(char c)

An example of using indexOf method is given below:

Above example prints 4 which the index of first ‘o’ in the string “hello world”. Index of a string always starts from zero.

 

The overloaded indexOf method is used to find the position (number) of a specified string in the invoking string. Syntax of this method is given below:

int indexOf(String str)

An example of using indexOf method is given below:

Above example prints 6.

 

The lastIndexOf method is used to find the position (number) of a specified character from the end of the invoking string. Syntax of this method is given below:

int lastIndexOf(char c)

An example of using lastIndexOf method is given below:

Above example prints 7 which is the position of ‘o’ from the end of the invoking string “hello world”.

 

The overloaded lastIndexOf method is used to find the position (number) of a specified string from the end of the invoking string. Syntax of this method is given below:

int lastIndexOf(String str)

An example of using lastIndexOf method is given below:

Above example prints 18.

 

The substring method can be used to extract a sub string from the invoking string from a specified position to the end of the string. Syntax of this method is given below:

String substring(int index)

An example of substring method is given below:

Above example prints “llo world”. The starting index specified in the above example is 2.

 

The overloaded substring method can be used to extract a sub string from the invoking string from a specified start position to end position in the string. Syntax of this method is given below:

String substring(int startindex, int endindex)

An example of substring method is given below:

Above example prints “wor”. The starting index is 6 and the end index is 9. All the characters from starting index to excluding end index are returned.

 

The toLowerCase method can be used to convert all characters in a string to lower case characters. Syntax is as given below:

String toLowerCase()

An example of toLowerCase method is given below:

Above example prints “hello world”.

 

The toUpperCase method can be used to convert all characters in a string to upper case characters. Syntax is as given below:

String toUpperCase()

An example of toUpperCase method is given below:

Above example prints “HELLO WORLD”.

 

The startsWith method can be used to check whether the invoking string starts with a specified string or not. Syntax of this method is given below:

boolean startsWith(String str)

An example of startsWith method is given below:

Above example prints true since the invoking string “hello world” starts with the specified string “hello”.

 

Similarly, endsWith method can be used to find out whether a string ends with a specified string or not.

 

The overloaded valueOf method can be used to convert primitive type values like int, float, double etc to a String. Syntax of valueOf method that converts a given int value to a String value is given below:

static String valueOf(int value)

An example of valueOf method is given below:

Above example prints 10.

 

Above mentioned methods are the most frequently used methods of String class. You can have a look at other methods by clicking the link which is provided above.

 

Now we will look at the StringBuffer class and some of the methods available in that class.

 

StringBuffer Class

As already mentioned, strings created using StringBuffer class are mutable i.e., after creating a string, we can change the content of the string. Also strings created with StringBuffer class are thread safe (I will cover this aspect in future article on MultiThreading).

 

Creating Strings using StringBuffer Class

We can use the overloaded StringBuffer constructors as shown below:

The first line in the above example creates a empty StringBuffer object with a default capacity of 16 characters. The second line creates a StringBuffer object with a capacity of 30 characters and the last line creates a StringBuffer object from the supplied string “hello” and reserves an additional space for accommodating 16 characters to reduce reallocation.

Now let’s look at most of the frequently used methods available in the StringBuffer class.

 

StringBuffer Methods

The length method can be used to find the size of a StringBuffer object. Syntax of this method is given below:

int length()

An example of using length method is given below:

Above example prints 5 which is the number of characters (size) in the buffer.

 

The capacity method can be used to find the capacity of a StringBuffer object. Syntax of this method is given below:

int capacity()

An example of using capacity method is given below:

Above example prints 21 which is the capacity (size + 16) of the buffer.

 

You can use ensureCapacity and setLength methods to set the capacity and size of the buffer respectively. Syntax of each of these methods is given below:

void ensureCapacity(int minCapacity)

void setLength(int length)

 

The charAt method can be used to retrieve a single character from a specified position. Syntax of this method is given below:

char charAt(int pos)

An example of using charAt method is given below:

Above example prints the character ‘e’ which is available at the specified position 1.

 

The setCharAt method can be used to set (change) a character at a specific location in the buffer. Syntax of this method is given below:

void setCharAt(int pos, char ch)

An example of using setCharAt method is given below:

Above example prints “hallo”.

 

The getChars method can be used to extract a sub string from the buffer to a character array. Syntax of this method is given below:

void getChars(int startIndex, int endIndex, char target[], int targetStart)

In the above syntax, startIndex is the starting position in the invoking string and endIndex is the position up to which the characters are extracted plus one. target is the array in to which the sub string is extracted and targetStart specifies the index in the target array from which the sub string must be stored.

An example of getChars method is given below:

Above example prints “hel”.

 

The append method can be used to concatenate the string representation of different types of data to the end of a buffer. This method is overloaded. Syntax of this method which accepts a String argument is shown below:

StringBuffer append(String str)

An example of this method is given below:

Above example prints “helloworld”.

 

The insert method can be used to insert string representation of different types of data into a buffer at a specified position. This method is overloaded like append method. Syntax of this method for String type is given below:

StringBuffer insert(int index, String str)

An example of using insert method is given below:

Above example prints “helloworld”. Although the example inserts the string “world” at the end of the buffer, it can be inserted at any position you want.

 

The reverse method can be used to reverse the content of a buffer. Syntax of this method is given below:

StringBuffer reverse()

An example of using reverse method is given below:

Above example prints “olleh”.

 

The deleteCharAt method can be used to delete a character at specified location in the buffer. Syntax of this method is given below:

StringBuffer deleteCharAt(int pos)

An example of using deleteCharAt method is given below:

Above example prints “hllo”.

 

The delete method can be used delete a set of characters from the buffer. The starting index and ending index specifies the set of characters to be deleted. Syntax of this method is given below:

StringBuffer delete(int startIndex, int endIndex)

An example of using delete method is given below:

Above example prints “ho”. Characters from index 1 to 3 are deleted.

 

The replace method can be used to replace a set of characters with a specified string. The sub string is specified with starting index and ending index plus one. Syntax of this method is given below:

StringBuffer replace(int startIndex, int endIndex, String str)

An example of using replace method is given below:

Above example prints “halo”.

 

The substring method can be used to extract a substring from the buffer. This is method is overloaded. Syntax of this method is given below:

String substring(int startIndex)

String substring(int startIndex, int endIndex)

An example of using substring method is given below:

In the above example, line 2 prints “ello” and line 3 prints “ell”.

 

For a complete list of constructors and methods available in the StringBuffer class, refer this link.

 

StringBuilder Class

The StringBuilder class is similar to StringBuffer class in the sense that both classes contain same methods. The difference between them is in the case of performance. StringBuilder is faster than StringBuffer.

For a complete list of constructors and methods available in the StringBuilder class, refer this link.

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll Up
Thank you for visiting startertutorials.com! If you like this website do share with your friends by clicking on the social icons available on the left hand side.

As the domain name is quite large to remember, use this short domain to visit this site. Short domain: stuts.me