Java Number Programs for SDET

Number programs are the warm-up questions of Java coding rounds: reverse a number, check prime, palindrome, factorial, Armstrong, perfect and strong numbers, Fibonacci. Almost all of them use one pattern — digit extraction — and interviewers use them to see whether you handle the edges: zero, negative numbers, overflow and efficiency. Every program here comes from one Java class that was compiled and run; the outputs are real.

Advertisement

The Core Pattern: Digit Extraction

int digit = n % 10;     // last digit
n = n / 10;             // remove the last digit
rev = rev * 10 + digit; // append a digit (for reversing)

Reverse, palindrome, count digits, digit sum, Armstrong and strong numbers are all variations of this loop.

1. Even/Odd and Swapping

static boolean isEven(int n) { return n % 2 == 0; }
// isEven(10) → true, isEven(-7) → false

int a = 5, b = 9;
int t = a; a = b; b = t;          // a=9, b=5

Check n % 2 == 0 rather than n % 2 == 1 — in Java, -7 % 2 is -1, so the "== 1" version gets negative odd numbers wrong. The arithmetic swap without a temp variable (a = a + b; b = a - b; a = a - b;) is a popular trick question, but it can overflow — the temp variable is the safe answer.

2. Reverse a Number ⭐

static int reverse(int n) {
    int rev = 0;
    while (n != 0) {
        int digit = n % 10;                                   // keeps the sign for negatives
        if (rev > Integer.MAX_VALUE / 10 || rev < Integer.MIN_VALUE / 10)
            throw new ArithmeticException("overflow");
        rev = rev * 10 + digit;
        n /= 10;
    }
    return rev;
}
// reverse(12345) → 54321
// reverse(-120)  → -21      (trailing zeros disappear)
// reverse(1999999999) → overflow detected

The overflow check is the follow-up interviewers ask for: reversing 1999999999 would exceed int's range and silently produce a wrong number.

3. Count Digits

static int countDigits(int n) {
    if (n == 0) return 1;                   // the loop would return 0 for zero
    int count = 0;
    for (int x = Math.abs(n); x > 0; x /= 10) count++;
    return count;
}
// countDigits(0) → 1, countDigits(-4567) → 4

Alternative: String.valueOf(Math.abs(n)).length() — simpler, but interviewers usually want the loop.

4. Palindrome Number

static boolean isPalindrome(int n) {
    return n >= 0 && n == reverse(n);      // negatives can't be palindromes ("-121" vs "121-")
}
// 121 → true, 123 → false, -121 → false

5. Factorial

static long factorial(int n) {              // long is exact up to 20!
    long f = 1;
    for (int i = 2; i <= n; i++) f *= i;
    return f;
}
// factorial(5)  → 120
// factorial(20) → 2432902008176640000

With int, 13! silently overflows: the loop gives 1932053504 instead of 6227020800. Beyond 20!, even long overflows — use BigInteger (25! = 15511210043330985984000000).

6. Prime Number ⭐

static boolean isPrime(int n) {
    if (n < 2) return false;                           // 0 and 1 are not prime
    if (n % 2 == 0) return n == 2;                     // 2 is the only even prime
    for (int i = 3; (long) i * i <= n; i += 2)         // check odd divisors up to √n
        if (n % i == 0) return false;
    return true;
}
// Primes up to 30: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
// isPrime(97) → true, isPrime(1) → false

Why stop at √n? If n = a × b, one of the two factors must be ≤ √n — so if no divisor exists up to √n, there isn't one at all. Checking up to n/2 works but is far slower for large numbers. Skipping even numbers halves the work again.

7. Armstrong Number

A number equal to the sum of its digits, each raised to the power of the number of digits. For 153 (three digits): 1³ + 5³ + 3³ = 153. For 1634 (four digits): 1⁴ + 6⁴ + 3⁴ + 4⁴ = 1634.

static boolean isArmstrong(int n) {
    int digits = countDigits(n), sum = 0;
    for (int x = n; x > 0; x /= 10) sum += (int) Math.pow(x % 10, digits);
    return sum == n;
}
// Armstrong numbers below 10,000: 1–9, 153, 370, 371, 407, 1634, 8208, 9474

A common mistake is hard-coding the cube (Math.pow(digit, 3)) — that only works for three-digit numbers and wrongly rejects 1634, 8208 and 9474.

8. Perfect Number

The sum of its proper divisors (excluding itself) equals the number: 6 = 1 + 2 + 3.

static boolean isPerfect(int n) {
    if (n < 2) return false;
    int sum = 1;
    for (int i = 2; (long) i * i <= n; i++)
        if (n % i == 0) { sum += i; if (i != n / i) sum += n / i; }   // add both divisors of each pair
    return sum == n;
}
// Perfect numbers below 10,000: 6, 28, 496, 8128

9. Strong Number

The sum of the factorials of its digits equals the number: 145 = 1! + 4! + 5! = 1 + 24 + 120.

static boolean isStrong(int n) {
    int sum = 0;
    for (int x = n; x > 0; x /= 10) sum += factorial(x % 10);
    return n > 0 && sum == n;
}
// Strong numbers below 100,000: 1, 2, 145, 40585

10. Fibonacci Series

static List<Long> fibonacci(int count) {
    List<Long> out = new ArrayList<>();
    long a = 0, b = 1;
    for (int i = 0; i < count; i++) { out.add(a); long next = a + b; a = b; b = next; }
    return out;
}
// fibonacci(10) → [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

The iterative version is O(n). The "textbook" recursive version (fib(n-1) + fib(n-2)) is exponential — mention it only to explain why you didn't use it.

11. Quick Checks: Positive/Negative, Range and Leap Year

static String sign(int n)            { return n > 0 ? "positive" : n < 0 ? "negative" : "zero"; }
static boolean inRange(int n, int lo, int hi) { return n >= lo && n <= hi; }   // inclusive
static boolean isLeapYear(int y)     { return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0; }
sign(-5) → negative, sign(0) → zero
inRange(10, 1, 10) → true
leap: 2024 true, 1900 false, 2000 true, 2026 false

Zero is neither positive nor negative — handle it explicitly. Decide whether a range is inclusive and say so; here both ends are included. The leap-year rule has two exceptions: century years are not leap years (1900) unless divisible by 400 (2000) — interviewers test exactly those two years.

12. Sum of the First N Numbers, and Even/Odd Sums

static long sumFirstN(int n)         { return (long) n * (n + 1) / 2; }       // long: no overflow
static long[] sumEvenOdd(int n) {                                               // 1..n
    long even = 0, odd = 0;
    for (int i = 1; i <= n; i++) { if (i % 2 == 0) even += i; else odd += i; }
    return new long[]{even, odd};
}
sumFirstN(100) → 5050, sumFirstN(100000) → 5000050000
sumEvenOdd(10) → even 30, odd 25
int overflow trap: n * (n + 1) / 2 as int → 705082704

The formula n × (n + 1) / 2 is O(1) — mention it before writing a loop. Compute it in long: with int, n = 100000 gave 705,082,704 instead of 5,000,050,000, a silent overflow.

13. Factors of a Number

static List<Integer> factors(int n) {
    List<Integer> small = new ArrayList<>(), large = new ArrayList<>();
    for (int i = 1; i <= n / i; i++) {
        if (n % i == 0) { small.add(i); if (i != n / i) large.add(0, n / i); }
    }
    small.addAll(large);
    return small;
}
factors(36) → [1, 2, 3, 4, 6, 9, 12, 18, 36], factors(13) → [1, 13]

Factors come in pairs (i and n / i), so the loop only goes up to √n — the same idea as the prime check — and the i != n / i test stops 6 being added twice for 36. i <= n / i avoids the overflow that i * i <= n hits near Integer.MAX_VALUE.

14. Special Numbers: Magic, Harshad, Automorphic, Binary Check and Palindromes in a Range

static int digitSum(long n)          { int s = 0; while (n > 0) { s += n % 10; n /= 10; } return s; }
static boolean isMagic(int n)        { while (n > 9) n = digitSum(n); return n == 1; }
static boolean isHarshad(int n)      { return n > 0 && n % digitSum(n) == 0; }
static boolean isAutomorphic(int n) {
    long square = (long) n * n;
    long mod = 1;
    for (int t = n; t > 0; t /= 10) mod *= 10;
    if (n == 0) mod = 10;
    return square % mod == n;
}
static boolean isBinaryNumber(long n) {
    if (n < 0) return false;
    do { long d = n % 10; if (d > 1) return false; n /= 10; } while (n > 0);
    return true;
}
static List<Integer> palindromesBetween(int from, int to) {
    List<Integer> out = new ArrayList<>();
    for (int n = from; n <= to; n++) {
        int rev = 0;
        for (int t = n; t > 0; t /= 10) rev = rev * 10 + t % 10;
        if (n >= 0 && rev == n) out.add(n);
    }
    return out;
}
magic: 19 true, 23 false
harshad: 18 true, 19 false
automorphic: 25 true, 76 true, 7 false
binary: 101101 true, 1021 false
palindromes 100..200 → [101, 111, 121, 131, 141, 151, 161, 171, 181, 191]
  • Magic: keep summing digits until one digit is left; magic if it's 1 (19 → 10 → 1).
  • Harshad (Niven): divisible by the sum of its digits (18 ÷ 9 = 2).
  • Automorphic: the square ends with the number itself (25² = 625, 76² = 5776). Square in long.
  • Binary check: every digit is 0 or 1 — reuse digit extraction. (Number-system conversion is in Decimal to Binary and Back.)
  • Palindromes in a range: run the palindrome check from section 4 on every number in the range.

15. Simple and Compound Interest

static double simpleInterest(double principal, double ratePct, double years) {
    return principal * ratePct * years / 100;
}
static double compoundAmount(double principal, double ratePct, double years, int timesPerYear) {
    return principal * Math.pow(1 + ratePct / 100 / timesPerYear, timesPerYear * years);
}
simpleInterest(10000, 8%, 3y) → 2400.00
compoundAmount(10000, 8%, 3y, yearly) → 12597.12, quarterly → 12682.42

Simple interest is P × R × T / 100; compound amount is P × (1 + r/n)n×t, and the interest is that amount minus P. Compounding quarterly earned about 85 more than yearly on the same loan. For real money use BigDecimal with explicit rounding — double is fine for an interview formula, not for a bank.

All code in sections 11–15 comes from one class that was compiled and run on Java 21; the outputs above are real.

16. Largest of Three, Spy, Happy and Buzz Numbers

static int largestOfThree(int a, int b, int c) { return Math.max(a, Math.max(b, c)); }
static boolean isSpy(int n) {                       // digit sum == digit product
    int sum = 0, product = 1;
    for (int t = Math.abs(n); t > 0; t /= 10) { sum += t % 10; product *= t % 10; }
    return n > 0 && sum == product;
}
static boolean isHappy(int n) {                     // repeatedly sum the squares of digits; reaches 1?
    Set<Integer> seen = new HashSet<>();
    while (n != 1 && seen.add(n)) {
        int next = 0;
        for (int t = n; t > 0; t /= 10) next += (t % 10) * (t % 10);
        n = next;
    }
    return n == 1;
}
static boolean isBuzz(int n) { return n % 7 == 0 || Math.abs(n) % 10 == 7; }
largestOfThree(12, 45, 7) → 45, (-3, -9, -1) → -1
spy: 1124 true, 123 true, 1234 false
happy: 19 true, 7 true, 4 false
buzz: 49 true, 27 true, 12 false
  • Largest of three: nested Math.max — and test all-negative input, where a version that starts from 0 returns the wrong answer.
  • Spy: digit sum equals digit product (1+1+2+4 = 1×1×2×4 = 8).
  • Happy: keep replacing the number by the sum of the squares of its digits; happy if it reaches 1 (19 → 82 → 68 → 100 → 1). Unhappy numbers loop forever, so remember the values you've seen — a HashSet turns an infinite loop into a clean false.
  • Buzz: divisible by 7 or ends in 7.

The code in this section comes from one class that was compiled and run on Java 21; the outputs are real.

Complexity Summary

Program Time
Reverse, count digits, palindrome, Armstrong, strong O(d) — d = number of digits
Factorial, Fibonacci (iterative) O(n)
Prime, perfect (up to √n) O(√n)

Step through any of these line by line in the Java Code Visualizer — watching n, digit and rev change is the fastest way to understand digit extraction.

From the Interview Room

My automation work has been in Java — Selenium WebDriver scripts with TestNG in Eclipse — and I use OOP concepts such as classes and objects, method overloading, overriding and constructors in page classes and utilities. Small programs like this one are the building blocks of real framework code: looping through data, comparing expected and actual values, and handling edge cases. On Canolog, the many forms and screens across sales, inventory, finance and service are where keeping page details in POM classes and reusable steps in a business library paid off. Test with 0, 1, negative numbers and a large value before calling the program done.

📚 Official documentation: dev.java: Learn Java (Oracle) · Java 21 API documentation

Frequently Asked Questions

How do you reverse a number in Java?

Repeatedly take the last digit with % 10, append it with rev * 10 + digit, and drop it with / 10 until the number is 0 — checking for overflow.

How do you check whether a number is prime efficiently?

Return false below 2, handle 2 and even numbers, then test odd divisors only up to √n.

What is an Armstrong number?

A number equal to the sum of its digits each raised to the power of the digit count — 153 (3 digits) and 1634 (4 digits) are examples.

Perfect number vs strong number?

A perfect number equals the sum of its proper divisors (6, 28); a strong number equals the sum of the factorials of its digits (145).

Why does factorial give wrong answers for larger numbers?

Overflow: int fails from 13!, long from 21!. Use BigInteger for large values.