Spy Number in Java: Definition, Logic, and Program with Examples

Spy Number in Java

If you have been exploring number programs in Java, you already know that Java is a great language to practice logic-based programming through special number categories. One such fascinating category is the spy number in Java. It is simple to understand, fun to implement, and frequently asked in ICSE Class 10 exams, BCA/MCA practicals, and entry-level Java interviews.

A spy number is a number where the sum of its digits is equal to the product of its digits. For example, 1124 is a spy number because the sum 1+1+2+4 = 8 and the product 1×1×2×4 = 8 are both equal.

In this blog, you will learn the exact definition of a spy number in Java, the step-by-step logic behind it, multiple Java programs to check for spy numbers, a detailed dry run, and answers to frequently asked questions.

What is a Spy Number in Java?

A spy number in Java is a number for which the sum of all its digits equals the product of all its digits. The name “spy” comes from the idea that the number hides a mathematical secret within its digits.

This concept is commonly introduced in the context of iteration and loop-based programs, making it a perfect exercise for practicing digit extraction logic in Java.

Key Conditions for a Spy Number:

  • Extract every digit of the number.
  • Calculate the sum of all digits.
  • Calculate the product of all digits.
  • If sum equals product, the number is a spy number.

Spy Number Examples

Before writing any program, it helps to understand the logic with clear examples.

NumberSum of DigitsProduct of DigitsSpy Number?
11241+1+2+4 = 81×1×2×4 = 8Yes
1231+2+3 = 61×2×3 = 6Yes
222+2 = 42×2 = 4Yes
1241+2+4 = 71×2×4 = 8No
1321+3+2 = 61×3×2 = 6Yes

Algorithm to Check Spy Number in Java

Before writing the program, follow this step-by-step algorithm. This makes the coding phase much more structured and error-free.

  1. Accept the number as input from the user.
  2. Store the original number for later use.
  3. Initialize sum = 0 and prod = 1.
  4. Use a loop to extract each digit using num % 10.
  5. Add the digit to sum and multiply it into prod.
  6. Remove the last digit using num = num / 10.
  7. Repeat steps 4–6 until num becomes 0.
  8. After the loop, compare sum and prod.
  9. If sum == prod, print the number is a spy number; else, it is not.

Spy Number Program in Java Using While Loop

This is the most standard implementation of the spy number in Java. It uses a while loop to extract digits one by one, compute the sum and product, and then compare them.

import java.util.Scanner;


public class SpyNumber {
    public static void main(String[] args) {
        int r, n, num, mul = 1, sum = 0;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number: ");
        n = sc.nextInt();
        num = n;


        while (num > 0) {
            r = num % 10;      // Extract last digit
            sum = sum + r;     // Add to sum
            mul = mul * r;     // Multiply into product
            num = num / 10;    // Remove last digit
        }


        if (mul == sum) {
            System.out.println(n + " is a Spy Number");
        } else {
            System.out.println(n + " is not a Spy Number");
        }
    }
}

Output

Enter number: 1124
1124 is a Spy Number


Enter number: 124
124 is not a Spy Number

Code Explanation

r = num % 10 — extracts the last digit of the number.

sum = sum + r — adds the extracted digit to the running sum.

mul = mul * r — multiplies the digit into the running product.

num = num / 10 — removes the last digit by integer division.

The loop continues until all digits have been processed (num becomes 0), then the final comparison is made.

Spy Number Program in Java Using a Method

This version is more object-oriented and separates the spy number check into its own method. This style is commonly required in ICSE BlueJ-based programs where you define methods inside a class.


import java.util.Scanner;


public class KboatSpyNumber {


    public void spyCheck() {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter Number: ");
        int num = in.nextInt();
        int orgNum = num;


        int digit, sum = 0, prod = 1;


        while (num > 0) {
            digit = num % 10;
            sum += digit;
            prod *= digit;
            num /= 10;
        }


        if (sum == prod)
            System.out.println(orgNum + " is a Spy Number");
        else
            System.out.println(orgNum + " is not a Spy Number");
    }


    public static void main(String[] args) {
        KboatSpyNumber obj = new KboatSpyNumber();
        obj.spyCheck();
    }
}

By storing the original number in orgNum before the loop modifies num, we can print the correct input value in the final output message. This is an important detail that beginners often miss.

Spy Number Program in Java Using For Loop

While the while loop is most common, you can also implement the same logic using a for loop. This is useful if you want to practice different loop constructs.

import java.util.Scanner;


public class SpyNumberForLoop {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = sc.nextInt();


        int sum = 0, prod = 1;


        for (int num = n; num > 0; num /= 10) {
            int digit = num % 10;
            sum += digit;
            prod *= digit;
        }


        if (sum == prod)
            System.out.println(n + " is a Spy Number");
        else
            System.out.println(n + " is not a Spy Number");
    }
}

The for loop here handles initialization (num = n), condition (num > 0), and update (num /= 10) all in one line, keeping the code more compact.

Spy Number Program in Java: Print All Spy Numbers in a Range

This program prints all spy numbers between 1 and a given limit N. It is commonly used as an exercise in loop-based exam questions.


import java.util.Scanner;


public class SpyNumberRange {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter upper limit N: ");
        int N = sc.nextInt();


        System.out.println("Spy Numbers between 1 and " + N + ":");


        for (int i = 1; i <= N; i++) {
            int num = i, sum = 0, prod = 1;
            while (num > 0) {
                int d = num % 10;
                sum += d;
                prod *= d;
                num /= 10;
            }
            if (sum == prod)
                System.out.print(i + "  ");
        }
    }
}

Sample Output (N = 100)

Spy Numbers between 1 and 100:
1  2  3  4  5  6  7  8  9  22

Notice that all single-digit numbers (1–9) are spy numbers because the sum of a single digit equals its product trivially. The first multi-digit spy number is 22 (2+2=4, 2×2=4).

Dry Run / Iteration Trace for Input 1124

Let us trace the execution of the while loop for input 1124 step by step.

Initial values: num = 1124, sum = 0, prod = 1

Iterationnumdigit (num % 10)sumprodnum after /= 10
1112440+4 = 41×4 = 4112
211224+2 = 64×2 = 811
31116+1 = 78×1 = 81
4117+1 = 88×1 = 80
End088Loop exits

After the loop: sum = 8 and prod = 8. Since sum == prod, 1124 is confirmed as a Spy Number.

Common Mistakes to Avoid

common mistakes

When writing a spy number program in Java, beginners often make the following mistakes:

1. Initializing prod = 0 Instead of prod = 1

If you initialize prod = 0, the product will always remain 0 because any number multiplied by 0 is 0. Always initialize prod = 1 for multiplication accumulators.

2. Not Saving the Original Number

The while loop modifies the variable num until it becomes 0. If you do not store the original number before the loop, you cannot reference it in the output statement. Always copy: int orgNum = num; before the loop.

3. Using prod = 0 for Single-Digit Check

For single-digit numbers, the digit extracted is the number itself. Since sum and product will both equal the same single digit, all single-digit numbers are spy numbers by definition.

4. Integer Division Side Effects

Using num /= 10 performs integer division. This is correct and intentional for digit extraction. Do not use floating-point division here.

Spy Number vs Other Special Numbers in Java

To understand where spy numbers fit among other special number categories, here is a quick comparison:

Number TypeCondition / RuleExample
Spy NumberSum of digits = Product of digits1124 (sum=8, prod=8)
Armstrong NumberSum of (digit ^ number of digits) = original number153 (1³+5³+3³=153)
Neon NumberSum of digits of its square = original number9 (81 → 8+1=9)
Automorphic NumberSquare ends with the number itself5 (25 ends in 5)
Kaprekar NumberTwo parts of its square add up to the original number45 (2025 → 20+25=45)
Duck NumberContains at least one zero (no leading zeros)102
Disarium NumberSum of digits raised to positional powers = number135

Frequently Asked Questions (FAQs)

What is a spy number in Java?

A spy number in Java is a number where the sum of all its digits is equal to the product of all its digits. For example, 1124 is a spy number because 1+1+2+4 = 8 and 1×1×2×4 = 8.

Is 1124 a spy number?

Yes. The sum of digits of 1124 is 1+1+2+4 = 8, and the product of digits is 1×1×2×4 = 8. Since both are equal, 1124 is a spy number.

Is 123 a spy number?

Yes. The sum is 1+2+3 = 6 and the product is 1×2×3 = 6. Both are equal, so 123 is a spy number.

Are all single-digit numbers spy numbers?

Yes. For any single-digit number, the sum and product are both the number itself. Therefore, all numbers from 1 to 9 are spy numbers.

What is the difference between a spy number and an Armstrong number?

A spy number checks whether the sum of digits equals the product of digits. An Armstrong number checks whether the sum of each digit raised to the power of the total number of digits equals the original number. These are entirely different mathematical conditions.

Why is prod initialized to 1 and not 0 in the spy number program?

The product variable is initialized to 1 because multiplication by 1 does not change the value. If it were initialized to 0, the product would always remain 0, giving wrong results.

Can a two-digit number be a spy number?

Yes. For example, 22 is a spy number because 2+2 = 4 and 2×2 = 4. Similarly, 11, 13, and a few others also qualify.

Conclusion

The spy number in Java is a classic digit-manipulation problem that reinforces loop logic, modulo operations, and conditional checks. It is frequently asked in ICSE Class 10, BCA, MCA programs, and entry-level Java interviews.

To summarize the core logic: extract each digit of the number, track both the sum and product of those digits, and compare the two after the loop exits. If they are equal, the number is a spy number.