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
Stringas an argument and returns the primitiveintequivalent. If theStringcannot be parsed into an integer (e.g., it contains non-numeric characters), it throws aNumberFormatException. - 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
Stringto an integer, but it returns anIntegerobject (which can be unboxed to anintif needed). Similar toparseInt(), it throws aNumberFormatExceptionif theStringcannot 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
Stringto anInteger, interpreting theStringas a decimal, hexadecimal (if prefixed with "0x" or "0X"), or octal (if prefixed with "0"). The result is anIntegerobject, which can be unboxed to anint. - 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.