static Number parse(String s) { if (s == null || s.trim().length() == 0) { return 0; } return Long.parseLong(s); } This piece of code intermittently throws java.lang.NumberFormatException: For input string: "".
Running on Java version 11.0.20+8-LTS-sapmachine.
How is empty string passed into parseLong? I understand s.trim() and s are different instances but doesn't s.trim().length() != 0 infer s is non-empty?
UPDATE: Apologies, I had left out the fact that I am parsing with a DecimalFormat instance (naively thought it did not matter).
static java.text.DecimalFormat df = new java.text.DecimalFormat("#"); static Number parse(String s) throws java.text.ParseException { if (s == null || s.trim().length() == 0) { return 0; } return df.parse(s); } This code throws java.lang.NumberFormatException: For input string: "" from time to time on a live server. Stack trace:
java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Long.parseLong(Long.java:702) at java.lang.Long.parseLong(Long.java:817) at java.text.DigitList.getLong(DigitList.java:195) at java.text.DecimalFormat.parse(DecimalFormat.java:2121) at java.text.NumberFormat.parse(NumberFormat.java:429)
swhen this error is thrown?""); if I pass the empty string toparse, I correctly get0. Just because a string renders like the empty string does not mean that it is the empty string; it may contain invisible zero-width Unicode characters (such as a zero-width space), whichtrimdoesn't trim.sthat caused it. It's fairly likely that what you think is happening is not really.System.out.println(s.length());right before you call Long.parseLong. That will tell us whether your string is really empty.