Preserve empty fields in an order record in Java

A negative split limit retains a trailing empty field. This matters when an optional field has a defined position, even when the sender leaves it blank.

A simple example

Split with trailing fields retained

  1. Start with A comma after A
  2. Do this Split with trailing fields retained
  3. Result A and an empty field
The delimiter creates a second field even though nothing follows it.

Apply it to a real problem

  1. Start with Order A42 with quantity 2 and a blank final field
  2. Do this Split at each vertical bar
  3. Result Three columns
Preserving the last field keeps the row aligned with its three-column layout.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) throws Exception {
        String line = "A42|2|";
        System.out.println(Arrays.toString(line.split("\\|", -1)));
        System.out.println(line.split("\\|", -1).length + " columns");
    }
}
Output
[A42, 2, ]
3 columns

Official Java documentation