Search code examples
javaintegerlong-integerinteger-overflow

Java parseInt vs parseLong


Why are they different?

String a = "576055795";
long b = 10 * Integer.parseInt(a);
long c = 10 * Long.parseLong(a);

System.out.println(b); // Prints 1465590654
System.out.println(c); // Prints 5760557950

Solution

  • Integer.parseInt() returns an int, which is a signed 32-bit integer. 10 is also an int; multiplying 576055795 by 10 as ints overflows and yields an int, which is then promoted to a long.

    Long.parseLong() returns a long, which is a signed 64-bit integer. Multiplying it by 10 yields a long with no overflow.