Introduction
In this lab, you will learn how to check if a string can be converted to an integer in Java. This is a fundamental skill for handling user input or data from external sources.
You will explore the Integer.parseInt() method for attempting the conversion, learn how to handle potential errors using NumberFormatException, and discover techniques for validating a string before attempting to parse it, ensuring robust and error-free code.
Try Parsing with Integer.parseInt()
In this step, we will explore how to convert a String (text) into an int (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 method called Integer.parseInt() for this purpose. Let's see how it works.
First, make sure you are in the
~/projectdirectory. You can use the commandcd ~/projectin the Terminal if needed.Now, let's create a new Java file named
StringToInt.javain the~/projectdirectory. You can do this by right-clicking in the File Explorer on the left, selecting "New File", and typingStringToInt.java.Open the
StringToInt.javafile in the Code Editor and paste the following code:public class StringToInt { public static void main(String[] args) { String numberString = "123"; int numberInt = Integer.parseInt(numberString); System.out.println("The string is: " + numberString); System.out.println("The integer is: " + numberInt); } }Let's look at the new parts:
String numberString = "123";: We declare aStringvariable namednumberStringand assign it the value"123". Notice that"123"is enclosed in double quotes, indicating it's a string.int numberInt = Integer.parseInt(numberString);: This is the core of this step. We call theInteger.parseInt()method, passing ournumberStringas an argument. This method attempts to convert the string"123"into an integer. The result is stored in anintvariable namednumberInt.System.out.println("The string is: " + numberString);: This line prints the original string.System.out.println("The integer is: " + numberInt);: This line prints the converted integer.
Save the file (Ctrl+S or Cmd+S).
Now, let's compile the program. Open the Terminal and run the following command:
javac StringToInt.javaIf the compilation is successful, you should see no output, and a
StringToInt.classfile will be created in the~/projectdirectory.Finally, run the compiled program:
java StringToIntYou should see the following output:
The string is: 123 The integer is: 123As you can see, the
Integer.parseInt()method successfully converted the string"123"into the integer123.
In the next step, we will explore what happens when the string cannot be converted into an integer.
Catch NumberFormatException
In the previous step, we successfully converted a string containing only digits into an integer using Integer.parseInt(). But what happens if the string contains characters that are not digits? Let's find out.
When Integer.parseInt() tries to convert a string that is not a valid representation of a number, it throws a NumberFormatException. This is a type of error that indicates a problem with the format of the number string.
To handle such errors gracefully, we can use a try-catch block. A try-catch block allows us to "try" a piece of code that might cause an error, and if an error occurs, we can "catch" it and handle it in a specific way, preventing our program from crashing.
Let's modify our StringToInt.java program to demonstrate this.
Open the
StringToInt.javafile in the WebIDE editor.Modify the code to include a
try-catchblock and change the input string:public class StringToInt { public static void main(String[] args) { String numberString = "abc"; // This string cannot be parsed as an integer try { int numberInt = Integer.parseInt(numberString); System.out.println("The string is: " + numberString); System.out.println("The integer is: " + numberInt); } catch (NumberFormatException e) { System.out.println("Error: Could not convert the string to an integer."); System.out.println("Details: " + e.getMessage()); } } }Here's what we added:
String numberString = "abc";: We changed the string to"abc", which is clearly not a valid integer.try { ... }: The code inside thetryblock is what we want to attempt. In this case, it's theInteger.parseInt()call.catch (NumberFormatException e) { ... }: If aNumberFormatExceptionoccurs within thetryblock, the code inside thecatchblock will be executed.System.out.println("Error: Could not convert the string to an integer.");: This line prints a user-friendly error message.System.out.println("Details: " + e.getMessage());: This line prints more details about the exception, which can be helpful for debugging.
Save the file (Ctrl+S or Cmd+S).
Compile the modified program in the Terminal:
javac StringToInt.javaRun the compiled program:
java StringToIntThis time, because
"abc"cannot be parsed as an integer, theNumberFormatExceptionwill be caught, and you should see output similar to this:Error: Could not convert the string to an integer. Details: For input string: "abc"Instead of the program crashing, the
catchblock handled the error and printed a helpful message. This is a much better user experience!
Using try-catch blocks is crucial for writing robust programs that can handle unexpected input or situations.
Validate String Before Parsing
In the previous step, we learned how to catch a NumberFormatException when Integer.parseInt() fails. While catching exceptions is important for handling errors, it's often better to prevent the error from happening in the first place.
In this step, we will learn how to validate a string before attempting to parse it as an integer. This involves checking if the string contains only digits.
One way to do this is to iterate through each character of the string and check if it's a digit. Another common approach is to use regular expressions, but for beginners, a simple loop is easier to understand.
Let's modify our StringToInt.java program again to include a validation check.
Open the
StringToInt.javafile in the WebIDE editor.Replace the existing code with the following:
public class StringToInt { public static void main(String[] args) { String numberString = "123a"; // This string contains a non-digit character if (isValidInteger(numberString)) { int numberInt = Integer.parseInt(numberString); System.out.println("The string is: " + numberString); System.out.println("The integer is: " + numberInt); } else { System.out.println("Error: The string '" + numberString + "' is not a valid integer."); } } // Method to check if a string is a valid integer public static boolean isValidInteger(String str) { if (str == null || str.isEmpty()) { return false; // An empty or null string is not a valid integer } for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); if (i == 0 && (c == '-' || c == '+')) { // Allow a leading sign (+ or -) continue; } if (!Character.isDigit(c)) { return false; // Found a non-digit character } } return true; // All characters are digits (or a leading sign) } }Let's look at the changes:
- We added a new method called
isValidInteger(String str). This method takes a string as input and returnstrueif the string represents a valid integer, andfalseotherwise. - Inside
isValidInteger, we first check if the string is null or empty. - We then loop through each character of the string.
Character.isDigit(c)is a built-in Java method that checks if a character is a digit.- We added a check to allow a leading plus or minus sign.
- In the
mainmethod, we now use anif-elsestatement. We callisValidInteger()to check the string before attempting to parse it. - If
isValidInteger()returnstrue, we proceed withInteger.parseInt(). - If it returns
false, we print an error message without attempting to parse, thus avoiding theNumberFormatException.
- We added a new method called
Save the file (Ctrl+S or Cmd+S).
Compile the modified program in the Terminal:
javac StringToInt.javaRun the compiled program:
java StringToIntSince the string
"123a"contains a non-digit character, theisValidIntegermethod will returnfalse, and you should see the following output:Error: The string '123a' is not a valid integer.Now, let's change the string back to a valid integer to see the other branch of the
if-elsestatement.Change the
numberStringvariable back to"456"in theStringToInt.javafile:String numberString = "456";Save the file.
Compile and run the program again:
javac StringToInt.java java StringToIntThis time,
isValidIntegerwill returntrue, and you should see:The string is: 456 The integer is: 456
By validating the string before parsing, we can handle invalid input more gracefully and avoid runtime errors like NumberFormatException. This is a good practice for writing more robust and reliable code.
Summary
In this lab, we learned how to convert a String to an int in Java using the Integer.parseInt() method. We created a Java file, wrote code to demonstrate the conversion, and compiled the program. This method is essential for handling numerical input from various sources.



