Languages
[Edit]
EN

Java - convert string to integer

0 points
Created by:
Frank-van-Puffelen
439

In this article, we would like to show you how to convert string to integer in Java.

1. Using Integer parseInt()

In this example, we use Integer parseInt() method to convert text string to the integer.

public class Example {

    public static void main(String[] args) {
        String text = "10";
        try {
            int number = Integer.parseInt(text);
            System.out.println(number); // 10
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
}

Note:

If the string doesn't contain a valid integer it will throw a NumberFormatException.

2. Using Integer valueOf()

In this example, we use Integer valueOf() method to convert text string to the integer.

public class Example {

    public static void main(String[] args) {
        String text = "10";
        try {
            Integer number = Integer.valueOf(text);
            System.out.println(number); // 10
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
}

Note:

If the string doesn't contain a valid integer it will throw a NumberFormatException.

References

  1. Integer parseInt(String s) (Java Platform SE 7 )
  2. Integer valueOf(String s) (Java Platform SE 7 )
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.

Cross technology - convert string to integer

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