Languages
[Edit]
EN

Java - convert string to integer

0 points
Created by:
Frank-van-Puffelen
289

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 )
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