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

My String contains only numbers, and I want to return the number it represents.

For example, given the string "1234" the result should be the number 1234.

0 votes

There are 3 ways to do this -

**Integer.parseInt() Method**

String string = "1234";

int number = Integer.parseInt(string);

This method can throw a NumberFormatException , if the string doesn’t contain a number and cannot be parsed to an integer number.

To avoid this Exception, you can use the code below

int number;

try {

number = Integer.parseInt(string);

}

catch (NumberFormatException e)

{

number = 0;

}

**Integer.valueOf() Method**

This method is similar to the above method, the only difference is that parseInt() method has return type primitive int whereas valueOf() has return type as Integer class.

Again, the code for this while taking care of exception will be

Integer number;

try {

number = Integer.valueOf(string);

}

catch (NumberFormatException e)

{

number = 0;

}

**Use Integer.decode()**

** **This method is only applicable for **decimal, hexadecimal and octal**** Numbers.**

Octal numbers are numbers that start with plus/minus sign (optional) and then suffix ‘0’

Decimal numbers are numbers that start with plus/minus sign (optional).

Hex numbers are numbers that start with plus/minus sign (optional) and then suffix ‘0x’ or ‘0X’ .