C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: We always want to assign an int variable to the result of the parseInt method. This is the parsing result.
Unsigned: The method parseUnsignedInt does nearly the same thing as parseInt, but does not allow negative numbers in the argument string.
Java program that uses parseInt, parseUnsignedInt
public class Program {
public static void main(String[] args) {
String value = "1000";
// Parse with parseInt: the string can be negative.
int result = Integer.parseInt(value);
System.out.println(result);
System.out.println(result + 1);
// Parse with parseUnsignedInt: minus sign not allowed.
int result2 = Integer.parseUnsignedInt(value);
System.out.println(result2);
System.out.println(result2 + 2);
}
}
Output
1000
1001
1000
1002
Note: To avoid NumberFormatException, we can develop a method that tests for validity before calling parseInt.
Java program that causes NumberFormatException
public class Program {
public static void main(String[] args) {
String invalid = "turnip";
// This causes a NumberFormatException.
int result = Integer.parseInt(invalid);
}
}
Output
Exception in thread "main" java.lang.NumberFormatException:
For input string: "turnip"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)....
Java program that uses parseUnsignedInt, causes error
public class Program {
public static void main(String[] args) {
String test = "-100";
// ParseInt handles signed integers.
int value = Integer.parseInt(test);
System.out.println(value == -100);
// ParseUnsignedInt throws an Exception.
value = Integer.parseUnsignedInt(test);
}
}
Output
true
Exception in thread "main" java.lang.NumberFormatException:
Illegal leading minus sign on unsigned string -100.
at java.lang.Integer.parseUnsignedInt....
Java program that uses try, catch, parseInt
public class Program {
public static void main(String[] args) {
String invalid = "turnip";
int result = -100; // A default result.
try {
// This throws an exception because the string is invalid.
result = Integer.parseInt(invalid);
} catch (NumberFormatException n) {
// ... Do nothing.
}
System.out.println(result); // Prints default result.
}
}
Output
-100
IsDigit: The Character.isDigit method returns true for valid digits, and false otherwise.
Note: This program does not cause any exceptions, even though some of the strings are not valid numeric data.
Java program that checks for valid number strings
public class Program {
static boolean isValidNumber(String value) {
// Loop over all characters in the String.
// ... If isDigit is false, this method too returns false.
for (int i = 0; i < value.length(); i++) {
if (!Character.isDigit(value.charAt(i))) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String[] values = { "cat", "100", "200", "dog" };
for (String value : values) {
// If this is a valid number, parse it.
if (isValidNumber(value)) {
int number = Integer.parseInt(value);
System.out.println(number);
}
}
}
}
Output
100
200
Java program that uses parseDouble
public class Program {
public static void main(String[] args) {
String data = "12.01";
// Parse the double in the String.
double value = Double.parseDouble(data);
if (value == 12.01) {
System.out.println("String converted to Double!");
}
}
}
Output
String converted to Double!
Version 1: Here we reuse the isValidNumber method. We call this method before using parseInt.
Version 2: In this version of the code, we handle exceptions from parseInt with try and catch.
Result: Checking for valid strings (as done in version 1) is many times faster when invalid data is encountered.
Java program that times invalid int string parsing
public class Program {
static boolean isValidNumber(String value) {
// Return true if all characters are digits.
for (int i = 0; i < value.length(); i++) {
if (!Character.isDigit(value.charAt(i))) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String[] values = { "cat", "100", "200", "dog" };
long t1 = System.currentTimeMillis();
// Version 1: call isValidNumber before parseInt.
for (int i = 0; i < 1000000; i++) {
int sum = 0;
for (String v : values) {
if (isValidNumber(v)) {
sum += Integer.parseInt(v);
}
}
}
long t2 = System.currentTimeMillis();
// Version 2: handle Exception on invalid numbers.
for (int i = 0; i < 1000000; i++) {
int sum = 0;
for (String v : values) {
try {
sum += Integer.parseInt(v);
} catch (Exception ex) {
// ... Do nothing.
}
}
}
long t3 = System.currentTimeMillis();
// ... Times.
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}
Output
72 ms: isValidNumber, Integer.parseInt
1686 ms: try, Integer.parseInt, catch
And: To handle digits, parseIntFast multiplies by 10—so the digit to the left of the current one is ten times greater in the result int.
Version 1: This version of the code uses the custom parseIntFast method to parse numbers character-by-character.
Version 2: Here we invoke the Integer.parseInt method that is part of the Integer class.
Result: The parseIntFast method requires less than half the time of Integer.parseInt. It may also avoid exceptions.
Java program that benchmarks fast int parsing
public class Program {
public static int parseIntFast(String value) {
// Loop over the string, adjusting ASCII value to integer value.
// ... Multiply previous result by 10 as we progress.
int result = 0;
for (int i = 0; i < value.length(); i++) {
result = 10 * result + (value.charAt(i) - 48);
}
return result;
}
public static void main(String[] args) {
String test = "1234";
System.out.println(parseIntFast(test));
long t1 = System.currentTimeMillis();
// Version 1: use optimized parse method.
for (int i = 0; i < 10000000; i++) {
int v = parseIntFast(test);
if (v != 1234) {
return;
}
}
long t2 = System.currentTimeMillis();
// Version 2: use built-in parse method.
for (int i = 0; i < 10000000; i++) {
int v = Integer.parseInt(test);
if (v != 1234) {
return;
}
}
long t3 = System.currentTimeMillis();
// ... Times.
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}
Output
1234
74 ms parseIntFast
168 ms Integer.parseInt