I need to parse string hex value to the Integer value. Like this:
String hex = "2A"; //The answer is 42
int intValue = Integer.parseInt(hex, 16);
But when I insert an incorrect hex value (for example “LL”) then I get java.lang.NumberFormatException: For input string: "LL" How I can avoid it (for example return 0)?
Just catch the exception and set the default value. However, you need to declare the variable outside the
tryblock.If you need to set the value using an initializer expression (say, for a
finalvariable), you’ll have to package up the logic in a method: