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)