Java: How to convert strings to numbers

Question: How do I convert a String to an int or a float in Java?

Short answer: You want to use the Integer.parseInt() or Float.parseFloat() methods.

Here’s an example Java program that shows how to convert a String to either an int or a float:

package com.devdaily.javasamples;

public class ConvertStringToNumber {

    public static void main(String[] args) {

        try {
            // string to int
            String s = "5";
            int i = Integer.parseInt(s);
            System.out.println("int value = " + i);

            // string to float
            float f = Float.parseFloat(s);
            System.out.println("float value = " + f);

        } catch (NumberFormatException nfe) {
            System.err.println(nfe.getMessage());
        }

    }

}

As you can see from the sample code, the trick is to use either the parseInt method of the Integer class, or the parseFloat method of the Float class to perform the conversion. As either of these methods can throw a NumberFormatException you should either handle that exception, or let it be thrown by your method.