Java String Methods

String is one of the most common data type in most of programming language. String can be described as a sequence of characters. In Java's object-oriented world, a String is an object that represents a sequence of characters. The java.lang.String class is used to create String object. This article will list down several common methods in String class - based on JDK 8, with sample on how to use those methods.

charAt()

String str = "Programming With Java";
System.out.printf("\"%s\" char at 12: %s%n", str, str.charAt(12));
                    

"Programming With Java" char at 12: W

compareTo() and compareToIgnoreCase()

String class implements Comparable interface, which provides methods:

Both compares two strings lexicographically, based on the Unicode value of each character in the strings, that will return:

  • if String1 > String2, it returns a positive number
  • if String1 < String2, it returns a negative number
  • if String1 == String2, it returns 0
String str1 = "java";
String str2 = "java";
String str3 = "Java";
String str4 = "lava";
System.out.println(str1.compareTo(str2));  //  0 -> both are equal
System.out.println(str1.compareTo(str3));  // 32 -> "j" is 32 characters greater than "J" 
System.out.println(str1.compareTo(str4));  // -2 -> "j" is 2 characters lower than "l"

System.out.println("j: " + (int) 'j');  // j: 106
System.out.println("J: " + (int) 'J');  // J: 74
System.out.println("l: " + (int) 'l');  // l: 108

System.out.println(str1.compareToIgnoreCase(str2));  // 0 -> both are equal
System.out.println(str1.compareToIgnoreCase(str3));  // 0 -> equals since ignore case
System.out.println(str1.compareToIgnoreCase(str4));  // -2 -> "j" is 2 characters lower than "l"
                    

concat()

String str = "Programming";
System.out.println(str);
str = str.concat(" with");
System.out.println(str);
str = str.concat(" Java");
System.out.println(str);
                    

Programming
Programming with
Programming with Java

contains()

  • boolean contains(CharSequence s): Returns true if and only if this string contains the specified sequence of char values, otherwise returns false.
String str = "Programming with Java"; 
System.out.println(str.contains("with"));  // true
System.out.println(str.contains("java"));  // false - case sensitive
System.out.println(str.contains("ram"));   // true
                    

endsWith()

  • boolean endsWith(String suffix): Tests if this string ends with the specified suffix. If it's ends with the given suffix, it will return true else returns false.
String str = "Dariawan, Java Tutorials"; 
System.out.println(str.endsWith("s"));          // true
System.out.println(str.endsWith("Tutorials"));  // true   
System.out.println(str.endsWith("tutorials"));  // false - case sensitive
                    

equals() and equalsIgnoreCase()

Another String comparison methods:

String str1 = "Python";
String str2 = "Python";
String str3 = "python";
String str4 = "Jython";
System.out.println(str1.equals(str2));  // true -> both String are equal
System.out.println(str1.equals(str3));  // false
System.out.println(str1.equals(str4));  // false

System.out.println(str1.equalsIgnoreCase(str2));  // true -> both String are equal
System.out.println(str1.equalsIgnoreCase(str3));  // true -> case insensitive
System.out.println(str1.equalsIgnoreCase(str4));  // false
                    

format()

import java.util.Locale;

String str = "OutOfMemory";

// %s %d and %n is used to append the string
System.out.print(String.format("\"%s\" length: %d%n", str, str.length()));

// pi, the ratio of the circumference of a circle to its diameter
// using locale as Locale.US
System.out.println(String.format(Locale.US, "pi = %+10.9f", Math.PI));
// using locale as Locale.US
System.out.println(String.format(Locale.FRANCE, "pi = %+10.9f", Math.PI));

// The '(' numeric flag may be used to format negative numbers with
// parentheses rather than a minus sign.  Group separators are
// automatically inserted.
System.out.print(String.format("Balance: $ %(,.2f%n", 42304.6f));
System.out.print(String.format("Balance: $ %(,.2f%n", -134.257f));
                    

"OutOfMemory" length: 11
pi = +3.141592654
pi = +3,141592654
Balance: $ 42,304.60
Balance: $ (134.26)

As you can see "%n" resulted of new line.

getBytes()

  • byte[] getBytes(): Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
  • byte[] getBytes(Charset charset): Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.
  • byte[] getBytes(String charsetName): Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
byte[] arr1 = "I came".getBytes();
System.out.println(Arrays.toString(arr1));

byte[] arr2 = "I säw".getBytes(StandardCharsets.ISO_8859_1);
System.out.println(Arrays.toString(arr2));

try {
    byte[] arr3 = "I conquered".getBytes("UTF-8");
    System.out.println(Arrays.toString(arr3));
} catch (UnsupportedEncodingException ex) {
    System.out.println("UnsupportedEncodingException for UTF-8");
}
                    

[73, 32, 99, 97, 109, 101]
[73, 32, 115, -28, 119]
[73, 32, 99, 111, 110, 113, 117, 101, 114, 101, 100]

indexOf()

  • int indexOf(int ch): Returns the index within this string of the first occurrence of the specified character.
  • int indexOf(int ch, int fromIndex): Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
  • int indexOf(String str): Returns the index within this string of the first occurrence of the specified substring.
  • int indexOf(String str, int fromIndex): Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

If no such character occurs in this string, then -1 is returned.

String s = "Write programs that do one thing and do it well";
System.out.println(s.indexOf("do"));     // 20
System.out.println(s.indexOf("do", 30)); // 37
System.out.println(s.indexOf("code"));   // -1 -> not found
System.out.println(s.indexOf('e'));      // 4
System.out.println(s.indexOf('e', 20));  // 25
System.out.println(s.indexOf('e', 40));  // 44
System.out.println(s.indexOf('P', 40));  // -1 -> not found, 'p' case-sensitive
                    

intern()

  • String intern(): Returns a canonical representation for the string object.

When we create a String using string literal, it will be created in string pool, but when we create a String using "new" keyword, it will create the String object in the heap, even though the value is already exists in string pool. When intern() method is called in new String, it will check if there is already a String with the same value in the pool. If yes, then it returns the reference of that String object from the pool. If not, then it creates a new String with the value in the pool and returns the reference.

String str1 = "Do One Thing Well";
String str2 = "Do One Thing Well";
String str3 = new String("Do One Thing Well");

System.out.println(str1 == str2);  // true
System.out.println(str2 == str3);  // false

String str4 = str3.intern();
System.out.println(str1 == str4);  // true
System.out.println(str3 == str4);  // false
                    

isEmpty()

  • boolean isEmpty(): Returns true if, and only if, length() is 0.
String str1 = "Programming";
String str2 = " ";
String str3 = "";
String str4 = null;
System.out.println(str1.isEmpty());  // false
System.out.println(str2.isEmpty());  // false - length > 0
System.out.println(str3.isEmpty());  // true
System.out.println(str4.isEmpty());  // NullPointerException
                    

join()

import java.util.Arrays; import java.util.List;

List<String> ls = Arrays.asList(new String[]{"programming", "with", "java"});
System.out.println(String.join("-", ls));

System.out.println(String.join(" ", "Write", "once", "run", "anywhere"));
                    

programming-with-java
Write once run anywhere

lastIndexOf()

  • int lastIndexOf(int ch): Returns the index within this string of the last occurrence of the specified character.
  • int lastIndexOf(int ch, int fromIndex): Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
  • int lastIndexOf(String str): Returns the index within this string of the last occurrence of the specified substring.
  • int lastIndexOf(String str, int fromIndex): Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

The String is searched backwards starting at the last character. If no such character occurs in this string, then -1 is returned.

String s = "Write programs that do one thing and do it well";
System.out.println(s.lastIndexOf("do"));     // 37
System.out.println(s.lastIndexOf("do", 30)); // 20
System.out.println(s.lastIndexOf("do", 10)); // -1 -> not found
System.out.println(s.lastIndexOf('a'));      // 33
System.out.println(s.lastIndexOf('a', 20));  // 17
System.out.println(s.lastIndexOf('b'));      // -1 -> not found
                    

length()

  • int length(): Returns the length of this string.
String str1 = "Programming";
String str2 = "Programming With";
String str3 = "Programming With Java";
System.out.printf("String length: %d [%s]%n", str1.length(), str1);
System.out.printf("String length: %d [%s]%n", str2.length(), str2);
System.out.printf("String length: %d [%s]%n", str3.length(), str3);
                    

String length: 11 [Programming]
String length: 16 [Programming With]
String length: 21 [Programming With Java]

replace(), replaceAll(), and replaceFirst()

String str1 = "Winter Is Coming";
System.out.println(str1.replace(' ', '-'));
System.out.println(str1.replace("Winter", "Autumn"));
System.out.println(str1.replace("winter", "autumn"));  // no change - case-sensitive

String str2 = "In Xanadu did Kubla Khan\n" +
        "A stately pleasure-dome decree:\n" +
        "Where Alph, the sacred river, ran";
System.out.println(str2);
// replace new line with space
System.out.println(str2.replaceAll("\\n", " "));
// replace first new line with space
System.out.println(str2.replaceFirst("\\n", " "));

String str3 = "Game of Thrones";
// Only Replace first 'o' with 'i'
System.out.println(str3.replaceFirst("o", "i"));
                    

Winter-Is-Coming
Autumn Is Coming
Winter Is Coming
In Xanadu did Kubla Khan
A stately pleasure-dome decree:
Where Alph, the sacred river, ran
In Xanadu did Kubla Khan A stately pleasure-dome decree: Where Alph, the sacred river, ran
In Xanadu did Kubla Khan A stately pleasure-dome decree:
Where Alph, the sacred river, ran
Game if Thrones

The replace method will replace all occurrences of a char or CharSequence. On the other hand, both String arguments to replaceFirst and replaceAll are regular expressions (regex). Using the wrong function can lead to subtle bugs.

split()

import java.util.Arrays;

String str = "Write once run anywhere";
String[] arr1 = str.split(" ");
System.out.printf("Split with only regex: %s%n", Arrays.toString(arr1));

String[] arr2 = str.split(" ", 3);
System.out.printf("Split with regex and limit: %s%n", Arrays.toString(arr2));
                    

Split with only regex: [Write, once, run, anywhere]
Split with regex and limit: [Write, once, run anywhere]

startsWith()

String str = "Dariawan, Java Tutorials"; 
System.out.println(str.startsWith("D"));           // true
System.out.println(str.startsWith("J"));           // false
System.out.println(str.startsWith("J", 10));       // true
System.out.println(str.startsWith("Dariawan"));    // true   
System.out.println(str.startsWith("dariawan"));    // false - case sensitive
System.out.println(str.startsWith("ariawan", 1));  // true
System.out.println(str.startsWith("Java", 10));    // true
                    

substring()

String str = "dariawan.com, Java Tutorials with examples";
System.out.println(str.substring(14));
System.out.println(str.substring(14, 28));
                    

Java Tutorials with examples
Java Tutorials

toCharArray()

  • char[] toCharArray(): Converts this string to a new character array.
String str = "Core Java";
char[] arr = str.toCharArray();
System.out.println(Arrays.toString(arr));
                    

[C, o, r, e,  , J, a, v, a]

toLowerCase()

  • String toLowerCase(): Converts all of the characters in this String to lower case using the rules of the default locale.
  • String toLowerCase(Locale locale): Converts all of the characters in this String to lower case using the rules of the given Locale.
import java.util.Locale;

String str1 = "DARIAWAN.COM, Java Tutorials with examples";
System.out.println(str1.toLowerCase());

String str2 = "Süleymaniye Camii, İstanbul";
System.out.println(str2.toLowerCase());
System.out.println(str2.toLowerCase(new Locale("tr", "TR")));
                    

dariawan.com, java tutorials with examples
süleymaniye camii, i?stanbul
süleymaniye camii, istanbul

toLowerCase() and toUpperCase respects internationalization (i18n). It performs the case conversion with respect to your Locale. As example, when you call toLowerCase(), internally toLowerCase(Locale.getDefault()) is getting called. It is locale sensitive and you should not write a logic around it interpreting locale independently.

toUpperCase()

  • String toUpperCase(): Converts all of the characters in this String to upper case using the rules of the default locale.
  • String toUpperCase(Locale locale): Converts all of the characters in this String to upper case using the rules of the given Locale.
import java.util.Locale;

String str1 = "DARIAWAN.COM, Java Tutorials with examples";
System.out.println(str1.toUpperCase());

String str2 = "Phanàrion, İstanbul";
System.out.println(str2.toUpperCase());
System.out.println(str2.toUpperCase(new Locale("tr", "TR")));
                    

DARIAWAN.COM, JAVA TUTORIALS WITH EXAMPLES
PHANÀRION, ?STANBUL
PHANÀR?ON, ?STANBUL

trim()

  • String trim(): Returns a string whose value is this string, with any leading and trailing whitespace removed.
String str = "  Write once, run forever   ";
System.out.printf("[%s]%n", str);         // without trim()  
System.out.printf("[%s]%n", str.trim());  // with trim()
                    

[  Write once, run forever   ]
[Write once, run forever]

Check about strip(),stripLeading(), and stripTrailing() in Java 11 - New Methods in java.lang.String

valueOf()

import java.util.HashMap; import java.util.Map;

System.out.println(String.valueOf(false));
System.out.println(String.valueOf('L'));
System.out.println(String.valueOf(new char[] {'J', 'A', 'V', 'A'}));
System.out.println(String.valueOf(new char[] {'G', 'r', 'o', 'o', 'v', 'y'}, 1, 3));
System.out.println(String.valueOf(2.35d));
System.out.println(String.valueOf(3.14f));
System.out.println(String.valueOf(12));
System.out.println(String.valueOf(79l));

// Object will print based on toString()
Map map = new HashMap<String, String>();
map.put("KEY1", "Value1");
map.put("KEY2", "Value2");
System.out.println(String.valueOf(map));
                    

false
L
JAVA
roo
2.35
3.14
12
79
{KEY2=Value2, KEY1=Value1}