Substrings and Platform Independent new line Separator


Substrings

String text = "Let's learn programming";
String part1 = text.substring(5); // " learn programming"
String part2 = text.substring(5, 10); // "learn"
String part3 = text.substring(5, part2.length() - 3); // "lea"

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 = "2023年08月05日";
dateString = dateString.substring(0, 4) + "-" + dateString.substring(5, 7) + "-" +
            dateString.substring(8, 10);
// Result will be 2023-08-05

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.

Version < 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.

Version ≥ 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.


Platform independent new line separator


Since the new line separator varies from platform to platform (e.g. \n on Unix-like systems or \r\n on Windows) it is often necessary to have a platform-independent way of accessing it. In Java it can be retrieved from a system property:

System.getProperty("line.separator")

Version ≥ Java SE 7

Because the new line separator is so commonly needed, from Java 7 on a shortcut method returning exactly the same result as the code above is available:

System.lineSeparator()

Note : Since it is very unlikely that the new line separator changes during the program's execution, it is a good idea to store it in in a static final variable instead of retrieving it from the system property every time it is needed.

When using String.format, use %n rather than \n or '\r\n' to output a platform independent new line separator.

System.out.println(String.format('line 1: %s.%nline 2: %s%n', lines[0],lines[1]));

Basic Programs