Java String Methods – 27 String Functions You Must Know

Java String class has a lot of methods. There are many methods to get the characters of the string object. There are many methods to split the string into an array or to create substrings. Since String is immutable, the original string remains unchanged. If the method is returning a string object, it’s creating a new object from the original string and returning it.

Java String Methods

Some important Java String methods are:

  • length()
  • isEmpty() and isBlank()
  • charAt()
  • getChars() and toCharArray()
  • getBytes()
  • equals(), hashCode() and equalsIgnoreCase()
  • contentEquals()
  • compareTo() and compareToIgnoreCase()
  • startsWith() and endsWith()
  • indexOf() and lastIndexOf()
  • substring() and subSequence()
  • concat()
  • matches()
  • replace(), replaceFirst(), and replaceAll()
  • contains()
  • split()
  • join()
  • toLowerCase() and toUpperCase()
  • trim(), strip(), stripLeading(), and stripTrailing()
  • lines()
  • indent()
  • transform()
  • format()
  • intern()
  • valueOf() and copyValueOf()
  • repeat()
  • describeConstable() and resolveConstantDesc()
  • formatted(), stripIndent(), and translateEscapes()

Let’s look into these methods one by one with examples.

1. length()

The length() method returns the length of the string object.

jshell> String s = "Hello World";
s ==> "Hello World"

jshell> s.length()
$2 ==> 11

2. isEmpty() and isBlank()

String isEmpty() method returns True if the string length is 0 i.e. an empty string.

The isBlank() utility method was added to the String class in Java 11 release. It returns True if the string is empty or contains only whitespaces.

jshell> String empty = "";
empty ==> ""

jshell> String whitespaces = " \t ";
whitespaces ==> " \t "

jshell> empty.isEmpty()
$5 ==> true

jshell> whitespaces.isEmpty()
$6 ==> false

jshell> empty.isBlank()
$7 ==> true

jshell> whitespaces.isBlank()
$8 ==> true

3. charAt(int index)

This method returns the character at the given index. If the index is out of range, StringIndexOutOfBoundsException is thrown.

jshell> String str = "Java";
str ==> "Java"

jshell> str.charAt(2)
$10 ==> 'v'

jshell> str.charAt(20)
|  Exception java.lang.StringIndexOutOfBoundsException: String index out of range: 20
|        at StringLatin1.charAt (StringLatin1.java:48)
|        at String.charAt (String.java:709)
|        at (#11:1)

4. getChars() and toCharArray()

The getChars() method is used to populate a character array values from this string. The method syntax is:

getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)

  • srcBegin is the index of the first character to copy from this string.
  • srcEnd is the index after the last character in the string to copy.
  • dst[] is the destination character array.
  • dstBegin is the offset index in the destination char array.
jshell> String str = "1234567890";
str ==> "1234567890"

jshell> char[] dest = new char[5];
dest ==> char[5] { '\000', '\000', '\000', '\000', '\000' }

jshell> str.getChars(2, 5, dest, 1)

jshell> System.out.println(Arrays.toString(dest));
[, 3, 4, 5, ]

String toCharArray() method returns the character array populated from the string characters.

jshell> String str = "1234567890";
str ==> "1234567890"

jshell> str.toCharArray()
$18 ==> char[10] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' }

5. getBytes()

This method returns byte array created from the string. There are three overloaded getBytes() method.

  1. getBytes(): decode the bytes using the system default character set encoding.
  2. getBytes(Charset charset): The character set is used to decode the bytes.
  3. getBytes(String charsetName): The charsetName is used to get the actual Charset instance for decoding.
jshell> String str = "Hello";
str ==> "Hello"

jshell> str.getBytes();
$20 ==> byte[5] { 72, 101, 108, 108, 111 }

jshell> import java.nio.charset.StandardCharsets;

jshell> str.getBytes(StandardCharsets.UTF_16);
$22 ==> byte[12] { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111 }

jshell> str.getBytes("UTF-16");
$23 ==> byte[12] { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111 }

jshell> str.getBytes("UTF-8");
$24 ==> byte[5] { 72, 101, 108, 108, 111 }

6. equals(), hashCode() and equalsIgnoreCase()

The equals(Object obj) method returns true if and only if the object is a string and represents the same sequence of characters as this string. If you are wondering why the argument type is Object and not String, it’s because the method is being overridden here from the Object class. The equals() method is used in Hashtable implementations along with the hashCode() method.

jshell> String s1 = "Hello"
s1 ==> "Hello"

jshell> s1.equals(new Object())
$26 ==> false

jshell> s1.equals("Hello")
$28 ==> true

The hashCode() method returns the integer hash value of the string. It’s cached when the string is created and uses the following formula.

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

Here s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation.

jshell> String s = "Java"
s ==> "Java"

jshell> s.hashCode()
$30 ==> 2301506

jshell> String s2 = "Java"
s2 ==> "Java"

jshell> s2.hashCode()
$32 ==> 2301506

jshell> "String".hashCode()
$33 ==> -1808118735

If you are wondering why the hashCode() value is negative, it’s because the value returned from the formula is larger than the maximum value of the integer. So it’s causing integer overflow and in that case, the hashcode can be negative.

The equalsIgnoreCase(String str) compares this string with the given string, ignoring case considerations.

jshell> "Java".equalsIgnoreCase("JAVA")
$34 ==> true

jshell> "Java".equalsIgnoreCase("JA")
$35 ==> false

7. contentEquals()

This method compares the content of the string with the CharSequence object. It’s used to compare the string with the StringBuilder and StringBuffer instances.

jshell> String str = "12345"
str ==> "12345"

jshell> StringBuffer sb = new StringBuffer()
sb ==> 

jshell> sb.append("12345")
$38 ==> 12345

jshell> str.contentEquals(sb)
$39 ==> true

jshell> StringBuilder sb1 = new StringBuilder(sb)
sb1 ==> 12345

jshell> str.contentEquals(sb1)
$41 ==> true

8. compareTo() and compareToIgnoreCase()

String implements Comparable interface. So, we can compare two strings lexicographically using the compareTo() method.

The compareToIgnoreCase() method also performs the lexicographical comparison, ignoring case.

jshell> "Java".compareTo("Java")
$42 ==> 0

jshell> "Java".compareTo("Jb")
$43 ==> -1

jshell> "Java".compareToIgnoreCase("JAVA")
$44 ==> 0

jshell> "Java".compareToIgnoreCase("JB")
$45 ==> -1

Recommended Reading: Java String Comparison

9. startsWith() and endsWith()

These methods are used to check if the string has given prefix or suffix strings or not. They return a boolean result. The startsWith() has an overloaded method to provide the integer value as the offset index.

jshell> "123456".startsWith("123")
$46 ==> true

jshell> "123456".startsWith("34")
$47 ==> false

jshell> "123456".startsWith("34", 2)
$48 ==> true

jshell> "123456".endsWith("456")
$49 ==> true

jshell> "123456".endsWith("45")
$50 ==> false

10. indexOf() and lastIndexOf()

There are four overloaded indexOf() methods.

  • indexOf(int ch): returns the first index of the character in the string. If the character is not present, then returns -1.
  • indexOf(int ch, int fromIndex): the second parameter specifies the index from where to search for the character.
  • indexOf(String str): returns the index of the first occurrence of the substring.
  • indexOf(String str, int fromIndex): returns the index of the first occurrence of the substring starting from the given index.
jshell> "Java".indexOf('a')
$51 ==> 1

jshell> "Java".indexOf('a', 2)
$52 ==> 3

jshell> "Java".indexOf("av")
$53 ==> 1

jshell> "Java".indexOf("av", 2)
$54 ==> -1

Similarly, there are four overloaded lastIndexOf() methods. The behavior is similar, except that the last index is returned. The search for the character or the substring starts from backward.

  • lastIndexOf(int ch)
  • lastIndexOf(int ch, int fromIndex): the search is performed from backward, the returned index is between 0 and fromIndex.
  • lastIndexOf(String str)
  • lastIndexOf(String str, int fromIndex)
jshell> "Java".lastIndexOf('a')
$55 ==> 3

jshell> "Java".lastIndexOf('a', 2)
$56 ==> 1

jshell> "Java".lastIndexOf("av")
$57 ==> 1

jshell> "Java".lastIndexOf("av", 3)
$58 ==> 1

11. substring() and subSequence()

The substring() method is used to create a substring from this string. The subSequence() also creates a substring and internally calls the substring() method.

jshell> String str = "Java String"
str ==> "Java String"

jshell> str.substring(5)
$60 ==> "String"

jshell> str.substring(5, 8)
$61 ==> "Str"

jshell> str.subSequence(5, 8)
$62 ==> "Str"

12. concat()

The concat() method concatenates this string with the given string and returns it.

jshell> "Java".concat("String")
$63 ==> "JavaString"

13. matches()

This method is used for regular expression pattern matching. If the string matches the given regex, it returns true.

jshell> String str = "Java"
str ==> "Java"

jshell> str.matches("^J.v.")
$67 ==> true

jshell> str.matches("\\D{4}")
$68 ==> true

14. replace(), replaceFirst(), and replaceAll()

These methods are used to replace part of the string with the given character or substring. There are four methods to replace string characters.

  1. replace(char oldChar, char newChar)
  2. replaceFirst(String regex, String replacement)
  3. replaceAll(String regex, String replacement)
  4. replace(CharSequence target, CharSequence replacement)

15. contains()

This method returns true if the string contains the given character sequence.

jshell> "Java".contains("av")
$69 ==> true

jshell> "Java".contains(new StringBuilder("Ja"))
$70 ==> true

16. split()

This method is used to split the string around the matches of the given regex. There are two variations of this method.

  1. split(String regex, int limit): The limit parameter defines the number of records in the result string array.
  2. split(String regex): returns the string array with all the substrings around the regex matches.

Recommended Reading: Java String split() Method

17. join()

This static method was added to the String class in Java 8 release. It is used to concatenate a group of strings with the given delimiter to form a new string. It’s very useful in creating CSV string from a list or array of strings.

jshell> String.join(",", "A", "B", "C");
$1 ==> "A,B,C"

Recommended Reading: Java String join() Method

18. toLowerCase() and toUpperCase()

These methods are used to create lowercase and uppercase strings from this string. There are overloaded methods to specify the Locale to be used for the conversion.

jshell> "Java".toUpperCase()
$71 ==> "JAVA"

jshell> "JavA".toLowerCase()
$72 ==> "java"

jshell> "Java".toUpperCase(Locale.US)
$73 ==> "JAVA"

jshell> "JavA".toLowerCase(Locale.UK)
$74 ==> "java"

19. trim(), strip(), stripLeading(), and stripTrailing()

The trim() method returns a new string after stripping all the leading and trailing whitespaces. This method considers any character whose codepoint is less than or equal to ‘U+0020’ as a whitespace character.

The strip() method was added to the String class in Java 11 release. This method uses Character.isWhitespace() method to remove leading and trailing whitespaces from a string. This is the recommended method to remove whitespaces from a string object.

The stripLeading() and stripTrailing() methods remove leading and trailing whitespaces respectively.

jshell> String str = "  \t Hi  \t"
str ==> "  \t Hi  \t"

jshell> str.trim()
$76 ==> "Hi"

jshell> str.strip()
$77 ==> "Hi"

jshell> str.stripLeading()
$78 ==> "Hi  \t"

jshell> str.stripTrailing()
$79 ==> "  \t Hi"

20. lines()

This method returns a stream of lines extracted from this string, separated by line terminators.

jshell> String str = "Hi\nHello\nYes\r\nNo\n";
str ==> "Hi\nHello\nYes\r\nNo\n"

jshell> List<String> lines = new ArrayList<>();
lines ==> []

jshell> str.lines().forEach(s -> lines.add(s));

jshell> System.out.println(lines);
[Hi, Hello, Yes, No]

Recommended Reading: Java String lines() Method

21. indent()

This method is used to indent every line in the string and normalize the newline characters. It was added to String API in Java 12 release. You can read more about it at Java String indent() Method Examples.

22. transform()

This method is used to apply a function to this string. The function should accept a single string argument and return an object. Some of the real-world usage are to create a list of strings from a CSV string and transforming a string to a list of objects.

Recommended Reading: Java String transform() Method

23. format()

Java String format() method returns a formatted string using the given format and the arguments. It’s inspired by the C language sprintf() method.

Recommended Reading: Java String format() Method Examples

24. intern()

This method returns the canonical representation of the string. It’s a native method. When a string is created using new operator, it gets created outside the string pool. The intern() method moves the string to the pool and returns the reference.

Recommended Reading: Java String intern() Method

25. valueOf() and copyValueOf()

Java String valueOf() method is used to get the string representation of the argument. There are various overloaded valueOf() methods that accept primitive data types, char array, and object. The String valueOf() methods are static. You can read more about them at Java String valueOf() Method Examples.

26. repeat()

Java String repeat() method returns a new string whose value is the concatenation of this string given number of times.

27. describeConstable() and resolveConstantDesc()

These methods are added to support Constants’ API for the String class. These methods were added to the String class in Java 12 release.

jshell> String s = "Hi"
s ==> "Hi"

jshell> s.describeConstable()
$85 ==> Optional[Hi]

jshell> import java.lang.invoke.MethodHandles;

jshell> s.resolveConstantDesc(MethodHandles.lookup());
$87 ==> "Hi"

Reference: Java 13 String API Docs