Handy Java 11 to 17 additions
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Between Java 11 and Java 17, many small methods were added to classes you already use, such as String, Files and the collections. Each one replaces a few lines of old helper code, and helpful NullPointerException messages (Java 14) tell you exactly which value was null.
String methods: isBlank, strip, repeat and lines (Java 11)
Form input is messy: extra spaces, empty answers, text pasted from a phone. Java 11 added four String methods for this kind of cleanup.
Example 1 · Cleaning form input with isBlank, strip, repeat and lines
import java.util.List;
public class StringAdditionsDemo { public static void main(String[] args) { String spaces = " "; System.out.println("isEmpty: " + spaces.isEmpty() + ", isBlank: " + spaces.isBlank());
String pasted = "\u2003 Asha Verma \u2003"; System.out.println("length " + pasted.length() + ", after trim " + pasted.trim().length() + ", after strip " + pasted.strip().length()); System.out.println("strip: [" + pasted.strip() + "]"); System.out.println("stripLeading: [" + " Pune ".stripLeading() + "]");
System.out.println("=".repeat(24)); String address = "Flat 4B, Lake View\nMG Road\nBengaluru 560001"; System.out.println("Address lines: " + address.lines().count()); address.lines().map(line -> " " + line).forEach(System.out::println); System.out.println("=".repeat(24));
List<String> answers = List.of("Yes", " ", "", "No"); long filled = answers.stream().filter(a -> !a.isBlank()).count(); System.out.println("Filled answers: " + filled + " of " + answers.size()); }}isEmpty: false, isBlank: true length 14, after trim 14, after strip 10 strip: [Asha Verma] stripLeading: [Pune ] ======================== Address lines: 3 Flat 4B, Lake View MG Road Bengaluru 560001 ======================== Filled answers: 2 of 4
What this code does
\u2003is a wide Unicode space.trim()does not treat it as whitespace, so it stays;strip()removes it.isBlank()sees a string of spaces as empty input, whichisEmpty()does not.repeatdraws the divider, andlines()gives a stream of lines, so counting and indenting them takes one line each.
" ".isBlank()→true;" ".isEmpty()→false"\u2003Asha\u2003".strip()→Asha;trim()leaves the wide spaces"=".repeat(5)→=====address.lines().count()→ number of lines
isBlank() is true when a string is empty or only whitespace, so " ".isBlank() is true while " ".isEmpty() is false. strip() removes whitespace from both ends, like trim(), but it understands Unicode whitespace, such as the wide spaces some keyboards and websites insert. trim() only removes characters up to the plain space. stripLeading() and stripTrailing() work on one end. repeat(n) repeats a string, which is handy for divider lines: "-".repeat(30). lines() splits text at line breaks and returns a stream of lines, so you can count, filter or map them.
Helpful NullPointerException messages (Java 14)
Before Java 14, a crash in student.address().city().length() said only NullPointerException and a line number. Any of three values could have been null, and you had to guess which.
- Read the action:
Cannot invoke "Address.city()"means a call tocity()failed. - Read the cause:
because the return value of "Student.address()" is null. - Go to the code that created that object and find why
addresswas never set. - Fix the cause (set the value, or handle the missing case), not only the crash line.
Example 2 · Reading a helpful NullPointerException message
record Address(String city, int pin) { }
record Student(String name, Address address) { }
public class HelpfulNpeDemo { static String[] hostelRooms = {"A-12", null, "C-7"};
static String cityCode(Student s) { return s.address().city().substring(0, 3).toUpperCase(); }
public static void main(String[] args) { Student ravi = new Student("Ravi", new Address("Chennai", 600001)); Student meena = new Student("Meena", null); System.out.println(ravi.name() + ": " + cityCode(ravi));
try { System.out.println(meena.name() + ": " + cityCode(meena)); } catch (NullPointerException e) { System.out.println("Error: " + e.getMessage()); }
try { System.out.println("Room 2 block: " + hostelRooms[1].charAt(0)); } catch (NullPointerException e) { System.out.println("Error: " + e.getMessage()); } }}Ravi: CHE Error: Cannot invoke "Address.city()" because the return value of "Student.address()" is null Error: Cannot invoke "String.charAt(int)" because "HelpfulNpeDemo.hostelRooms[1]" is null
What this code does
- The first message says Java tried to call
city(), and the value it was called on was the result ofStudent.address(). So Meena's address is the missing piece, not her name or her city. - For an array element, the message names the exact slot:
hostelRooms[1]. Normally you would let the exception show in the console; here it is caught only so the program can print the message and continue.
Since Java 14, and switched on by default since Java 15, the message names the exact part that failed: Cannot invoke "Address.city()" because the return value of "Student.address()" is null. Read it in two halves. The first half says what Java tried to do (call city()). The second half says which value was null (the result of address()). The message names fields, array elements and method results. For local variables, it shows the real name only when the class was compiled with debug information, which IDEs do by default; otherwise you see a placeholder like "<local4>".
Collection.toArray(String[]::new) and Files.readString (Java 11)
Some older APIs still want arrays. Converting a list used to need list.toArray(new String[0]) or new String[list.size()]. Java 11 added toArray(String[]::new): you pass a method reference to the array constructor, and the collection creates an array of the right type and size.
Example 3 · toArray(String[]::new) and other one-liners
import java.util.Arrays;import java.util.List;import java.util.Optional;import java.util.function.Predicate;
public class SmallApiAdditionsDemo { public static void main(String[] args) { List<String> subjects = List.of("Maths", " ", "Physics", "", "Chemistry");
// Java 16 toList, Java 11 Predicate.not List<String> real = subjects.stream() .filter(Predicate.not(String::isBlank)) .toList(); System.out.println("Subjects: " + real);
// Java 11 toArray with an array constructor reference String[] asArray = real.toArray(String[]::new); System.out.println("Array: " + Arrays.toString(asArray) + ", length " + asArray.length);
// Java 11 Optional.isEmpty Optional<String> lab = real.stream().filter(s -> s.startsWith("Bio")).findFirst(); System.out.println("Biology lab missing: " + lab.isEmpty()); }}Subjects: [Maths, Physics, Chemistry] Array: [Maths, Physics, Chemistry], length 3 Biology lab missing: true
What this code does
toArray(String[]::new)creates aString[]of exactly the right size; the old forms needednew String[0]ornew String[list.size()].Predicate.not(String::isBlank)reads better thans -> !s.isBlank()in a long chain.toList()returns an unmodifiable list, andisEmpty()is the opposite ofisPresent().
Example 4 · Files.writeString and Files.readString
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class FilesStringDemo { public static void main(String[] args) throws IOException { Path notice = Files.createTempFile("notice", ".txt");
String text = """ Holiday on 2 October. Lab exams start on 6 October. Bring your ID card. """; Files.writeString(notice, text);
String back = Files.readString(notice); System.out.print(back); System.out.println("Same as written: " + back.equals(text)); System.out.println("Lines: " + back.lines().count() + ", characters: " + back.length());
Files.delete(notice); System.out.println("File deleted: " + Files.notExists(notice)); }}Holiday on 2 October. Lab exams start on 6 October. Bring your ID card. Same as written: true Lines: 3, characters: 72 File deleted: true
What this code does
Files.writeStringwrites the whole text in one call andFiles.readStringreads it back as oneString, both in UTF-8. There is no reader, loop orStringBuilder.- Both methods can fail, for example if the disk is full, so they throw the checked
IOException; heremaindeclares it. A temporary file keeps the example from leaving files behind.
Reading a small text file used to mean a BufferedReader, a loop and a StringBuilder. Java 11 added Files.readString(path) and Files.writeString(path, text), which read or write the whole file in one call, using UTF-8 by default. Path.of("notice.txt") (also Java 11) builds the path. Both methods throw IOException, which you must handle or declare. A few more one-liners from the same years are worth knowing: stream.toList() (Java 16) instead of collect(Collectors.toList()), Optional.isEmpty() (Java 11), and Predicate.not(...) (Java 11) for filters like filter(Predicate.not(String::isBlank)).
Files.readString loads the whole file into memory. It is right for config files and small notes; for a large log file, read it line by line with Files.lines.Reading release notes to find what changed
Java now ships a new version every six months, and every few years one is a long-term support (LTS) release that gets updates for years: 11, 17 and 21 so far.
java -versionjavac -versionjavac --release 17 Main.java- Check your version:
java -versionandjavac -version(they should match). - Open the release notes for the versions between yours and the target.
- Look for "New Features", "Removed Features" and "Deprecated" sections.
- Open the JEP of any feature you want to use to see its exact rules.
- Note whether it is standard or still a preview in your version.
- Compile with
--release 17(or your target) to catch use of newer APIs.
Companies usually run an LTS, so it helps to know which features belong to which version.
Each release has official release notes listing new features, removed features and changed behaviour. Each larger feature also has a JEP (JDK Enhancement Proposal), a numbered document that explains what it does and why. Some features first appear as a preview: usable only with the --enable-preview flag, and possibly changed before they become standard.
Next step
Check your understanding
12 quick questions