Blog Archive

Java convert String to Int example

Use Integer.parseInt method. It is extremely easy and most flexible way of converting String to Integer. Here is an example of string to int conversion...
package com.as400samplecode;

public class ConvertStringtoInteger {

    public static void main(String[] args) {

        String myString = "400";

        try
        {
            int myInteger = Integer.parseInt(myString);
            System.out.println(myInteger);
        }
        catch (NumberFormatException e){ 
            e.printStackTrace();
        } 

    }

}

Another way to convert String to Int is using the static method ValueOf(string)


Returns an Integer object holding the value of the specified String. The argument is interpreted as representing a signed decimal integer, exactly as if the argument were given to the parseInt(java.lang.String) method. The result is an Integer object that represents the integer value specified by the string.

In other words, this method returns an Integer object equal to the value of:
new Integer(Integer.parseInt(s))

No comments :

Post a Comment