How do you convert a String to an integer in Java?

In Java, there are several ways to convert a String to an int. The most common methods are using Integer.parseInt() and Integer.valueOf(). These methods are used to take a String that represents a number and convert it into an integer type (int).

1. Using Integer.parseInt():

  • Method: Integer.parseInt(String s)
  • What it does: This method takes a String as an argument and returns the primitive int equivalent. If the String cannot be parsed into an integer (e.g., it contains non-numeric characters), it throws a NumberFormatException.
  • Example:

java String numberStr = "123"; int number = Integer.parseInt(numberStr); System.out.println(number); // Output: 123 * Error Handling:

java try { String invalidStr = "123abc"; int invalidNumber = Integer.parseInt(invalidStr); } catch (NumberFormatException e) { System.out.println("Invalid number format: " + e.getMessage()); }

2. Using Integer.valueOf():

  • Method: Integer.valueOf(String s)
  • What it does: This method also converts a String to an integer, but it returns an Integer object (which can be unboxed to an int if needed). Similar to parseInt(), it throws a NumberFormatException if the String cannot be parsed.
  • Example:

java String numberStr = "456"; Integer numberObject = Integer.valueOf(numberStr); int number = numberObject; // Auto-unboxing to primitive int System.out.println(number); // Output: 456

3. Using Integer.decode() (For Strings with Prefixes):

  • Method: Integer.decode(String s)
  • What it does: This method can convert a String to an Integer, interpreting the String as a decimal, hexadecimal (if prefixed with "0x" or "0X"), or octal (if prefixed with "0"). The result is an Integer object, which can be unboxed to an int.
  • Example:

java String hexStr = "0x1A"; int number = Integer.decode(hexStr); System.out.println(number); // Output: 26

Conclusion:

To convert a String to an integer in Java, the most straightforward and commonly used method is Integer.parseInt(), which converts the String to a primitive int. Alternatively, Integer.valueOf() can be used when you need an Integer object. For strings representing numbers in different bases, such as hexadecimal or octal, Integer.decode() can be used. Always handle potential NumberFormatException to ensure the application does not crash if the String is not a valid number.