To convert a string to an int
in Java, you can use the parseInt()
method of the Integer
class. This method takes a string as an argument and returns the integer value represented by the string.
Here's an example of how you can convert a string to an int
in Java:
import java.lang.Integer; // ... String str = "123"; int num = Integer.parseInt(str);
In this example, the str
variable holds the string "123", and the num
variable holds the integer value represented by the string.
It's important to note that the parseInt()
method throws a NumberFormatException
if the string does not contain a parsable integer. You should handle this exception appropriately in your code.
You can also use the valueOf()
method of the Integer
class to convert a string to an int
. This method works similarly to parseInt()
, but it returns an Integer
object instead of an int
primitive.