How to Convert String to int in Java

Channel: Linux
Abstract: NumberFormatException exception will occur. class ConvertStringToInt3 { public static void main(String args[]) { String id = "5abc"} } }12345678910111

Java is an object orientied programming languege. In Java you can use Integer.parseInt() or Integer.valueOf() functions to convert String value to an int value. In any case String is not a convertible then NumberFormatException will occur.

#1. Using Integer.parseInt()

Integer.parseInt() converts string value and returns an int primitive as result. For below example, first, we store 5 as a string value to id variable. Then convert it to integer and save to result variable.

class ConvertStringToInt1 { public static void main(String args[]){ String id = "5"; int result = Integer.parseInt(id); System.out.println(result); } }123456789class ConvertStringToInt1 {  public static void main(String args[]){ String id = "5"; int result = Integer.parseInt(id); System.out.println(result); }}

Save the above content in ConvsertStringToInt1.java file and compile and run this program.

Compile:

javac ConvertStringToInt1.java

Run:

java ConvertStringToInt1

5
#2. Using Integer.valueOf()

Integer.valueOf() also uses Integer.parseInt function in backend but in result, it provides and Integer object value.

class ConvertStringToInt2 { public static void main(String args[]){ String id = "5"; Integer result = Integer.valueOf(id); System.out.println(result); } }123456789class ConvertStringToInt2 {  public static void main(String args[]){ String id = "5"; Integer result = Integer.valueOf(id); System.out.println(result); }}

Save the above content in ConvsertStringToInt2.java file and compile and run this program.

Compile:

javac ConvertStringToInt2.java

Run:

java ConvertStringToInt2

5
#3. Exception in Conversion

If the given input is not parsable by the any of the above methods, NumberFormatException will be thrown. As in the below example, we are storing string」5abc」 in id variable which contains alphabets. If we try to convert this number to int, NumberFormatException exception will occur.

class ConvertStringToInt3 { public static void main(String args[]) { String id = "5abc"; try{ int result = Integer.parseInt(id); System.out.println(result); }catch(NumberFormatException e){ System.out.println(e); } } }1234567891011121314class ConvertStringToInt3 {  public static void main(String args[]) { String id = "5abc"; try{ int result = Integer.parseInt(id); System.out.println(result); }catch(NumberFormatException e){ System.out.println(e); } }}

Save the above content in ConvsertStringToInt3.java file and compile and run this program.

Compile:

javac ConvertStringToInt3.java

Run:

java ConvertStringToInt3

java.lang.NumberFormatException: For input string: "5abc"

Reference:

http://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html

Ref From: tecadmin
Channels: stringJavaint

Related articles