Table of Contents
- What the ICSE Class 9 Java syllabus covers
- Input and output programs
- Operators and Math method programs
- Conditional programs: if, else and switch
- Loop programs: for, while and do while
- Number programs: prime, palindrome, Armstrong and more
- Pattern programs with nested for loops
- Character programs: a preview of Class 10 strings
- Printable list of all 51 programs (PDF style)
- The most important Class 9 Java programs
- Practice programs (try these yourself)
- Class 9 Java programs in BlueJ
- How we teach it
- Frequently asked questions
- From Class 9 to the board year
The Java programs for ICSE Class 9 that matter are the ones built from the Class 9 Computer Applications units: input with Scanner, operators and Math methods, if and switch, loops, nested loops for patterns, and number programs such as prime, palindrome and Armstrong. Below are 51 of them in seven families, each compiled with javac and run on Java 21, with the exact output pasted under the code. Practise them in that order and every Class 10 program later is built from pieces you already own.
Each program uses fixed sample values so it runs the moment you paste it into BlueJ, except the input family, where the output shown is a real run with the typed input named above it. When a school question says accept from the user, swap the fixed value for a Scanner line; the logic, which is what earns the marks, stays the same.
Already in Class 10? Our bank of 50 Java programs for ICSE Class 10 picks up where this page stops, and our Class 9 Java revision for Class 10 shows exactly where each Class 9 topic comes back in the board paper.
What the ICSE Class 9 Java syllabus covers
The CISCE syllabus for Class 9 Computer Applications is organised as units, and the programming ones run in this order: an introduction to object oriented ideas, objects and classes, values and data types, operators, input in Java, the Math library methods, conditional constructs (if and switch), iterative constructs (for, while, do while) and nested for loops. There is also a unit on computing and ethics, which is theory, so it has no programs here. Arrays and String methods belong to Class 10. We could not load the CISCE site to quote it (it refuses automated requests), so check your school's copy of the current syllabus for the exact wording and any marks split.
| Class 9 unit | What the programs practise | Programs on this page |
|---|---|---|
| Input in Java | Scanner, print and println, escape sequences | 1 to 6 |
| Operators and Math methods | Arithmetic, increment, ternary, casting, Math.sqrt and Math.pow | 7 to 13 |
| Conditional constructs | if, if else ladders, nested if, switch with break | 14 to 22 |
| Iterative constructs | for, while, do while, running totals, digit extraction | 23 to 32 |
| Number programs | Prime, palindrome, Armstrong, perfect and other special numbers | 33 to 41 |
| Nested for loops | Star, number and letter patterns | 42 to 48 |
| Characters (a Class 10 preview) | char arithmetic, Unicode codes, walking a word | 49 to 51 |
Name the family before you write
Read the question and say which family it belongs to. Digit by digit? That is the while loop with % 10 and / 10. Rows and columns? That is a nested for. Students who classify first rarely freeze in a test.
Input and output programs
The first programs of Class 9 are about getting values in and printing them out neatly. The difference between print and println, escape sequences such as \t and \n, and the Scanner methods nextInt(), nextDouble() and next() all come up as short output questions.
1. Print, println and escape sequences
Question: Write a program to show the difference between print and println, and use \t and \n in the output.
public class EscapeDemo {
public static void main(String[] args) {
System.out.print("Modern ");
System.out.println("Java");
System.out.println("Name\tClass\tRoll");
System.out.println("Asha\t9B\t14");
System.out.println("Line one\nLine two");
System.out.println("She said \"hello\"");
}
}
Modern Java
Name Class Roll
Asha 9B 14
Line one
Line two
She said "hello"
2. Sum and average of three numbers (Scanner)
Question: Accept three integers from the user and print their sum and average.
import java.util.Scanner;
public class SumAverage {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter three numbers: ");
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int sum = a + b + c;
double avg = sum / 3.0;
System.out.println();
System.out.println("Sum = " + sum);
System.out.println("Average = " + avg);
}
}
Enter three numbers:
Sum = 135
Average = 45.0
Notice sum / 3.0. Dividing by the int 3 would throw the fraction away, a favourite trap in output questions. The empty println() only moves to a new line, because the typed numbers are not echoed when the output is captured.
3. Area and perimeter of a rectangle
Question: Accept the length and breadth of a rectangle and print its area and perimeter.
import java.util.Scanner;
public class Rectangle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Length: ");
double l = sc.nextDouble();
System.out.print("Breadth: ");
double b = sc.nextDouble();
System.out.println();
System.out.println("Area = " + (l * b));
System.out.println("Perimeter = " + (2 * (l + b)));
}
}
Length: Breadth:
Area = 100.0
Perimeter = 41.0
4. Swap two numbers with a third variable
Question: Write a program to swap the values of two variables using a third variable.
public class SwapThird {
public static void main(String[] args) {
int a = 15, b = 40;
System.out.println("Before: a = " + a + ", b = " + b);
int t = a;
a = b;
b = t;
System.out.println("After: a = " + a + ", b = " + b);
}
}
Before: a = 15, b = 40
After: a = 40, b = 15
5. Swap two numbers without a third variable
Question: Swap two integers without using a third variable.
public class SwapNoTemp {
public static void main(String[] args) {
int a = 15, b = 40;
a = a + b; // a = 55
b = a - b; // b = 15
a = a - b; // a = 40
System.out.println("a = " + a + ", b = " + b);
}
}
a = 40, b = 15
6. Read a name and a number together
Question: Accept a student's first name and age, and print a sentence using both.
import java.util.Scanner;
public class NameAge {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("First name: ");
String name = sc.next();
System.out.print("Age: ");
int age = sc.nextInt();
System.out.println();
System.out.println(name + " will be " + (age + 5) + " in five years.");
}
}
First name: Age:
Kabir will be 19 in five years.
next() reads one word. To read a full line with spaces you would use nextLine(), and mixing it after nextInt() needs an extra nextLine() to clear the leftover line break.
Operators and Math method programs
Operators are where Class 9 output questions live: pre and post increment, integer division, the remainder operator, the ternary operator and casting. The Math library programs then show which methods return double and which return long or int.
7. Pre and post increment
Question: Predict and print the output of pre and post increment and decrement.
public class IncDec {
public static void main(String[] args) {
int x = 5;
int y = x++ + ++x; // 5 + 7
System.out.println("x = " + x + ", y = " + y);
int p = 10;
int q = p-- - --p; // 10 - 8
System.out.println("p = " + p + ", q = " + q);
}
}
x = 7, y = 12
p = 8, q = 2
Read left to right. x++ hands over 5 and then makes x 6; ++x makes x 7 and hands over 7. So y is 12 and x ends at 7.
8. Integer division and remainder
Question: Show the result of /, % and a cast on the same values.
public class DivMod {
public static void main(String[] args) {
int a = 17, b = 5;
System.out.println("17 / 5 = " + (a / b));
System.out.println("17 % 5 = " + (a % b));
System.out.println("(double) 17 / 5 = " + ((double) a / b));
System.out.println("-17 % 5 = " + (-a % b));
}
}
17 / 5 = 3
17 % 5 = 2
(double) 17 / 5 = 3.4
-17 % 5 = -2
The sign of a remainder in Java follows the left operand, which is why -17 % 5 is -2, not 3.
9. Largest of two numbers with the ternary operator
Question: Use the conditional (ternary) operator to find the larger of two numbers.
public class TernaryMax {
public static void main(String[] args) {
int a = 48, b = 73;
int max = (a > b) ? a : b;
System.out.println("Larger = " + max);
String type = (max % 2 == 0) ? "even" : "odd";
System.out.println("It is " + type);
}
}
Larger = 73
It is odd
10. Math library methods
Question: Print the result of Math.sqrt, Math.cbrt, Math.pow, Math.abs, Math.round, Math.ceil, Math.floor, Math.max and Math.min.
public class MathMethods {
public static void main(String[] args) {
System.out.println(Math.sqrt(144));
System.out.println(Math.cbrt(27));
System.out.println(Math.pow(2, 10));
System.out.println(Math.abs(-7.5));
System.out.println(Math.round(4.5));
System.out.println(Math.round(-4.5));
System.out.println(Math.ceil(4.1));
System.out.println(Math.floor(-4.1));
System.out.println(Math.max(12, 19) + " " + Math.min(12, 19));
}
}
12.0
3.0
1024.0
7.5
5
-4
5.0
-5.0
19 12
Two lines catch students every year: Math.round(-4.5) is -4, because round adds 0.5 and takes the floor, and Math.pow always returns a double, so 2 to the power 10 prints as 1024.0.
11. Roots of a quadratic equation
Question: Find the roots of ax² + bx + c = 0 for a = 1, b = -7, c = 10 using the formula.
public class QuadRoots {
public static void main(String[] args) {
double a = 1, b = -7, c = 10;
double d = b * b - 4 * a * c;
double r1 = (-b + Math.sqrt(d)) / (2 * a);
double r2 = (-b - Math.sqrt(d)) / (2 * a);
System.out.println("Discriminant = " + d);
System.out.println("Roots: " + r1 + " and " + r2);
}
}
Discriminant = 9.0
Roots: 5.0 and 2.0
12. Distance between two points
Question: Find the distance between the points (3, 4) and (9, 12).
public class Distance {
public static void main(String[] args) {
int x1 = 3, y1 = 4, x2 = 9, y2 = 12;
double d = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
System.out.println("Distance = " + d);
}
}
Distance = 10.0
13. Type casting and conversion
Question: Show implicit and explicit type conversion in one program.
public class Casting {
public static void main(String[] args) {
int i = 7;
double d = i; // implicit (widening)
double e = 9.87;
int j = (int) e; // explicit, fraction is cut
char ch = 'A';
int code = ch; // char to int gives its code
char next = (char) (ch + 2);
System.out.println(d + " " + j + " " + code + " " + next);
System.out.println(5 / 2 + 1.5);
}
}
7.0 9 65 C
3.5
The last line is a classic: 5 / 2 is evaluated first as int division and gives 2, and only then does 1.5 make the expression a double.
Conditional programs: if, else and switch
Conditional constructs turn a calculation into a decision. Class 9 tests the if else ladder, nested if, logical operators and switch, including what happens when a break is missing.
14. Even or odd
Question: Check whether a number is even or odd.
public class EvenOdd {
public static void main(String[] args) {
int n = 47;
if (n % 2 == 0)
System.out.println(n + " is even");
else
System.out.println(n + " is odd");
}
}
47 is odd
15. Largest of three numbers
Question: Find the largest of three numbers using if else if.
public class LargestThree {
public static void main(String[] args) {
int a = 25, b = 62, c = 41;
int big;
if (a >= b && a >= c)
big = a;
else if (b >= c)
big = b;
else
big = c;
System.out.println("Largest = " + big);
}
}
Largest = 62
16. Leap year
Question: Check whether a given year is a leap year.
public class LeapYear {
public static void main(String[] args) {
int y = 1900;
if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0)
System.out.println(y + " is a leap year");
else
System.out.println(y + " is not a leap year");
}
}
1900 is not a leap year
1900 is divisible by 4 but it is a century year not divisible by 400, so it is not a leap year. Change y to 2000 or 2024 and both print as leap years.
17. Grade from marks
Question: Print the grade for given marks: A for 90 and above, B for 75 to 89, C for 60 to 74, D for 40 to 59, otherwise E.
public class GradeLadder {
public static void main(String[] args) {
int marks = 78;
char grade;
if (marks >= 90)
grade = 'A';
else if (marks >= 75)
grade = 'B';
else if (marks >= 60)
grade = 'C';
else if (marks >= 40)
grade = 'D';
else
grade = 'E';
System.out.println("Marks " + marks + ": grade " + grade);
}
}
Marks 78: grade B
18. Type of triangle
Question: Accept three sides, check whether they form a triangle, and if so say whether it is equilateral, isosceles or scalene.
public class TriangleType {
public static void main(String[] args) {
int a = 7, b = 7, c = 10;
if (a + b > c && b + c > a && a + c > b) {
if (a == b && b == c)
System.out.println("Equilateral triangle");
else if (a == b || b == c || a == c)
System.out.println("Isosceles triangle");
else
System.out.println("Scalene triangle");
} else {
System.out.println("These sides cannot form a triangle");
}
}
}
Isosceles triangle
19. BMI category
Question: Calculate the body mass index for a weight of 52 kg and height of 1.6 m and print its category: below 18.5 underweight, below 25 normal, below 30 overweight, otherwise obese.
public class BmiCategory {
public static void main(String[] args) {
double w = 52, h = 1.6;
double bmi = w / (h * h);
System.out.println("BMI = " + Math.round(bmi * 10) / 10.0);
if (bmi < 18.5)
System.out.println("Underweight");
else if (bmi < 25)
System.out.println("Normal");
else if (bmi < 30)
System.out.println("Overweight");
else
System.out.println("Obese");
}
}
BMI = 20.3
Normal
Math.round(bmi * 10) / 10.0 is the standard trick for rounding to one decimal place without printf.
20. Day of the week with switch
Question: Accept a number from 1 to 7 and print the day name using switch.
public class DayName {
public static void main(String[] args) {
int d = 5;
switch (d) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
case 5: System.out.println("Friday"); break;
case 6: System.out.println("Saturday"); break;
case 7: System.out.println("Sunday"); break;
default: System.out.println("Invalid day number");
}
}
}
Friday
21. Menu driven area calculator
Question: Using switch, print the area of a circle (choice 1), square (choice 2) or rectangle (choice 3).
public class AreaMenu {
public static void main(String[] args) {
int choice = 1;
double r = 7, s = 9, l = 12, b = 5;
switch (choice) {
case 1:
System.out.println("Area of circle = " + (Math.PI * r * r));
break;
case 2:
System.out.println("Area of square = " + (s * s));
break;
case 3:
System.out.println("Area of rectangle = " + (l * b));
break;
default:
System.out.println("Wrong choice");
}
}
}
Area of circle = 153.93804002589985
Menu driven programs are the switch question schools love. Change choice to 2 or 3 to see the other branches.
22. Fall-through when break is missing
Question: Predict the output of a switch in which the break statements are missing.
public class FallThrough {
public static void main(String[] args) {
int n = 2;
switch (n) {
case 1: System.out.println("one");
case 2: System.out.println("two");
case 3: System.out.println("three");
default: System.out.println("done");
}
}
}
two
three
done
Without break, control falls through every case below the match. That is why case 2 prints three lines.
Loop programs: for, while and do while
Loops are the biggest Class 9 unit by program count. Most loop programs are one of two shapes: a counter loop that builds a running total, or a while loop that peels digits off a number with % 10 and / 10.
23. Multiplication table
Question: Print the multiplication table of 7 up to 10.
public class Table7 {
public static void main(String[] args) {
int n = 7;
for (int i = 1; i <= 10; i++)
System.out.println(n + " x " + i + " = " + (n * i));
}
}
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
24. Sum of the first n natural numbers
Question: Find the sum of the first 50 natural numbers using a for loop, and check it against the formula n(n + 1)/2.
public class SumNatural {
public static void main(String[] args) {
int n = 50, sum = 0;
for (int i = 1; i <= n; i++)
sum += i;
System.out.println("Loop sum = " + sum);
System.out.println("Formula = " + n * (n + 1) / 2);
}
}
Loop sum = 1275
Formula = 1275
25. Factorial
Question: Find the factorial of 10. Use long so larger values fit.
public class Factorial {
public static void main(String[] args) {
int n = 10;
long f = 1;
for (int i = 2; i <= n; i++)
f *= i;
System.out.println(n + "! = " + f);
}
}
10! = 3628800
26. Fibonacci series
Question: Print the first 12 terms of the Fibonacci series.
public class Fibonacci {
public static void main(String[] args) {
int a = 0, b = 1;
for (int i = 1; i <= 12; i++) {
System.out.print(a + " ");
int c = a + b;
a = b;
b = c;
}
System.out.println();
}
}
0 1 1 2 3 5 8 13 21 34 55 89
27. Sum and count of digits
Question: Find the number of digits and the sum of digits of 58216.
public class DigitSum {
public static void main(String[] args) {
int n = 58216, sum = 0, count = 0;
while (n > 0) {
sum += n % 10;
count++;
n /= 10;
}
System.out.println("Digits = " + count + ", sum = " + sum);
}
}
Digits = 5, sum = 22
28. Reverse a number
Question: Reverse the digits of 2048.
public class ReverseNum {
public static void main(String[] args) {
int n = 2048, rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
System.out.println("Reversed = " + rev);
}
}
Reversed = 8402
This is the loop in the trace table above. Every palindrome, Armstrong and special number program later reuses these four lines.
29. HCF and LCM
Question: Find the HCF (GCD) and LCM of 36 and 60 using the Euclidean method.
public class HcfLcm {
public static void main(String[] args) {
int a = 36, b = 60;
int x = a, y = b;
while (y != 0) {
int r = x % y;
x = y;
y = r;
}
int hcf = x;
int lcm = (a * b) / hcf;
System.out.println("HCF = " + hcf + ", LCM = " + lcm);
}
}
HCF = 12, LCM = 180
30. Sum of a series
Question: Find the sum S = 1 + 1/2 + 1/3 + ... + 1/10.
public class HarmonicSum {
public static void main(String[] args) {
double s = 0;
for (int i = 1; i <= 10; i++)
s += 1.0 / i;
System.out.println("S = " + s);
}
}
S = 2.9289682539682538
Write 1.0 / i, not 1 / i. With two ints, 1 / 2 is 0 and the sum would stop at 1.0.
31. Series with powers
Question: Find the sum S = x + x²/2 + x³/3 + ... up to 5 terms for x = 2.
public class PowerSeries {
public static void main(String[] args) {
int x = 2;
double s = 0;
for (int i = 1; i <= 5; i++)
s += Math.pow(x, i) / i;
System.out.println("S = " + s);
}
}
S = 17.066666666666666
32. do while runs at least once
Question: Show the difference between while and do while when the condition is false at the start.
public class DoWhileDemo {
public static void main(String[] args) {
int i = 10;
while (i < 5) {
System.out.println("while: " + i);
i++;
}
int j = 10;
do {
System.out.println("do while: " + j);
j++;
} while (j < 5);
}
}
do while: 10
The while loop checks first and never runs. The do while body runs once before its condition is tested, which is the whole difference examiners ask about.
Number programs: prime, palindrome, Armstrong and more
Number programs combine a loop with one test. Most extract digits; a few count factors. These are the programs most often called important because they come back in Class 10 Section B almost every year.
33. Prime number
Question: Check whether 97 is a prime number.
public class PrimeCheck {
public static void main(String[] args) {
int n = 97, factors = 0;
for (int i = 1; i <= n; i++)
if (n % i == 0)
factors++;
if (factors == 2)
System.out.println(n + " is prime");
else
System.out.println(n + " is not prime");
}
}
97 is prime
Counting factors is the version most Class 9 textbooks teach. A faster version stops at the square root of n; both give the same answer.
34. Prime numbers in a range
Question: Print all prime numbers between 1 and 50.
public class PrimesRange {
public static void main(String[] args) {
for (int n = 2; n <= 50; n++) {
boolean prime = true;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
prime = false;
break;
}
}
if (prime)
System.out.print(n + " ");
}
System.out.println();
}
}
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
35. Palindrome number
Question: Check whether 12321 is a palindrome number.
public class PalinNum {
public static void main(String[] args) {
int n = 12321, temp = n, rev = 0;
while (temp > 0) {
rev = rev * 10 + temp % 10;
temp /= 10;
}
System.out.println(n + (rev == n ? " is a palindrome" : " is not a palindrome"));
}
}
12321 is a palindrome
Keep the original in n and work on a copy. Destroying the original is the most common bug in this whole family.
36. Armstrong number
Question: Check whether 153 is an Armstrong number (the sum of the cubes of its digits equals the number).
public class Armstrong {
public static void main(String[] args) {
int n = 153, temp = n, sum = 0;
while (temp > 0) {
int d = temp % 10;
sum += d * d * d;
temp /= 10;
}
System.out.println(n + (sum == n ? " is an Armstrong number" : " is not an Armstrong number"));
}
}
153 is an Armstrong number
37. Perfect number
Question: Check whether 28 is a perfect number (the sum of its factors other than itself equals the number).
public class Perfect {
public static void main(String[] args) {
int n = 28, sum = 0;
for (int i = 1; i < n; i++)
if (n % i == 0)
sum += i;
System.out.println("Sum of factors = " + sum);
System.out.println(n + (sum == n ? " is perfect" : " is not perfect"));
}
}
Sum of factors = 28
28 is perfect
38. Niven (Harshad) number
Question: Check whether 126 is a Niven number (divisible by the sum of its digits).
public class Niven {
public static void main(String[] args) {
int n = 126, temp = n, sum = 0;
while (temp > 0) {
sum += temp % 10;
temp /= 10;
}
System.out.println(n + (n % sum == 0 ? " is a Niven number" : " is not a Niven number"));
}
}
126 is a Niven number
39. Neon number
Question: Check whether 9 is a Neon number (the sum of the digits of its square equals the number).
public class Neon {
public static void main(String[] args) {
int n = 9, sq = n * n, sum = 0;
while (sq > 0) {
sum += sq % 10;
sq /= 10;
}
System.out.println(n + (sum == n ? " is a Neon number" : " is not a Neon number"));
}
}
9 is a Neon number
40. Spy number
Question: Check whether 1124 is a Spy number (the sum of its digits equals their product).
public class Spy {
public static void main(String[] args) {
int n = 1124, temp = n, sum = 0, prod = 1;
while (temp > 0) {
int d = temp % 10;
sum += d;
prod *= d;
temp /= 10;
}
System.out.println("Sum = " + sum + ", product = " + prod);
System.out.println(n + (sum == prod ? " is a Spy number" : " is not a Spy number"));
}
}
Sum = 8, product = 8
1124 is a Spy number
41. Buzz number
Question: Check whether 147 is a Buzz number (it ends in 7 or is divisible by 7).
public class Buzz {
public static void main(String[] args) {
int n = 147;
if (n % 10 == 7 || n % 7 == 0)
System.out.println(n + " is a Buzz number");
else
System.out.println(n + " is not a Buzz number");
}
}
147 is a Buzz number
Pattern programs with nested for loops
Every pattern program is the same two decisions: the outer loop counts rows, the inner loop decides what to print on each row and how many times. Find the rule linking the row number to what is printed and the code writes itself.
42. Right triangle of stars
Question: Print a right angled triangle of stars with 5 rows.
public class StarTriangle {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++)
System.out.print("* ");
System.out.println();
}
}
}
*
* *
* * *
* * * *
* * * * *
43. Number triangle
Question: Print the pattern 1, 1 2, 1 2 3 and so on for 5 rows.
public class NumTriangle {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++)
System.out.print(j + " ");
System.out.println();
}
}
}
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
44. Inverted number triangle
Question: Print 5 rows starting with 1 2 3 4 5 and removing the last number on each row.
public class InvTriangle {
public static void main(String[] args) {
for (int i = 5; i >= 1; i--) {
for (int j = 1; j <= i; j++)
System.out.print(j + " ");
System.out.println();
}
}
}
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
45. Floyd's triangle
Question: Print Floyd's triangle with 5 rows.
public class Floyd {
public static void main(String[] args) {
int k = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(k + "\t");
k++;
}
System.out.println();
}
}
}
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
46. Pyramid of stars
Question: Print a centred pyramid of stars with 5 rows.
public class Pyramid {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int s = 1; s <= n - i; s++)
System.out.print(" ");
for (int j = 1; j <= 2 * i - 1; j++)
System.out.print("*");
System.out.println();
}
}
}
*
***
*****
*******
*********
A pyramid adds a second inner loop for the spaces: n - i spaces, then 2i - 1 stars.
47. Binary triangle
Question: Print a triangle of alternating 1s and 0s, where each row starts with 1 on odd rows and 0 on even rows.
public class BinaryTriangle {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++)
System.out.print((i + j) % 2 == 0 ? "1 " : "0 ");
System.out.println();
}
}
}
1
0 1
1 0 1
0 1 0 1
1 0 1 0 1
48. Letter triangle
Question: Print A, A B, A B C and so on for 5 rows.
public class LetterTriangle {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (char c = 'A'; c < 'A' + i; c++)
System.out.print(c + " ");
System.out.println();
}
}
}
A
A B
A B C
A B C D
A B C D E
A char can be a loop counter, because each letter has a number code and c++ moves to the next letter.
Character programs: a preview of Class 10 strings
String methods such as charAt() and length() are formally a Class 10 topic, but many schools introduce them late in Class 9, and the char type itself is pure Class 9. These three programs sit on the line between the two years.
49. Character codes and case change
Question: Print the Unicode code of a letter, then convert lower case to upper case using arithmetic.
public class CharCodes {
public static void main(String[] args) {
char c = 'g';
System.out.println("Code of " + c + " = " + (int) c);
char up = (char) (c - 32);
System.out.println("Upper case = " + up);
System.out.println("Is it a vowel? " + (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'));
}
}
Code of g = 103
Upper case = G
Is it a vowel? false
Lower and upper case letters are exactly 32 codes apart: 'a' is 97 and 'A' is 65.
50. Count vowels in a word
Question: Count the vowels in the word EDUCATION.
public class CountVowels {
public static void main(String[] args) {
String w = "EDUCATION";
int v = 0;
for (int i = 0; i < w.length(); i++) {
char ch = w.charAt(i);
if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
v++;
}
System.out.println("Vowels in " + w + " = " + v);
}
}
Vowels in EDUCATION = 5
51. Reverse a word and check palindrome
Question: Reverse the word LEVEL and check whether it is a palindrome.
public class WordPalin {
public static void main(String[] args) {
String w = "LEVEL", rev = "";
for (int i = w.length() - 1; i >= 0; i--)
rev = rev + w.charAt(i);
System.out.println("Reversed: " + rev);
System.out.println(w.equals(rev) ? "Palindrome" : "Not a palindrome");
}
}
Reversed: LEVEL
Palindrome
Compare Strings with equals(), never ==. This is the same idea as the palindrome number, applied to letters.
Printable list of all 51 programs (PDF style)
Many students search for a PDF of Class 9 Java programs to tick off before a test. Here is the whole list as a checklist. Print this page or save it as a PDF from your browser's print menu (choose Save as PDF), and tick each program once you can write it from memory without looking.
| Family | Programs |
|---|---|
| Input and output | 1. Print, println and escape sequences; 2. Sum and average of three numbers (Scanner); 3. Area and perimeter of a rectangle; 4. Swap two numbers with a third variable; 5. Swap two numbers without a third variable; 6. Read a name and a number together |
| Operators and Math | 7. Pre and post increment; 8. Integer division and remainder; 9. Largest of two numbers with the ternary operator; 10. Math library methods; 11. Roots of a quadratic equation; 12. Distance between two points; 13. Type casting and conversion |
| Conditions | 14. Even or odd; 15. Largest of three numbers; 16. Leap year; 17. Grade from marks; 18. Type of triangle; 19. BMI category; 20. Day of the week with switch; 21. Menu driven area calculator; 22. Fall-through when break is missing |
| Loops | 23. Multiplication table; 24. Sum of the first n natural numbers; 25. Factorial; 26. Fibonacci series; 27. Sum and count of digits; 28. Reverse a number; 29. HCF and LCM; 30. Sum of a series; 31. Series with powers; 32. do while runs at least once |
| Number programs | 33. Prime number; 34. Prime numbers in a range; 35. Palindrome number; 36. Armstrong number; 37. Perfect number; 38. Niven (Harshad) number; 39. Neon number; 40. Spy number; 41. Buzz number |
| Patterns | 42. Right triangle of stars; 43. Number triangle; 44. Inverted number triangle; 45. Floyd's triangle; 46. Pyramid of stars; 47. Binary triangle; 48. Letter triangle |
| Characters | 49. Character codes and case change; 50. Count vowels in a word; 51. Reverse a word and check palindrome |
The most important Class 9 Java programs
If time is short before a test, these are the programs to master first, because each one teaches a technique the others reuse:
- Reverse a number (digit extraction) and its cousins palindrome, Armstrong and Spy.
- Prime check (factor counting) and perfect number.
- Largest of three and the grade ladder (if else if).
- Menu driven switch, plus a fall-through output question.
- Fibonacci and a series sum with
1.0 / i. - Right triangle, Floyd's triangle and the pyramid for nested loops.
- Math methods output, especially round, ceil, floor and pow.
Practice programs (try these yourself)
Reading solved programs builds recognition. Writing unseen ones builds skill. Each task below uses only techniques from this page; the program it resembles is in brackets, so you can check your approach without copying it.
- Print all the Armstrong numbers between 100 and 999 (36 inside a loop).
- Accept a number and print the product of its odd digits only (27).
- Print the first 10 terms of 1, 4, 9, 16, ... and their sum (24).
- Check whether a number is a Duck number: it contains a zero, but does not start with one (27).
- Accept a character and say whether it is a letter, a digit or a special character (49).
- Print the pattern 5 4 3 2 1, 5 4 3 2, ... down to 5 (44).
- Accept three angles and say whether they form a triangle and whether it is acute, right or obtuse (18).
- Using switch, convert a temperature to Celsius or Fahrenheit depending on a choice (21).
- Find the sum of the series 1 - 2 + 3 - 4 + ... up to n terms (31).
- Count how many times the digit 7 appears in a long number (27).
How to check your own answer
Pick an input small enough to work out by hand, trace your program on paper, then run it. If the paper and the screen disagree, the difference is the bug, and finding it teaches more than the program did.
Class 9 Java programs in BlueJ
ICSE schools teach Java in BlueJ. Every program here is a normal Java class with a main method, so it runs in BlueJ unchanged: create a new class, paste the code, compile, right click the class and choose the main method. BlueJ also lets you call a method without main and type the arguments in a dialog, which is why some school answers have no Scanner at all. Both styles are accepted as long as the logic is right.
How we teach it
In our classes a student explains their thinking out loud before typing, and we trace a loop line by line until they can predict every step, the way the reverse number table above works. Students derive the rule for a pattern from the rows before seeing any code, solve the same problem three ways (factor counting, square root, and a flag for primes, for example), and treat every error message as data rather than failure. You can see this on how we teach, read about our Java classes for ICSE students, or look at the ICSE Computer Applications course for Classes 9 and 10. The first class is free: book a free trial class.
Frequently asked questions
Digit programs (reverse, palindrome, Armstrong, sum of digits), prime and perfect numbers, the if else ladder, a menu driven switch, Fibonacci and series sums, and nested loop patterns such as Floyd's triangle and the pyramid. Together they cover every programming unit of Class 9.
This page works as one: the printable list above names all 51 programs by family, and your browser's print menu can save the whole page, code and output included, as a PDF.
Right triangles of stars, numbers and letters, inverted triangles, Floyd's triangle, binary (0 and 1) triangles and centred pyramids. All are nested for loops where the outer loop counts rows.
Arrays and String methods are Class 10 topics in the CISCE syllabus. Class 9 covers the char type and its codes, and some schools introduce charAt and length early, which is why three simple character programs are included here as a preview.
Only when the question says accept or input. Otherwise fixed values or method parameters in BlueJ are fine. Converting is a three line change: import java.util.Scanner, create the Scanner, and read the value with nextInt or nextDouble.
A while loop checks its condition before the first run, so it may run zero times. A do while loop runs its body once and then checks, so it always runs at least once. Program 32 shows both with the same false condition.
Enough to cover every family twice: once solved, once unseen. The 51 solved programs here plus the 10 practice tasks do that. Typing each one, rather than reading it, is what makes the logic stick.
Class 10 adds arrays, String methods, user defined methods with parameters, constructors and library classes such as wrapper classes. The loops, conditions and digit logic underneath are the Class 9 ones, which is why Class 9 practice pays off in the board year.
From Class 9 to the board year
When these feel easy, move to the 50 Java programs for ICSE Class 10, and use the Class 9 Java revision for Class 10 to see where each topic returns in the board paper. For patterns in more depth, our pattern programs page goes further, and the string handling guide is the natural next step after the character programs.