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

 

You can convert a String to an int in Java using the Integer.parseInt() method or by using the Integer.valueOf() method. Here's how you can do it:

1. Using Integer.parseInt():

java
public class StringToIntExample { public static void main(String[] args) { String str = "123"; int intValue = Integer.parseInt(str); System.out.println("Parsed int value: " + intValue); } }

In this example, the Integer.parseInt() method is used to convert the string "123" to an integer value.

2. Using Integer.valueOf():

java
public class StringToIntExample { public static void main(String[] args) { String str = "456"; Integer integerValue = Integer.valueOf(str); System.out.println("Parsed Integer value: " + integerValue); } }

In this example, the Integer.valueOf() method is used to convert the string "456" to an Integer object, which can be auto-unboxed to an int if needed.

Both methods work similarly to parse a string representation of an integer into an int value. However, be aware that if the string cannot be parsed as a valid integer, a NumberFormatException will be thrown. You should handle this exception appropriately in your code.

Comments