Java Guide: Convert String to an int

Problem:
I want to convert my String “4711” to an actual number, so I can do some calculations. What do I do?

Answer:
To convert a String to an int you can use the ‘Integer.parseInt(StringToConvert)’ function. Just assign this function to an int variable to get the String value as an integer value.

Example:
//assign values to variables
String numbersAsString = “4711“;
int numbersAsInt;

//catch possible NumberFormatException
try {
//parse String to int
numbersAsInt = Integer.parseInt(numbersAsString);
}
catch (NumberFormatException e) {
numberAsInt = 0;
}


Java API


back