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 is 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 a new String in Java is to assign a string literal directly to the String reference like,
1 |
String str = "abc"; |
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, a reference of that literal is returned instead of creating a new string object.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
String str1 = "hello"; String str2 = "hello"; String str3 = "world"; if(str1 == str2) System.out.println("Same objects"); else System.out.println("Different objects"); if(str1 == str3) System.out.println("Same objects"); else System.out.println("Different objects"); |
Output
1 2 |
Same objects Different objects |
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 the 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.
1 |
String str = new String(); |
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.
1 2 3 |
//byte array containing ascii values byte b[] = {104, 101, 108, 108, 111}; System.out.println( new String(b) ); |
Output
1 |
hello |
You can specify the desired character set using the overloaded String constructor which also accepts the character set along with the byte array.
1 2 |
//creates a string from byte array using utf-8 charset String str = new String(b, StandardCharsets.UTF_8); |
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.
1 2 3 4 5 6 7 8 9 10 |
byte b[] = {104, 101, 108, 108, 111}; /* * Will create a new string from the byte array * elements starting from 0 index and total 2 * elements i.e. first and second elements */ //will print he String str = new String(b, 0, 2); System.out.println( str ); |
Output
1 |
he |
You can also specify the character set to use just like the default constructor using the below given overloaded constructor.
1 |
String(byte[] b, int offset, int length, Charset charset) |
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.
1 2 3 4 5 6 7 8 9 10 |
StringBuffer sbf = new StringBuffer("From StringBuffer"); String str1 = new String(sbf); System.out.println( str1 ); StringBuilder sbld = new StringBuilder("From StringBuilder"); String str2 = new String(sbld); System.out.println( str2 ); |
Output
1 2 |
From StringBuffer From StringBuilder |
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.
1 2 3 4 5 6 7 8 9 10 |
String str = "Java String Tutorial"; //this will print J, the first character System.out.println( str.charAt(0) ); //this will print S System.out.println( str.charAt(5) ); //this will print l, the last character System.out.println( str.charAt( str.length() - 1 )); |
Output
1 2 3 |
J S l |
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.
1 2 3 4 5 6 7 8 9 10 11 12 |
String str = "Hello"; String str2 = str.concat("World"); //this will print HelloWorld System.out.println(str2); /* * You can also chain the concat method * as given below. */ //this will print Hello World System.out.println( "Hello".concat(" ").concat("World") ); |
Output
1 2 |
HelloWorld Hello World |
To know more about the differences between the concat
method and concatenation using + operator, visit the 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.
1 |
System.out.println( "Hi".length() ); |
Output
1 |
2 |
You can iterate through the characters of the string using the charAt
and length
methods as given below.
1 2 3 4 |
String str = "Java is fun"; for(int i = 0 ; i < str.length(); i++){ System.out.println( str.charAt(i)); } |
Output
1 2 3 4 5 6 7 8 9 10 11 |
J a v a i s f u n |
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.
1 2 3 4 |
String str = "Java is fun"; System.out.println( "First character of string: " + str.charAt(0)); System.out.println( "Last character of string: " + str.charAt( str.length() - 1 )); |
Output
1 2 |
First character of string: J Last character of string: n |
If you try to access the character which is out of the range, it throws StringIndexOutOfBoundsException
.
1 2 |
String str = "Java is fun"; System.out.println( str.charAt( str.length() )); |
Output
1 2 |
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 11 at java.lang.String.charAt(Unknown Source) |
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.
1 2 3 4 5 6 |
String str = "byte array"; //the getBytes method converts string to byte array byte[] bytes = str.getBytes(); System.out.println( Arrays.toString(bytes) ); |
Output
1 |
[98, 121, 116, 101, 32, 97, 114, 114, 97, 121] |
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.
1 |
public void getChars(int startIndex, int endIndex, char[] charArray, int arrayStartIndex) |
This method copies the string characters starting from the startIndex (inclusive) to endIndex (exclusive) to the specified char array starting from the index arrayStartIndex.
1 2 3 4 5 6 7 8 9 10 11 |
String str = "Java String tutorial"; char[] array = new char[]{'h', 'e', 'l', 'l','o'}; /* * copies the string characters with index * 0, 1 and 2 to the array starting from * the array index 2 */ str.getChars(0, 3, array, 2); System.out.println(array); |
Output
1 |
heJav |
The getChars
method throws IndexOutOfBoundsException
if any of the below-given conditions 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.
1 2 3 4 5 6 7 8 9 10 11 |
String str = "Search character"; /* * The indexOf method only returns the * index of the first occurrence of the character */ //will print 1, that is position 2 in the string System.out.println( str.indexOf('e') ); //will print -1, as character z is not present in the string System.out.println( str.indexOf('z') ); |
Output
1 2 |
1 -1 |
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.
1 2 3 4 5 6 7 8 |
String str = "Search character"; /* * this will start searching for a character 'e' * from index 2 i.e. position 3 in the string */ //will print 14, that is position 15 in the string System.out.println( str.indexOf('e', 2) ); |
Output
1 |
14 |
Similarly, to search for the character’s last index, use the lastIndexOf
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
String str = "Search character"; /* * The lastIndexOf method searches the string * backwards for a given character */ //this will print 14, i.e. position 15 in the string System.out.println( str.lastIndexOf('e') ); /* * you can also specify the index * you want to start searching from */ /* * this will print 1, because it will start searching * for character 'e' from index 13 in the backward * direction */ System.out.println( str.lastIndexOf('e', 13) ); |
Output
1 2 |
14 1 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
String str = "Java string Java substring"; /* * Use indexOf method to search substring within * string. It returns the starting index of the * substring if found, -1 if not found. */ //this will return 0 as Java starts at 0 index in the string System.out.println( str.indexOf("Java") ); /* * you can also specify the search start index. */ //this will print 12, i.e. position 13 in the string System.out.println( str.indexOf("Java", 1) ); /* * To search the last occurrence of the substring * in the string, use lastIndexOf method. */ //this will return 12 System.out.println( str.lastIndexOf("Java") ); /* * Similarly, you can specify the start index * to find the last occurrence. * It searches backwards from the given index */ System.out.println( str.lastIndexOf("Java", 11) ); |
Output
1 2 3 4 |
0 12 12 0 |
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.
1 2 3 4 5 6 7 8 9 10 11 |
String str = ""; if(str.isEmpty()) System.out.println("String is empty"); else System.out.println("String is not empty"); str = "a"; if(str.isEmpty()) System.out.println("String is empty"); else System.out.println("String is not empty"); |
Output
1 2 |
String is empty String is not empty |
You can also use the length
method of the String class and compare it with the 0 to check if the string is empty.
1 2 3 4 5 |
String str = ""; if(str.length() == 0) System.out.println("String is empty"); else System.out.println("String is not empty"); |
Output
1 |
String is empty |
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 methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/** * Returns the length of this string. * The length is equal to the number of <a href="Character.html#unicode">Unicode * code units</a> in the string. * * @return the length of the sequence of characters represented by this * object. */ public int length() { return value.length; } /** * Returns {@code true} if, and only if, {@link #length()} is {@code 0}. * * @return {@code true} if {@link #length()} is {@code 0}, otherwise * {@code false} * * @since 1.6 */ public boolean isEmpty() { return value.length == 0; } |
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.
1 |
public static String join(CharSequence delimiter, CharSequence... elements) |
This method returns a new string containing specified CharSequence elements joined together by the specified delimiter.
1 2 3 4 5 6 7 8 |
/* * Use join method to join individual strings * by the given delimiter */ String str = String.join("-", "One", "Two", "Three"); //this will print One-Two-Three System.out.println("Joined String: " + str); |
Output
1 |
Joined String: One-Two-Three |
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.
1 2 3 4 |
String[] strArray = new String[]{"Red", "Green", "Blue"}; //this will print Red|Green|Blue System.out.println( String.join("|", strArray) ); |
Output
1 |
Red|Green|Blue |
The join method is overloaded to accept the Iterable type too, so that you can also use this method for List, Set, etc.
1 |
public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) |
1 2 3 4 5 6 7 |
List<String> listWeekend = new ArrayList<String>(); listWeekend.add("Friday"); listWeekend.add("Saturday"); listWeekend.add("Sunday"); //this will print Friday, Saturday, Sunday System.out.println( String.join(", ", listWeekend) ); |
Output
1 |
Friday, Saturday, Sunday |
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.
1 2 3 4 5 6 |
String[] strDays = new String[]{"Saturday", "Sunday", "Monday", "Tuesday"}; for(String day : strDays){ boolean isWeekend = day.matches( "(Satur|Sun)day" ); System.out.println( day + " => " + isWeekend ); } |
Output
1 2 3 4 |
Saturday => true Sunday => true Monday => false Tuesday => false |
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.
1 2 |
String strDay = "sunday"; System.out.println( strDay.matches("day") ); |
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.
1 2 |
String strDay = "sunday"; System.out.println( strDay.matches(".*day.*") ); |
Output
1 |
true |
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.
1 |
boolean regionMatches(int startInex, String otherString, int otherStartIndex, int totalLength) |
Example:
1 2 3 4 5 6 7 8 9 10 |
String strDay = "Sunday"; String strAnotherDay = "Monday"; /* * this will compare strDay's substring * starting from index 2 for length of 3 (i.e. "day") * with substring of strAnotherDay * starting from index 2 for length of 3 (i.e. also "day") */ System.out.println( strDay.regionMatches(2, strAnotherDay, 2, 3) ); |
Output
1 |
true |
The regionMatches
method is case sensitive, so it will return false if there is a difference in the substring case.
1 2 3 4 5 |
String strDay = "SUNDAY"; String strAnotherDay = "monday"; //will print false System.out.println( strDay.regionMatches(2, strAnotherDay, 2, 3) ); |
Output
1 |
false |
If you want to ignore the case while matching string regions or substrings, use an overloaded regionMatches
method that has the ignore case parameter.
1 |
boolean regionMatches(boolean ignoreCase, int startInex, String otherString, int otherStartIndex, int totalLength) |
If the ignoreCase parameter is true, the cases of the substrings will be ignored while matching.
1 2 3 4 5 |
String strDay = "SUNDAY"; String strAnotherDay = "monday"; //this will print true System.out.println( strDay.regionMatches(true, 2, strAnotherDay, 2, 3) ); |
Output
1 |
true |
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.
1 |
String replace(char old, char new) |
1 2 3 |
String str = "Hello"; System.out.println( "Replaced String: " + str.replace('l', 'o') ); System.out.println("Original String: " + str); |
Output
1 2 |
Replaced String: Heooo Original String: Hello |
Similarly, you can replace all the occurrences of a substring with specified new substring using the overloaded replace
method with CharSequence arguments.
1 |
String replace(CharSequence old, CharSequence new) |
Example:
1 2 3 |
String str = "Hello World, Hello"; System.out.println( "Replaced String: " + str.replace("Hello", "Hi") ); System.out.println("Original String: " + str); |
Output
1 2 |
Replaced String: Hi World, Hi Original String: Hello World, Hello |
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 the PatternSyntaxException
if the provided regular expression is invalid.
1 2 3 4 5 6 |
String str = "Java String Examples"; String newStr = str.replaceAll("\\s+", ", "); System.out.println("Original String: " + str); System.out.println("Replaced String: " + newStr); |
Output
1 2 |
Original String: Java String Examples Replaced String: Java, String, Examples |
The \\s+
regex pattern means one or more spaces, 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.
1 2 3 4 5 6 |
String str = "Java String Examples"; String newStr = str.replaceFirst("\\s+", ", "); System.out.println("Original String: " + str); System.out.println("Replaced String: " + newStr); |
Output
1 2 |
Original String: Java String Examples Replaced String: Java, String Examples |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
String str = "String in Java with examples"; /* * This will split the string at every * space and stores each part in the array * and returns it */ //specify the regex pattern to split the string String[] parts = str.split("\\s+"); for(String part : parts){ System.out.println(part); } |
Output
1 2 3 4 5 |
String in Java with examples |
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.
1 |
String[] parts = str.split("\\s+", 2); |
Output
1 2 |
String in Java with examples |
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.
1 2 3 4 5 6 7 8 9 10 |
String str = "July"; //will print true System.out.println( str.startsWith("Ju") ); //will print false System.out.println( str.startsWith("Jun") ); //will also print false, because it is case sensitive System.out.println( str.startsWith("ju") ); |
Output
1 2 3 |
true false false |
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.
1 2 3 4 5 6 7 8 9 |
String str = "Monday"; /* * Specify the start index to * check if the substring starts * with the given string */ //will print true System.out.println( str.startsWith("day", 3) ); |
Output
1 |
true |
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.
1 2 3 4 5 6 7 8 9 10 |
String str = "Java tutorial"; //will print true System.out.println( str.endsWith("ial") ); //will print false System.out.println( str.endsWith("eal") ); //will also print false, because it is case sensitive System.out.println( str.endsWith("iaL") ); |
Output
1 2 3 |
true false false |
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.
1 2 3 4 5 6 |
String str = "hello world"; //this will get the substring from index 6 to the end String substring = str.substring(6); System.out.println(substring); |
Output
1 |
world |
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.
1 |
public String substring(int start, int end) |
Here, the start index is inclusive while the end index is exclusive.
1 2 3 4 5 6 7 8 9 10 |
String str = "hello world"; /* * This will get substring starting from * the index 6 and ending at 7. Remember, the * end index is exclusive. */ String substring = str.substring(6, 8); System.out.println(substring); |
Output
1 |
wo |
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.
1 |
public CharSequence subSequence(int startIndex, int endIndex) |
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
1 2 |
String str = "String tutorial with examples"; System.out.println( str.subSequence(7, 15) ); |
Output
1 |
tutorial |
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.
1 2 3 4 |
String str = "String to char array"; char[] array = str.toCharArray(); System.out.println( Arrays.toString(array) ); |
Output
1 |
[S, t, r, i, n, g, , t, o, , c, h, a, r, , a, r, r, a, y] |
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.
1 2 3 4 |
String str = "CONVERT To lOwer Case"; System.out.println("Original string: " + str); System.out.println("Lower case string: " + str.toLowerCase() ); |
Output
1 2 |
Original string: CONVERT To lOwer Case Lower case string: convert to lower case |
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.
1 |
str = str.toLowerCase(); |
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.
1 2 3 4 |
String str = "convert TO uPPer cAsE"; System.out.println("Original string: " + str); System.out.println("Upper case string: " + str.toUpperCase() ); |
Output
1 2 |
Original string: convert TO uPPer cAsE Upper case string: CONVERT TO UPPER CASE |
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.
1 2 |
String str = " remove all the spaces "; System.out.println( str.trim() ); |
Output
1 |
remove all the spaces |
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.
1 2 |
String str = " remove all the spaces "; System.out.println( str.replaceAll("\\s+", "") ); |
Output
1 |
removeallthespaces |
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.
1 2 3 |
//int to String int i = 5; System.out.println("int to String: " + String.valueOf(i) ); |
Output
1 |
int to String: 5 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
String str1 = "hello"; String str2 = "hello"; String str3 = "heLLo"; String str4 = new String("hello"); //will print equals 1, because both string contains same characters if(str1.equals(str2)){ System.out.println("equals 1"); }else{ System.out.println("not equal 1"); } //will print not equal 2, because character case is not same if(str1.equals(str3)){ System.out.println("equals 2"); }else{ System.out.println("not equal 2"); } //will print equals 3, because both string contains same characters if(str1.equals(str4)){ System.out.println("equals 3"); }else{ System.out.println("not equal 3"); } |
Output
1 2 3 |
equals 1 not equal 2 equals 3 |
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.
1 2 3 4 5 |
String str1 = "HELLO"; String str2 = "hello"; System.out.println( "equals: " + str1.equals(str2) ); System.out.println( "equalsIgnoreCase: " + str1.equalsIgnoreCase(str2) ); |
Output
1 2 |
equals: false equalsIgnoreCase: true |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
String str1 = "a"; String str2 = "A"; String str3 = "a"; String str4 = "b"; //will print the difference, i.e. +32 in ascii value System.out.println( str1.compareTo(str2) ); //will print 0 because both the strings are same System.out.println( str1.compareTo(str3) ); //will print -1, because str1 preceeds str4 lexicographically System.out.println( str1.compareTo(str4) ); |
Output
1 2 3 |
32 0 -1 |
How to compare two strings contents with the contentEquals method?
The contentEquals
method compares strings’ content with the specified character sequence. This method returns true if the content is the same, false otherwise.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
String str1 = "hello"; String str2 = "Hello"; String str3 = "hello"; StringBuilder sbr = new StringBuilder("hello"); //will print false, as they differ in contents System.out.println( str1.contentEquals(str2) ); //will print true, as both have same character sequence System.out.println( str1.contentEquals(str3) ); //will print true, as both have same character sequence System.out.println( str1.contentEquals(sbr) ); |
Output
1 2 3 |
false true true |
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.
1 2 3 4 5 6 7 8 9 10 |
String str = "Java Strings"; //will print true System.out.println( str.contains("Java") ); //will print false, as the case is different System.out.println( str.contains("java") ); //will print true System.out.println( str.contains("tring") ); |
Output
1 2 3 |
true false true |
The contains
method accepts the CharSequence argument, which means you can also use StringBuilder or StringBuffer object as well.
1 2 3 4 5 |
String str = "Java Strings"; StringBuilder sbr = new StringBuilder("ava"); //will print true System.out.println( str.contains(sbr) ); |
Output
1 |
true |
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.
1 2 3 4 5 |
String str1 = "Java"; String str2 = "Java"; if(str1 == str2) System.out.println("Same"); |
Output
1 |
same |
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.
1 2 3 4 5 6 7 |
String str1 = "Java"; String str2 = new String("Java"); if(str1 == str2) System.out.println("Same"); else System.out.println("different"); |
Output
1 |
different |
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.
1 2 3 4 5 6 7 8 9 |
String str1 = "Java"; //intern the string object, i.e. reuse from the pool String str2 = new String("Java").intern(); if(str1 == str2) System.out.println("Same"); else System.out.println("different"); |
Output
1 |
same |
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.
1 |
public static String format(String format, Object... arguments) |
Example
1 2 3 4 5 6 7 8 9 10 11 |
//string substitution System.out.println( String.format("%s is the best", "Java") ); //number substitution System.out.println( String.format("%s is number %d programming language", "Java", 1) ); //date and time formatting, making hour, minute and seconds double digits System.out.println( String.format("Time is %02d:%02d:%02d", 1, 22, 9) ); //number formatting, max 2 decimal places System.out.println( String.format("%.2f", 1.39342342) ); |
Output
1 2 3 4 |
Java is the best Java is number 1 programming language Time is 01:22:09 1.39 |
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
- How to create and use String array
- How to concatenate Strings in Java
- How to replace substring in String using substring method
- How to find substring in String using indexOf method
- How to check if String contains substring using contains method
- How to check password strength in Java
- How to validate password String using regular expression
- How to validate String containing username using regular expression
- How to check if String is empty
- How to check if String is palindrome
- How to remove last character from String
- How to get String length in Java
- How to split String in Java
- How to split String by words
- How to split String into equal length substrings
- How to split String by new line characters
- How to split String by comma
- How to split String by pipe (|) character
- How to split String by dot (.) character
- How to count number of words in String
- How to get substring from String
- How to get count of substring in String
- How to capitalize first character of each word of String
- How to convert first character of String to lower case
- How to capitalize first character of String
- How to remove duplicate words from String
- How to mask certain characters in String with asterisk (*) sign
- How to create String with specified number of characters
- How to initialize String array
- How to pad String with zeros
- How to create random String in Java
- How to remove duplicate values from String array
- How to remove HTML tags from String
- How to keep only letters and numbers in String
- How to keep only letters in String
- How to keep only numbers in String
- How to remove non ascii characters from String
- How to convert String to title case
- How to check if the String is in lower case
- How to check if the String is in upper case
- How to invert case of String
- How to convert String to upper case or lower case
- How to check if String ends with another String or substring
- How to check if String starts with another String or substring
- How to check if String starts with a number
- How to remove leading and trailing spaces from String
- How to remove multiple consecutive spaces from String
- How to check if String array contains a value
- How to sort String array
- How to sort String array containing numbers
- How to reverse String array
- How to remove leading zeros from String using regular expression
- How to allow only alphanumeric characters in String using a-zA-Z0-9 regular expression pattern
String Conversion Examples
- Convert StringBuilder to String, String to StringBuilder
- Convert InputStream to String
- Convert String to InputStream
- Convert ArrayList to comma separated String
- Convert comma separated String to ArrayList or List
- Convert ArrayList to String array
- Convert int array to String
- Convert String to ArrayList
- Convert byte array to String
- Convert String to byte array
- Convert String to String array
- Convert String array to String
- How to convert exception stack trace to String
- Convert List to String
- Convert String to a character array (char array)
- Convert String containing number to wrapper class object
- Convert char to String
- Convert primitive boolean to String object
- Convert primitive short value to String object
- Convert primitive byte value to String object
- Convert primitive double value to String object
- Convert primitive float value to String object
- Convert primitive long value to String object
- Convert primitive int value to String object
- Convert String object to boolean primitive type
- Convert String object to short primitive type
- Convert String object to byte primitive type
- Convert String object to double primitive type
- Convert String object to float primitive type
- Convert String object to long primitive type
- Convert String object to int primitive type
- Convert String array to ArrayList
- Convert String to respective primitive values
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.