Java Convert String to int

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

Integer.parseInt() and Integer.valueOf() methods can be used to convert String to integer in Java. These methods are defined under the Integer class in java.lang package.

The Integer.parseInt() method converts String to int (primitive data type) in Java. However, the Integer.valueOf() method can be used to convert String to an instance of the Integer class in Java. Both methods throw NumberFormatException when the String input contains characters other than digits.

Convert String to Integer in Java

Convert String to int in Java: Integer.parseInt()

The parseInt() method converts a String to a primitive (basic) data type, i.e., int in Java. The parseInt() method is a static Integer class method.

Signature

Syntax

Example

Output:

Convert string to int in java

Convert String to int in Java: Integer.valueOf()

Integer.valueOf() method returns the Integer object when a string literal is passed as an argument. It takes in the string or an integer as a first argument and converts it into an Integer object. This works the same as parseInt() and changes a string to an integer in Java for the radix argument.

Syntax

Example

Output:

Convert string to integer java

NumberFormatException Case

While converting string to integer in Java using the above method, If the string literal provided as an argument is ill-formatted, i.e., contains characters other than numerics, NumberFormatException is thrown. The Integer.parseInt() and Integer.valueOf() throw NumberFormatException when the string input contains invalid characters.

Code:

Output:

Important Points

  • The presence of leading zeroes in the string will not be counted using the parseInt() or the valueOf() method.
  • The first character, ‘+’ or ‘-’, indicates the sign of the number, which is accepted by both methods of changing the String to int in Java.

Code:

Output:

Conclusion

  • Integer.parseInt() converts a String to an int primitive data type, while Integer.valueOf() converts it to an Integer object.
  • Both methods throw a NumberFormatException if the input String is null, empty, or contains non-numeric characters.
  • Overloaded versions of both methods allow specifying the radix (base) of the String representation for conversion, which is useful for parsing strings representing numbers in non-decimal bases like binary or hexadecimal.