Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Java Dictionary

  1. Home
  2. Java Dictionary
  3. Integer.parseInt() / Double.parseDouble()

Integer.parseInt() / Double.parseDouble()

A method that converts a numeric string into a numeric type that can be used in calculations. Use it when you need to treat values read from user input or files as numbers. If a string that cannot be converted is passed, an exception is thrown.

Syntax

// Converts a string to int.
int variableName = Integer.parseInt(string);

// Converts a string to double.
double variableName = Double.parseDouble(string);

// Converts a string to float.
float variableName = Float.parseFloat(string);

// Converts a string to long.
long variableName = Long.parseLong(string);

Method List

MethodDescription
Integer.parseInt(String s)Converts a string to an int value. Throws NumberFormatException if the string cannot be converted.
Double.parseDouble(String s)Converts a string to a double value.
Float.parseFloat(String s)Converts a string to a float value.
Long.parseLong(String s)Converts a string to a long value.

Sample Code

// Converts a string to int.
String numStr = "42";
int num = Integer.parseInt(numStr);
System.out.println(num + 10); // Prints "52".

// Converts a string to double.
String priceStr = "3.14";
double price = Double.parseDouble(priceStr);
System.out.println(price * 2); // Prints "6.28".

// Converts a string to long (for large numbers).
String bigStr = "9999999999";
long big = Long.parseLong(bigStr);
System.out.println(big); // Prints "9999999999".

// A string that cannot be converted throws an exception.
try {
    int invalid = Integer.parseInt("abc"); // Throws NumberFormatException.
} catch (NumberFormatException e) {
    System.out.println("Cannot convert: " + e.getMessage());
}

// To convert a number to a string (the reverse), use String.valueOf().
int value = 100;
String str = String.valueOf(value);
System.out.println(str.getClass().getSimpleName()); // Prints "String".

Notes

Parse methods such as parseInt() throw a NumberFormatException if the string cannot be converted (e.g., alphabetic characters, empty strings, or strings containing only spaces). When converting uncertain values such as user input, handle the exception with a try-catch block.

The two-argument form Integer.parseInt(string, radix) lets you convert binary, octal, or hexadecimal strings to decimal (e.g., Integer.parseInt("FF", 16) returns 255).

For integer constants and base conversion, see Integer.MAX_VALUE / MIN_VALUE / toBinaryString().

If you find any errors or copyright issues, please .