Java – Integer.parseInt does not parse String to int

javatype-conversion

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){
  if(uploadItem.isFormField()){
    String fieldName = uploadItem.getFieldName();
    String fieldValue = uploadItem.getString();
    if(fieldName.equals("business_id")){
        out.println("BizStr: "+ fieldValue +"\n");
        out.println("BizInt: "+ Integer.parseInt(fieldValue )+"\n");
    }
  }
}

Why is this string not being parsed into integer?

Best Solution

Testing:

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");