How do I Convert A String To An Integer In Java?

In this Tutorial, we will learn How to convert a String to an int in Java? We can convert a string into an integer in two ways one by parsing and the other by getting the value from the string.

String To An Integer

Ways To Convert A String To An Integer

There are two ways to convert a String to integers so we will discuss both of them in detail and understand to use them in the future.

Integer.parseInt()

It is a way to convert a String to an integer. It is a method that can be used to convert a string in any of the primitive data types like float, decimals, etc. simply by putting the data type before and after the word .parse for example

for float Float.parseFloat() and similarly for decimals also Decimal.parseDecimal(). Let us take an example and understand it better.

String str = "25";
        try{
            int number = Integer.parseInt(str);
            System.out.println(number); // output = 25
        }
        catch (NumberFormatException ex){
            ex.printStackTrace();
        }

Here we can see we have taken the input as a string and then converted it to integers and then printed it. we used parse to convert it.

Integer.valueOf()

It is also a way to convert a string to an integer In this we directly extract the integer from the string. for making some calculations on them.

Let’s take an example to understand this method and get a clear idea of how does work and how to use it.

String str = "25";
        try{
            Integer number = Integer.valueOf(str);
            System.out.println(number); // output = 25
        }
        catch (NumberFormatException ex){
            ex.printStackTrace();
        }

In the above example, we have to take the input as a string and then converted it into integers using Integer.valueOf() and then printed using consol.

 

To learn more about How to I Convert A String To An Integer In Java? at: convert String to Integer

And also visit Java Tutorials By Prakhar YadavTo to get the list of solutions of java and have a look at Python’s list: What is the difference Between methods Append and Extend? for other python related problems.

Leave a Comment

%d bloggers like this: