How to convert String to int in Java

When converting from String to int, it is important that the string contains a valid integer value. While converting from int to string, is relatively easy, some things can be done wrong in the opposite direction.

Convert String to simple int

The Integer class contains a static method that can be used to do just that: Integer.parseInt(String s). The method takes a string that consists only of digits. Only a plus or minus sign is allowed at the beginning.

Integer.parseInt("");       // Error - no numbers
Integer.parseInt("5");      // correct
Integer.parseInt("-5");     // correct
Integer.parseInt("+5");     // correct
Integer.parseInt(" 5");     // Error - Space
Integer.parseInt("5.5");    // Error - point not allowed
Integer.parseInt("5,5");    // Error - comma not allowed
Integer.parseInt("5_000");  // Error - Separator not allowed

A string containing illegal characters throws a java.lang.NumberFormatException. Please note that neither separators nor spaces are allowed.

java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More
Convert String to Integer object

To convert a string into an object of the Integer class, there is the static method Integer.valueOf(String s):

Integer i = Integer.valueOf("1");

Of course, the result of Integer.parseInt() can also simply be assigned to an Integer object using autoboxing:

Integer i = Integer.parseInt("1");
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *