Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
5 views
in Java by (1.1k points)

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.

1 Answer

0 votes
by (13.2k points)

There are 3 ways to do this -

  1. 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;

}

  1. 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;

}

  1. 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’ .

Related questions

0 votes
1 answer
asked Jul 26, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...