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:

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

The parseInt() method takes a String as an argument and returns the corresponding int value. If the String does not contain a valid integer, it will throw a NumberFormatException.

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

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

Both of these methods work for strings that contain decimal numbers, as well as strings that represent hexadecimal, octal, and binary numbers.

Note that these methods only work for strings that represent positive integers. If you need to parse negative integers or floating-point numbers, you can use the parseDouble() or parseFloat() method of the Double or Float class, respectively.