Java – Integer.parseInt does not parse String to int


The code below is from a Servlet trying to read data from a submitted html form. The variable fieldValue is a String and prints correct value (like so BizStr: 5) but when I try to parse this value to integer, it does not print anything.

for(FileItem uploadItem : uploadItems){
    String fieldName = uploadItem.getFieldName();
    String fieldValue = uploadItem.getString();
        out.println("BizStr: "+ fieldValue +"\n");
        out.println("BizInt: "+ Integer.parseInt(fieldValue )+"\n");

Why is this string not being parsed into integer?

Best Solution


Integer.parseInt(" 5");  // space before; yields NumberFormatException

Integer.parseInt("5 ");  // space after; yields NumberFormatException

Try trim() on the fieldValue before parsing:

out.println("BizInt: "+ Integer.parseInt(fieldValue.trim() )+"\n");