Java how to convert string to int

Java how to convert string to int

To convert a string to an integer in Java, you can use the Integer.parseInt method, which parses the string as an integer and returns the result.

Here is an example of how you can use the Integer.parseInt method to convert a string to an int:

String s = "123";
int x = Integer.parseInt(s);
Source:‮w‬ww.lautturi.com

This code assigns the string "123" to the variable s, and then converts it to the integer 123 using the Integer.parseInt method. The result is stored in the variable x.

If the string cannot be parsed as an integer, the Integer.parseInt method will throw a NumberFormatException. You can handle this exception by enclosing the call to Integer.parseInt in a try-catch block:

try {
  int x = Integer.parseInt(s);
} catch (NumberFormatException e) {
  // handle the exception
}

Note that the Integer.parseInt method only works for integers in the range of Integer.MIN_VALUE (-2147483648) to Integer.MAX_VALUE (2147483647). If you need to parse larger integers, you can use the Long.parseLong method or a custom parser.

Created Time:2017-11-03 22:21:04  Author:lautturi