Convert String to int in java

 Posted On  | Yashwant Chavan 

This tutorial you will learn how to convert String to int using java API's.

Integer.parseInt(String s)

Parses the string argument as a signed decimal integer. throws NumberFormatException if the string does not contain a parsable integer.

String str = "200";
int number = Integer.parseInt(str);
System.out.println(number);

Integer.valueOf(String s)

Returns an Integer object holding the value of the specified String. The argument is interpreted as representing a signed decimal integer. throws NumberFormatException if the string does not contain a parsable integer.

String str = "200";
number = Integer.valueOf(str);
System.out.println(number);

java.lang.NumberFormatException

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.100f is non parsable integer value, So it will throw "NumberFormatException" exception.

String wrongValue = "100f"; 
number = Integer.valueOf(wrongValue);
System.out.println(number);

output

Exception in thread "main" java.lang.NumberFormatException: For input string: "100f"
 at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
 at java.lang.Integer.parseInt(Integer.java:580)
 at java.lang.Integer.valueOf(Integer.java:766)
 at com.technicalkeeda.app.StringToIntExample.main(StringToIntExample.java:15)

Full Example - String to int conversion Example

package com.technicalkeeda.app;

public class StringToIntExample {
    public static void main(String args[]) {
        String str = "200";
        int number = Integer.parseInt(str);
        System.out.println(number);


        number = Integer.valueOf(str);
        System.out.println(number);

        String wrongValue = "100f";

        number = Integer.valueOf(wrongValue);
        System.out.println(number);

    }
}

output

200
200
Exception in thread "main" java.lang.NumberFormatException: For input string: "100f"
 at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
 at java.lang.Integer.parseInt(Integer.java:580)
 at java.lang.Integer.valueOf(Integer.java:766)
 at com.technicalkeeda.app.StringToIntExample.main(StringToIntExample.java:15)


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0331 seconds.