Our example demonstrates how to parse numbers from strings in Java, which is a common task in many programs.
When you run this program, you’ll see the following output:
In Java, we use the Double.parseDouble() method to parse floating-point numbers, and Integer.parseInt() for parsing integers. The Integer.parseUnsignedInt() method is used for parsing unsigned integers.
For Integer.parseInt(), you can specify the radix (base) of the number system as the second argument. This allows you to parse numbers in different bases, such as hexadecimal.
Java’s parsing methods throw a NumberFormatException when given invalid input, which we catch and handle in a try-catch block.
Next, we’ll look at another common parsing task: URLs.