To convert a string to an int
value in Java, you can use the Integer.parseInt
method. This method takes a string as an argument and returns the int
value represented by that string.
Here's an example of how to use the Integer.parseInt
method:
String s = "123"; int i = Integer.parseInt(s); // i is 123
Note that the Integer.parseInt
method only works for strings that represent a valid int
value. If the input string is empty or contains non-numeric characters, the Integer.parseInt
method will throw a NumberFormatException
.
Here's an example of how you can handle the NumberFormatException
:
String s = "123"; try { int i = Integer.parseInt(s); } catch (NumberFormatException e) { e.printStackTrace(); }
It's a good idea to handle this exception in a try-catch
block, as shown in the example above, to avoid your program crashing if the input string is not a valid representation of an int
value.
You can find more information about the Integer.parseInt
method and examples of how to use it in the Java documentation.