How to convert String to Int in Java ?

DeeKay January 20, 2017 at 3:25 am · JAVA API

To convert String to Int in Java, you can use the below methods of Integer class.

Methods to convert String to Int

1) Integer.parseInt() code example


/**
 * Created on Nov 19, 2016 Copyright(c) https://kodehelp.com All Rights Reserved.
 */
package com.kodehelp.java.lang;

/**
 * @author https://kodehelp.com
 */
public class ConvertStringToInt {

    public static void main(String args[]){

        String strNumber = "12345";
        int number = Integer.parseInt(strNumber);
        System.out.println(number);
    }
}

2) Integer.valueOf() code example

Other way to convert String to Int is to use Integer.valueOf() method. This method will return Integer object from which you can get int value by calling it’s intValue() method.

 


/**
 * Created on Nov 19, 2016 Copyright(c) https://kodehelp.com All Rights Reserved.
 */
package com.kodehelp.java.lang;

/**
 * @author https://kodehelp.com
 */
public class ConvertStringToInt {

    public static void main(String args[]){

        String strNumber = "12345";
        Integer numberObject = Integer.valueOf(strNumber);
        System.out.println(numberObject.intValue());
    }
}

 

Note: If the string does not contain a parsable integer, a NumberFormatException will be thrown.