Fundamentals 23 min read

Classic Java Algorithm Exercises with Sample Solutions

This article presents a collection of classic algorithm problems for Java developers, including Fibonacci rabbit counting, prime number detection, Armstrong numbers, prime factorization, grade classification, GCD/LCM calculation, character statistics, series summation, perfect numbers, falling ball distance, three‑digit permutations, profit‑bonus calculation, age puzzles, pattern printing, and more, each accompanied by complete Java source code.

Java Captain
Java Captain
Java Captain
Classic Java Algorithm Exercises with Sample Solutions

Even when doing web development, you often encounter algorithmic challenges; this article extracts several classic practice algorithms and provides reference solutions in Java.

Program 1 – Fibonacci Rabbit Problem

Problem: A pair of rabbits reproduces each month after the third month, forming a Fibonacci sequence. Compute the total number of rabbits each month.

public class test01 {
    public static void main(String[] args) {
        int f1=1,f2=1,f;
        int M=30;
        System.out.println(1);
        System.out.println(2);
        for(int i=3;i<M;i++) {
            f=f2;
            f2=f1+f2;
            f1=f;
            System.out.println(f2);
        }
    }
}

Program 2 – Prime Numbers Between 101 and 200

Problem: Count and output all prime numbers in the range 101‑200.

public class test02 {
    public static void main(String[] args) {
        int count=0;
        for(int i=101;i<200;i+=2) {
            boolean flag=true;
            for(int j=2;j<=Math.sqrt(i);j++) {
                if(i%j==0) {
                    flag=false;
                    break;
                }
            }
            if(flag==true) {
                count++;
                System.out.println(i);
            }
        }
        System.out.println(count);
    }
}

Program 3 – Armstrong (Narcissistic) Numbers

Problem: Print all three‑digit numbers whose sum of cubes of digits equals the number itself (e.g., 153).

public class test03 {
    public static void main(String[] args) {
        int a,b,c;
        for(int i=101;i<1000;i++) {
            a=i%10;
            b=i/10%10;
            c=i/100;
            if(a*a*a+b*b*b+c*c*c==i)
                System.out.println(i);
        }
    }
}

Program 4 – Prime Factorization

Problem: Decompose a positive integer into its prime factors.

import java.util.Scanner;
public class test04 {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        int n=input.nextInt();
        int k=2;
        while(n>=k) {
            if(n==k) {
                System.out.println(k);
                break;
            } else if(n%k==0) {
                System.out.println(k);
                n=n/k;
            } else {
                k++;
            }
        }
    }
}

Program 5 – Grade Classification Using Nested Ternary Operator

Problem: Map a score to grades A, B, or C based on thresholds.

import java.util.Scanner;public class test05 {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        int score=input.nextInt();
        char grade=score>=90?'A':score>=60?'B':'C';
        System.out.println(grade);
    }
}

Program 6 – GCD and LCM

Problem: Compute the greatest common divisor and least common multiple of two positive integers.

import java.util.Scanner;public class test06 {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        int a=input.nextInt();
        int b=input.nextInt();
        test06 test=new test06();
        int i = test.gongyinshu(a, b);
        System.out.println("最小公因数"+i);
        System.out.println("最大公倍数"+a*b/i);
    }
    public int gongyinshu(int a,int b) {
        if(a<b) {
            int t=b;
            b=a;
            a=t;
        }
        while(b!=0) {
            if(a==b)
                return a;
            int x=b;
            b=a%b;
            a=x;
        }
        return a;
    }
}

Program 7 – Character Statistics

Problem: Count letters, spaces, digits, and other characters in an input line.

import java.util.Scanner;public class test07 {
    public static void main(String[] args) {
        int abccount=0,spacecount=0,numcount=0,othercount=0;
        Scanner input=new Scanner(System.in);
        String toString=input.nextLine();
        char[] ch=toString.toCharArray();
        for(int i=0;i<ch.length;i++) {
            if(Character.isLetter(ch[i])) {
                abccount++;
            } else if(Character.isDigit(ch[i])) {
                numcount++;
            } else if(Character.isSpaceChar(ch[i])){
                spacecount++;
            } else {
                othercount++;
            }
        }
        System.out.println(abccount);
        System.out.println(spacecount);
        System.out.println(numcount);
        System.out.println(othercount);
    }
}

Program 8 – Sum of Series a + aa + aaa + …

Problem: Compute the sum of a series where each term appends the digit a (e.g., 2+22+222+…).

import java.util.Scanner;public class test08 {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        int a=input.nextInt();
        int n=input.nextInt();
        int sum=0,b=0;
        for(int i=0;i<n;i++) {
            b+=a;
            sum+=b;
            a=a*10;
        }
        System.out.println(sum);
    }
}

Program 9 – Perfect Numbers up to 1000

Problem: Find all numbers equal to the sum of their proper divisors.

public class test09 {
    public static void main(String[] args) {
        for(int i=1;i<=1000;i++) {
            int t = 0;
            for(int j=1;j<=i/2;j++) {
                if(i%j==0) {
                    t+=j;
                }
            }
            if(t==i) {
                System.out.println(i);
            }
        }
    }
}

Program 10 – Falling Ball Distance and Bounce Height

Problem: A ball drops from 100 m, rebounds to half the height each time; compute total distance after 10 contacts and the 10th bounce height.

public class test10 {
    public static void main(String[] args) {
        double h=100;
        double s=100;
        for(int i=1;i<=10;i++) {
            h=h/2;
            s=s+2*h;
        }
        System.out.println(s);
        System.out.println(h);
    }
}

Program 11 – Three‑Digit Permutations from {1,2,3,4}

Problem: Generate all distinct three‑digit numbers without repeated digits using digits 1‑4.

class test11 {
    public static void main(String[] args) {
        int count=0;
        for(int i=1;i<5;i++) {
            for(int j=1;j<5;j++) {
                for(int k=1;k<5;k++) {
                    if(i!=j&&j!=k&&i!=k) {
                        count++;
                        System.out.println(i*100+j*10+k);
                    }
                }
            }
        }
        System.out.println(count);
    }
}

Program 12 – Profit‑Based Bonus Calculation

Problem: Compute bonus based on tiered profit percentages.

test12 {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        double x=input.nextDouble();
        double y=0;
        if(x>0&&x<=10) {
            y=x*0.1;
        } else if(x>10&&x<=20) {
            y=10*0.1+(x-10)*0.075;
        } else if(x>20&&x<=40) {
            y=10*0.1+10*0.075+(x-20)*0.05;
        } else if(x>40&&x<=60) {
            y=10*0.1+10*0.075+20*0.05+(x-40)*0.03;
        } else if(x>60&&x<=100) {
            y=10*0.1+10*0.075+20*0.05+20*0.03+(x-60)*0.015;
        } else if(x>100) {
            y=10*0.1+10*0.075+20*0.05+20*0.03+40*0.015+(x-100)*0.01;
        }
        System.out.println(y);
    }
}

Program 13 – Integer Satisfying Two Square Conditions

Problem: Find integer n such that n+100 and n+268 are both perfect squares.

public class test13 {
    public static void main(String[] args) {
        for(int i=-100;i<10000;i++) {
            if(Math.sqrt(i+100)%1==0 && Math.sqrt(i+268)%1==0) {
                System.out.println(i);
            }
        }
    }
}

Program 14 – Day of Year Calculator

Problem: Given a date, determine its ordinal day within the year.

import java.util.*;public class lianxi14 {
    public static void main(String[] args) {
        int year, month, day;
        int days = 0;
        int d = 0;
        int e;
        input fymd = new input();
        do {
            e = 0;
            System.out.print("输入年:");
            year = fymd.input();
            System.out.print("输入月:");
            month = fymd.input();
            System.out.print("输入天:");
            day = fymd.input();
            if(year<0||month<0||month>12||day<0||day>31) {
                System.out.println("输入错误,请重新输入!");
                e=1;
            }
        } while(e==1);
        for(int i=1; i<month; i++) {
            switch (i) {
                case 1:case 3:case 5:case 7:case 8:case 10:case 12:
                    days = 31; break;
                case 4:case 6:case 9:case 11:
                    days = 30; break;
                case 2:
                    if((year%400==0)|| (year%4==0 && year%100!=0)) {
                        days = 29;
                    } else {
                        days = 28;
                    }
                    break;
            }
            d += days;
        }
        System.out.println(year+"-"+month+"-"+day+"是这年的第"+(d+day)+"天。");
    }
}
class input{
    public int input() {
        int value = 0;
        Scanner s = new Scanner(System.in);
        value = s.nextInt();
        return value;
    }
}

Program 15 – Sorting Three Integers

Problem: Output three integers in ascending order.

public class test15 {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        int x=input.nextInt();
        int y=input.nextInt();
        int z=input.nextInt();
        int t=0;
        if(x>y) { t=x; x=y; y=t; }
        if(y>z) { t=z; z=y; y=t; }
        if(x>y) { t=x; x=y; y=t; }
        System.out.println(x+""+y+""+z);
    }
}

Program 16 – 9×9 Multiplication Table

Problem: Print the classic 9×9 multiplication table.

public class test16 {
    public static void main(String[] args) {
        for(int i=1;i<10;i++){
            for(int j=1;j<=i;j++) {
                System.out.print(i+"*"+j+"="+i*j);
                System.out.print(" ");
            }
            System.out.println("");
        }
    }
}

Program 17 – Monkey and Peach Problem

Problem: Determine the initial number of peaches given the consumption pattern over ten days.

public class test17 {
    public static void main(String[] args) {
        int x=1;
        for(int i=10;i>1;i--) {
            x=(x+1)*2;
        }
        System.out.println(x);
    }
}

Program 18 – Table Tennis Team Matching

Problem: Find a matching of three players from each team respecting given constraints.

public class test18 {
    public static void main(String[] args) {
        for(char i='x';i<='z';i++) {
            for(char j='x';j<='z';j++) {
                if(i!=j) {
                    for(char k='x';k<='z';k++) {
                        if(i!=k && j!=k) {
                            if(i!='x' && j!='x' && j!='z') {
                                System.out.println("a:"+i+"
b:"+j+"
c:"+k);
                            }
                        }
                    }
                }
            }
        }
    }
}

Program 19 – Diamond Pattern Printing

Problem: Print a symmetric diamond shape using asterisks.

public class lianxi19 {
    public static void main(String[] args) {
        int H = 7, W = 7; // high and width must be equal odd numbers
        for(int i=0; i<(H+1)/2; i++) {
            for(int j=0; j<W/2-i; j++) {
                System.out.print(" ");
            }
            for(int k=1; k<(i+1)*2; k++) {
                System.out.print('*');
            }
            System.out.println();
        }
        for(int i=1; i<=H/2; i++) {
            for(int j=1; j<=i; j++) {
                System.out.print(" ");
            }
            for(int k=1; k<=W-2*i; k++) {
                System.out.print('*');
            }
            System.out.println();
        }
    }
}

Program 20 – Sum of First 20 Terms of a Fraction Sequence

Problem: Compute the sum of the series 2/1, 3/2, 5/3, 8/5, … for the first 20 terms.

public class test20 {
    public static void main(String[] args) {
        double sum=0, ver=2;
        for(int i=1;i<=10;i++) {
            sum+=ver/i;
            ver+=i;
        }
        System.out.println(sum);
    }
}

Program 21 – Sum of Factorials 1! to 20!

Problem: Calculate 1 + 2! + 3! + … + 20!.

public class test21 {
    public static void main(String[] args) {
        long sum=0, ver=1;
        for(int i=1;i<=20;i++) {
            ver=ver*i;
            sum+=ver;
        }
        System.out.println(sum);
    }
}

Program 22 – Recursive Computation of 5!

Problem: Use recursion to compute 5 factorial.

public class test22 {
    public static void main(String[] args) {
        System.out.println(fac(5));
    }
    public static int fac(int i) {
        if(i==1) return 1;
        else {
            return i*fac(i-1);
        }
    }
}

Program 23 – Age Increment Puzzle

Problem: Starting from age 10, each subsequent person is 2 years older; find the fifth person's age.

public class test23 {
    public static void main(String[] args) {
        int age=10;
        for(int i=2;i<=5;i++) {
            age+=2;
        }
        System.out.println(age);
    }
}

Program 24 – Digit Count and Reverse Printing

Problem: For a positive integer (≤5 digits), output its length and the digits in reverse order.

import java.util.Scanner;
public class test24 {
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        String toString=input.nextLine();
        char[] num=toString.toCharArray();
        System.out.println(num.length);
        for(int i=num.length;i>0;i--) {
            System.out.print(num[i-1]);
        }
    }
}

Program 25 – Palindrome Check for a 5‑Digit Number

Problem: Determine whether a five‑digit integer is a palindrome.

import java.util.Scanner;public class test25 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int numtest=input.nextInt();
        System.out.println(ver(numtest));
    }
    public static boolean ver(int num) {
        if(num<0||(num!=0 && num%10==0))
            return false;
        int ver=0;
        while(num>ver) {
            ver=ver*10+num%10;
            num=num/10;
        }
        return(num==ver||num==ver/10);
    }
}

These examples cover a broad range of fundamental algorithmic concepts useful for interview preparation and programming practice.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaAlgorithmsPracticeProgramming Exercises
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.