How to convert String to int in Java

Previous
Next

In this article, we are going to see how we can convert from a String data type into integer data type in Java.

Conversion Modes

There are two ways in which String data can be converted into integer. They are:

  • Using the static method parseInt(String) of the java.lang.Integer wrapper class
  • Using the static method valueOf(String) of the java.lang.Integer wrapper class
  • Using the constructor of Integer wrapper class that takes String as its parameter

Let us see both the modes and how to do them.

parseInt(String) method

The class java.lang.Integer has a static method called parseInt(String) that allows the programmer to easily convert a String containing integer type data(i.e. numbers with no decimal points or post decimal values) into the corresponding Integer value. The function returns a value of primitive ‘int’ type.

Let us see a code snippet to illustrate the same:

The above code on execution provides the following output:

45

What if String is not convertible to int

If String is not convertible to int, you will get below exception.

Exception in thread “main” java.lang.NumberFormatException: For input string: “45.1”
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.valueOf(Integer.java:983)
at org.arpit.java2blog.java8.ConvertStringToInteger.main(ConvertStringToInteger.java:8)

Using valueOf(String) method

You can also use valueOf(String) method to convert String to int in java. You can call Integer’s intValue() to convert it to primitive type.

The above code on execution provides the following output:

45

Using the Integer class constructor

The other method to convert to Integer is by using the parameterized constructor of java.lang.Integer class that accepts a String as a parameter input. This creates an object of the Integer class that stores the value of the String data sent as Integer, and can be accessed using its intValue() function or by accessing the wrapper class object itself.

Let us see the code snippet:

The above code on execution provides the following output:

45

That’s all about String to Integer conversion.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog