Categories
java

String to int in java

String to int in java

Converting string to int in java is frequently used by java developers,
In this example we will learn how to convert from string to int using java

Syntax

Integer.parseInt("100");
Integer.valueOf("1000");

Example using parseInt method

public class StringToIntExample {
	public static void main(String[] args) {
		try {
			String s = "100";
			// Below line will convert string to int using parseInt
			int numberValue = Integer.parseInt(s);
			System.out.println("Printing integer value " + numberValue);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output

Printing integer value 100

Example using valueOf method

public class StringToIntExample {
	public static void main(String[] args) {
		try {
			String s = "222";
			// Below line will convert string to int using valueOf
			int numberValue = Integer.valueOf(s);
			System.out.println("Printing integer value " + numberValue);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output

Printing integer value 222

Exception

java.lang.NumberFormatException: For input string:
we have a possible to get above exception when a string have alphabets in it

Example for Exception

public class StringToIntExample {
	public static void main(String[] args) {
		try {
			// In below string we have alphabets so we cannot convert it to int
			String s = "222A";
			// Below line will convert string to int using valueOf
			int numberValue = Integer.valueOf(s);
			System.out.println("Printing integer value " + numberValue);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output

java.lang.NumberFormatException: For input string: "222A"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)
at com.geeks.overloading.StringToIntExample.main(StringToIntExample.java:9)
Reference

https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#valueOf(java.lang.String)

Leave a Reply

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