Bird
0
0

You want to safely parse a String input to an int in Java, returning -1 if the input is not a valid number. Which code snippet correctly implements this?

hard📝 Application Q15 of 15
Java - Command Line Arguments

You want to safely parse a String input to an int in Java, returning -1 if the input is not a valid number. Which code snippet correctly implements this?

Aint parseSafe(String s) { try { return Integer.parseInt(s); } catch (NumberFormatException e) { return -1; } }
Bint parseSafe(String s) { return Integer.parseInt(s); }
Cint parseSafe(String s) { if (s.matches("\\d+")) return Integer.parseInt(s); else return 0; }
Dint parseSafe(String s) { return Integer.valueOf(s); }
Step-by-Step Solution
Solution:
  1. Step 1: Understand safe parsing with exception handling

    Using try-catch around Integer.parseInt catches invalid input and returns fallback.
  2. Step 2: Check each option's behavior

    The snippet with try-catch returns parsed int or -1 on error. Snippets without proper handling throw exceptions, return 0 instead of -1, or use valueOf which returns an Integer object not int.
  3. Final Answer:

    The try-catch code returning -1 on NumberFormatException -> Option A
  4. Quick Check:

    Try-catch with -1 fallback handles invalid input [OK]
Quick Trick: Use try-catch to handle invalid input safely [OK]
Common Mistakes:
  • Not handling NumberFormatException
  • Returning wrong fallback value
  • Confusing Integer.valueOf with parseInt

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes