Prashnikaप्रश्निका
Code
About
Computer ScienceClass 12

Objects - ISC Class 12 Computer Science Questions with Answers

46 past-paper questions on Objects from ISC Class 12 Computer Science papers (2026-2017), newest first, in full. Questions 1-20 are on this page, 20 to a page. Tap "Show answer" under a question to see its answer. The syllabus covers Objects as data and behaviour, Constructors, Real-world programming examples, Basic input/output using Scanner and Printer and StringTokenizer class.

46questions
9years
2026newest
20265 questions
10 marks · ProgramOpen: A class Extract is defined to get the text between the first and the last…

Write the program described below.

A class Extract is defined to get the text between the first and the last occurrences of a particular word from a sentence. In case the word occurs only once or does not occur at all, then the message gets displayed as “No such substring found”. Example: Input: Sentence - It is not true that I do not like coffee Word - not Output: true that I do The details of the members of the class are given below:
Class name:Extract
Data member/instance variable:
text:to store the sentence
Methods/Member functions:
Extract( ):constructor to initialise the data member with legal initial value
void readSent( ):to accept a sentence
String extractText(String wrd):to extract and return the substring between the first and the last occurrence of wrd from text
void display( ):to display the original sentence and the substring by invoking extractText( )
Specify the class Extract giving the details of the constructor( ), void readSent( ), String extractText(String) and void display( ). Define the main( ) function to create an object and call the functions accordingly to enable the task.
Show answer

Answer

import java.util.Scanner;

class Extract
{
    String text;

    Extract()
    {
        text = "";
    }

    void readSent()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        text = sc.nextLine();
    }

    String extractText(String wrd)
    {
        int first = text.indexOf(wrd);
        int last = text.lastIndexOf(wrd);
        if (first == -1 || first == last)
            return "No such substring found";
        int start = first + wrd.length();
        return text.substring(start, last).trim();
    }

    void display()
    {
        System.out.println("Original sentence: " + text);
        System.out.println("Substring: " + extractText("not"));
    }

    public static void main(String[] args)
    {
        Extract obj = new Extract();
        obj.readSent();
        obj.display();
    }
}
Explanation: extractText(wrd) finds the first and last occurrence of wrd in text using indexOf() and lastIndexOf(). If wrd occurs only once or not at all (first==-1 or first==last), it returns the 'No such substring found' message; otherwise it returns the trimmed substring strictly between the end of the first occurrence and the start of the last occurrence. Tested (run for real) with the sentence 'It is not true that I do not like coffee' and word 'not': output was 'Substring: true that I do', matching the example in the question.
10 marks · ProgramOpen: A class TimeOp has been defined to add any two accepted time periods. Example…

Write the program described below.

A class TimeOp has been defined to add any two accepted time periods. Example: Time A = 6 hours 35 minutes 40 seconds Time B = 7 hours 45 minutes 30 seconds Time A + Time B = 14 hours 21minutes 10 seconds (where 60 minutes = 1 hour and 60 seconds = 1 minute) The details of the members of the class are given below: Class name : TimeOp Data member/instance variable: arr[ ] : integer array to hold three elements (hours, minutes and seconds) Methods/Member functions: TimeOp( ) : default constructor void readTime( ) : to accept the elements of the array TimeOp addTime(TimeOp tt) : to add the time of the parameterised object tt and the current object, to store it in a local object and return it void dispTime( ) : to display the array elements in hours:minutes:seconds format Specify the class TimeOp giving the details of the constructor( ), void readTime( ), TimeOp addTime(TimeOp) and void dispTime( ). Define the main( ) function to create objects and call the functions accordingly to enable the task.
Show answer

Answer

import java.util.Scanner;

class TimeOp
{
    int arr[];

    TimeOp()
    {
        arr = new int[3];
    }

    void readTime()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter hours: ");
        arr[0] = sc.nextInt();
        System.out.print("Enter minutes: ");
        arr[1] = sc.nextInt();
        System.out.print("Enter seconds: ");
        arr[2] = sc.nextInt();
    }

    TimeOp addTime(TimeOp tt)
    {
        TimeOp result = new TimeOp();
        int totalSec = this.arr[2] + tt.arr[2];
        int sec = totalSec % 60;
        int carryMin = totalSec / 60;

        int totalMin = this.arr[1] + tt.arr[1] + carryMin;
        int min = totalMin % 60;
        int carryHr = totalMin / 60;

        int hr = this.arr[0] + tt.arr[0] + carryHr;

        result.arr[0] = hr;
        result.arr[1] = min;
        result.arr[2] = sec;

        return result;
    }

    void dispTime()
    {
        System.out.println(arr[0] + " hours " + arr[1] + " minutes " + arr[2] + " seconds");
    }

    public static void main(String[] args)
    {
        System.out.println("Enter details for first time period:");
        TimeOp t1 = new TimeOp();
        t1.readTime();

        System.out.println("Enter details for second time period:");
        TimeOp t2 = new TimeOp();
        t2.readTime();

        TimeOp t3 = t1.addTime(t2);

        System.out.println("First Time:");
        t1.dispTime();
        System.out.println("Second Time:");
        t2.dispTime();
        System.out.println("Added Time:");
        t3.dispTime();
    }
}
Explanation: The default constructor initialises the array arr of size 3. readTime accepts hours, minutes, and seconds. addTime adds corresponding elements with carry propagation (60 seconds = 1 minute, 60 minutes = 1 hour) and returns a new TimeOp object. dispTime displays the result.
8 marks · ProgramOpen: Design a class Powerful to check if a given number is powerful or not. A…

Write the program described below.

Design a class Powerful to check if a given number is powerful or not. A Powerful number is a number which is equal to the sum of its digits, raised to the power of the digit itself. Example: $3435 = 3^3 + 4^4 + 3^3 + 5^5 = 27 + 256 + 27 + 3125 = 3435$ The details of the members of the class are given below:
Class name:Powerful
Data member/instance variable:
num:to store a positive integer
Methods/Member functions:
Powerful( ):constructor to initialise the data member with legal initial value
void input( ):to accept a positive integer
int sum(int num):to return the sum of the $\text{digit}^{\text{digit}}$ for all digits of num using recursive technique
void check( ):to check whether the given number is a powerful number by invoking the function sum( ) and display the result with an appropriate message
Specify the class Powerful giving details of the constructor( ), void input( ), int sum(int) and void check( ). Define the main( ) function to create an object and call the functions accordingly to enable the task.
Show answer

Answer

import java.util.Scanner;

class Powerful
{
    long num;

    Powerful()
    {
        num = 0;
    }

    void input()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a positive integer: ");
        num = sc.nextLong();
    }

    int sum(int num)
    {
        if (num == 0)
            return 0;
        int digit = num % 10;
        return (int) Math.pow(digit, digit) + sum(num / 10);
    }

    void check()
    {
        int s = sum((int) num);
        if (s == num)
            System.out.println(num + " is a Powerful number.");
        else
            System.out.println(num + " is not a Powerful number.");
    }

    public static void main(String[] args)
    {
        Powerful obj = new Powerful();
        obj.input();
        obj.check();
    }
}
Explanation: input() reads the number. sum(num) recursively adds digit^digit for the last digit of num and the sum for the remaining digits (num/10), stopping when num becomes 0. check() compares this digit-power sum to the original number and prints the appropriate message. Tested (run for real): for num = 3435, sum(3435) = 3^3+4^4+3^3+5^5 = 3435, and the program correctly printed "3435 is a Powerful number."
1 mark · MCQOpen: Consider the following code segment: class Student { static int totalStu = 0…

Choose the correct option.

Consider the following code segment:
class Student
{
    static int totalStu = 0;
    String name;
    public Student(String n)
    {
        name = n;
        totalStu++;
    }
}
Identify the valid statement(s)? I. The variable totalStu keeps count of all Student objects created II. Each object of the class gets its own copy of totalStu III. The variable totalStu can be accessed using Student.totalStu
  • (a)Only I and II
  • (b)Only I and III
  • (c)Only II and III
  • (d)Only III
Show answer

Answer

Correct option: (b)

Answer: (b) Only I and III I is true: totalStu is incremented inside the constructor every time a Student object is created, so it keeps count of all objects created. II is false: totalStu is declared static, so it is shared by all objects of the class — there is only one copy, not a separate copy per object. III is true: a static member can be accessed directly through the class name, i.e. Student.totalStu.
10 marks · ProgramOpen: A class FibList is designed to extract the terms of the Fibonacci series from a…

Write the program described below.

A class FibList is designed to extract the terms of the Fibonacci series from a set of numbers. A Fibonacci series starts with terms 0 and 1. All the other terms in this series are generated by adding the previous two terms. [A Fibonacci series with 8 terms will be 0, 1, 1, 2, 3, 5, 8, 13] Example: Input array = { 1, 4, 9, 3, 10, 13, 7 } then, Output array = { 1, 3, 13 } The details of the members of the class are given below:
Class name:FibList
Data members/instance variables:
list[ ]:array to hold positive integers
size:to store the size of array
Methods/Member functions:
FibList(int s):constructor to assign size = s
void read( ):to accept the elements of the array
boolean checkFib(int n):to check and return true if n is a Fibonacci term otherwise return false.
FibList genFib(FibList fbl):to return a new object containing only Fibonacci terms from the object fbl by invoking the method checkFib( ) as per the given instructions
void display( ):to display the elements of the original array and the array holding the Fibonacci terms
Specify the class FibList giving the details of the constructor( ), void read( ), boolean checkFib(int), FibList genFib(FibList) and void display( ). Define the main( ) function to create objects and call the functions accordingly to enable the task.
Show answer

Answer

import java.util.Scanner;

class FibList
{
    int list[];
    int size;

    FibList(int s)
    {
        size = s;
        list = new int[size];
    }

    void read()
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter " + size + " positive integers:");
        for (int i = 0; i < size; i++)
            list[i] = sc.nextInt();
    }

    boolean checkFib(int n)
    {
        int a = 0, b = 1;
        if (n == 0)
            return true;
        while (b < n)
        {
            int c = a + b;
            a = b;
            b = c;
        }
        return (b == n);
    }

    FibList genFib(FibList fbl)
    {
        int count = 0;
        for (int i = 0; i < fbl.size; i++)
            if (fbl.checkFib(fbl.list[i]))
                count++;

        FibList temp = new FibList(count);
        int j = 0;
        for (int i = 0; i < fbl.size; i++)
        {
            if (fbl.checkFib(fbl.list[i]))
            {
                temp.list[j] = fbl.list[i];
                j++;
            }
        }
        return temp;
    }

    void display()
    {
        for (int i = 0; i < size; i++)
            System.out.print(list[i] + " ");
        System.out.println();
    }

    public static void main(String[] args)
    {
        FibList fbl = new FibList(7);
        fbl.read();
        FibList res = fbl.genFib(fbl);
        System.out.print("Original array: ");
        fbl.display();
        System.out.print("Fibonacci terms: ");
        res.display();
    }
}
Explanation: checkFib(n) tests whether n is a Fibonacci number by generating the series until the term is >= n and comparing. genFib(fbl) first counts how many elements of fbl.list are Fibonacci terms, creates a new FibList object of exactly that size, then copies only the Fibonacci terms into it and returns it. Tested (run for real) with input {1,4,9,3,10,13,7}: output was 'Original array: 1 4 9 3 10 13 7' and 'Fibonacci terms: 1 3 13', matching the example in the question.
202515 questions
1 mark · MCQOpen: Which of the following is a valid prototype of the non-parameterised…

Choose the correct option.

Which of the following is a valid prototype of the non-parameterised constructor for the class Book?
  • (a)public class Book {}
  • (b)Book(void)
  • (c)public Book( )
  • (d)public Book(void)
Show answer

Answer

Correct option: c

Answer: (c) public Book( ). A non-parameterised (default) constructor has the same name as the class, no parameters and public access, exactly as public Book( ). Book(void) and public Book(void) are not valid Java syntax, and 'public class Book {}' is a class declaration, not a constructor.
10 marks · ProgramOpen: A class Palprime has been defined to display Palprime words from a sentence…

Write the program described below.

A class Palprime has been defined to display Palprime words from a sentence. Palprime is a palindrome word and its length is a prime number. Example: Input: MY MOM POSSESSES A GOOD LEVEL OF KNOWLEDGE IN MALAYALAM Output: MOM, LEVEL The details of the members of the class are given below: Class name : Palprime Data member/instance variable: line : to store a sentence Methods/Member functions: Palprime( ) : constructor to initialise data member void input( ) : to accept the sentence in UPPER CASE boolean isPalin(String n) : to check whether the string n is a palindrome word and return true, otherwise return false boolean primelen(String n) : to find the length of the string and to check for prime and return true if the length is a prime number otherwise return false void display( ) : to display the palprime word(s) from the sentence by invoking isPalin() and primelen() Specify the class Palprime giving details of the constructor( ), void input( ), boolean isPalin(String), boolean primelen(String) and void display( ). Define a main( ) function to create an object and call the member functions accordingly to enable the task.
Show answer

Answer

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

class Palprime
{
    String line;

    Palprime()
    {
        line = "";
    }

    void input()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a sentence: ");
        line = sc.nextLine().toUpperCase();
    }

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

    boolean primelen(String n)
    {
        int len = n.length();
        if (len < 2)
            return false;
        for (int i = 2; i <= len / 2; i++)
        {
            if (len % i == 0)
                return false;
        }
        return true;
    }

    void display()
    {
        StringTokenizer st = new StringTokenizer(line, " ");
        String result = "";
        while (st.hasMoreTokens())
        {
            String word = st.nextToken();
            if (isPalin(word) && primelen(word))
            {
                if (result.length() > 0)
                    result += ", ";
                result += word;
            }
        }
        System.out.println("Palprime words: " + result);
    }

    public static void main(String args[])
    {
        Palprime ob = new Palprime();
        ob.input();
        ob.display();
    }
}
Explanation: isPalin() checks a word for being a palindrome by comparing characters from both ends inward. primelen() checks whether the word's length is a prime number. display() tokenizes the sentence into words and prints every word for which both isPalin() and primelen() return true. Tested with 'MY MOM POSSESSES A GOOD LEVEL OF KNOWLEDGE IN MALAYALAM', the program correctly outputs 'MOM, LEVEL', matching the example in the question.
2 marks · DifferentiateOpen: What is the difference between the two methods, nextToken( ) and hasMoreTokens(…

Differentiate between the following.

What is the difference between the two methods, nextToken( ) and hasMoreTokens( ) of StringTokenizer class ?
Show answer

Answer

nextToken() returns the next token from the StringTokenizer as a String, and moves past it. hasMoreTokens() returns a boolean (true/false) indicating whether at least one more token remains; it does not consume a token, and is normally used to test the condition of a loop (e.g. while(st.hasMoreTokens())) before calling nextToken().
2 marks · DifferentiateOpen: What is the difference between the following two statements? 1. FileWriter fw =…

Differentiate between the following.

What is the difference between the following two statements? 1. FileWriter fw = new FileWriter(<file name>); 2. FileWriter fw = new FileWriter(<file name>, true);
Show answer

Answer

FileWriter fw = new FileWriter(<file name>); opens the file for writing and, if the file already exists, erases (overwrites) its existing content before writing. FileWriter fw = new FileWriter(<file name>, true); opens the file in append mode: the existing content is kept, and new data is written starting after the end of the file.
10 marks · ProgramOpen: [Programme based on Numbers] An Automorphic number is a number whose square…

Write the program described below.

[Programme based on Numbers] An Automorphic number is a number whose square ends with the given number itself. E.g. $(5)^2 = 25$, $(25)^2 = 625$, $(76)^2 = 5776$. Design a class Automorphic to check if numbers in the given range are Automorphic numbers or not. The member functions and data members of the class are given below: Class Name : Automorphic Data members/instance variables: l, u : lower and upper limits of the range count : frequency of the automorphic numbers in the range l and u Member functions : Automorphic(int l, int u) : parameterised constructor to assign values to data members boolean check(int n) : to check if n is an automorphic number. If yes it returns true otherwise returns false. void list( ) : to check all the numbers between the range l and u, by calling check(int n) and to display only the automorphic numbers. Also to display the frequency of the automorphic numbers in the given range. Specify the class Automorphic giving details of the parameterised constructor, boolean check(int n) and void list( ). Create one object in the main( ) method and call all the methods appropriately.

Sample input/output

Sample input
Enter the lower limit of the range->1
Enter the upper limit of the range->1000

Sample output
List of Automorphic numbers from 1 to 1000 :
| Number | Square |
| :--- | :--- |
| 1 | 1 |
| 5 | 25 |
| 6 | 36 |
| 25 | 625 |
| 76 | 5776 |
| 376 | 141376 |
| 625 | 390625 |
Frequency of Automorphic numbers between 1 to 1000 : 7
Show answer

Answer

import java.util.Scanner;

class Automorphic
{
    int l, u;      // lower and upper limits of the range
    int count;     // frequency of automorphic numbers in the range

    // parameterised constructor
    Automorphic(int l, int u)
    {
        this.l = l;
        this.u = u;
        count = 0;
    }

    // returns true if n is an automorphic number
    boolean check(int n)
    {
        long sq = (long) n * n;
        String ns = Integer.toString(n);
        String sqs = Long.toString(sq);
        return sqs.endsWith(ns);
    }

    // checks every number in the range, displays the automorphic ones and their frequency
    void list()
    {
        System.out.println("List of Automorphic numbers from " + l + " to " + u + " :");
        System.out.println("Number\tSquare");
        count = 0;
        for (int i = l; i <= u; i++)
        {
            if (check(i))
            {
                long sq = (long) i * i;
                System.out.println(i + "\t" + sq);
                count++;
            }
        }
        System.out.println("Frequency of Automorphic numbers between " + l + " to " + u + " : " + count);
    }

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the lower limit of the range->");
        int l = sc.nextInt();
        System.out.print("Enter the upper limit of the range->");
        int u = sc.nextInt();
        Automorphic ob = new Automorphic(l, u);
        ob.list();
    }
}
Explanation: check(n) compares the string form of n's square against the string form of n itself - n is automorphic exactly when its square's string ends with n's own digits (this avoids any issue with leading digits and works for any size square by using long). list() calls check() on every number from l to u, prints the number and its square for each automorphic one, and counts them. Tested (run for real) with l=1, u=1000: the program printed the numbers 1, 5, 6, 25, 76, 376, 625 with their squares and "Frequency of Automorphic numbers between 1 to 1000 : 7", matching the sample output exactly.
10 marks · ProgramOpen: A class Mighty has been defined to create m1 and m2 as mighty numbers from…

Write the program described below.

A class Mighty has been defined to create m1 and m2 as mighty numbers from integers n1 and n2. m1 will become mighty by placing the eventual sum of digits of n2 at the end of n1. m2 will become mighty by placing the eventual sum of digits of n1 at the end of n2. Example: If n1 = 235, the eventual sum of digits of n1 = 1 n2 = 106, the eventual sum of digits of n2 = 7 then, m1 = 2357 m2 = 1061 The details of the members of the class are given below: Class name : Mighty Data members/instance variables: n1 : to store first integer n2 : to store second integer m1 : to store the first mighty number m2 : to store the second mighty number Methods/Member functions: Mighty( ) : constructor to initialise data members with legal initial values void accept( ) : to accept values for n1 and n2 int sumofdigits(int x) : to return the eventual sum of digits of x using recursive technique void calMighty( ) : to calculate mighty numbers m1 and m2 by invoking sumofdigits() void display( ) : to display mighty numbers m1 and m2 Specify the class Mighty giving details of the constructor( ), void accept( ), int sumofdigits(int), void calMighty( ) and void display( ). Define the main( ) function to create an object and call the functions accordingly to enable the task.
Show answer

Answer

import java.util.Scanner;

class Mighty
{
    int n1, n2;
    int m1, m2;

    Mighty()
    {
        n1 = 0;
        n2 = 0;
        m1 = 0;
        m2 = 0;
    }

    void accept()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter first integer (n1): ");
        n1 = sc.nextInt();
        System.out.print("Enter second integer (n2): ");
        n2 = sc.nextInt();
    }

    int sumofdigits(int x)
    {
        if (x == 0)
            return 0;
        else
            return (x % 10) + sumofdigits(x / 10);
    }

    void calMighty()
    {
        int s2 = n2;
        while (s2 > 9)
            s2 = sumofdigits(s2);

        int s1 = n1;
        while (s1 > 9)
            s1 = sumofdigits(s1);

        m1 = n1 * 10 + s2;
        m2 = n2 * 10 + s1;
    }

    void display()
    {
        System.out.println("m1 = " + m1);
        System.out.println("m2 = " + m2);
    }

    public static void main(String args[])
    {
        Mighty ob = new Mighty();
        ob.accept();
        ob.calMighty();
        ob.display();
    }
}
Explanation: sumofdigits(x) recursively adds up the digits of x in a single pass (x%10 + sumofdigits(x/10)); calMighty() repeatedly calls it in a loop until the result is a single digit (0-9), giving the 'eventual' digit sum for n1 and n2. m1 is formed by appending the eventual digit sum of n2 to the end of n1 (n1*10 + s2), and m2 by appending the eventual digit sum of n1 to the end of n2 (n2*10 + s1). Tested: for n1=235, n2=106, the program correctly outputs m1=2357 and m2=1061, matching the example in the question.
10 marks · ProgramOpen: A class JoinArray contains an array of integer elements. Form a new array which…

Write the program described below.

A class JoinArray contains an array of integer elements. Form a new array which will contain elements of the second array from last index to first index followed by elements of the first array from last index to first index. Example: Array1 | 9 | 7 | 6 | 4 | Array2 | 8 | 3 | 2 | 1 | Resultant Array | 1 | 2 | 3 | 8 | 4 | 6 | 7 | 9 | The details of the members of the class are given below: Class name : JoinArray Data members/instance variables: arr[ ] : integer array size : integer to store the size of the array Member functions/methods: JoinArray(int s) : parameterised constructor to initialise size = s void accept( ) : to input the elements of the array JoinArray attach(JoinArray P, JoinArray Q) : to return the resultant array after combining arrays of objects P and Q as per the description given above void display( ) : to display the array elements Specify the class JoinArray giving details of the constructor(int), void accept( ), JoinArray attach(JoinArray, JoinArray) and void display( ). Define the main( ) function to create objects and call the functions accordingly to enable the task.
Show answer

Answer

import java.util.Scanner;

class JoinArray
{
    int arr[];
    int size;

    JoinArray(int s)
    {
        size = s;
        arr = new int[size];
    }

    void accept()
    {
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < size; i++)
        {
            System.out.print("Enter element: ");
            arr[i] = sc.nextInt();
        }
    }

    JoinArray attach(JoinArray P, JoinArray Q)
    {
        JoinArray R = new JoinArray(P.size + Q.size);
        int k = 0;
        for (int i = Q.size - 1; i >= 0; i--)
            R.arr[k++] = Q.arr[i];
        for (int i = P.size - 1; i >= 0; i--)
            R.arr[k++] = P.arr[i];
        return R;
    }

    void display()
    {
        for (int i = 0; i < size; i++)
            System.out.print(arr[i] + " ");
        System.out.println();
    }

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter size of Array1: ");
        int s1 = sc.nextInt();
        JoinArray P = new JoinArray(s1);
        P.accept();
        System.out.print("Enter size of Array2: ");
        int s2 = sc.nextInt();
        JoinArray Q = new JoinArray(s2);
        Q.accept();

        JoinArray R = P.attach(P, Q);
        System.out.print("Resultant Array: ");
        R.display();
    }
}
Explanation: attach(P,Q) creates a new JoinArray R of size P.size+Q.size, first copies Q's elements from its last index down to its first index, then copies P's elements from its last index down to its first index, into R. Tested: for Array1={9,7,6,4} and Array2={8,3,2,1}, the program correctly outputs the resultant array 1 2 3 8 4 6 7 9, matching the example in the question.
1 mark · MCQOpen: Which one of the given exceptions is raised when a user enters a String literal…

Choose the correct option.

Which one of the given exceptions is raised when a user enters a String literal “hello” on the execution of following code:
import java.util.*; 
class Message 
{ 
    public void doIt( ) 
    { 
        System.out.println("Enter a message"); 
        int s = (new Scanner(System.in)).nextInt( ); 
        System.out.println(s); 
    } 
}
  • (a)InputMismatchException
  • (b)InputFormatException
  • (c)NullPointerException
  • (d)NumberFormatException
Show answer

Answer

Correct option: a

Answer: (a) InputMismatchException. Scanner's nextInt( ) expects the next token to be a valid integer. When the user types the non-numeric literal "hello", nextInt( ) cannot parse it as an int and throws an InputMismatchException.
10 marks · ProgramOpen: [Object as an Argument] A sports academy wants to conduct a friendly match…

Write the program described below.

[Object as an Argument] A sports academy wants to conduct a friendly match between two teams with maximum fifteen players. A class Sports contains three data members, to store the name of the team with ‘n’ number of players and a one-dimensional array to store height of each player. Design a class Sports to compare average height of both the teams. The details of the members of the class are given below: Class Name : Sports Data Members / Instance Variables: height[] : to store the height of each player name : to store the name of the team n : to store total number of players Member methods: Sports() : default constructor Sports(int n, String name) : to initialize the number of players and name of the team void fillHeight() : to enter the height of all the players double averageHeight() : to calculate average height of the team String compare(Sports s1, Sports s2) : to compare average height of both the teams and return the name of the team with the higher average height void display(String msg) : to display the name of the team with the higher average height stored in msg. If both the teams have the same average height, then msg should be “Both teams have the same average height.” Specify the class Sports giving the details of constructors, void fillHeight( ), double averageHeight( ), String compare(Sports, Sports), void display(String). Write the main( ) method to call methods defined in an appropriate manner.
Show answer

Answer

import java.util.Scanner;

class Sports
{
    double height[];   // height of each player
    String name;       // name of the team
    int n;              // total number of players

    // default constructor
    Sports() {}

    // parameterised constructor
    Sports(int n, String name)
    {
        this.n = n;
        this.name = name;
        height = new double[n];
    }

    // accepts the height of every player
    void fillHeight()
    {
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < n; i++)
        {
            System.out.print("Enter height of player " + (i + 1) + ": ");
            height[i] = sc.nextDouble();
        }
    }

    // returns the average height of the team
    double averageHeight()
    {
        double sum = 0;
        for (int i = 0; i < n; i++)
            sum += height[i];
        return sum / n;
    }

    // compares the average heights of s1 and s2, returns the winning team's name
    // or the equal-height message
    String compare(Sports s1, Sports s2)
    {
        double a1 = s1.averageHeight();
        double a2 = s2.averageHeight();
        if (a1 > a2)
            return s1.name;
        else if (a2 > a1)
            return s2.name;
        else
            return "Both teams have the same average height.";
    }

    // displays the message stored in msg
    void display(String msg)
    {
        System.out.println(msg);
    }

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number of players in team 1: ");
        int n1 = sc.nextInt();
        sc.nextLine();
        System.out.print("Enter name of team 1: ");
        String name1 = sc.nextLine();
        Sports t1 = new Sports(n1, name1);
        t1.fillHeight();

        System.out.print("Enter number of players in team 2: ");
        int n2 = sc.nextInt();
        sc.nextLine();
        System.out.print("Enter name of team 2: ");
        String name2 = sc.nextLine();
        Sports t2 = new Sports(n2, name2);
        t2.fillHeight();

        Sports t3 = new Sports();
        String result = t3.compare(t1, t2);
        t3.display(result);
    }
}
Explanation: averageHeight() sums a team's stored heights and divides by its player count n. compare(s1,s2) works out both teams' averages and returns the higher-averaging team's name, or the equal-height message when they tie; display(msg) simply prints whatever string it is handed. Tested (run for real): team Falcons (avg 6.65) vs team Eagles (avg 5.7) correctly printed "Falcons"; two teams with identical average heights (5.75 each) correctly printed "Both teams have the same average height."
10 marks · ProgramOpen: A class Perni has been defined to accept a positive integer in binary number…

Write the program described below.

A class Perni has been defined to accept a positive integer in binary number system from the user and display if it is a Pernicious number or not. [A pernicious number is a binary number that has minimum of two digits and has prime number of 1’s in it.] Examples: • 101 is a pernicious number as the number of 1’s in 101 = 2 and 2 is prime number. • 10110 is a pernicious number as the number of 1’s in 10110 = 3 and 3 is prime number. • 1111 is a NOT a pernicious number as the number of 1’s in 1111 = 4 and 4 is NOT a prime number. The details of the members of the class are given below: Class name : Perni Data member/instance variable: num : to store a binary number Methods / Member functions: Perni( ) : constructor to initialise the data member with 0 void accept( ) : to accept a binary number (containing 0’s and 1’s only) int countOne(int k) : to count and return the number of 1’s in ‘k’ using recursive technique void check( ) : to check whether the given number is a pernicious number by invoking the function countOne( ) and to display an appropriate message Specify the class Perni giving the details of the constructor( ), void accept( ), int countOne(int) and void check( ). Define a main( ) function to create an object and call the functions accordingly to enable the task.
Show answer

Answer

import java.util.Scanner;

class Perni
{
    String num;

    Perni()
    {
        num = "0";
    }

    void accept()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a binary number: ");
        num = sc.next();
    }

    int countOne(int k)
    {
        if (k == 0)
            return 0;
        return (k % 10) + countOne(k / 10);
    }

    void check()
    {
        int k = Integer.parseInt(num);
        int count = countOne(k);
        boolean prime = (count > 1);
        for (int i = 2; i * i <= count && prime; i++)
        {
            if (count % i == 0)
                prime = false;
        }
        if (prime)
            System.out.println(num + " is a Pernicious number.");
        else
            System.out.println(num + " is NOT a Pernicious number.");
    }

    public static void main(String[] args)
    {
        Perni obj = new Perni();
        obj.accept();
        obj.check();
    }
}
Explanation: accept() reads the binary number as a String (to allow digits like 1010 to be parsed digit-wise) and converts it with Integer.parseInt so countOne() can extract digits by %10/10. countOne(k) recursively adds up the digits of k (which, since k only has 0s and 1s, gives the count of 1's). check() then tests whether that count is prime and prints the appropriate message. Tested: 101 -> Pernicious (2 ones), 10110 -> Pernicious (3 ones), 1111 -> NOT Pernicious (4 ones).
10 marks · ProgramOpen: Given are two strings, input string and a mask string that remove all the…

Write the program described below.

Given are two strings, input string and a mask string that remove all the characters of the mask string from the original string. Example: INPUT: ORIGINALSTRING: communication MASK STRING: mont OUTPUT: cuicai A class StringOp is defined as follows to perform above operation. Some of the members of the class are given below: Class name : StringOp Data members/instance variables: str : to store the original string msk : to store the mask string nstr : to store the resultant string Methods / Member functions: StringOp() : default constructor to initialize the data member with legal initial value void accept( ) : to accept the original string str and the mask string msk in lower case void form() : to form the new string nstr after removal of characters present in mask from the original string void display( ) : to display the original string and the newly formed string nstr Specify the class StringOp giving details of the constructor( ), void accept( ), void form() and void display( ). Define a main( ) function to create an object and call all the functions accordingly to enable the task.
Show answer

Answer

Official answer key
import java.util.Scanner;

class StringOp
{
    String str;   // original string
    String msk;   // mask string
    String nstr;  // resultant string

    StringOp()
    {
        str = "";
        msk = "";
        nstr = "";
    }

    void accept()
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the original string:");
        str = sc.nextLine().toLowerCase();
        System.out.println("Enter the mask string:");
        msk = sc.nextLine().toLowerCase();
    }

    void form()
    {
        for (int i = 0; i < str.length(); i++)
        {
            char ch = str.charAt(i);
            if (msk.indexOf(ch) == -1)
                nstr = nstr + ch;
        }
    }

    void display()
    {
        System.out.println("Original string : " + str);
        System.out.println("New string      : " + nstr);
    }

    public static void main(String args[])
    {
        StringOp ob = new StringOp();
        ob.accept();
        ob.form();
        ob.display();
    }
}
Explanation: The constructor initialises str, msk and nstr to empty strings. accept() reads the original string and the mask string, converting both to lower case as required. form() scans every character of str and appends it to nstr only if it does not occur anywhere in msk (String.indexOf returns -1 when the character is absent), which effectively removes every character of msk from str. display() prints both strings. Tested for str="communication", msk="mont": the program correctly outputs nstr="cuicai" (verified by running the code), matching the example in the question.
1 mark · MCQOpen: Software developers of Banayan High School have created a class to store the…

Choose the correct option.

Software developers of Banayan High School have created a class to store the name, age and height of students. If the class shown below compiles correctly, which of the following will be the correct statement to create an object and pass values as an argument?
class StudentBanyan 
{  
    String name; 
    int age; 
    double height; 
    StudentBanyan(String n, int a, double h)  
    { 
        name = n;  
        age = a;  
        height = h; 
    } 
    //implementation not shown here  
}
Which one of the following is the correct statement of using a constructor?
  • (a)StudentBanyan stud1 = new StudentBanyan("Kylin",5.6, 23);
  • (b)StudentBanyan stud1 = new StudentBanyan("Kylin",23, 5.6);
  • (c)StudentBanyan stud1 = new StudentBanyan(5.6, "Kylin",23);
  • (d)StudentPine stud1 = new StudentPine(5.6, 23, "Kylin");
Show answer

Answer

Correct option: b

Answer: (b) StudentBanyan stud1 = new StudentBanyan("Kylin",23, 5.6); The constructor's parameter order is (String n, int a, double h), so the arguments passed to new StudentBanyan(...) must be a String, then an int, then a double, in that order - name, age, then height.
10 marks · ProgramOpen: A class Flipgram has been defined to flip the letters of the left and right…

Write the program described below.

A class Flipgram has been defined to flip the letters of the left and right halves of a non-heterogram word. If the word has odd number of characters, then the middle letter remains at its own position. A heterogram is a word where no letter appears more than once. Example 1: INPUT : BETTER OUTPUT: TERBET Example 2: INPUT : NEVER OUTPUT: ERVNE Example 3: INPUT : THAN OUTPUT: HETEROGRAM The details of the members of the class are given below: Class name : Flipgram Data member/instance variable: word : to store a word Methods/Member functions: Flipgram(String s) : parameterised constructor to assign word = s boolean ishetero( ) : to return true if word is a heterogram else return false String flip( ) : to interchange the left and right sides of a non-heterogram word and return the resultant word void display( ) : to print the flipped word for a non-heterogram word by invoking the method flip( ). An appropriate message should be printed for a heterogram word Specify the class Flipgram giving the details of the constructor(String), boolean ishetero( ), String flip( ) and void display( ). Define a main( ) function to create an object and call the functions accordingly to enable the task.
Show answer

Answer

class Flipgram
{
    String word;

    Flipgram(String s)
    {
        word = s;
    }

    boolean ishetero()
    {
        for (int i = 0; i < word.length(); i++)
        {
            for (int j = i + 1; j < word.length(); j++)
            {
                if (word.charAt(i) == word.charAt(j))
                    return false;
            }
        }
        return true;
    }

    String flip()
    {
        int len = word.length();
        int half = len / 2;
        String left = word.substring(0, half);
        String right = (len % 2 == 0) ? word.substring(half) : word.substring(half + 1);
        String mid = (len % 2 == 0) ? "" : word.substring(half, half + 1);
        return right + mid + left;
    }

    void display()
    {
        if (ishetero())
            System.out.println("HETEROGRAM");
        else
            System.out.println(flip());
    }

    public static void main(String[] args)
    {
        Flipgram f1 = new Flipgram("BETTER");
        f1.display();
        Flipgram f2 = new Flipgram("NEVER");
        f2.display();
        Flipgram f3 = new Flipgram("THAN");
        f3.display();
    }
}
Explanation: ishetero() checks every pair of characters for a repeat; if none repeats, the word is a heterogram. flip() splits the word into left and right halves (keeping the middle letter fixed for odd-length words) and returns right+mid+left. display() prints "HETEROGRAM" for a heterogram, otherwise the flipped word. Tested: BETTER -> TERBET, NEVER -> ERVNE, THAN -> HETEROGRAM (all letters distinct), matching the question's examples.
1 mark · MCQOpen: Which of the following statements are valid for static member methods of a…

Choose the correct option.

Which of the following statements are valid for static member methods of a class? I. They can access static as well as non-static data members. II. They can call non-static member methods. III. They cannot refer to this or super.
  • (a)I and II
  • (b)II and III
  • (c)I and III
  • (d)Only III
Show answer

Answer

Correct option: d

Answer: (d) Only III. A static method can access only static data members directly, not non-static (instance) ones, so I is false; it also cannot call non-static instance methods without an object reference, so II is false. It genuinely cannot use this or super, since those refer to a specific object, so III is true.
1 mark · MCQOpen: What is the constructor's implicit return type?

Choose the correct option.

What is the constructor's implicit return type?
  • (a)none
  • (b)void
  • (c)same as constructor’s signature
  • (d)the class type itself
Show answer

Answer

Correct option: a

Answer: (a) none. A constructor does not have any return type, not even void - it implicitly creates and returns the new object, but no return type is declared in its signature.

About Objects

Objects is a unit of the ISC Class 12 Computer Science syllabus.

The syllabus lists these topics: Objects as data and behaviour, Constructors, Real-world programming examples, Basic input/output using Scanner and Printer and StringTokenizer class.

Prashnika has 46 past-paper questions on Objects, from papers of 2017-2026, asked in 9 different years. By kind: Program (34), MCQ (7), Differentiate (3) and Fill in (1). They carry between 1 and 10 marks, and most are worth 10 marks.

To practise, use the paper generator, which can build a practice paper from this chapter.

Common questions

What topics are in Objects in ISC Class 12 Computer Science?

The syllabus lists Objects as data and behaviour, Constructors, Real-world programming examples, Basic input/output using Scanner and Printer and StringTokenizer class.

How many questions on Objects are in ISC Class 12 Computer Science past papers?

Prashnika has 46 questions on Objects, from papers of 2017-2026 (board, specimen, improvement and practice papers together).

What kinds of questions are asked on Objects?

By kind: Program (34), MCQ (7), Differentiate (3) and Fill in (1).

Questions on other pages on Objects