Download java eBook


String s = "this is an example";
String a = s.substring(11); // a will hold the string starting at character 11 until the end ("example")
String b = s.substring(5, 10); // b will hold the string starting at character 5 and ending right before character 10 ("is an")
String b = s.substring(5, b.length()-3); // b will hold the string starting at character 5 ending right before b' s lenght is out of 3  ("is an exam")

Substrings may also be applied to slice and add/replace character into its original String. For instance, you faced a Chinese date containing Chinese characters but you want to store it as a well format Date String.

String datestring = "2015年11月17日"
datestring = datestring.substring(0, 4) + "-" + datestring.substring(5,7) + "-" + datestring.substring(8,10);
//Result will be 2015-11-17

The substring method extracts a piece of a String. When provided one parameter, the parameter is the start and the piece extends until the end of the String. When given two parameters, the first parameter is the starting character and the second parameter is the index of the character right after the end (the character at the index is not included). An easy way to check is the subtraction of the first parameter from the second should yield the expected length of the string.

Java SE 7

In JDK <7u6 versions the substring method instantiates a String that shares the same backing char[] as the original String and has the internal offset and count fields set to the result start and length. Such sharing may cause memory leaks, that can be prevented by calling new String(s.substring(...)) to force creation of a copy, after which the char[] can be garbage collected.

Java SE 7

From JDK 7u6 the substring method always copies the entire underlying char[] array, making the complexity linear compared to the previous constant one but guaranteeing the absence of memory leaks at the same time.


Contributors: 8
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial:

Download eBook