Introduction
In this lab, you will learn different methods to check if a given string in Java represents a numeric value. We will start by exploring how to attempt parsing a string into an integer and handle potential errors when the string is not a valid number.
Following that, you will discover how to leverage the power of regular expressions for a more flexible and robust numeric check. Finally, we will extend our understanding to handle strings that represent negative numbers and decimal values, ensuring our numeric checks are comprehensive.
Attempt Parsing String to Integer
In this step, we will explore how to convert a string (text) into an integer (a whole number) in Java. This is a common task in programming, especially when you need to get numerical input from a user or read numbers from a file.
Java provides a built-in way to do this using the Integer.parseInt() method. However, what happens if the string doesn't actually represent a valid number? Let's find out by writing a simple Java program.
Open the
HelloJava.javafile in the WebIDE editor if it's not already open.Replace the entire contents of the file with the following code:
public class HelloJava { public static void main(String[] args) { String numberString = "123"; int number = Integer.parseInt(numberString); System.out.println("Successfully parsed: " + number); String invalidString = "abc"; try { int invalidNumber = Integer.parseInt(invalidString); System.out.println("This line will not be reached."); } catch (NumberFormatException e) { System.out.println("Error: Could not parse '" + invalidString + "' to an integer."); System.out.println("Exception details: " + e.getMessage()); } } }Let's look at the new parts of this code:
String numberString = "123";: We create a string variablenumberStringand assign it the value"123".int number = Integer.parseInt(numberString);: This is the core of the conversion.Integer.parseInt()attempts to convert the string"123"into an integer. Since"123"is a valid integer representation, this will succeed, and the integer value123will be stored in thenumbervariable.String invalidString = "abc";: We create another string variableinvalidStringand assign it the value"abc". This string does not represent a valid integer.try { ... } catch (NumberFormatException e) { ... }: This is atry-catchblock, which is used for handling errors (exceptions) in Java.- The code inside the
tryblock is where we put the operation that might cause an error. In this case, it'sInteger.parseInt(invalidString). - If
Integer.parseInt("abc")fails because"abc"is not a valid number, it will "throw" aNumberFormatException. - The
catch (NumberFormatException e)block "catches" this specific type of exception. The code inside thecatchblock will then be executed.
- The code inside the
System.out.println("Error: Could not parse '" + invalidString + "' to an integer.");: This line will be printed if theNumberFormatExceptionoccurs.System.out.println("Exception details: " + e.getMessage());: This prints a more specific message about the error provided by the exception objecte.
Save the file (Ctrl+S or Cmd+S).
Compile the program in the Terminal:
javac HelloJava.javaIf there are no errors, you will see no output.
Run the compiled program:
java HelloJavaYou should see output similar to this:
Successfully parsed: 123 Error: Could not parse 'abc' to an integer. Exception details: For input string: "abc"This output shows that the first parsing attempt was successful, but the second attempt with the invalid string
"abc"resulted in aNumberFormatException, and ourcatchblock handled it gracefully by printing an error message.
This demonstrates the importance of handling potential errors when converting strings to numbers, as not all strings can be successfully parsed. Using try-catch blocks is a standard way to manage such situations in Java.
Use Regular Expression for Numeric Check
In the previous step, we saw that Integer.parseInt() throws an exception if the string is not a valid integer. While try-catch is useful for handling the error when it happens, sometimes you might want to check if a string can be parsed into a number before attempting the conversion. This is where Regular Expressions (Regex) come in handy.
Regular Expressions are powerful patterns used to match character combinations in strings. We can use a simple regex pattern to check if a string consists only of digits.
Open the
HelloJava.javafile in the WebIDE editor.Replace the entire contents of the file with the following code:
public class HelloJava { public static void main(String[] args) { String numberString = "123"; String invalidString = "abc"; String mixedString = "123a"; System.out.println("Checking string: \"" + numberString + "\""); if (numberString.matches("\\d+")) { System.out.println(" Matches the pattern (contains only digits)."); int number = Integer.parseInt(numberString); System.out.println(" Parsed integer: " + number); } else { System.out.println(" Does not match the pattern."); } System.out.println("\nChecking string: \"" + invalidString + "\""); if (invalidString.matches("\\d+")) { System.out.println(" Matches the pattern (contains only digits)."); } else { System.out.println(" Does not match the pattern."); } System.out.println("\nChecking string: \"" + mixedString + "\""); if (mixedString.matches("\\d+")) { System.out.println(" Matches the pattern (contains only digits)."); } else { System.out.println(" Does not match the pattern."); } } }Let's break down the new parts:
numberString.matches("\\d+"): This is the key part. Thematches()method is available on all String objects in Java. It checks if the entire string matches the given regular expression pattern."\\d+": This is the regular expression pattern.\\d: This matches any digit (0 through 9). We use\\because\is a special character in Java strings, so we need to escape it.+: This is a quantifier that means "one or more" of the preceding element. So,\\d+means "one or more digits".
- The
ifstatement checks the result ofmatches(). If it returnstrue, it means the string consists entirely of one or more digits. If it returnsfalse, it means the string contains characters other than digits or is empty.
Save the file (Ctrl+S or Cmd+S).
Compile the program in the Terminal:
javac HelloJava.javaYou should see no output if compilation is successful.
Run the compiled program:
java HelloJavaYou should see output similar to this:
Checking string: "123" Matches the pattern (contains only digits). Parsed integer: 123 Checking string: "abc" Does not match the pattern. Checking string: "123a" Does not match the pattern.As you can see, the
matches("\\d+")check correctly identified"123"as containing only digits, while"abc"and"123a"did not match the pattern. This approach allows you to validate the string format before attempting to parse it, potentially avoidingNumberFormatExceptionin some cases.
Handle Negative and Decimal Numbers
In the previous steps, we focused on parsing positive whole numbers. However, numbers can also be negative or have decimal points. In this step, we'll learn how to handle these cases when converting strings to numbers in Java.
Java provides different methods for parsing different types of numbers:
Integer.parseInt(): For whole numbers (integers).Double.parseDouble(): For numbers with decimal points (floating-point numbers).
Let's modify our program to handle negative integers and decimal numbers.
Open the
HelloJava.javafile in the WebIDE editor.Replace the entire contents of the file with the following code:
public class HelloJava { public static void main(String[] args) { String positiveIntString = "456"; String negativeIntString = "-789"; String decimalString = "123.45"; String invalidString = "not a number"; // Handling Integers (positive and negative) System.out.println("Attempting to parse integers:"); try { int positiveInt = Integer.parseInt(positiveIntString); System.out.println(" Parsed '" + positiveIntString + "' as integer: " + positiveInt); } catch (NumberFormatException e) { System.out.println(" Could not parse '" + positiveIntString + "' as integer."); } try { int negativeInt = Integer.parseInt(negativeIntString); System.out.println(" Parsed '" + negativeIntString + "' as integer: " + negativeInt); } catch (NumberFormatException e) { System.out.println(" Could not parse '" + negativeIntString + "' as integer."); } try { int decimalAsInt = Integer.parseInt(decimalString); System.out.println(" Parsed '" + decimalString + "' as integer: " + decimalAsInt); } catch (NumberFormatException e) { System.out.println(" Could not parse '" + decimalString + "' as integer."); } // Handling Decimal Numbers System.out.println("\nAttempting to parse decimal numbers:"); try { double decimal = Double.parseDouble(decimalString); System.out.println(" Parsed '" + decimalString + "' as double: " + decimal); } catch (NumberFormatException e) { System.out.println(" Could not parse '" + decimalString + "' as double."); } try { double intAsDouble = Double.parseDouble(positiveIntString); System.out.println(" Parsed '" + positiveIntString + "' as double: " + intAsDouble); } catch (NumberFormatException e) { System.out.println(" Could not parse '" + positiveIntString + "' as double."); } try { double invalidAsDouble = Double.parseDouble(invalidString); System.out.println(" Parsed '" + invalidString + "' as double: " + invalidAsDouble); } catch (NumberFormatException e) { System.out.println(" Could not parse '" + invalidString + "' as double."); } } }Here's what's happening:
- We now have strings representing a positive integer, a negative integer, a decimal number, and an invalid string.
- We use
Integer.parseInt()withintry-catchblocks to attempt parsing the strings as integers. Notice thatInteger.parseInt()can handle the negative sign (-). However, it will throw aNumberFormatExceptionif the string contains a decimal point or non-digit characters. - We use
Double.parseDouble()withintry-catchblocks to attempt parsing the strings as decimal numbers (doubles).Double.parseDouble()can handle both integers and numbers with decimal points. It will throw aNumberFormatExceptionfor strings that are not valid representations of a double.
Save the file (Ctrl+S or Cmd+S).
Compile the program in the Terminal:
javac HelloJava.javaYou should see no output if compilation is successful.
Run the compiled program:
java HelloJavaYou should see output similar to this:
Attempting to parse integers: Parsed '456' as integer: 456 Parsed '-789' as integer: -789 Could not parse '123.45' as integer. Attempting to parse decimal numbers: Parsed '123.45' as double: 123.45 Parsed '456' as double: 456.0 Could not parse 'not a number' as double.This output shows that
Integer.parseInt()correctly parsed the positive and negative integers but failed on the decimal string.Double.parseDouble()successfully parsed both the decimal string and the integer string (representing it as a double, e.g., 456.0), but failed on the invalid string.
This step demonstrates how to use the appropriate parsing methods for different number types and reinforces the importance of using try-catch blocks to handle potential NumberFormatException errors when the input string might not be in the expected format.
Summary
In this lab, we learned how to check if a string is numeric in Java. We first explored using Integer.parseInt() to attempt parsing a string into an integer, understanding that this method throws a NumberFormatException if the string is not a valid integer representation. We saw how to handle this exception using a try-catch block to gracefully manage non-numeric strings.
Building upon this, we then learned how to use regular expressions as a more flexible approach to check for numeric strings, which can handle various formats. Finally, we extended our understanding to include handling negative and decimal numbers when determining if a string represents a numeric value.



