How do I convert a String to an int in Java?

To convert a String to an int in Java, you can use the parseInt method of the Integer class. Here’s an example of how you can do this:

String str = "123";
int i = Integer.parseInt(str);

This converts the String "123" to the int value 123.

You can also use the valueOf method of the Integer class to achieve the same result:

String str = "123";
int i = Integer.valueOf(str);

Both of these methods will throw a NumberFormatException if the String is not a valid representation of an int.

Alternatively, you can use the DecimalFormat class to parse the String and convert it to an int. Here’s an example of how you can do this:

String str = "123";
DecimalFormat df = new DecimalFormat();
int i = df.parse(str).intValue();

This will also throw a ParseException if the String is not a valid representation of an int.