Table of Contents
- What ISC Computer Science expects in Java
- Number programs
- Array and matrix programs
- String programs
- Recursion programs
- Classes and objects programs
- Inheritance and interface programs
- Data structure programs: stack, queue and linked list
- Programs for the ISC practical file and project
- Which programs are most important for ISC?
- Class 11 versus Class 12 programs
- How we teach it
- Frequently asked questions
- Keep going
Java programs for ISC Class 11 and 12 fall into seven groups that the ISC Computer Science syllabus builds up over the two years: number programs, arrays and matrices, strings, recursion, classes and objects, inheritance with interfaces, and data structures such as stacks, queues and linked lists. Below are 37 practical style programs across those groups, each compiled with javac and run on Java 21, with the exact output under the code. They are the shapes that come back in the theory paper's programming questions, the practical exam and the program file you hand in.
Every program is written the ISC way: a class with data members, a constructor, member methods that each do one job, and a main method that creates an object and calls them. Values are fixed in the code so the output is reproducible; in the practical you would read them with Scanner, which changes only the input lines.
Coming from ICSE? The Class 10 bank of 50 Java programs for ICSE Class 10 covers the basics ISC assumes, and the Java programs for ICSE Class 9 go further back still.
What ISC Computer Science expects in Java
The CISCE syllabus for ISC Computer Science splits the Java work across two years. Class 11 covers objects and classes, primitive types and wrapper classes, expressions, statements and scope, methods, arrays and strings, input and output, and a first look at recursion, alongside theory units such as number systems, Boolean logic and computer organisation. Class 12 revisits all of that and adds deeper recursion, inheritance, interfaces and polymorphism, data structures (stacks, queues, dequeues, linked lists and binary trees) and the complexity of algorithms in big O terms. We could not load the CISCE site to quote the exact wording, so check your school's copy of the current syllabus for unit names and marks.
| Group | Mostly Class 11 or 12 | What examiners look for | Programs here |
|---|---|---|---|
| Number programs | 11, revised in 12 | Clean digit and factor logic in separate methods | 1 to 6 |
| Arrays and matrices | 11 and 12 | Sorting, searching, 2D traversal, boundary and diagonal work | 7 to 14 |
| Strings | 11 and 12 | Word splitting, frequency, ciphers, sorting words | 15 to 20 |
| Recursion | Introduced in 11, central in 12 | A correct base case and a smaller recursive call | 21 to 27 |
| Classes and objects | 11 and 12 | Constructors, objects passed to and returned from methods | 28 to 30 |
| Inheritance and interfaces | 12 | super, overriding, abstract methods, interfaces | 31 to 33 |
| Data structures | 12 | Overflow and underflow checks, pointer handling | 34 to 37 |
Write the algorithm first
ISC practical answers are usually expected to show an algorithm, the program and its output, and many schools also ask for a table of variables. Writing the steps in plain English before coding is not a formality: it is where most logic errors are caught.
Number programs
ISC number programs are the ICSE ones grown up: the same digit extraction and factor counting, but split into methods such as isPrime() and sumOfDigits() that a bigger check calls. Splitting them this way is what earns the method marks.
1. Disarium number
Question: A Disarium number is one whose digits, each raised to the power of its position, add up to the number itself, for example 135 = 1¹ + 3² + 5³. Write a class to check a number.
public class Disarium {
int num;
Disarium(int n) {
num = n;
}
int countDigits() {
return String.valueOf(num).length();
}
boolean isDisarium() {
int t = num, pos = countDigits(), sum = 0;
while (t > 0) {
sum += (int) Math.pow(t % 10, pos);
pos--;
t /= 10;
}
return sum == num;
}
public static void main(String[] args) {
int[] tests = {135, 89, 175, 120};
for (int n : tests) {
Disarium d = new Disarium(n);
System.out.println(n + (d.isDisarium() ? " is a Disarium number" : " is not a Disarium number"));
}
}
}
135 is a Disarium number
89 is a Disarium number
175 is a Disarium number
120 is not a Disarium number
2. Smith number
Question: A Smith number is a composite number whose digit sum equals the sum of the digits of its prime factors, counted with repetition. Check 666, 4937775, 85 and 21.
public class Smith {
static int digitSum(long n) {
int s = 0;
while (n > 0) {
s += n % 10;
n /= 10;
}
return s;
}
static boolean isSmith(long n) {
long t = n;
int factorSum = 0, factors = 0;
for (long f = 2; f * f <= t; f++) {
while (t % f == 0) {
factorSum += digitSum(f);
factors++;
t /= f;
}
}
if (t > 1) {
factorSum += digitSum(t);
factors++;
}
return factors > 1 && factorSum == digitSum(n);
}
public static void main(String[] args) {
long[] tests = {666, 4937775, 85, 21};
for (long n : tests)
System.out.println(n + (isSmith(n) ? " is a Smith number" : " is not a Smith number"));
}
}
666 is a Smith number
4937775 is a Smith number
85 is a Smith number
21 is not a Smith number
666 factorises as 2 x 3 x 3 x 37. The digit sums of the factors are 2 + 3 + 3 + 10 = 18, and 6 + 6 + 6 is also 18. The factors > 1 check rules out primes, which would otherwise pass trivially.
3. Kaprekar number
Question: A Kaprekar number n has a square that can be split into a left part and a right part (the right part having as many digits as n) that add up to n, for example 45² = 2025 and 20 + 25 = 45. Print all Kaprekar numbers below 1000.
public class Kaprekar {
static boolean isKaprekar(int n) {
if (n == 1)
return true;
long sq = (long) n * n;
int d = String.valueOf(n).length();
long p = (long) Math.pow(10, d);
long right = sq % p, left = sq / p;
return right > 0 && left + right == n;
}
public static void main(String[] args) {
for (int n = 1; n < 1000; n++)
if (isKaprekar(n))
System.out.print(n + " ");
System.out.println();
}
}
1 9 45 55 99 297 703 999
4. Happy number
Question: A number is happy if repeatedly replacing it by the sum of the squares of its digits eventually reaches 1. Check 19 and 4.
public class Happy {
static int next(int n) {
int s = 0;
while (n > 0) {
int d = n % 10;
s += d * d;
n /= 10;
}
return s;
}
static boolean isHappy(int n) {
while (n != 1 && n != 4) // every unhappy number falls into a cycle containing 4
n = next(n);
return n == 1;
}
public static void main(String[] args) {
System.out.println("19 -> " + next(19) + " -> " + next(next(19)) + " -> " + next(next(next(19))));
System.out.println("19 happy? " + isHappy(19));
System.out.println("4 happy? " + isHappy(4));
}
}
19 -> 82 -> 68 -> 100
19 happy? true
4 happy? false
5. Goldbach pairs
Question: Goldbach's conjecture says every even number greater than 2 is the sum of two primes. It has never been proved, but no counterexample has been found. Print all such prime pairs for 30.
public class Goldbach {
static boolean isPrime(int n) {
if (n < 2)
return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
public static void main(String[] args) {
int n = 30;
System.out.println("Prime pairs that add up to " + n + ":");
for (int a = 2; a <= n / 2; a++)
if (isPrime(a) && isPrime(n - a))
System.out.println(a + ", " + (n - a));
}
}
Prime pairs that add up to 30:
7, 23
11, 19
13, 17
6. Prime palindromes in a range
Question: Print all numbers between 100 and 1000 that are both prime and palindromes, and how many there are.
public class PrimePalin {
static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0) return false;
return true;
}
static int reverse(int n) {
int r = 0;
while (n > 0) {
r = r * 10 + n % 10;
n /= 10;
}
return r;
}
public static void main(String[] args) {
int count = 0;
for (int n = 100; n <= 1000; n++) {
if (isPrime(n) && reverse(n) == n) {
System.out.print(n + " ");
count++;
}
}
System.out.println("\nFrequency = " + count);
}
}
101 131 151 181 191 313 353 373 383 727 757 787 797 919 929
Frequency = 15
Array and matrix programs
Array questions in ISC test two things: the classic algorithms (binary search, selection and bubble sort, insertion) and two dimensional traversal: rows, columns, diagonals and the boundary. Most matrix programs are one nested loop with the right condition on i and j.
7. Binary search
Question: Search for 47 in a sorted array using binary search, and print how many comparisons it took.
public class BinarySearch {
public static void main(String[] args) {
int[] a = {3, 9, 14, 21, 30, 38, 47, 55, 62, 70};
int key = 47, lo = 0, hi = a.length - 1, steps = 0, pos = -1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
steps++;
if (a[mid] == key) {
pos = mid;
break;
} else if (a[mid] < key)
lo = mid + 1;
else
hi = mid - 1;
}
System.out.println("Found at index " + pos + " after " + steps + " comparisons");
}
}
Found at index 6 after 4 comparisons
8. Selection sort
Question: Sort an array in ascending order using selection sort and print the array after each pass.
import java.util.Arrays;
public class SelectionSort {
public static void main(String[] args) {
int[] a = {29, 10, 14, 37, 13};
for (int i = 0; i < a.length - 1; i++) {
int min = i;
for (int j = i + 1; j < a.length; j++)
if (a[j] < a[min])
min = j;
int t = a[i]; a[i] = a[min]; a[min] = t;
System.out.println("Pass " + (i + 1) + ": " + Arrays.toString(a));
}
}
}
Pass 1: [10, 29, 14, 37, 13]
Pass 2: [10, 13, 14, 37, 29]
Pass 3: [10, 13, 14, 37, 29]
Pass 4: [10, 13, 14, 29, 37]
9. Insertion sort
Question: Sort an array of names alphabetically using insertion sort.
import java.util.Arrays;
public class InsertionSort {
public static void main(String[] args) {
String[] s = {"Meera", "Arjun", "Zoya", "Dev", "Kiran"};
for (int i = 1; i < s.length; i++) {
String key = s[i];
int j = i - 1;
while (j >= 0 && s[j].compareTo(key) > 0) {
s[j + 1] = s[j];
j--;
}
s[j + 1] = key;
}
System.out.println(Arrays.toString(s));
}
}
[Arjun, Dev, Kiran, Meera, Zoya]
10. Transpose and symmetric check
Question: Find the transpose of a square matrix and check whether the matrix is symmetric.
public class Symmetric {
public static void main(String[] args) {
int[][] m = {{1, 2, 3}, {2, 5, 6}, {3, 6, 9}};
int n = m.length;
boolean sym = true;
System.out.println("Transpose:");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(m[j][i] + "\t");
if (m[i][j] != m[j][i])
sym = false;
}
System.out.println();
}
System.out.println(sym ? "The matrix is symmetric" : "The matrix is not symmetric");
}
}
Transpose:
1 2 3
2 5 6
3 6 9
The matrix is symmetric
11. Matrix multiplication
Question: Multiply a 2 x 3 matrix by a 3 x 2 matrix.
public class MatMul {
public static void main(String[] args) {
int[][] a = {{1, 2, 3}, {4, 5, 6}};
int[][] b = {{7, 8}, {9, 10}, {11, 12}};
int[][] c = new int[2][2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 3; k++)
c[i][j] += a[i][k] * b[k][j];
for (int[] row : c) {
for (int v : row)
System.out.print(v + "\t");
System.out.println();
}
}
}
58 64
139 154
The rule to remember: columns of the first must equal rows of the second, and the inner loop k runs over that shared size.
12. Rotate a matrix 90 degrees clockwise
Question: Rotate a 3 x 3 matrix by 90 degrees clockwise and print it.
public class Rotate90 {
public static void main(String[] args) {
int[][] m = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int n = m.length;
int[][] r = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
r[j][n - 1 - i] = m[i][j];
for (int[] row : r) {
for (int v : row)
System.out.print(v + " ");
System.out.println();
}
}
}
7 4 1
8 5 2
9 6 3
13. Boundary elements and diagonal sums
Question: Print the boundary elements of a 4 x 4 matrix, their sum, and the sums of both diagonals.
public class Boundary {
public static void main(String[] args) {
int[][] m = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}};
int n = m.length, bsum = 0, left = 0, right = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || j == 0 || i == n - 1 || j == n - 1) {
System.out.print(m[i][j] + "\t");
bsum += m[i][j];
} else {
System.out.print("\t");
}
if (i == j) left += m[i][j];
if (i + j == n - 1) right += m[i][j];
}
System.out.println();
}
System.out.println("Boundary sum = " + bsum);
System.out.println("Left diagonal = " + left + ", right diagonal = " + right);
}
}
1 2 3 4
5 8
9 12
13 14 15 16
Boundary sum = 102
Left diagonal = 34, right diagonal = 34
14. Saddle point
Question: A saddle point is an element that is the smallest in its row and the largest in its column. Find it in a 3 x 3 matrix.
public class SaddlePoint {
public static void main(String[] args) {
int[][] m = {{4, 16, 12}, {2, 8, 14}, {1, 3, 6}};
int n = m.length;
boolean found = false;
for (int i = 0; i < n; i++) {
int col = 0;
for (int j = 1; j < n; j++)
if (m[i][j] < m[i][col])
col = j;
int v = m[i][col];
boolean largest = true;
for (int k = 0; k < n; k++)
if (m[k][col] > v)
largest = false;
if (largest) {
System.out.println("Saddle point = " + v + " at row " + i + ", column " + col);
found = true;
}
}
if (!found)
System.out.println("No saddle point");
}
}
Saddle point = 4 at row 0, column 0
String programs
ISC string questions usually hand you a sentence that ends in a full stop, question mark or exclamation mark and ask you to work word by word. Splitting with split(" ") or a StringTokenizer, then working on each word with charAt(), is the shape of almost all of them.
15. Sort the words of a sentence
Question: Accept a sentence ending in a full stop and print its words in alphabetical order, ignoring case.
public class SortWords {
public static void main(String[] args) {
String s = "Kites fly high above the old market.";
String[] w = s.substring(0, s.length() - 1).split(" ");
for (int i = 0; i < w.length - 1; i++)
for (int j = 0; j < w.length - 1 - i; j++)
if (w[j].compareToIgnoreCase(w[j + 1]) > 0) {
String t = w[j]; w[j] = w[j + 1]; w[j + 1] = t;
}
System.out.println(String.join(" ", w));
}
}
above fly high Kites market old the
16. Palindrome words in a sentence
Question: Print the palindrome words in a sentence and how many there are.
public class PalinWords {
static boolean isPalin(String w) {
int i = 0, j = w.length() - 1;
while (i < j)
if (w.charAt(i++) != w.charAt(j--))
return false;
return true;
}
public static void main(String[] args) {
String s = "MOM AND DAD ARE NOT AT NOON.";
String[] w = s.substring(0, s.length() - 1).split(" ");
int count = 0;
for (String x : w)
if (isPalin(x)) {
System.out.print(x + " ");
count++;
}
System.out.println("\nNumber of palindromic words = " + count);
}
}
MOM DAD NOON
Number of palindromic words = 3
17. Caesar cipher (ROT13)
Question: Encrypt a sentence with ROT13: each letter is moved 13 places along the alphabet, wrapping round, and other characters stay the same.
public class Rot13 {
static String rot13(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isUpperCase(c))
sb.append((char) ('A' + (c - 'A' + 13) % 26));
else if (Character.isLowerCase(c))
sb.append((char) ('a' + (c - 'a' + 13) % 26));
else
sb.append(c);
}
return sb.toString();
}
public static void main(String[] args) {
String s = "Meet me at Gate 4.";
String e = rot13(s);
System.out.println("Encrypted: " + e);
System.out.println("Decrypted: " + rot13(e));
}
}
Encrypted: Zrrg zr ng Tngr 4.
Decrypted: Meet me at Gate 4.
Because 13 is half of 26, applying ROT13 twice gives the original text back, which is a neat way to test the program.
18. Frequency of each letter
Question: Print the frequency of each letter in a word, in alphabetical order.
public class LetterFreq {
public static void main(String[] args) {
String w = "COMMITTEE";
int[] f = new int[26];
for (int i = 0; i < w.length(); i++)
f[w.charAt(i) - 'A']++;
for (int i = 0; i < 26; i++)
if (f[i] > 0)
System.out.println((char) ('A' + i) + " : " + f[i]);
}
}
C : 1
E : 2
I : 1
M : 2
O : 1
T : 2
19. Anagram check
Question: Check whether two words are anagrams of each other.
import java.util.Arrays;
public class Anagram {
static boolean isAnagram(String a, String b) {
char[] x = a.toLowerCase().toCharArray();
char[] y = b.toLowerCase().toCharArray();
Arrays.sort(x);
Arrays.sort(y);
return Arrays.equals(x, y);
}
public static void main(String[] args) {
System.out.println("LISTEN, SILENT: " + isAnagram("LISTEN", "SILENT"));
System.out.println("Night, Thing: " + isAnagram("Night", "Thing"));
System.out.println("APPLE, PAPER: " + isAnagram("APPLE", "PAPER"));
}
}
LISTEN, SILENT: true
Night, Thing: true
APPLE, PAPER: false
20. Capitalise and count vowels in each word
Question: Convert the first letter of every word to upper case and print each word with its number of vowels.
public class WordVowels {
public static void main(String[] args) {
String s = "the quick brown fox jumps";
String out = "";
for (String w : s.split(" ")) {
String cap = Character.toUpperCase(w.charAt(0)) + w.substring(1);
int v = 0;
for (char c : w.toCharArray())
if ("aeiou".indexOf(c) >= 0)
v++;
System.out.println(cap + " : " + v + " vowel(s)");
out += cap + " ";
}
System.out.println(out.trim());
}
}
The : 1 vowel(s)
Quick : 2 vowel(s)
Brown : 1 vowel(s)
Fox : 1 vowel(s)
Jumps : 1 vowel(s)
The Quick Brown Fox Jumps
Recursion programs
Recursion is the topic that most often separates a good ISC score from a great one. Every recursive method needs two things: a base case that stops, and a call on a smaller version of the problem. If you can say what the smaller problem is in one sentence, the method is nearly written.
21. Factorial and power by recursion
Question: Write recursive methods for n! and for x raised to the power n.
public class RecFactPow {
static long fact(int n) {
if (n <= 1)
return 1;
return n * fact(n - 1);
}
static double power(double x, int n) {
if (n == 0)
return 1;
return x * power(x, n - 1);
}
public static void main(String[] args) {
System.out.println("fact(4) = " + fact(4));
System.out.println("fact(15) = " + fact(15));
System.out.println("power(2, 10) = " + power(2, 10));
}
}
fact(4) = 24
fact(15) = 1307674368000
power(2, 10) = 1024.0
22. Fibonacci term by recursion
Question: Print the first 10 Fibonacci terms using a recursive method fib(n).
public class RecFib {
static int fib(int n) {
if (n <= 1)
return n;
return fib(n - 1) + fib(n - 2);
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++)
System.out.print(fib(i) + " ");
System.out.println();
}
}
0 1 1 2 3 5 8 13 21 34
This version is short but slow: fib(n) recomputes the same terms many times, so its running time grows exponentially. That contrast with the loop version is a good answer to an ISC complexity question.
23. HCF by recursion
Question: Find the HCF of two numbers with a recursive Euclid method.
public class RecGcd {
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
public static void main(String[] args) {
System.out.println("HCF(84, 36) = " + gcd(84, 36));
System.out.println("HCF(17, 5) = " + gcd(17, 5));
}
}
HCF(84, 36) = 12
HCF(17, 5) = 1
24. Decimal to binary by recursion
Question: Convert a decimal number to binary using recursion.
public class RecBinary {
static String toBinary(int n) {
if (n < 2)
return String.valueOf(n);
return toBinary(n / 2) + (n % 2);
}
public static void main(String[] args) {
int[] tests = {13, 64, 255};
for (int n : tests)
System.out.println(n + " = " + toBinary(n));
}
}
13 = 1101
64 = 1000000
255 = 11111111
25. Reverse a string and check palindrome by recursion
Question: Reverse a word recursively and use a second recursive method to check whether it is a palindrome.
public class RecString {
static String reverse(String s) {
if (s.length() <= 1)
return s;
return reverse(s.substring(1)) + s.charAt(0);
}
static boolean isPalin(String s, int i, int j) {
if (i >= j)
return true;
if (s.charAt(i) != s.charAt(j))
return false;
return isPalin(s, i + 1, j - 1);
}
public static void main(String[] args) {
String w = "RACECAR";
System.out.println(reverse("COMPUTER"));
System.out.println(w + " palindrome? " + isPalin(w, 0, w.length() - 1));
}
}
RETUPMOC
RACECAR palindrome? true
26. Sum of digits and Armstrong check by recursion
Question: Use a recursive method to find the sum of the cubes of the digits, and check whether 370 and 371 are Armstrong numbers.
public class RecArmstrong {
int num;
RecArmstrong(int n) {
num = n;
}
int sumCubes(int n) {
if (n == 0)
return 0;
int d = n % 10;
return d * d * d + sumCubes(n / 10);
}
void check() {
if (sumCubes(num) == num)
System.out.println(num + " is an Armstrong number");
else
System.out.println(num + " is not an Armstrong number");
}
public static void main(String[] args) {
new RecArmstrong(370).check();
new RecArmstrong(372).check();
}
}
370 is an Armstrong number
372 is not an Armstrong number
This is the classic ISC shape: a class with a data member, a constructor, one recursive method and one method that uses it.
27. Tower of Hanoi
Question: Print the moves needed to shift 3 discs from peg A to peg C using peg B.
public class Hanoi {
static int moves = 0;
static void solve(int n, char from, char via, char to) {
if (n == 0)
return;
solve(n - 1, from, to, via);
System.out.println("Move disc " + n + " from " + from + " to " + to);
moves++;
solve(n - 1, via, from, to);
}
public static void main(String[] args) {
solve(3, 'A', 'B', 'C');
System.out.println("Total moves = " + moves);
}
}
Move disc 1 from A to C
Move disc 2 from A to B
Move disc 1 from C to B
Move disc 3 from A to C
Move disc 1 from B to A
Move disc 2 from B to C
Move disc 1 from A to C
Total moves = 7
n discs always take 2n - 1 moves, so 3 discs take 7.
Classes and objects programs
ISC class design questions give you a specification: data members, a constructor and member methods with exact names. Follow the names exactly, keep each method to its one job, and write a short main that proves it works.
28. Time addition with objects
Question: Design a class Time with hours and minutes, a method that adds two Time objects and returns a new one, and a display method.
public class Time {
int hrs, min;
Time(int h, int m) {
hrs = h;
min = m;
}
Time add(Time t) {
int total = (hrs + t.hrs) * 60 + min + t.min;
return new Time(total / 60, total % 60);
}
void display() {
System.out.println(hrs + " hours " + min + " minutes");
}
public static void main(String[] args) {
Time a = new Time(2, 45);
Time b = new Time(3, 30);
Time c = a.add(b);
c.display();
}
}
6 hours 15 minutes
Passing an object in and returning a new object is a pattern ISC asks for directly. Note that add reads t.hrs, the other object's member.
29. Fraction class
Question: Design a class Fraction with a numerator and denominator, methods to add two fractions and to reduce a fraction to its lowest terms.
public class Fraction {
int num, den;
Fraction(int n, int d) {
num = n;
den = d;
reduce();
}
static int gcd(int a, int b) {
return b == 0 ? Math.abs(a) : gcd(b, a % b);
}
void reduce() {
int g = gcd(num, den);
num /= g;
den /= g;
}
Fraction add(Fraction f) {
return new Fraction(num * f.den + f.num * den, den * f.den);
}
public String toString() {
return num + "/" + den;
}
public static void main(String[] args) {
Fraction a = new Fraction(3, 4);
Fraction b = new Fraction(5, 6);
System.out.println(a + " + " + b + " = " + a.add(b));
System.out.println("12/18 reduces to " + new Fraction(12, 18));
}
}
3/4 + 5/6 = 19/12
12/18 reduces to 2/3
30. Water tank with validation
Question: Design a class Tank with a capacity and a current level in litres, and methods fill and draw. A fill that would overflow, or a draw of more than the tank holds, must be refused.
public class Tank {
int capacity, level;
Tank(int cap) {
capacity = cap;
level = 0;
}
void fill(int litres) {
if (level + litres > capacity)
System.out.println("Refused: only " + (capacity - level) + " litres of space left");
else {
level += litres;
System.out.println("Filled " + litres + ", level now " + level);
}
}
void draw(int litres) {
if (litres > level)
System.out.println("Refused: only " + level + " litres in the tank");
else {
level -= litres;
System.out.println("Drew " + litres + ", level now " + level);
}
}
public static void main(String[] args) {
Tank t = new Tank(500);
t.fill(350);
t.fill(200);
t.draw(400);
t.draw(120);
}
}
Filled 350, level now 350
Refused: only 150 litres of space left
Refused: only 350 litres in the tank
Drew 120, level now 230
Validation inside the method, not in main, is what the specification usually means by refusing an operation: the object protects its own data.
Inheritance and interface programs
Class 12 inheritance questions are written in two parts: a base class is given in full, and you write the derived class that extends it, calls the base constructor with super, and overrides a method. Examiners check three things: extends, the super(...) call, and an overriding method with the same signature.
31. Base and derived class with super
Question: A class Record stores names and marks of 5 students. Derive a class Highest that finds and prints the topper. Use super to call the base constructor and override display().
class Record {
protected String[] names;
protected int[] marks;
Record(String[] n, int[] m) {
names = n;
marks = m;
}
void display() {
for (int i = 0; i < names.length; i++)
System.out.println(names[i] + "\t" + marks[i]);
}
}
public class Highest extends Record {
int index;
Highest(String[] n, int[] m) {
super(n, m);
}
void find() {
index = 0;
for (int i = 1; i < marks.length; i++)
if (marks[i] > marks[index])
index = i;
}
@Override
void display() {
super.display();
System.out.println("Topper: " + names[index] + " with " + marks[index]);
}
public static void main(String[] args) {
Highest h = new Highest(new String[]{"Aman", "Bela", "Chirag", "Diya", "Eshan"},
new int[]{78, 91, 66, 88, 91});
h.find();
h.display();
}
}
Aman 78
Bela 91
Chirag 66
Diya 88
Eshan 91
Topper: Bela with 91
With a tie (Bela and Eshan both have 91), the strict > keeps the first one found. Say so in your answer if the question does not specify.
32. Abstract class and overriding
Question: Write an abstract class Shape with an abstract method area(), and two subclasses Circle and Rectangle. Store both in a Shape array and print each area.
abstract class Shape {
abstract double area();
String name() {
return getClass().getSimpleName();
}
}
class Circle extends Shape {
double r;
Circle(double r) { this.r = r; }
double area() { return Math.PI * r * r; }
}
class Rectangle extends Shape {
double l, b;
Rectangle(double l, double b) { this.l = l; this.b = b; }
double area() { return l * b; }
}
public class ShapeDemo {
public static void main(String[] args) {
Shape[] shapes = {new Circle(2), new Rectangle(4, 5.5)};
for (Shape s : shapes)
System.out.printf("%s area = %.2f%n", s.name(), s.area());
}
}
Circle area = 12.57
Rectangle area = 22.00
Calling s.area() on a Shape reference runs the right subclass method at run time. That is dynamic binding, the polymorphism ISC asks you to explain.
33. Interface implementation
Question: Define an interface Data with a method volume(), and a class Cylinder that implements it.
interface Data {
double PI = 3.142;
double volume();
}
public class Cylinder implements Data {
double r, h;
Cylinder(double r, double h) {
this.r = r;
this.h = h;
}
public double volume() {
return PI * r * r * h;
}
public static void main(String[] args) {
Data d = new Cylinder(3, 10);
System.out.println("Volume = " + d.volume());
}
}
Volume = 282.78
Interface fields are automatically public static final, and an implementing method must be declared public, a frequent compile error in exam answers.
Data structure programs: stack, queue and linked list
The ISC data structures are built on arrays and simple node classes. Every operation needs its boundary check: overflow when the structure is full, underflow when it is empty. Leaving out those checks costs marks even when the main logic is right.
34. Stack using an array
Question: Implement a stack of integers with push, pop and display, including overflow and underflow messages.
public class Stack {
int[] arr;
int top, cap;
Stack(int n) {
cap = n;
arr = new int[n];
top = -1;
}
void push(int v) {
if (top == cap - 1)
System.out.println("Stack overflow, cannot push " + v);
else
arr[++top] = v;
}
int pop() {
if (top == -1) {
System.out.println("Stack underflow");
return -9999;
}
return arr[top--];
}
void display() {
System.out.print("Stack (top first): ");
for (int i = top; i >= 0; i--)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main(String[] args) {
Stack s = new Stack(3);
s.push(10); s.push(20); s.push(30); s.push(40);
s.display();
System.out.println("Popped " + s.pop());
s.display();
s.pop(); s.pop(); s.pop();
}
}
Stack overflow, cannot push 40
Stack (top first): 30 20 10
Popped 30
Stack (top first): 20 10
Stack underflow
35. Circular queue
Question: Implement a circular queue of size 4 with insert, delete and display, showing how the rear wraps round.
public class CircularQueue {
int[] q;
int front, rear, size, count;
CircularQueue(int n) {
size = n;
q = new int[n];
front = 0;
rear = -1;
count = 0;
}
void insert(int v) {
if (count == size) {
System.out.println("Queue full, cannot insert " + v);
return;
}
rear = (rear + 1) % size;
q[rear] = v;
count++;
}
int delete() {
if (count == 0) {
System.out.println("Queue empty");
return -9999;
}
int v = q[front];
front = (front + 1) % size;
count--;
return v;
}
void display() {
System.out.print("Queue: ");
for (int i = 0; i < count; i++)
System.out.print(q[(front + i) % size] + " ");
System.out.println(" (front=" + front + ", rear=" + rear + ")");
}
public static void main(String[] args) {
CircularQueue cq = new CircularQueue(4);
cq.insert(5); cq.insert(10); cq.insert(15); cq.insert(20);
cq.insert(25);
System.out.println("Deleted " + cq.delete());
System.out.println("Deleted " + cq.delete());
cq.insert(25); cq.insert(30);
cq.display();
}
}
Queue full, cannot insert 25
Deleted 5
Deleted 10
Queue: 15 20 25 30 (front=2, rear=1)
The % size is the whole trick: after index 3 the rear goes back to 0, reusing the slots freed by deletions.
36. Dequeue (double ended queue)
Question: Implement a dequeue in an array that allows insertion and deletion at both the front and the rear.
public class Dequeue {
int[] d;
int front, rear, cap;
Dequeue(int n) {
cap = n;
d = new int[n];
front = rear = n / 2; // start in the middle so both ends have room
}
void addFront(int v) {
if (front == 0) { System.out.println("No room at front for " + v); return; }
d[--front] = v;
}
void addRear(int v) {
if (rear == cap) { System.out.println("No room at rear for " + v); return; }
d[rear++] = v;
}
int popFront() {
if (front == rear) { System.out.println("Dequeue empty"); return -9999; }
return d[front++];
}
int popRear() {
if (front == rear) { System.out.println("Dequeue empty"); return -9999; }
return d[--rear];
}
void show() {
System.out.print("Dequeue: ");
for (int i = front; i < rear; i++)
System.out.print(d[i] + " ");
System.out.println();
}
public static void main(String[] args) {
Dequeue dq = new Dequeue(6);
dq.addRear(1); dq.addRear(2); dq.addFront(9); dq.addFront(8);
dq.show();
System.out.println("From front: " + dq.popFront() + ", from rear: " + dq.popRear());
dq.show();
}
}
Dequeue: 8 9 1 2
From front: 8, from rear: 2
Dequeue: 9 1
37. Singly linked list
Question: Create a linked list of nodes with insertion at the end, deletion of a given value, counting of nodes and display.
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
public class LinkedList1 {
Node head;
void insertEnd(int v) {
Node n = new Node(v);
if (head == null) {
head = n;
return;
}
Node p = head;
while (p.next != null)
p = p.next;
p.next = n;
}
void delete(int v) {
if (head == null) return;
if (head.data == v) { head = head.next; return; }
Node p = head;
while (p.next != null && p.next.data != v)
p = p.next;
if (p.next != null)
p.next = p.next.next;
}
int count() {
int c = 0;
for (Node p = head; p != null; p = p.next)
c++;
return c;
}
void display() {
for (Node p = head; p != null; p = p.next)
System.out.print(p.data + " -> ");
System.out.println("null (" + count() + " nodes)");
}
public static void main(String[] args) {
LinkedList1 list = new LinkedList1();
list.insertEnd(12); list.insertEnd(7); list.insertEnd(25); list.insertEnd(3);
list.display();
list.delete(25);
list.display();
list.delete(12);
list.display();
}
}
12 -> 7 -> 25 -> 3 -> null (4 nodes)
12 -> 7 -> 3 -> null (3 nodes)
7 -> 3 -> null (2 nodes)
ISC linked list questions often ask for just one method, for example count the nodes or find the largest value, given the Node class. The traversal line for (Node p = head; p != null; p = p.next) is the heart of every one of them.
Programs for the ISC practical file and project
Schools ask ISC students to keep a program file and to complete project work alongside the written paper. The exact requirements come from your school and the current CISCE regulations, but a program write-up that teachers accept almost everywhere has five parts:
- The question, copied exactly.
- An algorithm in numbered plain English steps.
- The program, with comments that say what each method does.
- A variable description table: name, type and purpose of each variable.
- Output for at least two inputs, including an edge case such as 0, an empty sentence or a full stack.
For a project, pick one idea and carry it end to end rather than collecting unrelated programs. Ideas that fit the syllabus well: a library system with a linked list of books, a quiz that stores questions in an array of objects, a matrix toolkit with a menu, a text analyser for word frequency and palindromes, or a simple bank system with inheritance (a SavingsAccount extending Account). For more ideas see Java programs every college student should know and our Java projects for students page.
| Variable | Type | Purpose (for the Stack program) |
|---|---|---|
| arr | int[] | Holds the stack elements |
| top | int | Index of the top element, -1 when empty |
| cap | int | Maximum number of elements |
| v | int | Value being pushed |
Variable tables are quick marks
A variable description table takes two minutes and is often listed in the marking scheme for practical work. Write it as you code, not at the end, and it also doubles as a check that every variable has one clear job.
Which programs are most important for ISC?
If you have one week, revise in this order, because each group appears in some form almost every year:
- Recursion: factorial, power, HCF, binary conversion, string reverse and palindrome, and one recursive number check inside a class.
- Inheritance: a base class plus a derived class with
superand an overridden method. - Stack and queue with overflow and underflow, including the circular queue.
- Linked list traversal methods: count, search, delete.
- Matrices: boundary, diagonals, transpose and rotation.
- Strings: sentence splitting, word sorting, palindromic words and a cipher.
- Number checks written as methods: Disarium, Smith, Kaprekar, prime palindrome.
Class 11 versus Class 12 programs
Class 11 programs are mostly single classes: number checks, array algorithms, string handling and simple recursion. Class 12 programs add structure: two classes related by inheritance, an interface, a data structure with its own rules, and recursion that works on strings, arrays or objects. If you are in Class 11, programs 1 to 23 (numbers, arrays, strings and the first recursion programs) are your core; in Class 12 everything here is fair game, and the Class 12 paper still draws on the Class 11 skills.
How we teach it
In our ISC classes a student explains their algorithm before typing a line, and we trace recursive calls and loops step by step until they can predict the output, the same way the call stack figure above works. Students derive a rule from examples before seeing the method, solve the same problem three ways (a loop, recursion and a library method, for instance), and treat every compile error as data to learn from. You can see how this works on how we teach, read about our support for ISC Class 11 Computer Science and ISC Class 12 Computer Science, or look at our Java classes for ICSE and ISC students. The first class is free: book a free trial class.
Frequently asked questions
Recursion (factorial, power, HCF, binary conversion, string palindromes), an inheritance pair using super and overriding, stack and queue operations with overflow and underflow, linked list traversal methods, matrix programs such as boundary elements and rotation, and string programs that work word by word.
Number checks written as methods (Disarium, Kaprekar, Smith, Happy), sorting and searching in arrays, two dimensional matrix work, sentence and word handling with strings, and simple recursion. Most are single classes with a constructor and member methods.
Read all the questions first and pick the one whose logic you can see end to end. Write the algorithm in numbered steps, then the program with comments, then run it on the sample input and one edge case of your own. Check the output against your algorithm before you call the examiner.
Recursion is part of the ISC Computer Science syllabus, introduced in Class 11 and used heavily in Class 12, so expect it in the paper. Practise reading a recursive method as well as writing one, because output questions trace recursive calls.
When a question says accept or input, use Scanner (or BufferedReader if your school prefers it). The programs here use fixed values so the output can be shown exactly; replacing those lines with Scanner reads does not change the logic.
Questions often give a Node class and ask for one method, such as counting nodes, finding the largest element or deleting a node, so practise each traversal method on its own as well as the full program.
One substantial program or small system, its algorithm, a variable description table, comments, sample outputs and a short explanation of how it works. Check your school's guidelines for length and format, since they set the details.
Class 12 is usually harder because recursion, inheritance and data structures need you to hold several objects or calls in your head at once. A solid Class 11, especially arrays and methods, makes Class 12 much easier.
Keep going
For more string practice beyond ISC, our string and array programs in Java collection adds interview style problems, and Java constructors explained is worth a read before the class design questions. Students heading into a computer science degree will find the next steps in our Java DSA course.