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 primitiveint
equivalent. If theString
cannot 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
String
to an integer, but it returns anInteger
object (which can be unboxed to anint
if needed). Similar toparseInt()
, it throws aNumberFormatException
if theString
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 anInteger
, interpreting theString
as a decimal, hexadecimal (if prefixed with "0x" or "0X"), or octal (if prefixed with "0"). The result is anInteger
object, 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.