Java course

Parse and validate text values

1.5.3 — Parse and validate text values

Parsing converts text into a value your code can use. Validation checks whether that value is allowed.

String holds text, int and long hold whole numbers, and System.out.println prints a value. An array holds several values and uses indexes starting at 0. Every example below supplies its own text.

Convert numeric text to an int

Integer.parseInt("12") returns the integer 12. After conversion, adding 1 gives 13. Adding 1 directly to the String joins text instead.

The input must describe a whole number within the int range. Text such as twelve or 3.5 is not accepted. This method needs no import because Integer belongs to java.lang.

Remove surrounding spaces first

trim() returns text without ordinary leading and trailing spaces. parseInt does not ignore these spaces itself.

Call trim before parsing: Integer.parseInt(spacedText.trim()). The original String remains unchanged.

Use long for larger whole numbers

Long.parseLong(...) returns a long. Here the text contains 5000000000, which is larger than int can hold.

Choose the type for the values you expect. These methods reject text outside their respective number ranges.

API reference, in plain language: Integer.parseInt converts decimal text into an int; Long.parseLong does the same for long. Both report unsuitable numeric text with NumberFormatException. [Integer API](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Integer.html#parseInt(java.lang.String)), [Long API](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Long.html#parseLong(java.lang.String)).

Handle text that is not a number

The next input cannot be converted. parseInt throws a NumberFormatException and stops the try block. The catch block handles that problem and prints a clear message.

error names the exception object. Later statements can still run after catch. This is not a valid count of zero; conversion failed.

Separate a name and a count

For this exercise, the format is exactly name:count, with one colon. split(":", -1) produces an array of parts and keeps empty parts at the end.

Keeping empty parts makes a missing count visible: Ada: produces two parts, with the second empty. Check the number of parts before reading index 1.

[API reference](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html#split(java.lang.String,int)): a negative limit keeps trailing empty results. Our separator is the simple colon character.

Check the format, name, and count

Validate in order: first require exactly two parts, then a nonempty name, then a whole-number count of at least zero. isEmpty() is true for text with no characters.

Print the accepted name and count only after all checks pass. A negative value can be parsed successfully but still fails the count rule.

InputResult
Ada:2Name: Ada, Count: 2
Ada or Ada:2:3Use name:count
:2Name must not be empty
Ada: or Ada:twoCount must be a whole number
Ada:-1Count must be at least 0

Each row describes the complete validation cell below. Change only rawEntry to try it.

Practice: trim before parsing

This cell tries to parse " 12 " directly, so it prints Not a whole number. Change only the argument to parseInt from practiceText to practiceText.trim().

The completed cell should print 12.

Hint

Use Integer.parseInt(practiceText.trim()). The catch block can stay as it is.

Worked solution
String practiceText = " 12 ";
try {
    int practiceNumber = Integer.parseInt(practiceText.trim());
    System.out.println(practiceNumber);
} catch (NumberFormatException error) {
    System.out.println("Not a whole number");
}

Try different text

In your completed cell, change only practiceText:

TextExpected output
"0"0
" 7 "7
"-1"-1
"3.5"Not a whole number
""Not a whole number

This practice cell checks conversion only. The earlier validation cell adds the rule that a count cannot be negative.

Enable JavaScript to run the Java notebook.