How to convert String to Int in Java ?

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.

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.