Duck Number Program in Java Using Loop and String

⚡ Direct Answer & Key Takeaway

A Duck number is a positive integer that contains at least one digit '0', provided '0' does not appear as a leading digit—so 305 and 4021 are Duck numbers, while 035, 007, and 0 are not. Because `Scanner.nextInt()` strips leading zeroes from 035 and turns it into 35, reading input as a `String` verifies `str.charAt(0) != '0'` before running either a character scan or a `while (temp > 0)` digit-extraction check.

1. Why Leading Zeroes Disqualify a Duck Number

Positioning of the digit zero separates valid Duck numbers from disqualified inputs. By definition, a Duck number is a positive integer that contains at least one zero anywhere EXCEPT at the very beginning. Thus, `305`, `700`, and `1024` are Duck numbers, whereas `035`, `0080`, `123`, and `0` are not. Why does this leading-zero rule trip up Java beginners? When a user types `0350` into `Scanner.nextInt()`, Java parses the token numerically and strips the leading zero, storing `350` in `int num`. Your loop then detects the trailing zero in `350` and wrongly prints "Duck number." Reading the input first as a `String` preserves every typed character so leading zeroes are caught immediately before numeric parsing.

  • Leading zero anywhere at index 0 immediately disqualifies the input (`0350` -> NOT Duck).
  • Zeroes at index >= 1 (middle or trailing, like `4021` or `120`) satisfy the Duck condition.
  • Numbers with no zeroes at all (`1234`) and single-digit `0` are not Duck numbers.

2. Comparing String Inspection Against Numeric While-Loop

Combining String inspection with numeric while-loop checking highlights the strengths of both ICSE syllabus techniques. In `isDuckByString(String input)`, checking `input.charAt(0) == '0'` rejects leading zeroes in O(1) time, verifying all characters via `Character.isDigit` blocks signs or letters, and `input.indexOf('0') > 0` confirms a zero exists after the first digit. Meanwhile, `isDuckByLoop(int num)` demonstrates classic integer arithmetic: `while (temp > 0)` inspects `digit = temp % 10`, sets `hasZero = true` and breaks the instant `digit == 0`, and strips digits via `temp /= 10`. Notice that `isDuckByLoop` alone works reliably whenever the caller has already excluded leading-zero strings; pairing both in `main` gives complete protection against `"0350"` while showcasing standard loop tracing.

  • `input.indexOf('0') > 0` guarantees `'0'` appears at index 1 or later, never at index 0.
  • `while (temp > 0)` breaks early as soon as `digit == 0`, avoiding unnecessary iterations.
  • Always validate `input.matches("\\d+")` before calling `Integer.parseInt(input)`.

3. Dry Run Comparison for 0350 and 4021

Tracing two contrasting inputs—`"0350"` and `"4021"`—clarifies how both methods cooperate. For `input = "0350"`, `isDuckByString("0350")` inspects `input.charAt(0)`, finds `'0'`, and returns `false` on line 5 without scanning further. In `main`, `input.charAt(0) != '0'` also evaluates to `false`, so `Integer.parseInt` is skipped and the program prints `0350 is NOT a Duck number.` Now trace `input = "4021"`: `isDuckByString` confirms `charAt(0) == '4' != '0'`, all characters are digits, and `indexOf('0')` returns `1 > 0` (`true`). Next, `num = 4021` enters `isDuckByLoop`: Pass 1 extracts `1 != 0` (`temp = 402`); Pass 2 extracts `2 != 0` (`temp = 40`); Pass 3 extracts `0 == 0`, sets `hasZero = true`, and breaks, outputting `4021 is a Duck number.`

  • Input "0350": charAt(0) == '0' -> returns false immediately -> NOT a Duck number.
  • Input "4021" String check: indexOf('0') == 1 (> 0) -> returns true.
  • Input "4021" Loop trace: digit 1 (temp=402) -> digit 2 (temp=40) -> digit 0 (hasZero=true, break).

4. DuckNumber.java (ICSE BlueJ: String & Loop)

import java.util.Scanner;

public class DuckNumber {
    public static boolean isDuckByString(String input) {
        if (input.isEmpty() || input.charAt(0) == '0') {
            return false;
        }
        for (int i = 1; i < input.length(); i++) {
            if (!Character.isDigit(input.charAt(i))) {
                return false;
            }
        }
        if (!Character.isDigit(input.charAt(0))) {
            return false;
        }
        return input.indexOf('0') > 0;
    }

    public static boolean isDuckByLoop(int num) {
        if (num <= 0) {
            return false;
        }
        int temp = num;
        boolean hasZero = false;
        while (temp > 0) {
            int digit = temp % 10;
            if (digit == 0) {
                hasZero = true;
                break;
            }
            temp = temp / 10;
        }
        return hasZero;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a positive number: ");
        String input = sc.next().trim();

        boolean duckString = isDuckByString(input);
        boolean duckLoop = false;
        if (input.charAt(0) != '0' && input.matches("\\d+")) {
            int num = Integer.parseInt(input);
            duckLoop = isDuckByLoop(num);
        }

        if (duckString && duckLoop) {
            System.out.println(input + " is a Duck number.");
        } else {
            System.out.println(input + " is NOT a Duck number.");
        }
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter a positive number: 4021
4021 is a Duck number.

Enter a positive number: 0350
0350 is NOT a Duck number.

5. Variable Description Table (VDT)

Variable NameData TypePurpose in Program
scScannerReads the user input token from standard input
inputStringStores the trimmed raw input string to preserve any leading zero
numintHolds the parsed integer passed into the numeric loop method
tempintMutable copy of num divided by 10 during digit extraction
digitintCurrent rightmost digit inspected for equality with 0
hasZerobooleanTracks whether at least one zero digit was encountered in the loop
🎯 1-on-1 Live Mentorship & Free Study Kit

Ace ICSE String & Loop Questions With 1-on-1 Coaching

Master both String-based and numeric loop algorithms for ICSE Java exams with IIT/NIT mentors at 4Achievers Junior (Grades 3-12, 1-on-1 & 1:4 Micro-Pods).

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Reading input with `sc.nextInt()` when test cases include leading-zero strings like `0350`; `nextInt()` converts `0350` to `350`, falsely reporting it as a Duck number.
  • Avoid Mistake: Writing `input.indexOf('0') != -1` without verifying `input.charAt(0) != '0'`, which mistakenly classifies `012` as a Duck number.
  • Avoid Mistake: Attempting `Integer.parseInt(input)` before validating that `input` contains only digits, crashing with `NumberFormatException` on invalid inputs like `-305` or `12a0`.
  • Examiner / Mentor Tip: If the board question explicitly specifies "without using String", read an `int` with `Scanner` and state the assumption that inputs have no leading zeroes.
  • Examiner / Mentor Tip: Explain in your viva why `input.indexOf('0') > 0` is cleaner than `>= 0`: index 0 must never be `'0'`.
  • Examiner / Mentor Tip: Document helper methods clearly and list both `String` and `int`/`boolean` variables in your VDT.

7. Interactive Concept Check Quiz

Question: Which of the following inputs is NOT a Duck number?

8. Frequently Asked Questions

Does a trailing zero like in 120 make it a Duck number?
Yes. A Duck number only requires that the number does not START with zero and contains at least one zero anywhere after the first digit—so trailing zeroes in 120 or 1000 make them valid Duck numbers.
Why does ICSE prefer String input over nextInt() for Duck numbers?
`Scanner.nextInt()` discards leading zeroes automatically, turning `0405` into `405`. Reading as a `String` preserves the leading `'0'` character so your program can reject `0405` accurately.
Is 0 itself classified as a Duck number?
No. A single `0` starts with zero (and is not a positive integer with an internal or trailing zero), so `0` is never a Duck number.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class