Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.

Categories: Core Java Basics. 2 Comments on Strings in Java
5
(1)

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.

 

Introduction to Strings

 

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).

 


Subscribe to our monthly newsletter. Get notified about latest articles, offers and contests.


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:

String s1 = "This is string s1.";
String s2 = new String("This is string s2.");

 

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:

String str = "hello";
str = str + "world";

 

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:

str = new StringBuffer().append(str).append("world").toString();

 

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:

String str = "hello";
System.out.println(str.length());

 

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:

String str1 = "hello";
String str2 = new String("hello");
System.out.println(str1.equals(str2));

 

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:

String str1 = "hello";
String str2 = new String("hello");
System.out.println(str1.compareTo(str2));

 

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

 

Another example of compareTo method is given below:

String str1 = "hallo";
String str2 = new String("hello");
System.out.println(str1.compareTo(str2));

 

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:

String str1 = "hello world";
System.out.println(str1.indexOf('o'));

 

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:

String str1 = "hello world";
System.out.println(str1.indexOf("wor"));

 

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:

String str1 = "hello world";
System.out.println(str1.lastIndexOf('o'));

 

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:

String str1 = "I am a good and I am bad";
System.out.println(str1.lastIndexOf("am"));

 

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:

String str1 = "hello world";
System.out.println(str1.substring(2));

 

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:

String str1 = "hello world";
System.out.println(str1.substring(6, 9));

 

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:

String str1 = "Hello World";
System.out.println(str1.toLowerCase());

 

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:

String str1 = "Hello World";
System.out.println(str1.toUpperCase());

 

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:

String str1 = "hello world";
System.out.println(str1.startsWith("hello"));

 

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:

int x = 10;
String str = String.valueOf(x);
System.out.println(str);

 

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:

StringBuffer sb1 = new StringBuffer();
StringBuffer sb2 = new StringBuffer(30);
StringBuffer sb3 = new StringBuffer("hello");

 

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:

StringBuffer sb1 = new StringBuffer("hello");
System.out.println(sb1.length());

 

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:

StringBuffer sb1 = new StringBuffer("hello");
System.out.println(sb1.capacity());

 

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:

StringBuffer sb1 = new StringBuffer("hello");
System.out.println(sb1.charAt(1));

 

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:

StringBuffer sb1 = new StringBuffer("hello");
sb1.setCharAt(1, 'a');
System.out.println(sb1);

 

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:

char[] target = new char[10];
StringBuffer sb1 = new StringBuffer("hello");
sb1.getChars(0,  3, target, 0);
System.out.println(target);

 

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:

StringBuffer sb1 = new StringBuffer("hello");
System.out.println(sb1.append("world"));

 

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:

StringBuffer sb1 = new StringBuffer("hello");
System.out.println(sb1.insert(5,"world"));

 

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:

StringBuffer sb1 = new StringBuffer("hello");
System.out.println(sb1.reverse());

 

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:

StringBuffer sb1 = new StringBuffer("hello");
System.out.println(sb1.deleteCharAt(1));

 

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:

StringBuffer sb1 = new StringBuffer("hello");
System.out.println(sb1.delete(1, 4));

 

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:

StringBuffer sb1 = new StringBuffer("hello");
System.out.println(sb1.replace(1, 3, "a"));

 

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:

StringBuffer sb1 = new StringBuffer("hello");
System.out.println(sb1.substring(1));
System.out.println(sb1.substring(1, 4));

 

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.

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Suryateja Pericherla

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.

He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.

He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.

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.

2 Comments

You can follow any responses to this entry through the RSS 2.0 feed.

String is thread safe

Java String is the most important topic which is mostly asked in core java interviews.
here you explained very well.
thanks

Leave a Reply

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