Java – Convert String to int - LearnHowToCode SarkariResult.com Interview Questions and Answers LearnHowToCodeOnline
Java

Java – Convert String to int


In Java, you can use Integer.parseInt() to convert a String to int.
1. Integer.parseInt() Examples
Example to convert a String “10” to an primitive int.


String number = "10";
int result = Integer.parseInt(number);
System.out.println(result);
Output
10
2. Integer.valueOf() Examples
Alternatively, you can use Integer.valueOf(), it will returns an Integer object.
String number = "10";
Integer result = Integer.valueOf(number);
System.out.println(result);
Output
10
Note
In summary, parseInt(String) returns a primitive int, whereas valueOf(String) returns a new Integer() object.

3. NumberFormatException

If the string does not contain a parsable integer, a NumberFormatException will be thrown.
String number = "10A";
int result = Integer.parseInt(number);
System.out.println(result);
Output
Exception in thread "main" java.lang.NumberFormatException: For input string: "10A"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)

About Mariano

I'm Ethan Mariano a software engineer by profession and reader/writter by passion.I have good understanding and knowledge of AngularJS, Database, javascript, web development, digital marketing and exploring other technologies related to Software development.

0 comments:

Featured post

Political Full Forms List

Acronym Full Form MLA Member of Legislative Assembly RSS Really Simple Syndication, Rashtriya Swayamsevak Sangh UNESCO United Nations E...

Powered by Blogger.