Languages
[Edit]
EN

Java - convert String to int

9 points
Created by:
Payne
654

The best way to convert String to int in java:

Other short solutions:

In this post we will cover couple of different ways how to convert String to int or Integer.

1. Using Integer.parseInt()

Edit

Convert String "123" to primitive int with Integer.parseInt()

Output:

2. Using Integer.valueOf()

Edit

Convert String "123" to Integer object with Integer.valueOf()

Output:

3. Using constructor - new Integer(String s)

Edit

Output:

4. Using Integer.decode()

Edit

Output:

5. Using Guava - Ints.tryParse()

Edit

Output:

6. String to int with sign + or -

Edit

Both methods:

  • Integer.parseInt("123")
  • Integer.valueOf("123")

accepts plus sign '+' and minut sign '-'.

Code example:

Output:

7. Example of java.lang.NumberFormatException

Edit

Output:

Both methods:

  • Integer.parseInt("123")
  • Integer.valueOf("123")

will throw java.lang.NumberFormatException if we try to parse anything else then:
digits or '+', '-' as first character.

As stated in java docs of Integer.parseInt()

The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.
Throws: 
NumberFormatException - if the string does not contain a parsable integer

8. ASCII to int - Java atoi implementation

Edit

We can convert string to integer by implementing our own atoi() method. ATOI stands for ASCII to integer. Take a look at this atoi java implementation:
ASCII to int - Java implementation

Merged questions

Edit
  1. Java - how to convert String to int
  2. Java - cast String to int
  3. How do I change String type to Integer in java?
  4. String to int conversion in java

Reference

Edit
  1. Integer.parseInt() - docs
  2. Integer.valueOf() - docs
  3. NumberFormatException - docs
  4. Type conversion - wiki
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - String conversion

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join