Java String Tutorial with Examples

Java String tutorial with examples will help you understand how to use the String class in Java in an easy way. String in Java is an Object that represents the sequence of characters. All String literals used in the Java programs like “Hello” or “World” are implemented as String objects.

The String in Java is immutable. That means the value of the String object cannot be changed once it is created. When you try to alter the value of the String object, a new object is created and assigned back to the reference. StringBuffer and StringBuilder classes support mutable strings.

String class in Java implements the CharSequence interface which represents a sequence of characters and declared as a final class, so you cannot extend it. StringBuffer and StringBuilder classes also implement the CharSequence interface. String class also implements Comparable and Serializable interfaces to allow string objects to be compared with one another and save/load state respectively.

How to create a new String object in Java?

There are several ways to create a String object in Java. The simplest way to create new String in Java is to assign a string literal directly to the String reference like,

Java maintains a pool of string literals. String literals contained in this pool are reused. When you assign a string literal directly to the reference as given above and if the same string literal already exists in the pool, reference of that literal is returned instead of creating a new string object.

Output

As you can see from the output when we created a new string reference using the same literal “hello”, the same object is returned from the pool. If you want to create a new object, always use new keyword with any of the below given String constructors.

String Constructors

The String class in Java provides several constructors to create a new String object.

How to create a new empty String object?

The default constructor of the String class creates an empty String object.

How to create a new String object from the byte array?

The String(byte[] byte) constructor creates a new string object from the argument byte array using the default character set of the platform.

Output

You can specify the desired character set using the overloaded String constructor which also accepts the character set along with the byte array.

You can also create a string object from the partial byte array using the overloaded constructor which accepts byte array, offset and length arguments like given below.

Output

You can also specify the character set to use just like the default constructor using the below given overloaded constructor.

How to create a new String object from StringBuffer or StringBuilder object?

The overloaded constructors String(StringBuffer sb) or String(StringBuilder sb) are used to create a new string object from the existing StringBuffer and StringBuilder objects respectively.

Output

Java String Methods

Below given are some of the most useful String class methods.

How to get a character at the specified index using the charAt method?

The charAt method returns a character at the specified index in the String. The index is 0 based, so the first character is at index 0 and the last character is at the strings’ length – 1 index.

Output

How to concatenate two strings using the concat method?

The concat method of the String class appends the specified string at the end of this string object. If the argument string is empty (i.e. length = 0), this String object is returned. Otherwise, a new String object is created having the character sequence of this string followed by the argument string.

Output

To know more about the differences between the concat method and concatenation using + operator, visit how to concatenate String example.

How to find string length using the length method?

The length method of the String class returns the length of this String object. In other words, it is equal to the number of Unicode code units contained in the string.

Output

You can iterate through the characters of the string using the charAt and length methods as given below.

Output

The index of the character starts at the 0 index and ends at the string’s length – 1 index. So the first character of the string is located at the 0 index and the last character of the string is located at length – 1 index.

Output

If you try to access the character which is out of the range, it throws StringIndexOutOfBoundsException.

Output

The above code tries to access the character located at the index equal to the string’s length, while the index ends at the string’s length – 1 index.

How to convert String to a byte array using the getBytes method?

The getBytes method of the String class encodes the string into the sequence of bytes using the default character set and returns the result as a new byte array.

Output

The above given method encodes the string to bytes using the underlying platform’s default character set. If you want to specify the character set, use an overloaded getBytes(Charset charset) method that encodes the string using the given character set.

How to copy characters from String to char array using the getChars method?

The getChars method copies the given characters from this string to the specified array.

This method copies the string characters starting from the startIndex (inclusive) to endIndex (exclusive) to the specified char array starting from the index arrayStartIndex.

Output

The getChars method throws IndexOutOfBoundsException if any of the below given condition is true.

1. If the startIndex or the arrayStartIndex is negative.

2. The startIndex is greater than the endIndex.

3. The endIndex is greater than the string’s length.

4. (endIndex – startIndex) + arrayStartInex is greater than the array’s length

How to search for a character in a string using the indexOf and lastIndexOf methods?

The indexOf method returns the index of the given character within the string. This method returns the index of the first occurrence of the character in the given string. If the character is not found within the string, it returns -1.

Output

The default indexOf method starts to search the character from index 0. You can also specify the start index from where you want to search for a character in the string using an overloaded indexOf(char ch, int startIndex) method.

Output

Similarly, to search for the character’s last index, use the lastIndexOf method.

Output

How to search for a substring in a string using the indexOf method?

The indexOf and lastIndexOf methods are overloaded to accept the String parameter as well. So you can search for the substring within the string in the same way you search for a character within the string as given above.

Output

How to check if the string is empty using the isEmpty method?

The isEmpty method of the String class returns true if the string length is 0, false otherwise.

Output

You can also use the length method of the String class and compare it with the 0 to check if the string is empty.

Output

Internally, the isEmpty method refers to the same member attribute to check if the string is empty or not. Have a look at the OpenJDK String class source code for both the methods.

How to join multiple strings by delimiter using the join method?

The join method of the String class joins multiple strings by the specified delimiter.

This method returns a new string containing specified CharSequence elements joined together by the specified delimiter.

Output

The array elements can also be joined using the join method as given below. The array has to be of type CharSequence for this to work.

Output

The join method is overloaded to accept the Iterable type too, so that you can also use this method for List, Set, etc.

Output

Note: Both of these join methods works for the classes implementing the CharSequence interface only (like String, StringBuffer, or StringBuilder).

How to match the string with a regular expression pattern using the matches method?

The matches method returns true if this string matches the specified regular expression pattern. It returns false otherwise.

Output

The regular expression pattern (Satur|Sun)day checks if the string matches with either “Satur” or “Sun” followed by the “day”. If it does, it returns true.

Please note that the matches method matches the whole string against the pattern. It returns false for the partial matches as given below.

So even though the string contains “day”, the matches method returns false. In order to make it return true, we need to match the whole string using the pattern as given below.

Output

The pattern .*day.* means any character any number of times, followed by “day”, followed by any character any number of times. Now the complete string matches with the pattern and so the matches method returns true.

To know more about regular expressions, check out Java regular expression tutorial with examples.

How to match two string’s substring using the regionMatches method?

The regionMatches method compares two string’s substrings to check if they are equal.

Example:

Output

The regionMatches method is case sensitive, so it will return false if there is a difference in the substring case.

Output

If you want to ignore the case while matching string regions or substrings, use an overloaded regionMatches method that has the ignore case parameter.

If the ignoreCase parameter is true, the cases of the substrings will be ignored while matching.

Output

How to replace a character or substring in the string using the replace, replaceAll, and replaceFirst methods?

Using the replace method:

The replace method of the String class replaces all the occurrences of a given character or substring with the specified new value.

Output

Similarly, you can replace all the occurrences of a substring by specified new substring using the overloaded replace method with CharSequence arguments.

Example:

Output

Important Notes about the replace method:

1. Even though the String class has separate replace and replaceAll methods, the replace method also replaces all the occurrences of the given character or substring.

2. As you can see from the output, the replace method does not change the original string object. It creates a new object with the replaced character sequence and returns it. The original string object stays unchanged.

Using the replaceAll method:

The replaceAll method replaces all the occurrences of the substring matching with the given regular expression with the specified new replacement string. This method throws a PatternSyntaxException if the provided regular expression is invalid.

Output

The \\s+ regex pattern means one or more space, so our replaceAll method replaced all the spaces in the original string with the given replacement string and returned a new string object. Please note that the original string object remains unchanged.

Difference between the replace and replaceAll methods:

While both the methods replace all the occurrences of the match, there are a couple of differences between them.

1. The replace method is overloaded for char and CharSequence types, while there is only one version of the replaceAll method.

2. Unlike the replace method, you can specify a regular expression pattern in the replaceAll method.

Using the replaceFirst method:

The replaceFirst method is the same as the replaceAll method, except that it only replaces the first occurrence of the match with the given replacement.

Output

As you can see from the output, the replaceFirst method only replaced the first match with the specified replacement.

How to split a string into multiple substrings using the split method?

The split method splits the string around the regular expression pattern matches. This method returns a String array having string parts.

Output

The above given method returns all the results. If you want to restrict the number of parts to a certain number, use an overloaded split method that restricts the number of parts to be returned in the string array.

Output

As you can see from the output, this time the split method returned only two parts. Have a look at the complete string split example to know more.

How to check if the string starts with a substring using the startsWith method?

The startsWith method returns true if this string is starting with the specified substring. It returns false otherwise.

Output

The above method checks if the string is starting with the specified substring from index 0. If you want to check if the substring of this string starts with another substring, you can use an overloaded startsWith method that accepts the index from where the comparison should start.

Output

How to check if the string ends with substring using the endsWith method?

The endsWith method returns true if this string ends with the specified substring. It returns false otherwise.

Output

How to get a substring from string using the substring method?

The substring method of the String class returns substring from the string starting at the specified index. The substring starts at the specified index and ends at the end of the string.

Output

The substring method throws IndexOutOfBoundsException if the start index is negative or greater than the string’s length.

If you want to get the substring starting and ending at the specified index, use an overloaded substring method having start and end index parameters.

Here, the start index is inclusive while the end index is exclusive.

Output

This method also throws IndexOutOfBoundsException if the start index is negative, or the start index is greater than the end index, or the end index is greater than the string length.

Note: Just like the other string methods, the substring method does not modify the original string object. Plus, always make sure to check the length of the string to avoid the IndexOutOfBoundsException while using any of these substring methods.

How to get a substring from the string using the subSequence method?

The subSequence method returns a character sequence from this string starting and ending at the specified index.

It returns the substring from the string starting at the startIndex and ending at the endIndex. The startIndex is inclusive, while the endIndex is exclusive.

Example

Output

Difference between the subSequence method and the substring method:

Both the methods are exactly the same except for the return types. The substring method returns a String, while the subSequence method returns the CharSequence. The subSequence method is defined in the String class only to implement the CharSequence interface.

How to convert string to character array using the toCharArray method?

The toCharArray method converts the string object to a char array.

Output

How to convert a string to lower case using the toLowerCase method?

The toLowerCase method converts all the characters in the string to lower case.

Output

The original string object stays unchanged. If you want to use the same reference, you need to assign the result of the toLowerCase method to the original reference as given below.

How to convert string to upper case using the toUpperCase method?

Just like the toLowerCase method, the toUpperCase method converts all the characters of the string object to the upper case. This method returns a new string object having all the characters converted to the upper case.

Output

How to remove leading and trailing spaces from the string using the trim method?

The trim method of the String class removes leading and trailing spaces from the string and returns a new string object.

Output

As you can see from the output, the trim method does not remove the spaces between the characters or words, only from the start and end of the string. If you want to remove all the spaces from the string, including the spaces between the characters or words, you will need to use the regular expression along with the replaceAll method as given below.

Output

The \\s+ pattern means one or more space characters.

How to convert primitive types and Object to a string using the valueOf method?

The String class in Java provides several valueOf methods to convert different types to the String type. These methods convert the specified type to the String type. Let’s have a look at an example of converting int to String using the valueOf method.

Output

The valueOf method is overloaded for boolean, char, char array, double, float, int, long, and Object types to convert various primitive types and an Object to the String type.

How to compare two strings using the equals and equalsIgnoreCase methods?

The equals method of the String class returns true if the argument string contains the same character sequence as this string object. It returns false otherwise.

Output

The equals method is case sensitive, which means if the two strings being compared have the exact same characters but in a different case, it returns false. If you want to compare the string contents ignoring the character case, use the equalsIgnoreCase method.

Output

How to compare two strings using the compareTo method?

The compareTo method compares two string objects lexicographically. All the characters of this string are compared with the characters of the other string lexicographically. It returns a negative number if this string precedes the other string lexicographically, a positive integer if this string follows the other string lexicographically, or 0 if both the strings are the same.

Output

How to compare two strings contents with the contentEquals method?

The contentEquals method compares this strings’ content with the specified character sequence. This method returns true if the content is the same, false otherwise.

Output

What are the differences between equals, contentEquals, and compareTo methods?

1. The contentEquals method accepts CharSequence as an argument. That means we can compare the contents of a string with the classes implementing the CharSequence interface like StringBuilder or StringBuffer. The equals and compareTo methods only work with the String type.

2. The compareTo method returns an integer while the equals and compareTo methods return boolean as a result.

What is the recommended way to compare strings?

If you want to compare two string objects’ content, the equals method is recommended. It should be faster than the compareTo method and makes the code intent clear. If you want to compare the string object’s content with StringBuffer or StringBuilder’s content then use the contentEquals method. This applies to almost all the cases except the case where you need the lexicographical result of the comparison. In that case, you need to use the compareTo method.

How to check if the string contains the substring using contains method?

The contains method returns true if this string object contains the specified sequence of characters. It returns false otherwise.

Output

The contains method accepts the CharSequence argument, which means you can also use StringBuilder or StringBuffer object as well.

Output

How to intern string using the intern method?

The String class in Java internally maintains a private pool for storing the unique strings. This pool is initially empty and grows later as the string objects are created. All the string objects created by assigning the string literals are interned automatically. That means if the content is the same for two string objects, they refer to the same string stored in the pool.

Output

As you can see from the output, the str1 and str2 references refer to the same string object containing “Java”. Remember, this applies to the string objects created using the assignment of string literals. This does not apply to the string objects created using the new keyword.

Output

Since the str2 object is created using the new keyword, it does not utilize the “Java” literal already stored in the pool. The intern method of the String class allows you to do that. When an intern method is called, and if the pool has the string having the same content, then that string object is returned from the pool. If not, the String object is added to the pool for later reuse and reference to that object is returned.

Output

So, say for example, if your program has 1000 string objects containing “Java”, interning them will have only one copy of “Java” stored instead of 1000 times. Sounds awesome, right?

The catch:

The string pool is stored in the JVM heap from Java 8 onwards. If you store more strings in the pool, the overall application will have less memory for other uses. Plus, there is a performance hit if a very large number of strings are stored in the pool. Given the tradeoffs, it makes sense to intern the strings objects which are likely to have a very large number of duplicates so that the memory saved justifies the performance cost.

How to format string using the format method?

The format method of the String class formats the String in C’s printf style. Internally, the format method uses the java.util.Formatter class to format the string in the specified argument.

Example

Output

For the complete list of all the formatting options, please refer to the Java 8 Formatter class.

I tried to explain various methods of the String class in Java for searching strings, extracting substrings, split the string in various chunks, and concatenating strings in this Java String tutorial. Below given Java String examples will talk about these methods in more detail.

Java String Examples

String Conversion Examples

References:
Java String class Javadoc

Please let me know if you liked the Java String tutorial with examples in the comments section below. Also, let me know if you liked the Java String examples I have provided above.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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