Skip to content
Computer ScienceISC Class 12 · Chapter 10

Arrays and Strings in Java: ISC Class 12 Computer Science

Updated 15 October 2026 · Fact-checked

An array stores many values of one type under one name, with constant-time access by index. ISC Class 12 covers one- and two-dimensional arrays, row-major and column-major address calculation, searching, maximum and minimum, bubble, selection and insertion sort, solving linear equations, and the String and StringBuffer classes.

What Arrays, Strings is about

The syllabus asks for:
1. Arrays (single and multi-dimensional) as structured data types; access in constant time regardless of size.
2. Address calculation: row major and column major.
3. Algorithms using arrays: searching, maximum and minimum, sorting (bubble, selection, insertion), solving systems of linear equations.
4. Strings: the String class and its operations (accessing characters, substrings, concatenation, replacement, indexOf), and StringBuffer for heavy manipulation.

This is the most programmed chapter: Part I Question 2 had an address-calculation item [2] in both 2024 and 2025, and Section B often has an array program (sorting, matrices, passing array objects) and a string program (words, characters, ASCII codes). The 2024 paper asked for insertion sort in descending order and a word's characters with their codes; 2025 asked for column sums of two matrix objects and a word-flipping program.

All programs on this page were compiled and run, and every output shown is the actual output.

Weightage: CISCE publishes no chapter or unit weightage for ISC Computer Science. Arrays, Strings is part of Section B, 10 of the 2027 syllabus and can be asked anywhere in the 70-mark Paper 1 (Part I compulsory: ten 1-mark items and a 10-mark short-answer question; Part II: two of three 10-mark questions in each of Sections A and B, and two of three 5-mark questions in Section C).Source: CISCE ISC Computer Science (868) syllabus, examination year 2027; latest Paper 1 specimen (2025) and the 2025 board paper

Key concepts

One- and two-dimensional arrays

Declaration and creation:
int[] a = new int[5]; (indices 0 to 4, elements set to 0)
int[] b = {5, 12, 19}; (initialiser list)
int[][] m = new int[3][4]; (3 rows, 4 columns)

Key facts:
1. Index starts at 0; the last index is length - 1. a.length gives the size (a field, not a method). For a 2D array m.length is the number of rows and m[0].length the number of columns.
2. Accessing an index outside the range throws ArrayIndexOutOfBoundsException.
3. Access time is constant: the address of a[i] is computed directly from the base address, so reaching a[999] takes no longer than a[0].
4. Arrays are objects: an array variable holds a reference; passing it to a method lets the method change the elements.
5. In a class, declare the array as a data member and allocate it with new in the constructor once its size is known: arr = new int[size];.

Common array code: reading with a loop and Scanner; sum and average; counting elements that satisfy a condition (for example odd numbers); maximum and minimum (start from the first element, not 0); reversing; row, column and diagonal sums of a matrix; transpose (t[j][i] = m[i][j]); symmetric check (m[i][j] == m[j][i] for all i, j).

Worked example

[2] Write code to find the average of only the odd elements of an int array arr, handling the case when there are none. (Apply)

Try it first, then show the solutionSolution
  1. int sum = 0, c = 0; for (int i = 0; i < arr.length; i++) if (arr[i] % 2 != 0) { sum += arr[i]; c++; } - 1 mark.
  2. double avg = (c == 0) ? 0 : (double) sum / c; (divide by the count of odd numbers, not by arr.length, and after the loop) - 1 mark.

Answer: Sum and count the odd elements in one loop, then after the loop compute (double) sum / c, using 0 (or a message) when c is 0. For {29, 10, 14, 37, 13} the average is (29 + 37 + 13) / 3 = 26.33...

Address calculation: row major and column major

Memory is a single line of bytes, so a 2D array must be stored row by row (row major, used by Java and C) or column by column (column major).

For an array A[Lr..Ur, Lc..Uc] with base address B and W bytes per element:
Number of rows R = Ur - Lr + 1; number of columns C = Uc - Lc + 1.

Row major: Address of A[I][J] = B + W × [ (I - Lr) × C + (J - Lc) ]
Column major: Address of A[I][J] = B + W × [ (J - Lc) × R + (I - Lr) ]

(For a 1D array A[L..U]: Address of A[I] = B + W × (I - L).)

Worked check for A[-3..12, 5..20], W = 4, B = 1000, element A[4][9]: R = 16, C = 16.
Row major: 1000 + 4 × [(4 + 3) × 16 + (9 - 5)] = 1000 + 4 × 116 = 1464.
Column major: 1000 + 4 × [(9 - 5) × 16 + (4 + 3)] = 1000 + 4 × 71 = 1284.

// Address of A[I][J] for an array declared A[Lr..Ur, Lc..Uc] with base address B and W bytes per element.
public class Address
{
    static long rowMajor(long B, int W, int Lr, int Lc, int Uc, int I, int J)
    {
        int cols = Uc - Lc + 1;
        return B + (long) W * ((I - Lr) * cols + (J - Lc));
    }

    static long colMajor(long B, int W, int Lr, int Ur, int Lc, int I, int J)
    {
        int rows = Ur - Lr + 1;
        return B + (long) W * ((J - Lc) * rows + (I - Lr));
    }

    public static void main(String[] args)
    {
        // A[-3..12, 5..20], W = 4, B = 1000, element A[4][9]
        System.out.println("Row major:    " + rowMajor(1000, 4, -3, 5, 20, 4, 9));
        System.out.println("Column major: " + colMajor(1000, 4, -3, 12, 5, 4, 9));
        // P[1..10, 1..8], W = 2, B = 2000, element P[6][3]
        System.out.println("P row major:  " + rowMajor(2000, 2, 1, 1, 8, 6, 3));
        System.out.println("P col major:  " + colMajor(2000, 2, 1, 10, 1, 6, 3));
    }
}

Output:

Row major:    1464
Column major: 1284
P row major:  2084
P col major:  2050

Tip: in row major you multiply by the number of columns; in column major by the number of rows. Count rows and columns carefully when lower bounds are negative (from -3 to 12 is 16 values).

Worked example

[2] An array P[1..10, 1..8] is stored column-major with 2 bytes per element and base address 2000. Find the address of P[6][3]. (Apply)

Try it first, then show the solutionSolution
  1. R = 10 - 1 + 1 = 10; column major: B + W × [(J - Lc) × R + (I - Lr)] - 1 mark.
  2. 2000 + 2 × [(3 - 1) × 10 + (6 - 1)] = 2000 + 2 × 25 = 2050 - 1 mark.

Answer: 2050 (row major would give 2000 + 2 × [5 × 8 + 2] = 2084).

Searching: linear and binary

Linear search: check each element in turn until the key is found or the array ends. Works on any array; up to n comparisons.

Binary search: only for a sorted array. Compare the key with the middle element: if equal, found; if the key is larger, search the right half (lo = mid + 1); if smaller, the left half (hi = mid - 1); stop when lo > hi (not found). Each comparison halves the search range, so at most about log2 n + 1 comparisons.

// Linear search, iterative binary search (with a trace) and maximum/minimum.
public class Searches
{
    static int linear(int[] a, int key)
    {
        for (int i = 0; i < a.length; i++)
            if (a[i] == key)
                return i;
        return -1;
    }

    static int binary(int[] a, int key)       // a must be sorted in ascending order
    {
        int lo = 0, hi = a.length - 1;
        while (lo <= hi)
        {
            int mid = (lo + hi) / 2;
            System.out.println("lo=" + lo + " hi=" + hi + " mid=" + mid + " a[mid]=" + a[mid]);
            if (a[mid] == key)
                return mid;
            else if (a[mid] < key)
                lo = mid + 1;
            else
                hi = mid - 1;
        }
        return -1;
    }

    public static void main(String[] args)
    {
        int[] a = {5, 12, 19, 23, 31, 44, 56, 70};
        System.out.println("linear(31) = " + linear(a, 31));
        System.out.println("binary(56) = " + binary(a, 56));
        System.out.println("binary(20) = " + binary(a, 20));
        int max = a[0], min = a[0];
        for (int v : a)
        {
            if (v > max) max = v;
            if (v < min) min = v;
        }
        System.out.println("max = " + max + ", min = " + min);
    }
}

Output:

linear(31) = 4
lo=0 hi=7 mid=3 a[mid]=23
lo=4 hi=7 mid=5 a[mid]=44
lo=6 hi=7 mid=6 a[mid]=56
binary(56) = 6
lo=0 hi=7 mid=3 a[mid]=23
lo=0 hi=2 mid=1 a[mid]=12
lo=2 hi=2 mid=2 a[mid]=19
binary(20) = -1
max = 70, min = 5

The trace shows binary search finding 56 in three steps and concluding that 20 is absent after three steps, when lo passes hi.

Maximum and minimum: start with the first element (not 0, which fails for all-negative data) and update in one pass.

Worked example

[2] Trace a binary search for 44 in {5, 12, 19, 23, 31, 44, 56, 70}. (Apply)

Try it first, then show the solutionSolution
  1. lo = 0, hi = 7, mid = 3: a[3] = 23 < 44 → lo = 4 - 1 mark.
  2. lo = 4, hi = 7, mid = 5: a[5] = 44 → found at index 5 - 1 mark.

Answer: Found at index 5 after two comparisons.

Sorting: bubble, selection and insertion

Bubble sort: compare adjacent pairs and swap if out of order; after pass i the i largest elements are in place at the end. n - 1 passes (can stop early if a pass makes no swap).
Selection sort: in pass i find the smallest of the unsorted part and swap it into position i. Exactly one swap per pass.
Insertion sort: take elements one by one from index 1 and insert each into its correct place among the already sorted elements on its left, shifting larger (for ascending) or smaller (for descending) ones right.

For descending insertion sort the shifting condition is j >= 0 && a[j] < key; test j >= 0 first so that a[-1] is never accessed (short-circuit &&).

// Bubble, selection and insertion sort, printing the array after every pass.
public class Sorts
{
    static void show(String label, int[] a)
    {
        System.out.print(label);
        for (int v : a)
            System.out.print(" " + v);
        System.out.println();
    }

    static void bubble(int[] a)                 // ascending
    {
        for (int i = 0; i < a.length - 1; i++)
        {
            for (int j = 0; j < a.length - 1 - i; j++)
                if (a[j] > a[j + 1])
                {
                    int t = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = t;
                }
            show("bubble pass " + (i + 1) + ":", a);
        }
    }

    static void selection(int[] a)              // ascending
    {
        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;
            show("selection pass " + (i + 1) + ":", a);
        }
    }

    static void insertionDesc(int[] a)          // descending
    {
        for (int i = 1; i < a.length; i++)
        {
            int key = a[i];
            int j = i - 1;
            while (j >= 0 && a[j] < key)        // test j >= 0 first to stay inside the array
            {
                a[j + 1] = a[j];                // shift smaller elements right
                j--;
            }
            a[j + 1] = key;
            show("insertion pass " + i + ":", a);
        }
    }

    public static void main(String[] args)
    {
        bubble(new int[] {29, 10, 14, 37, 13});
        selection(new int[] {29, 10, 14, 37, 13});
        insertionDesc(new int[] {29, 10, 14, 37, 13});
    }
}

Output:

bubble pass 1: 10 14 29 13 37
bubble pass 2: 10 14 13 29 37
bubble pass 3: 10 13 14 29 37
bubble pass 4: 10 13 14 29 37
selection pass 1: 10 29 14 37 13
selection pass 2: 10 13 14 37 29
selection pass 3: 10 13 14 37 29
selection pass 4: 10 13 14 29 37
insertion pass 1: 29 10 14 37 13
insertion pass 2: 29 14 10 37 13
insertion pass 3: 37 29 14 10 13
insertion pass 4: 37 29 14 13 10

Comparison: all three take about n² comparisons in the worst case. Insertion sort is fast on nearly sorted data (best case about n); selection sort makes the fewest swaps; bubble sort is the simplest to code.

Worked example

[2] Show the array {29, 10, 14, 37, 13} after the first two passes of insertion sort in descending order. (Apply)

Try it first, then show the solutionSolution
  1. Pass 1 (key 10): 10 < 29, stays → 29 10 14 37 13 - 1 mark.
  2. Pass 2 (key 14): 10 shifts right, 14 placed after 29 → 29 14 10 37 13 - 1 mark.

Answer: After pass 1: 29 10 14 37 13; after pass 2: 29 14 10 37 13 (program output).

Matrices and systems of linear equations

Two-dimensional arrays model matrices. Nested loops visit every element: the outer loop for rows, the inner for columns (or the other way round for column-wise work such as column sums).

Solving two linear equations a1x + b1y = c1 and a2x + b2y = c2 by Cramer's rule with an array of coefficients:
D = a1b2 - b1a2; Dx = c1b2 - b1c2; Dy = a1c2 - c1a2; if D ≠ 0, x = Dx / D and y = Dy / D (if D = 0 there is no unique solution).

// 2D arrays: transpose, symmetric check, and solving two linear equations by Cramer's rule.
public class Matrix
{
    static boolean symmetric(int[][] m)
    {
        for (int i = 0; i < m.length; i++)
            for (int j = 0; j < m.length; j++)
                if (m[i][j] != m[j][i])
                    return false;
        return true;
    }

    public static void main(String[] args)
    {
        int[][] a = {{1, 7, 3}, {7, 4, 5}, {3, 5, 6}};
        int[][] b = {{1, 2}, {3, 4}};
        System.out.println("a symmetric? " + symmetric(a) + ", b symmetric? " + symmetric(b));

        int[][] t = new int[2][2];
        for (int i = 0; i < 2; i++)
            for (int j = 0; j < 2; j++)
                t[j][i] = b[i][j];
        System.out.println("transpose of b: " + t[0][0] + " " + t[0][1] + " / " + t[1][0] + " " + t[1][1]);

        // 2x + 3y = 13, 5x - y = 7 written as coefficient array {a1, b1, c1}, {a2, b2, c2}
        double[][] e = {{2, 3, 13}, {5, -1, 7}};
        double D = e[0][0] * e[1][1] - e[0][1] * e[1][0];
        double Dx = e[0][2] * e[1][1] - e[0][1] * e[1][2];
        double Dy = e[0][0] * e[1][2] - e[0][2] * e[1][0];
        System.out.println("D = " + D + ", x = " + Dx / D + ", y = " + Dy / D);
    }
}

Output:

a symmetric? true, b symmetric? false
transpose of b: 1 3 / 2 4
D = -17.0, x = 2.0, y = 3.0

For 2x + 3y = 13 and 5x - y = 7: D = -2 - 15 = -17, Dx = -13 - 21 = -34, Dy = 14 - 65 = -51, so x = 2 and y = 3. Larger systems use Gaussian elimination (reduce to triangular form by row operations, then back-substitute).

Worked example

[2] Write the loop that computes the sum of each column of an m × n matrix mat. (Apply)

Try it first, then show the solutionSolution
  1. Outer loop over columns j from 0 to n - 1; reset s = 0 - 1 mark.
  2. Inner loop over rows i: s += mat[i][j]; print or store s after the inner loop - 1 mark.

Answer: for (int j = 0; j < n; j++) { int s = 0; for (int i = 0; i < m; i++) s += mat[i][j]; System.out.println("Column " + j + ": " + s); }

String and StringBuffer

String objects are immutable: methods return new strings and never change the original. Key methods:

MethodResult
length( )number of characters
charAt(i)character at index i
indexOf(ch or str), lastIndexOf(ch)first or last position, or -1
substring(b), substring(b, e)characters from b to the end, or from b to e - 1
concat(s), +joined string
replace(a, b)every a replaced by b
toUpperCase( ), toLowerCase( ), trim( )case change; spaces removed at both ends
equals(s), equalsIgnoreCase(s)content comparison
compareTo(s)0 if equal, negative if earlier in dictionary order, positive if later
startsWith, endsWith, containsboolean tests

Use equals( ), not ==, to compare string contents.

StringBuffer is a mutable sequence of characters, efficient when a string is changed many times: append( ), insert(i, s), reverse( ), deleteCharAt(i), delete(b, e), setCharAt(i, ch), replace(b, e, s), length( ), toString( ).

// String and StringBuffer methods with their outputs.
public class StringOps
{
    public static void main(String[] args)
    {
        String s = "Computer Science";
        System.out.println(s.length() + " " + s.charAt(3) + " " + s.indexOf('e') + " " + s.lastIndexOf('e'));
        System.out.println(s.substring(9) + "|" + s.substring(0, 8) + "|" + s.indexOf("Sci"));
        System.out.println(s.toUpperCase() + " " + s.replace('e', '*'));
        System.out.println("apple".compareTo("apricot") + " " + "Bat".equalsIgnoreCase("bAT") + " " + "abc".equals("ABC"));
        System.out.println("  trim me  ".trim() + "|" + "a-b-c".replace("-", "") + "|" + "ISC".concat("2027"));
        System.out.println("level".startsWith("le") + " " + "level".endsWith("vel") + " " + "level".contains("eve"));

        StringBuffer sb = new StringBuffer("PROGRAM");
        sb.reverse();
        System.out.println(sb);
        sb.reverse().insert(3, "-").append("S");
        System.out.println(sb + " " + sb.length());
        sb.deleteCharAt(3).setCharAt(0, 'p');
        System.out.println(sb);
    }
}

Output:

16 p 6 15
Science|Computer|9
COMPUTER SCIENCE Comput*r Sci*nc*
-2 true false
trim me|abc|ISC2027
true true true
MARGORP
PRO-GRAMS 9
pROGRAMS

Note "apple".compareTo("apricot") is 'p' - 'r' = -2 (the first differing characters).

A complete string program: words of a sentence sorted by length (insertion sort on a String array) with palindromes counted.

import java.util.Scanner;
import java.util.StringTokenizer;

// Accepts a sentence in upper case ending with '.', '?' or '!', counts its palindromic words,
// and prints the words arranged in ascending order of length (insertion sort; equal lengths keep their order).
public class WordSort
{
    String sent;
    String[] w;
    int n;

    WordSort()
    {
        sent = "";
        n = 0;
    }

    void accept()
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a sentence:");
        sent = sc.nextLine().trim().toUpperCase();
    }

    boolean valid()
    {
        char last = sent.charAt(sent.length() - 1);
        return last == '.' || last == '?' || last == '!';
    }

    boolean isPalin(String x)
    {
        int i = 0, j = x.length() - 1;
        while (i < j)
        {
            if (x.charAt(i) != x.charAt(j))
                return false;
            i++;
            j--;
        }
        return true;
    }

    void split()
    {
        StringTokenizer st = new StringTokenizer(sent.substring(0, sent.length() - 1));
        n = st.countTokens();
        w = new String[n];
        for (int i = 0; i < n; i++)
            w[i] = st.nextToken();
    }

    void sortByLength()
    {
        for (int i = 1; i < n; i++)
        {
            String key = w[i];
            int j = i - 1;
            while (j >= 0 && w[j].length() > key.length())
            {
                w[j + 1] = w[j];
                j--;
            }
            w[j + 1] = key;
        }
    }

    void display()
    {
        if (!valid())
        {
            System.out.println("INVALID INPUT");
            return;
        }
        split();
        int count = 0;
        for (int i = 0; i < n; i++)
            if (isPalin(w[i]))
                count++;
        sortByLength();
        System.out.println("Palindromic words: " + count);
        for (int i = 0; i < n; i++)
            System.out.print(w[i] + " ");
        System.out.println();
    }

    public static void main(String[] args)
    {
        WordSort ob = new WordSort();
        ob.accept();
        ob.display();
    }
}

Input: madam and her civic friends refer to noon tea.

Enter a sentence:
Palindromic words: 4
TO AND HER TEA NOON MADAM CIVIC REFER FRIENDS

Worked example

[2] Give the output: String s = "Computer Science"; System.out.println(s.substring(9) + "|" + s.indexOf("Sci")); (Apply)

Try it first, then show the solutionSolution
  1. Index 9 is 'S' (C0 ... r7, space 8, S9), so substring(9) = "Science" - 1 mark.
  2. "Sci" starts at 9; output Science|9 - 1 mark.

Answer: Science|9

Arrays, Strings in real life

Each concept, met in an everyday situation. Read the situation, answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.

Row-major storage

Imagine a cinema hall where seats are numbered continuously row by row: row A seats 1-20, row B seats 21-40, and so on.

How would you find the seat number of row D, seat 7, and which storage order is this like?

Try it first, then show the solutionSolution
  1. Three full rows come before row D: 3 × 20 = 60 seats.
  2. Seat number = 60 + 7 = 67: the row-major formula (I - Lr) × C + (J - Lc), plus 1 for numbering from 1.

Answer: Seat 67; this is row-major ordering, the same idea used to compute array addresses.

Memory hook: Full rows first, then the seat.

Binary search

Suppose you look for a word in a printed dictionary by opening near the middle and then moving to the half where the word must be.

Which search is this, and what must be true of the dictionary?

Try it first, then show the solutionSolution
  1. Halving the range each time is binary search.
  2. It works only because the dictionary is sorted alphabetically.

Answer: Binary search, which needs sorted data; it finds a word among thousands in a few steps.

Memory hook: Sorted first, then halve.

Insertion sort

Imagine sorting playing cards in your hand: you pick each new card and slide it left until it sits in the right place.

Which sorting method is this?

Try it first, then show the solutionSolution
  1. The cards on the left are always sorted.
  2. Each new card is inserted by shifting bigger cards right.

Answer: Insertion sort.

Memory hook: Pick a card, slide it home.

Topics in this chapter

Arrays, Strings: syntax and key facts

Row major
Addr = B + W × [ (I - Lr) × C + (J - Lc) ], C = Uc - Lc + 1
Multiply by columns.
Column major
Addr = B + W × [ (J - Lc) × R + (I - Lr) ], R = Ur - Lr + 1
Multiply by rows.
Binary search step
  1. 1.mid = (lo + hi) / 2; key > a[mid]
  2. 2.lo = mid + 1; key < a[mid]
  3. 3.hi = mid - 1
Stop when lo > hi.
Insertion sort (descending) condition
while (j >= 0 && a[j] < key) { a[j + 1] = a[j]; j--; } a[j + 1] = key;
Ascending uses a[j] > key.
Cramer's rule (2 × 2)
D = a1b2 - b1a2; x = (c1b2 - b1c2) / D; y = (a1c2 - c1a2) / D
D ≠ 0.
substring
s.substring(b, e) = characters b to e - 1
Length e - b.

How the board asks Arrays, Strings

The question patterns to expect, and the method that works for each.

Question typeHow it is askedMethod
Address calculation [2]Find the address of an element in row-major or column-major storage, often with negative lower bounds.Write the formula, compute R or C, substitute, show working, state the final address.
Array programs [10]Sorting (often insertion, sometimes descending), statistics of elements, matrix operations, arrays inside objects passed to methods.Allocate in the constructor; use the named sort exactly; return values from non-void methods.
String programs [10]Characters with codes, words of a sentence, palindromes, flipping or rearranging words, heterograms, frequency.Use charAt, length, substring, indexOf/lastIndexOf; validate the sentence's terminator if asked.
Output questions [1]-[2]Results of String and StringBuffer methods; sort passes; binary search traces.Count indices from 0; remember immutability of String.

Tricks to remember Arrays, Strings

Short memory aids. Say each one aloud once, then use it on a question the same day.

  • Row major × Columns, Column major × Rows

    The order name and the multiplier are opposites.

    Use it when: Address formulas.

  • Bubble bubbles, Selection selects, Insertion inserts

    Bubble: largest floats to the end. Selection: pick the minimum. Insertion: slide into place.

    Use it when: Sort identification.

  • substring end is exclusive

    (b, e) stops just before e.

    Use it when: String outputs.

Arrays, Strings: board-level solved questions

Ordered from board level to HOTS. Cover the solution, write your own, then compare step by step.

Example 1: String immutability · 1 mark · MCQBoard level

After String s = "java"; s.toUpperCase(); System.out.println(s); what is printed?
(a) JAVA
(b) java
(c) Java
(d) error

Try it first, then show the solutionSolution
  1. toUpperCase( ) returns a new string; the result was not stored.
  2. s still refers to "java".

Answer: (b) java.

Example 2: Row-major address · 2 marks · Short answerBoard level

[2] A[-3..12, 5..20] is stored row-major with 4 bytes per element and base address 1000. Find the address of A[4][9]. (Apply)

Try it first, then show the solutionSolution
  1. C = 20 - 5 + 1 = 16; Addr = B + W × [(I - Lr) × C + (J - Lc)].
  2. 1000 + 4 × [(4 + 3) × 16 + 4] = 1000 + 4 × 116 = 1464.

Answer: 1464 (program output).

Example 3: Assertion-reason: binary search · 1 mark · Assertion-reasonHarder board level

Assertion (A): Binary search cannot be applied directly to the array {31, 5, 70, 12}.
Reason (R): Binary search depends on the array being sorted.
(a) Both A and R are true and R is the correct explanation of A.
(b) Both A and R are true but R is not the correct explanation of A.
(c) A is true but R is false.
(d) A is false but R is true.

Try it first, then show the solutionSolution
  1. The array is unsorted, so halving decisions would be wrong: A is true.
  2. R gives exactly the reason.

Answer: (a) Both A and R are true and R is the correct explanation of A.

Example 4: Selection sort passes · 2 marks · Short answerHarder board level

[2] Show {29, 10, 14, 37, 13} after each of the first two passes of selection sort (ascending). (Apply)

Try it first, then show the solutionSolution
  1. Pass 1: minimum 10 swapped with 29 → 10 29 14 37 13.
  2. Pass 2: minimum of 29 14 37 13 is 13, swapped with 29 → 10 13 14 37 29.

Answer: 10 29 14 37 13, then 10 13 14 37 29 (program output).

Example 5: Bubble sort class with early exit · 10 marks · Long answerHOTS / competency

[10] Design a class Ranker with data members arr[ ] and size; a constructor Ranker(int s) that sets size and creates the array; void getArray( ) to accept the elements; void bubbleDesc( ) that sorts the array in descending order by bubble sort, stopping early when a pass makes no swap; int countAboveAvg( ) returning how many elements are greater than the average of all the elements; and void display( ) that prints the sorted array and, by invoking countAboveAvg( ), the count with a message. Write main( ). (Create)

Try it first, then show the solutionSolution
  1. Constructor: size = s; arr = new int[size];
  2. getArray( ): Scanner, loop i from 0 to size - 1 reading arr[i].
  3. bubbleDesc( ): for i from 0 to size - 2 { boolean swapped = false; for j from 0 to size - 2 - i, if (arr[j] < arr[j + 1]) swap and set swapped = true; if (!swapped) break; }
  4. countAboveAvg( ): first loop finds the sum; double avg = (double) sum / size; second loop counts arr[i] > avg; return the count.
  5. display( ): print the elements; print 'Elements above the average: ' + countAboveAvg( ).
  6. main( ): new Ranker(5), getArray( ), bubbleDesc( ), display( ). For 29 10 14 37 13: sorted 37 29 14 13 10; average 103 / 5 = 20.6, so 2 elements (37, 29) are above it. For 50 40 45 30 20 the second pass makes no swap, so the sort stops after 2 passes.

Answer: Sorted descending: 37 29 14 13 10; elements above the average (20.6): 2. With 50 40 45 30 20 the early exit stops after the second pass and the count is 3 (average 37). Checked by compiling and running the class.

Example 6: Word sorting program · 10 marks · Long answerHOTS / competency

[10] Design a class WordSort that accepts a sentence (converted to upper case) ending with '.', '?' or '!', reports INVALID INPUT otherwise, counts the palindromic words, and prints the words in ascending order of length, keeping the original order for words of equal length. Write the methods valid( ), isPalin(String), split( ), sortByLength( ), display( ) and main( ). (Create)

Try it first, then show the solutionSolution
  1. accept( ) reads and converts to upper case; valid( ) checks the last character.
  2. isPalin( ): two indices moving inwards, returning false on a mismatch.
  3. split( ): StringTokenizer on the sentence without its terminator; store words in a String array of size countTokens( ).
  4. sortByLength( ): insertion sort comparing lengths with >, which keeps equal-length words in order (stable).
  5. display( ): validate, split, count palindromes, sort, print count and words.
  6. Output for 'madam and her civic friends refer to noon tea.': Palindromic words: 4; TO AND HER TEA NOON MADAM CIVIC REFER FRIENDS.

Answer: See the compiled WordSort program and its output above.

Case-study practice (Section D style)

Read the situation, then answer every part. In the board paper this is a 6-mark question split into 2 + 1 + 1 + 2 marks.

Two matrices compared (case-based)

Matrix A = [[2, 3, 1], [7, 5, 6], [1, 4, 2]] is stored in an int[3][3] array in row-major order with base address 500 and 4 bytes per element (indices from 0).

  1. (i) · 2 marks

    Find the address of A[2][1].

    Answer

    Answer: 500 + 4 × (2 × 3 + 1) = 528.

    1 for formula, 1 for value.

  2. (ii) · 1 mark

    Give the column sums of A.

    Answer

    Answer: 10, 12, 9.

    1 mark.

  3. (iii) · 1 mark

    Is A symmetric? Justify.

    Answer

    Answer: No: A[0][1] = 3 but A[1][0] = 7.

    1 mark.

  4. (iv) · 2 marks

    Write the statement that stores the transpose of A in T.

    Answer

    Answer: for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) T[j][i] = A[i][j];

    1 for loops, 1 for index swap.

Where the marks are

How a typical answer is split into step marks. Show every step: a right final answer alone rarely earns full marks.

[2] Address calculation (row or column major). (2 marks)

StepMarks
Correct formula with R or C computed.1
Correct substitution and final address.1

[5] swapHalves(String). (5 marks)

StepMarks
Length and half computed.1
Left and right halves with substring.2
Middle letter for odd length.1
Correct concatenation and return.1

[10] Class Ranker (bubble sort descending with early exit, count above average). (10 marks)

StepMarks
Constructor with array allocation.1
getArray( ).1
Bubble sort with the descending condition and the no-swap exit.3
countAboveAvg( ): average after the first loop, count in the second, return.2
display( ) invoking countAboveAvg( ).1
main( ).1
Documentation.1

Where students lose marks in Arrays, Strings

The slips examiners see most often, and what to write instead.

  • Mistake: Wrong address formula or wrong number of columns

    CISCE examiners' comments: 2024 candidates 'Applied wrong address formula' and 'Substituted wrong values'; 2025 candidates 'Wrote the answer directly without formula/working', 'Used column major instead of row major' and 'Computed matrix size/number of columns incorrectly'.

    Do this: Write the formula first; compute C = Uc - Lc + 1 (or R) separately; show every substitution.

    Usually costs: 1-2 marks.

  • Mistake: Wrong sort, wrong order, or out-of-bounds condition

    CISCE examiners' comments, 2024: candidates 'Wrote bubble or selection sort, sorted ascending, outer loop from 0, or tested j>=0 after arr[j] causing out-of-bounds', and the array size was 'not defined in constructor'.

    Do this: Use the named technique; for descending insertion sort use while (j >= 0 && arr[j] < key); allocate the array in the constructor.

    Usually costs: 3-4 marks.

  • Mistake: Averages divided by the wrong count or computed inside the loop

    CISCE examiners' comments, 2024: in find( ) candidates 'did not count odd numbers (divided by array length), computed average inside loop, or did not return'.

    Do this: Count the selected elements, divide after the loop with a cast to double, and return the value.

    Usually costs: 1-2 marks.

  • Mistake: Character and code confusion in string programs

    CISCE examiners' comments, 2024: candidates 'Confused extracting characters and obtaining ASCII codes', 'Did not assume an initial lowest/highest', and 'Used extra instance variables'.

    Do this: char ch = w.charAt(i); int code = (int) ch; start lowest and highest from the first character; use local variables for working values.

    Usually costs: 1-3 marks.

  • Mistake: Inconsistent string-flipping logic

    CISCE examiners' comments, 2025: for flipping word halves, the common error was an 'Incorrect or logically inconsistent flip( ) implementation'.

    Do this: Build the result as right half + middle (if odd) + left half using substring with clearly computed indices; test with an odd and an even word.

    Usually costs: 2-3 marks.

Practice questions on Arrays, Strings

Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.

  1. Q1 · 1 mark · Very short answerBoard level

    What is the index of the last element of an array of length n?

    Hint

    Starts at 0.

    Answer

    n - 1.

  2. Q2 · 1 mark · Very short answerBoard level

    What does "ISC".concat("2027").length() return?

    Hint

    3 + 4.

    Answer

    7.

  3. Q3 · 1 mark · Very short answerBoard level

    Name the class used for mutable strings in the syllabus.

    Hint

    Buffer.

    Answer

    StringBuffer.

  4. Q4 · 1 mark · Very short answerHarder board level

    Give the output of new StringBuffer("PROGRAM").reverse().

    Hint

    Backwards.

    Answer

    MARGORP

  5. Q5 · 2 marks · Short answerHarder board level

    [2] A matrix M[-2..9, 3..12] is stored column-major with 2 bytes per element and base address 1500. Find the address of M[3][8].

    Hint

    R = 12.

    Answer

    R = 9 - (-2) + 1 = 12; 1500 + 2 × [(8 - 3) × 12 + (3 + 2)] = 1500 + 2 × 65 = 1630.

  6. Q6 · 2 marks · Short answerHarder board level

    [2] Write a method boolean isHetero(String w) that returns true if no letter appears more than once.

    Hint

    indexOf versus lastIndexOf.

    Answer

    boolean isHetero(String w) { for (int i = 0; i < w.length(); i++) if (w.indexOf(w.charAt(i)) != w.lastIndexOf(w.charAt(i))) return false; return true; } → "TRAIN" true, "LETTER" false.

  7. Q7 · 5 marks · Long answerHOTS / competency

    [5] Write a method that returns a word with its left and right halves swapped (the middle letter stays for odd lengths): "PLANET" → "NETPLA", "ROBOT" → "OTBRO".

    Hint

    Right half + middle + left half.

    Answer

    String swapHalves(String w) { int n = w.length(), h = n / 2; String left = w.substring(0, h); String right = w.substring(n - h); String mid = (n % 2 == 1) ? w.substring(h, h + 1) : ""; return right + mid + left; } PLANET → NETPLA; ROBOT → OTBRO (checked by running the code).

  8. Q8 · 10 marks · Long answerHOTS / competency

    [10] Design a class Frequency with a data member str; a constructor; void accept( ); and void show( ) that prints each distinct letter of str (case ignored) with its frequency, in alphabetical order, using an int array of size 26. Write main( ).

    Hint

    count[ch - 'A']++.

    Answer

    Constructor sets str = ""; accept( ) reads a line and converts to upper case; show( ): int[] f = new int[26]; for each character, if it is a letter, f[ch - 'A']++; then for i from 0 to 25, if f[i] > 0 print (char) (i + 'A') and f[i]. For "Banana Bread": A 4, B 2, D 1, E 1, N 2, R 1 (checked by running the code).

Test your recall

Answer in your head or on paper first, then open the card. Pulling an answer out of memory makes it stick far better than re-reading.

  1. 1.Row-major formula?Show answer

    B + W[(I - Lr)C + (J - Lc)].

  2. 2.Which sort makes one swap per pass?Show answer

    Selection sort.

  3. 3.Binary search requirement?Show answer

    Sorted array.

  4. 4."apple".compareTo("apricot")?Show answer

    -2.

  5. 5.Is String mutable?Show answer

    No; use StringBuffer for in-place changes.

Best order to study it

  1. 1D and 2D arrays: declaration, allocation, length, common loops.
  2. Address calculation row and column major.
  3. Linear and binary search; maximum and minimum.
  4. Bubble, selection, insertion sort with traces.
  5. Matrices and linear equations; String and StringBuffer programs.

Quick revision checklist

The night before the exam: can you do each of these without looking?

  • Index 0 to length - 1; constant-time access; arrays are objects.
  • Row major × C; column major × R; count bounds carefully.
  • Binary search: sorted; mid; lo = mid + 1 or hi = mid - 1.
  • Bubble: adjacent swaps. Selection: min to front. Insertion: shift and insert.
  • Descending insertion: while (j >= 0 && a[j] < key).
  • String immutable: length, charAt, indexOf, substring(b, e), equals, compareTo.
  • StringBuffer: append, insert, reverse, deleteCharAt, setCharAt.

Arrays, Strings: frequently asked questions

Do I need Arrays.sort( ) or other library sorts?

No. Questions name a technique (bubble, selection or insertion) and expect you to code it; library sorts earn no credit there.

Are bounds in address questions inclusive?

Yes. A[-3..12] has 12 - (-3) + 1 = 16 elements.

Should I use String or StringBuffer in programs?

String with concatenation is fine for most exam programs; use StringBuffer when the program builds or reverses strings repeatedly, as the syllabus suggests.

Based on: CISCE ISC 2027 Computer Science (868) syllabus; CISCE ISC Computer Science (868) Paper 1 specimen question paper and answer key (latest specimen, 2025); CISCE Analysis of Pupil Performance, ISC Computer Science (868), 2025; CISCE Analysis of Pupil Performance, ISC Computer Science (868), 2024