DEV Community

haytam_7
haytam_7

Posted on

Java: Convert String to a Number

When it comes to converting a string of numbers, like: "1234" into a number the first question that jumps to your mind is:
"They look like a number! why do I need to convert a number to a number?!"

Well, the computer doesn't see things the way we see them, a string consists of numbers is not a number! or at least according to the computer.

A string of numbers is a bunch of characters and they do not present a numeric value.

So in Java we have two ways to convert a string of 'numbers' to a real number, and here is how this could be done:

In this post I'm going to talk about converting string to int

Using Integer.parseInt()

This method will return the primitive numeric value of a string that contains only numbers, otherwise it will throw an error (NumberFormatException)

For example:

String testStr = "150";
        try{
            System.out.println(Integer.parseInt(testStr));
        } catch (NumberFormatException e) {
            System.out.print("Error: String doesn't contain a valid integer. " + e.getMessage());
        }
Enter fullscreen mode Exit fullscreen mode

Using Integer.valueOf()

This method will return an integer object of the passed parameter,
if the passed parameter isn't valid it will throw an error.
For example:

String testStr = "200";
        try{
            System.out.println(Integer.valueOf(testStr));
        } catch (NumberFormatException e) {
            System.out.print("Error: String doesn't contain a valid integer. " + e.getMessage());
        }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)