Number Parsing in Java
Our program demonstrates parsing numbers from strings, which is a basic but common task in many programs. Here’s how to do it in Java:
Here’s a breakdown of the code:
We use
Double.parseDouble()
to parse floating-point numbers. Unlike in the original example, Java doesn’t require specifying the precision.Integer.parseInt()
is used for parsing integers. We don’t need to specify the base (it’s assumed to be 10) or the bit size.For parsing hexadecimal numbers, we use
Integer.parseInt()
with a radix of 16.Java doesn’t have a direct equivalent to
ParseUint
, but we can useInteger.parseUnsignedInt()
which returns a long to accommodate larger values.Integer.parseInt()
serves the same purpose asAtoi
for basic base-10 integer parsing.In Java, parse methods throw a
NumberFormatException
on bad input, which we catch and print.
When you run this program, you should see output similar to this:
Next, we’ll look at another common parsing task: URLs.