Skip to content

Validation & Parsing

The Course
•
15 min study

Input text is not automatically a usable number. Integer.parseInt converts a String containing a valid whole-number representation to an int. Integer is a Java library class available without an import; parseInt is its static method, so you call it on the class name rather than on a new object. trim can remove surrounding spaces first. Numeric syntax (how a number is written) and domain rules (what your application allows) are separate: "0" can parse successfully while zero is still invalid for a session duration.

A contract should say what is accepted. Our final planner accepts a nonblank topic, trimmed at its edges, and a duration from 1 through 240 inclusive. Types alone cannot enforce these rules. Validate before storing a record, so rejected input cannot leave a half-created plan behind.

Guard references before calling methods

A String reference can be null, meaning no object. Test null before calling trim or isEmpty on it. The short-circuit operator from Day 2 makes this readable: null is rejected first, and the text operation is evaluated only when an object exists. Empty text and a string of spaces are different before trimming, but both fail our nonblank-topic rule afterward.

Some parsing inputs fail with NumberFormatException: letters, decimals where a whole number is required, or numbers outside int's range. The next lesson handles that failure explicitly. For now, run known-valid parsing examples and keep the boolean domain checks independently testable.

Parse first, then check the allowed range Java
public class Main {
    public static void main(String[] args) {
        String text = " 25 ";
        int minutes = Integer.parseInt(text.trim());

        System.out.println(minutes);
        System.out.println(validMinutes(minutes));
        System.out.println(validMinutes(0));
    }

    static boolean validMinutes(int minutes) {
        return minutes >= 1 && minutes <= 240;
    }
}
Check your prediction
Text
25
true
false

Parsing gives an integer, not permission to schedule it. Check 1, 240 and 241 as independent domain cases. The parsing step does not know anything about sessions or a daily plan.

Reject null and blank topics safely Java
public class Main {
    public static void main(String[] args) {
        System.out.println(validTopic(null));
        System.out.println(validTopic("   "));
        System.out.println(validTopic(" Java "));
    }

    static boolean validTopic(String topic) {
        return topic != null && !topic.trim().isEmpty();
    }
}
Check your prediction
Text
false
false
true

If topic is null, && skips the trim call. Reversing those operands would break the null case. Validation accepts a nonblank value but does not mutate the original String.

Reject before mutating Java
public class Main {
    public static void main(String[] args) {
        Tally tally = new Tally();
        System.out.println(tally.add(25));
        System.out.println(tally.add(-5));
        System.out.println(tally.total());
    }
}

class Tally {
    private int total;

    boolean add(int minutes) {
        if (minutes < 1 || minutes > 240) {
            return false;
        }

        total += minutes;
        return true;
    }

    int total() {
        return total;
    }
}
Check your prediction
Text
true
false
25

A failed update returns false and leaves the previous total intact. Test both the reported failure and the state afterward. Moving the mutation before validation violates this contract.

Choose where rejection belongs

Validation protects the point where a value becomes trusted. If a constructor accepts a blank topic and a report later tries to repair it, every other method still has to cope with the invalid object. Rejecting or normalizing before storage lets later methods rely on a simpler rule.

Normalization preserves the intended meaning under a stated policy: trimming surrounding spaces is allowed here. Replacing a negative duration with 1 invents a different plan and conceals the invalid request. Distinguish a useful cleanup from a fabricated default.

For an existing object, check two things after a rejected change: the method reported the rejection, and the state is still what it was. The Tally example does both: false, then a total that is still 25.

Your turn

Exercise

Validate a whole record

A planner record arrives as two pieces of text: a topic and a duration. Write acceptRecord(String topic, String minutesText), which returns true only when both parts are acceptable:

  • topic is not null and is not blank after trimming;
  • minutesText, after trimming, parses to a value from 1 through 240.

Contract: minutesText always holds a whole number, possibly with spaces around it (text like "oops" is the next lesson's job). topic may be null. The editor checks these cases:

topicminutesTextresult
" Java "" 25 "true
null"25"false
" ""25"false
"Java""0"false
"Java""240"true
"Java"" 241"false
Your workspace Java
public class Main {
    public static void main(String[] args) {
        System.out.println(acceptRecord(" Java ", " 25 "));
        System.out.println(acceptRecord(null, "25"));
    }

    static boolean acceptRecord(String topic, String minutesText) {
        return false; // Replace the placeholder.
    }
}
Hint 1: the idea

There are three separate questions: is there a topic object, does it have visible text, and is the parsed number in range? Each one alone can make the answer false, and the null question has to be asked before any method is called on topic.

Hint 2: a first step

Begin with if (topic == null || topic.trim().isEmpty()) { return false; }. After that guard, parse minutesText.trim() into an int and check its range as the playground above does.

Show one solution
Java
public class Main {
    public static void main(String[] args) {
        System.out.println(acceptRecord(" Java ", " 25 "));
        System.out.println(acceptRecord(null, "25"));
    }

    static boolean acceptRecord(String topic, String minutesText) {
        if (topic == null || topic.trim().isEmpty()) {
            return false;
        }

        int minutes = Integer.parseInt(minutesText.trim());
        return minutes >= 1 && minutes <= 240;
    }
}
Text
true
false

The order inside the first condition is the key: topic == null is tested first, and || skips topic.trim() when it is already true, so the null case returns false instead of crashing. Parsing happens only after the topic passed, and .trim() before parseInt is what lets " 25 " and " 241" parse at all.

Change it and explain

Write a small acceptance table containing raw text, parsed value if any, domain validity and expected action. Include "25", "0", "241", "oops" and an empty string. This makes the distinction between parse failures and rule failures visible before you introduce recovery code.

Validation is not a reason to catch every possible exception and pretend input was accepted. A clearly rejected record is more useful than a silent zero that later looks like real data. In the final project, successful records are added only after construction has validated them.

Was this article helpful?

Your response is saved on this device.