How to convert String to int in Java

  • 23 November 2020
  • ADM

 

How to convert String to int in Java - images/logos/java.jpg

 

To convert a string to int in Java you have two simple options using the static methods from Integer class:

  • Integer.parseInt(String s): returns a primitive int value;
  • Integer.valueOf(String s): returns an Integer object.

Ignoring any of the exceptions that can be thrown, all you need to do to convert a String to int is, use one of this lines of code to get a primitive int

int val1 = Integer.parseInt(value);
int val2 = Integer.valueOf(value);

or

Integer obj = Integer.valueOf(value);

to get an Integer object.

Note: even if the valueOf method is returning an Integer object you can use the primitive int because the boxing and unboxing will be done automatically.

Example

package com.admfactory;

public class IntConverter {

    public static void main(String[] args) {
	String value = "100";
	/** Use the value to see the exceptions */
	//String value = "number";

	try {
	    int val1 = Integer.parseInt(value);
	    System.out.println("val1: " + val1);
	} catch (NumberFormatException e) {
	    e.printStackTrace();
	}

	try {
	    int val2 = Integer.valueOf(value);
	    System.out.println("val2: " + val2);
	} catch (NumberFormatException e) {
	    e.printStackTrace();
	}

	try {
	    Integer obj = Integer.valueOf(value);
	    System.out.println("obj:  " + obj);
	} catch (NumberFormatException e) {
	    e.printStackTrace();
	}
    }
}

Output

If the value string is a valid integer like "1", "2", and so on, it will be converted to a Java primitive int with no problem. The output for this will be:

val1: 100
val2: 100
obj:  100

otherwise, if it fails for any reason, the conversion can throw a NumberFormatException, so to capture and deal with the possible error the code needs to be used in try/catch block as shown in the example. The output for this case will be:

java.lang.NumberFormatException: For input string: "number"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:492)
	at java.lang.Integer.parseInt(Integer.java:527)
	at com.admfactory.xml.IntLongConverter.main(IntLongConverter.java:10)

 

References