The String class includes various Java String methods for examining individual characters in a string. The String Methods perform various operations, including string comparison, search, copy, extracting a substring, converting to lowercase or uppercase, and so on.
A string is an immutable object that represents a sequence of characters. Once a string is created, it can’t be changed. However, there are many situations where we must perform different kinds of actions on a string. To do so, we must use the built-in Java string functions and assign the result set to a new string.
TIP: Please refer to the String article from Java to understand the creation of strings.
List of Java String methods
The following table shows the list of Java String Methods or functions available in the String Class. There is a separate article to explain each and every function, so use the hyperlinks to see the detailed explanation. However, this page gives a simple example for initial understanding.
| Modifier Type | Java String Methods | Description |
|---|---|---|
| char | chartAt(int index) | It returns the Character at the specified index position |
| int | codePointAt(int index) | This returns the Unicode of the Character at a specified index position |
| int | codePointBefore(int index) | It returns the Unicode of the Character before the specified index position |
| int | codePointCount(int start_index, int end_index) | It returns the Unicode of the Character at the specified index position |
| int | comapreTo(String str) | It compares two strings lexicographically. |
| int | compareToIgnoreCase(String str) | It compares two strings lexicographically. While comparing, this method ignores the case difference. |
| String | concat(String str) | This method helps to join the user-specified string to the end of the string and return the new string. |
| boolean | contains(CharSequence s) | This returns TRUE if and only if the string contains the user-specified sequence of characters. |
| boolean | contentEquals(CharSequence s) | It compares the string with the user-specified sequence of characters |
| boolean | contentEquals(StringBuffer sb) | It compares the string with the user-specified StringBuffer |
| Static String | copyValueOf(char[] anCharArray) | Returns the string that represents the character sequence in the specified array. |
| Static String | copyValueOf(char[] anCharArray, int offset, int count) | Returns the string that represents the character sequence in the specified array, starting at offset until it reaches the specified count. |
| boolean | endsWith(String suffix) | It tests whether the string ends with the suffix that we specified or not |
| boolean | equals(Object anObject) | It compares this string with the user-specified object |
| Boolean | equalsIgnoreCase(String another_String) | It compares this string with the user-specified string (another_String). Note, while comparing, it ignores the case sensitivity. |
| static String | format (String format, Object.. args) | It will return a formatted string using the user-specified format and arguments. |
| static String | format (locale l, String format, Object.. args) | It returns a formatted string using the user-specified locale, format, and arguments. |
| byte[] | getBytes() | It converts the string into a sequence of bytes using the platform default charset and stores it in a byte array. |
| byte[] | getBytes(Charset charset) | It converts the given string into a sequence of bytes using the specified charset and stores it in a byte array. |
| byte[] | getBytes(String charset_Name) | This Java string functions convert the string into a sequence of bytes using the named charset and stores it in a byte array. |
| char[] | getChar() | It copies a character sequence from the given starting position to the end position. |
| int | hashCode() | It returns the Hash code of the Java string |
| int | indexOf(int ch) | It returns the index position of the first occurrence of a specified character. It returns -1 if the specified character is not found |
| int | indexOf(int ch, int Starting_Index) | It returns the index position of the first occurrence of a given character. It returns -1 if the specified character is not found |
| int | indexOf(String str) | It returns the index position of the first occurrence of a specified substring. It returns -1 if the specified string is not found |
| int | indexOf(String str, int Start_Index) | It returns the index position of the first occurrence of a specified substring. It returns -1 if the specified string is not found |
| String | intern() | Returns the canonical representation for the String Object |
| Boolean | isEmpty() | This function returns TRUE if the length of this string is zero |
| Boolean | isBlank() | Returns True if a string is empty or filled with blank spaces. |
| String | join() | Joins the group of words using a specified separator from an iterable, like an array. |
| int | lastIndexOf(int ch) | It returns the index position of the last occurrence of a specified character. It returns -1 if the given character is not found |
| int | lastIndexOf(int ch, int End_Index) | Returns the index position of the last occurrence of a specified character. It returns -1 if the specified character is not found |
| int | lastIndexOf(String str) | It returns the index position of the last occurrence of a given character. It returns -1 if the specified character is not found |
| int | lastIndexOf(String str, int End_Index) | Returns the index position of the last occurrence of a specified character. It returns -1 if the given character is not found |
| int | length() | This returns the length of this string |
| boolean | matches(String regexp) | It tells whether this string matches a user-specified regular expression or not. |
| int | offsetByCodePoints(int index, int codePointOffset) | It returns the index within the string that is offset of a given index by codePointOffset code points |
| boolean | regionMatches(int toffset, String other, int offset, int len) | It test if two string regions are equal or not |
| boolean | regionMatches(boolean ignorecase, int toffset, String other, int offset, int len) | It tests if two string regions are equal or not |
| String | replace(char Old_Character, char New_Character) | Searches for specified characters and then replaces all the occurrences of Old_Character with New_Character |
| String | replace(CharSequence Old_sequence, CharSequence New_sequence) | It searches for a specified substring and then replaces all the occurrences of the Old_sequence substring with the new New_sequence substring. |
| String | replaceAll(String regexp, String replacement) | This Method searches for a specified regular expression. Then replace all the occurrences of the regular expression substring with the given replacement substring. |
| String | replaceFirst(String regexp, String replacement) | It searches for a specified regular expression and then replaces the first occurrence of the regular expression substring with the given replacement substring. |
| String | repeat() | Repeats a string for a given number of times. |
| String[] | split(String regex) | It splits the string into an Array of Substrings based on the separator we specified |
| String[] | split(String regex, int limit) | This one splits the string into an Array of Substrings based on the separator we specified |
| boolean | startsWith(String prefix) | It tests whether the string starts with the prefix that we specified or not |
| boolean | startsWith(String prefix, int limit) | It tests whether the substring of this string starts with the prefix that we specified or not |
| CharSequence | subsequence(int Starting_Index, int End_Index) | Returns a new sequence that is after the given sequence. |
| String | substring(int Starting_Index) | It extracts the characters from a string based on the specified indices |
| String | substring(int Starting_Index, int End_Index) | It extracts characters from a string based on the specified starting and end positions. |
| String | strip() | Removes leading and trailing blank spaces from a given string. |
| String | stripLeading() | Removes leading white spaces from a given string. |
| String | stripTrailing() | It removes trailing blank spaces from a given string. |
| char[] | toCharArray() | This converts the given string into an Array of Characters or a character array |
| int | toLowerCase() | It converts the given string into Lowercase letters using the default locale |
| String | toLowerCase (Locale locale) | It converts the given string into Lowercase letters by considering the user-specified locale |
| string | toString() | This String Method converts the given value into a String Object |
| string | toUpperCase() | It converts the given string into Uppercase letters |
| string | toUpperCase (Locale locale) | It converts the given string into Uppercase letters by considering the host environment’s current locale |
| string | trim() | This removes the white spaces from both ends |
| static String | ValueOf(boolean number) | Returns the string representation of the Boolean value |
| static String | ValueOf(char character) | String representation of a char |
| static String | ValueOf(char[] myArray) | String representation of a character array |
| static String | ValueOf(char[] myArray, int Offset, int count) | This returns the string representation of a subset character array. |
| static String | ValueOf(double number) | String representation of a double value |
| static String | ValueOf(float number) | String representation of a float value |
| static String | ValueOf(int number) | It returns the string representation of the Integer value. |
| static String | ValueOf(long number) | It returns the string representation of the Long value. |
| static String | ValueOf(Object obj) | String representation of an Object. |
Java String methods for case conversion
The toLowerCase() and toUpperCase() functions help convert the given string to lowercase and uppercase.
toLowerCase()
The toLowerCase() method does not accept any parameters and converts all characters in a given string to lowercase.
public class example {
public static void main(String[] args) {
String s = "uNITED sTATES";
System.out.println(s.toLowerCase());
}
}
united states
toUpperCase()
Similar to the toLowerCase(), the toUpperCase method does not accept any parameters and converts a given string’s characters to uppercase.
public class example {
public static void main(String[] args) {
String s = "united states";
System.out.println(s.toUpperCase());
}
}
UNITED STATES
Java string methods for comparison
There are two built-in string methods to perform string comparison: equals() and equalsIgnoreCase().
equals()
The equals() method accepts a string for comparison and checks whether the given two strings are equal or not. If they both are equal, it returns a Boolean True; otherwise, it returns false.
The following Java string methods example returns false because the equals() method is case-sensitive. So, both “USA” and “usa” are not the same.
public class example {
public static void main(String[] args) {
String s1 = "USA";
String s2 = "usa";
System.out.println(s1.equals(s2));
}
}
false
equalsIgnoreCase()
Unlike the equals() method, the equalsIgnoreCase() function performs string comparison irrespective of case. It returns true if they are both equal; otherwise, it returns false.
TIP: For case-sensitive string comparison, use the equals() method. On the other hand, use the equalsIgnoreCase() function for case-insensitive comparison.
public class example {
public static void main(String[] args) {
String s1 = "USA";
String s2 = "usa";
System.out.println(s1.equalsIgnoreCase(s2));
}
}
true
Java string functions – contentEquals()
The contentEquals() method also performs the string comparison. It checks whether both strings have the same character sequence.
public class example {
public static void main(String[] args) {
String s1 = "UK";
String s2 = "UK";
System.out.println(s1.contentEquals(s2));
}
}
true
compareTo()
The compareTo() method is one of the Java string methods that compares the two strings lexographically. It converts the characters in both strings into Unicode values and compares them against each other. If they are equal, it returns 0; otherwise, the compareTo() returns either a positive or negative value based on the number of characters.
public class example {
public static void main(String[] args) {
String s1 = "WHO";
String s2 = "WHO";
System.out.println(s1.compareTo(s2));
}
}
0
NOTE: If you add another character (O) at the end of the first string, the result is 1. If we add to the second string, the result is -1.
Java string functions – compareToIgnoreCase()
Similar to the compareTo() method, the compareToIgnoreCase() function compares the two strings lexographically without considering cases. Remember, the compareTo() performs case-sensitive string comparison. On the other hand, the compareToIgnoreCase() function ignores cases when comparing two strings.
public class example {
public static void main(String[] args) {
String s1 = "WHO";
String s2 = "who";
System.out.println(s1.compareToIgnoreCase(s2));
}
}
0
regionMatches()
Instead of comparing the whole string, the regionMatches() function compares a region (or part) of one string against the part of another string.
In the following Java string functions example, the character at index position 7 is “S”. So, the regionMatches() function compares States against the States from the second string.
public class example {
public static void main(String[] args) {
String s1 = "United States";
String s2 = "States";
System.out.println(s1.regionMatches(7, s2, 0, 6));
}
}
true
Java String methods for search operations
The following string functions perform the search operations.
indexOf()
The indexOf() function searches for the specified substring and returns the index position of the first occurrence. If the substring is not found, the indexOf() returns -1.
Although the “united” substring is repeated twice in a given string, the indexOf() returns the first occurrence index position. So, the result is 4.
public class example {
public static void main(String[] args) {
String s = "The united states and united kingdom";
System.out.println(s.indexOf("united"));
}
}
4
Java string methods – lastIndexOf()
The lastIndexOf() function searches for the last occurrence of a specified substring and returns the index position. If the substring is not found, the lastIndexOf() returns -1.
Although the “united” substring is available at index position 4, it returns 22 because the last occurrence is at that position.
public class example {
public static void main(String[] args) {
String s = "The united states and united kingdom";
System.out.println(s.lastIndexOf("united"));
}
}
22
contains()
The contains() method accepts a substring and checks whether the specified sequence of characters exists in a given string. If it exists, the contains() function returns Boolean true; otherwise, it returns false.
public class example {
public static void main(String[] args) {
String s = "The United Kingdom";
System.out.println(s.contains("King"));
}
}
true
NOTE: The contains() method is case sensitive; King and king are different.
Java string functions – startsWith()
The startsWith() function checks whether the string starts with a specified substring and returns true if it does; otherwise, false.
public class example {
public static void main(String[] args) {
String s = "The United States";
System.out.println(s.startsWith("Th"));
}
}
true
endsWith()
The endsWith() function checks whether the specified string ends with a given substring and returns true if it does; otherwise, false.
public class example {
public static void main(String[] args) {
String s = "The United States";
System.out.println(s.endsWith("United"));
}
}
false
Java String methods for string extraction
The string function that we mentioned here helps extract a single character, a substring, or a character sequence from a given string.
charAt()
The charAt() function accepts an integer value and returns the character at the given index position. The following example returns the character at the 12th index position (13th character).
public class example {
public static void main(String[] args) {
String str = "The Unites States Of America";
char str1 = str.charAt(12);
System.out.println(str1);
}
}
t
Java string functions – codePointAt()
The codePointAt() function accepts the index position as an argument and returns the Unicode value of a character at that position. The following example returns the 101 because the character at the 8th index position is “e” and its ASCII value is 101.
public class example {
public static void main(String[] args) {
String s = "The Unites States";
System.out.println(s.codePointAt(8));
}
}
101
codePointBefore()
The codePointBefore() function returns the Unicode value of a character before the specified index position. The following Java string functions example returns 85 because the character at the 4th index position (before the specified position) is “U” and its ASCII value is 85.
public class example {
public static void main(String[] args) {
String s = "The Unites States";
System.out.println(s.codePointBefore(5));
}
}
85
substring(int startIndex, int endIndex)
The substring() function accepts the starting and ending index positions as argument values. Next, the substring() returns a portion of the main string between those index positions (start, end – 1).
public class example {
public static void main(String[] args) {
String s = "united kingdom united states";
System.out.println(s.substring(7, 21));
}
}
kingdom united
Java string methods – subSequence()
Similar to the substring() function, the subSequence() method returns a new character sequence from the given starting and ending index positions.
public class example {
public static void main(String[] args) {
String s = "United Arab Emirates United Kingdom";
System.out.println(s.substring(12, 27));
}
}
Emirates United
Java String functions to replace a string
There are two versions of the replace() function, and other methods help perform string replacement.
replace(char old, char new)
The replace() function accepts two characters as arguments and performs the character replacement. It searches for the old characters in a given string and replaces them with new characters.
public class example {
public static void main(String[] args) {
String s = "united kingdom";
System.out.println(s.replace("n", "T"));
}
}
uTited kiTgdom
Java string functions – replace(substring, substring)
Apart from a single character, we can use the replace() function to replace a character sequence or substring with a completely new string.
public class example {
public static void main(String[] args) {
String s = "The united states and united kingdom";
System.out.println(s.replace("united", "UN"));
}
}
The UN states and UN kingdom
replaceAll()
The replaceAll() function replaces all occurrences of character sequences with a new string. It uses the regular expression as the first argument to search for multiple characters. The example below replaces all occurrences of the “u” and “t” with the “#” special character.
public class example {
public static void main(String[] args) {
String s = "united states and united kingdom";
System.out.println(s.replaceAll("[ut]", "#"));
}
}
#ni#ed s#a#es and #ni#ed kingdom
replaceFirst()
The replaceFirst() function is one of the Java string methods that replaces the first occurrences of a character sequence with a new string. No matter how many times the old character(s) are repeated, they replace the first occurrence.
public class example {
public static void main(String[] args) {
String s = "united states";
System.out.println(s.replaceFirst("[ut]", "#"));
}
}
#nited states
Java String functions to remove blank spaces
The trim() method is the most commonly used one to remove blank spaces. However, Java 11 introduces three more built-in string functions to remove white spaces from leading, trailing, and both.
trim()
The trim() method removes the white spaces from both sides of a string. It removes leading and trailing blank spaces. The following example removes the blank spaces from the left and right sides of the ” The United Kingdom ” message.
public class example {
public static void main(String[] args) {
String s = " The United Kingdom ";
System.out.println(s.trim());
}
}
The United Kingdom
strip(), stripLeading(), stripTrailing()
These three Java string methods were introduced in Java 11.
- strip(): Similar to the trim() function, the strip() method removes blank spaces from the left and right sides of a given string.
- stripLeading(): As the name suggests, it removes the leading blank spaces.
- stripTrailing(): As the name suggests, it removes the trailing blank spaces.
The following example demonstrates the strip(), stripLeading(), and stripTrailing() functions.
public class example {
public static void main(String[] args) {
String s = " The United States ";
System.out.println(s.strip());
System.out.println(s.stripLeading());
System.out.println(s.stripTrailing());
}
}
Result
The United States
The United States
The United States
Java String functions for concatenating Strings
Generally, users use the arithmetic + operator to perform string concatenation. However, we must use the built-in concat() function to join multiple strings.
concat()
As the name suggests, the concat() method performs string concatenation. It appends the given argument (substring) at the end of the specified string.
public class example {
public static void main(String[] args) {
String s1 = "The United ";
String s2 = "Arab Emirates";
System.out.println(s1.concat(s2));
}
}
The United Arab Emirates
Java string functions – join()
The join() method helps to join the elements from an iterable (for example, an array) to form a string. It uses the first argument to separate each word from the iterable.
In the following example, we join the words from a string array. Here, the join() method uses a comma and a space delimiter to separate each word.
public class example {
public static void main(String[] args) {
String[] countries = {"India", "USA", "UK", "China"};
String s = String.join(", ", countries);
System.out.println(s);
}
}
India, USA, UK, China
Other Java string functions
codePointCount()
The codePointCount() function accepts the start and end index positions and counts the Unicode points between them.
public class example {
public static void main(String[] args) {
String s = "The Unites States";
System.out.println(s.codePointCount(2, 6));
}
}
4
hashCode()
The hashCode() method is one of the Java string functions that returns the hash code value of a given string. There is a mathematical formula behind the hashCode calculation that we discussed in the hashCode article.
public class example {
public static void main(String[] args) {
String s = "Hi";
System.out.println(s.hashCode());
}
}
2337
Java string methods – repeat()
The repeat() method repeats the given string for the given number of times. It accepts an integer value and repeats for this many times. The following example repeats “Hi ” three times.
public class example {
public static void main(String[] args) {
String s = "Hi ";
System.out.println(s.repeat(3));
}
}
Hi Hi Hi
length()
As the name suggests, the length() function is one of the Java string functions that returns the length of a given string. In other words, it returns the total number of characters in a user-given string, including blank spaces.
The declared string in the following example has 13 characters and a blank space, so a total of 14 characters.
public class example {
public static void main(String[] args) {
String s = "United Nations";
System.out.println(s.length());
}
}
14
offsetByCodePoints()
The offsetByCodePoints() function helps to move some Unicode points within a string. The example below moves two characters forward.
public class example {
public static void main(String[] args) {
String s = "United";
System.out.println(s.offsetByCodePoints(0, 2));
}
}
2
Java string functions for split & format
split()
The split() method splits the given string into an array of substrings based on the specified separator. We can use a single character, a substring, or a regular expression as the separator. There is an optional second argument to limit the split process.
import java.util.Arrays;
public class example {
public static void main(String[] args) {
String s = "INDIA, CHINA, USA, UK, FRANCE";
String[] str = s.split(", ");
System.out.println(Arrays.toString(str));
}
}
[INDIA, CHINA, USA, UK, FRANCE]
NOTE: We can use the for loop to iterate over the string array items. For simplicity, we used the Array toString() function.
format()
The format() method helps format the user-given string using format specifiers. The following example is a simple demonstration of the Java string functions complex nature.
public class example {
public static void main(String[] args) {
String s = "United States";
String fs = String.format("The %s GDP is %.2f", s, 3.5);
System.out.println(fs);
}
}
The United States GDP is 3.50
Java String functions for conversion
copyValueof()
The copyValueOf() method returns the string representation of the sequence of characters specified in a character array.
public class example {
public static void main(String[] args) {
char[] ch = {'I', 'n', 'd', 'i', 'a'};
String s = String.copyValueOf(ch);
System.out.println(s);
}
}
India
getBytes()
The getBytes() method is one of the Java string functions that converts each character in a given string into an ASCII value and returns an array containing a sequence of bytes. We can use either a for loop or built-in array functions to read the array.
public class example {
public static void main(String[] args) {
String s = "INDIA";
byte[] bt = s.getBytes();
System.out.println(Arrays.toString(bt));
}
}
[73, 78, 68, 73, 65]
getChars()
The getChar() function accepts four arguments, which include the source starting and ending positions, the destination character array, and the starting position of the destination.
public class example {
public static void main(String[] args) {
String s = "INDIA";
int ln = s.length();
char[] cs = new char[ln];
s.getChars(0, ln, cs, 0);
System.out.println(cs);
for (char ch: cs) {
System.out.format("%c ", ch);
}
}
}
Result
INDIA
I N D I A
TIP: If you change the first argument value from 0 to 2, the above returns “DIA”.
toCharArray()
The toCharArray() method is one of the java string functions that converts the given string into a character array. We can perform various operations at the character level in a Char array.
public class example {
public static void main(String[] args) {
String s = "The united states";
char[] cn = s.toCharArray();
System.out.println(cn);
}
}
The united states
Java string methods – toString()
The toString() function returns a string representation of a given object. We can use the toString() function to convert any data type to a string. In the following example, the integer value 1000 is converted into a string.
public class example {
public static void main(String[] args) {
Integer n = 1000;
System.out.println(n.toString());
}
}
1000
valueOf()
The valueOf() function converts different kinds of data types, such as integers, Boolean, etc., to a string.
public class example {
public static void main(String[] args) {
boolean exists = true;
System.out.println(String.valueOf(exists));
}
}
true
TIP: The toString() method converts an object to a string. On the other hand, the valueOf() method converts a value to a string object.
intern()
The intern() method is one of the built-in Java string functions that returns the canonical representation of a given string. It is helpful in the string pool. The intern () method looks inside the string pool for the value, if it exists, references that subject; otherwise, it creates a new string with this text inside a string pool.
public class example {
public static void main(String[] args) {
String s1 = "USA";
String s2 = new String("USA");
System.out.println(s1 == s2);
System.out.println(s1 == s2.intern());
}
}
Result
false
true
Java String methods for validation
matches()
The matches() function checks whether the given string matches the user-specified regular expression or not. It returns True if it matches; otherwise, Boolean False. It’s a kind of wildcard matching.
The first statement returns false because both are not the same. However, in the second statement, we used (.*), which means it should start with United, followed by N number of characters (true).
public class example {
public static void main(String[] args) {
String s = "United Arab Emirates";
System.out.println(s.matches("United"));
System.out.println(s.matches("United(.*)"));
}
}
Result
false
true
isEmpty()
As the name suggests, the isEmpty() function checks whether the given string is empty or not. If it is empty, it returns Boolean True; otherwise, it returns False.
public class example {
public static void main(String[] args) {
String s = "";
System.out.println(s.isEmpty());
}
}
true
Java string methods – isBlank()
Similar to the isEmpty() function, the isBlank() method checks whether the given string is empty or not. However, it checks for an empty string and a string with empty spaces. If it is empty or filled with empty spaces, it returns Boolean True; otherwise, it returns False.
public class example {
public static void main(String[] args) {
String s = " ";
System.out.println(s.isBlank());
}
}
true