Prashnikaप्रश्निका

Objects - ISC Class 12 Computer Science Questions with Answers, Page 2

46 past-paper questions on Objects from ISC Class 12 Computer Science papers (2026-2017), newest first, in full. Questions 21-40 are on this page, 20 to a page. Tap "Show answer" under a question to see its answer.

Practise these questions with filters
2025 · 1 mark · MCQOpen: Which one of the following keywords will make the data member as a class…

Choose the correct option.

Which one of the following keywords will make the data member as a class variable?
  • (a)static
  • (b)final
  • (c)abstract
  • (d)public
Show answer

Answer

AI

Correct option: a

Answer: (a) static. Declaring a data member static makes it a class variable: a single copy shared by all objects of the class, rather than a separate copy per object.
2025 · 2 marks · Fill inOpen: A class teacher has kept the records of the marks obtained in Physics and…

Fill in the blanks marked ?1?, ?2? ... so that the code works.

A class teacher has kept the records of the marks obtained in Physics and Computer Science of 3 students along with the students’ name. Write a java program to display the name of those students, whose average marks are highest. File name is Student.txt (Assume that following data is written in file)
Student NamePhysicsComputer Science
Anurag9095
Brijesh9595
Toshali97100
Now, there are four places in the code marked as ?1?, ?2?, ?3? and ?4? and they must be replaced by the statements so that the program runs correctly.
import java.util.*; 
import java.io.*; 
class StuFile 
{ 
    public static void calculate() throws IOException 
    { 
        FileReader fr = new FileReader("Student.txt"); 
        BufferedReader br = new BufferedReader(fr); 
        String t, name, name1; 
        int ph, co; 
        double avg; 
        double max = 0; 
        while(?1?) 
        { 
            StringTokenizer st = new StringTokenizer(t); 
            name = ?2?; // Student name 
            ph = Integer.parseInt(st.nextToken()); // Physics marks 
            co = Integer.parseInt(st.nextToken()); // Computer Science marks 
            avg = (ph + co) / ?3?; 
            System.out.println(name + "- " + ph + ", " + co + ", " + avg); 
            if (max < avg) 
            { 
                max = avg; 
                name1 = name; 
            } // end of if 
        } // end of outer while 
        System.out.println("Name of students with highest average =" + name1); 
        ?4? 
    } // end of calculate method 
} // end of class StuFile

No answer yet.

2025 · 10 marks · ProgramOpen: Design a class Colsum to check if the sum of elements in each corresponding…

Write the program described below.

Design a class Colsum to check if the sum of elements in each corresponding column of two matrices is equal or not. Assume that the two matrices have the same dimensions. Example: Input: MATRIX A
231
756
142
MATRIX B
742
131
256
Output: Sum of corresponding columns is equal. The details of the members of the class are given below: Class name : Colsum Data members/instance variables: mat[ ][ ] : to store the integer array elements m : to store the number of rows n : to store the number of columns Member functions/methods: Colsum(int mm, int nn) : parameterised constructor to initialise the data members m = mm and n = nn void readArray( ) : to accept the elements into the array boolean check(Colsum A, Colsum B) : to check if the sum of elements in each column of the objects A and B is equal and return true otherwise, return false void print( ) : to display the array elements Specify the class Colsum giving details of the constructor(int, int), void readArray( ), boolean check(Colsum, Colsum), and void print( ). Define the main( ) function to create objects and call the functions accordingly to enable the task.
Show answer

Answer

AI
import java.util.Scanner;

class Colsum
{
    int mat[][];
    int m, n;

    Colsum(int mm, int nn)
    {
        m = mm;
        n = nn;
        mat = new int[m][n];
    }

    void readArray()
    {
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                mat[i][j] = sc.nextInt();
    }

    boolean check(Colsum A, Colsum B)
    {
        for (int j = 0; j < A.n; j++)
        {
            int sumA = 0, sumB = 0;
            for (int i = 0; i < A.m; i++)
            {
                sumA += A.mat[i][j];
                sumB += B.mat[i][j];
            }
            if (sumA != sumB)
                return false;
        }
        return true;
    }

    void print()
    {
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
                System.out.print(mat[i][j] + " ");
            System.out.println();
        }
    }

    public static void main(String[] args)
    {
        Colsum A = new Colsum(3, 3);
        A.readArray();
        Colsum B = new Colsum(3, 3);
        B.readArray();
        if (A.check(A, B))
            System.out.println("Sum of corresponding columns is equal.");
        else
            System.out.println("Sum of corresponding columns is not equal.");
    }
}
Explanation: check(A,B) sums each column of A and the corresponding column of B and compares them; it returns false as soon as any pair of column sums differ, else true after checking all columns. Tested with the example matrices from the question - output: "Sum of corresponding columns is equal." (column sums 10,12,9 match on both sides).
2024 · 10 marks · ProgramOpen: A class Composite contains a two-dimensional array of order [m x n]. The…

Write the program described below.

A class Composite contains a two-dimensional array of order [m x n]. The maximum values possible for both ‘m’ and ‘n’ is 20. Design a class Composite to fill the array with the first (m x n) composite numbers in column wise. [Composite numbers are those which have more than two factors.] The details of the members of the class are given below: Class name : Composite Data members/instance variables: arr[ ][ ] : integer array to store the composite numbers column wise m : integer to store the number of rows n : integer to store the number of columns Member functions/methods: Composite(int mm, int nn ) : to initialize the size of the matrix, m=mm and n=nn int isComposite( int p ) : to return 1 if the number is composite otherwise returns 0 void fill ( ) : to fill the elements of the array with the first (m × n) composite numbers in column wise void display( ) : to display the array in a matrix form Specify the class Composite giving details of the constructor(int,int), int isComposite(int), void fill( ) and void display( ). Define a main( ) function to create an object and call all the functions accordingly to enable the task.
Show answer

Answer

AI
class Composite
{
    int arr[][];
    int m, n;

    Composite(int mm, int nn)
    {
        m = mm;
        n = nn;
        arr = new int[m][n];
    }

    int isComposite(int p)
    {
        if (p < 4)
            return 0;
        int count = 0;
        for (int i = 1; i <= p; i++)
            if (p % i == 0)
                count++;
        return (count > 2) ? 1 : 0;
    }

    void fill()
    {
        int num = 3;
        for (int j = 0; j < n; j++)
        {
            for (int i = 0; i < m; i++)
            {
                num++;
                while (isComposite(num) == 0)
                    num++;
                arr[i][j] = num;
            }
        }
    }

    void display()
    {
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
                System.out.print(arr[i][j] + "\t");
            System.out.println();
        }
    }

    public static void main(String args[])
    {
        Composite obj = new Composite(3, 3);
        obj.fill();
        obj.display();
    }
}
Explanation: isComposite(p) counts all factors of p from 1 to p; a count greater than 2 means p is composite. fill() searches upward from 4 for successive composite numbers and stores them column by column (outer loop over columns j, inner loop over rows i), so the array is filled with the first m*n composite numbers in column-major order. Tested (run for real) with m=n=3: the first 9 composite numbers 4,6,8,9,10,12,14,15,16 were placed column-wise, and display() printed: 4 9 14 6 10 15 8 12 16
2024 · 10 marks · ProgramOpen: An Evil Number is a number which contains even number of 1’s in its binary…

Write the program described below.

An Evil Number is a number which contains even number of 1’s in its binary equivalent. Example: Binary equivalent of 10 = 1010 which contains even number on 1’s. Thus, 10 is an Evil Number. Design a class Evil to check if a given number is an Evil number or not. Some of the members of the class are given below: Class name : Evil Data members/instance variables: num : to store a positive integer number bin : to store the binary equivalent Methods / Member functions: Evil( ) : default constructor to initialize the data member with legal initial value void acceptNum( ) : to accept a positive integer number void rec_bin (int x) : to convert the decimal number into its binary equivalent using recursive technique void check( ) : to check whether the given number is an Evil number by invoking the function rec_bin() and to display the result with an appropriate message Specify the class Evil giving details of the constructor( ), void acceptNum( ), void rec_bin(int) and void check( ). Define a main( ) function to create an object and call all the functions accordingly to enable the task.
Show answer

Answer

AI
import java.util.Scanner;

class Evil
{
    int num;
    String bin;

    Evil()
    {
        num = 0;
        bin = "";
    }

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

    void rec_bin(int x)
    {
        if (x > 0)
        {
            rec_bin(x / 2);
            bin = bin + (x % 2);
        }
    }

    void check()
    {
        rec_bin(num);
        int count = 0;
        for (int i = 0; i < bin.length(); i++)
        {
            if (bin.charAt(i) == '1')
                count++;
        }
        if (count % 2 == 0)
            System.out.println(num + " is an Evil Number.");
        else
            System.out.println(num + " is not an Evil Number.");
    }

    public static void main(String args[])
    {
        Evil obj = new Evil();
        obj.acceptNum();
        obj.check();
    }
}
Explanation: rec_bin(x) recursively divides x by 2, and after the recursive call returns (i.e. once x becomes 0), it appends each remainder (x%2) to the string bin on the way back up the call stack, which builds the binary equivalent in the correct (MSB to LSB) order. check() calls rec_bin(num), counts the number of '1' characters in bin, and reports the number as Evil if that count is even. Tested (run for real): for num=10, rec_bin builds bin="1010" (two 1's, even), and the program correctly printed "10 is an Evil Number."
2024 · 10 marks · ProgramOpen: Design a class DeciHex to accept a positive integer in decimal number system…

Write the program described below.

Design a class DeciHex to accept a positive integer in decimal number system from the user and display its hexadecimal equivalent. Example 1: Decimal number = 25 Hexadecimal equivalent = 19 Example 2: Decimal number = 28 Hexadecimal equivalent = 1C Some of the members of the class are given below.
Class name:DeciHex
Data members/instance variables:
num:stores the positive integer
hexa:string to store the hexadecimal equivalent of num
Methods / Member functions:
DeciHex( ):constructor to initialise the data members with legal initial values
void getNum( ):to accept a positive integer
void convert(int n):to find the hexadecimal equivalent of the formal parameter ‘n’ using the recursive technique
void display( ):to display the decimal number and its hexadecimal equivalent by invoking the function convert( )
Specify the class DeciHex giving details of the constructor( ), void getNum( ), void convert(int) and void display(). Define a main() function to create an object and call all the functions accordingly to enable the task.
Show answer

Answer

AI
import java.util.Scanner;

class DeciHex
{
    int num;
    String hexa;

    DeciHex()
    {
        num = 0;
        hexa = "";
    }

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

    void convert(int n)
    {
        if (n == 0)
            return;
        int digit = n % 16;
        char ch;
        if (digit < 10)
            ch = (char) ('0' + digit);
        else
            ch = (char) ('A' + digit - 10);
        convert(n / 16);
        hexa = hexa + ch;
    }

    void display()
    {
        convert(num);
        if (hexa.equals(""))
            hexa = "0";
        System.out.println("Decimal number = " + num);
        System.out.println("Hexadecimal equivalent = " + hexa);
    }

    public static void main(String[] args)
    {
        DeciHex obj = new DeciHex();
        obj.getNum();
        obj.display();
    }
}
Explanation: The constructor initialises num=0 and hexa="". getNum() reads a positive integer. convert(n) is recursive: it finds the current least-significant hex digit (n%16), recurses on n/16 first (so more significant digits are processed and appended before less significant ones), then appends the current digit's hex character to hexa - this ensures the digits appear in the correct (most-significant-first) order. display() invokes convert(num) and then prints the decimal number and its hexadecimal equivalent. Tested: input 25 gives hexadecimal 19, and input 28 gives hexadecimal 1C, matching both given examples exactly.
2024 · 10 marks · ProgramOpen: A class Encode has been defined to replace only the vowels in a word by the…

Write the program described below.

A class Encode has been defined to replace only the vowels in a word by the next corresponding vowel and form a new word. i.e. A → E, E → I, I → O, O → U, U → A and a → e, e → i, i → o, o → u, and u → a Example: Input: Institution Output: Onstotatoun Some of the members of the class are given below: Class name : Encode Data members/instance variables: word : to store a word length : integer to store the length of the word new_word : to store the encoded word Methods / Member functions: Encode( ) : default constructor to initialize data members with legal initial values void acceptWord( ) : to accept a word void nextVowel( ) : to replace only the vowels from the word stored in ‘word’ by the next corresponding vowel and to assign it to ‘newword’, with the remaining alphabets unchanged void display( ) : to display the original word along with the encrypted word Specify the class Encode giving details of the constructor( ), void acceptWord( ), void nextVowel( ) and void display( ). Define a main ( ) function to create an object and call the functions accordingly to enable the task.
Show answer

Answer

AI
import java.util.Scanner;

class Encode
{
    String word, new_word;
    int length;

    Encode()
    {
        word = "";
        new_word = "";
        length = 0;
    }

    void acceptWord()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a word: ");
        word = sc.nextLine();
        length = word.length();
    }

    void nextVowel()
    {
        for (int i = 0; i < length; i++)
        {
            char ch = word.charAt(i);
            switch (ch)
            {
                case 'A': new_word += 'E'; break;
                case 'E': new_word += 'I'; break;
                case 'I': new_word += 'O'; break;
                case 'O': new_word += 'U'; break;
                case 'U': new_word += 'A'; break;
                case 'a': new_word += 'e'; break;
                case 'e': new_word += 'i'; break;
                case 'i': new_word += 'o'; break;
                case 'o': new_word += 'u'; break;
                case 'u': new_word += 'a'; break;
                default: new_word += ch;
            }
        }
    }

    void display()
    {
        System.out.println("Original word : " + word);
        System.out.println("Encoded word  : " + new_word);
    }

    public static void main(String args[])
    {
        Encode obj = new Encode();
        obj.acceptWord();
        obj.nextVowel();
        obj.display();
    }
}
Explanation: nextVowel() scans each character of word; if it is one of the 10 vowels (upper- or lower-case), it is replaced by the next vowel in the cycle A->E->I->O->U->A (and a->e->i->o->u->a) using a switch statement, while all other (consonant) characters are copied unchanged into new_word. Tested (run for real): for word="Institution", the program correctly produced new_word="Onstotatoun", matching the example given in the question.
2023 · 10 marks · ProgramOpen: Design a class Pronic to check if a given number is a pronic number or not. [ A…

Write the program described below.

Design a class Pronic to check if a given number is a pronic number or not. [ A number is said to be pronic if the product of two consecutive numbers is equal to the number] Example: 0 = 0 × 1 2 = 1 × 2 6 = 2 × 3 12 = 3 × 4 thus, 0, 2, 6, 12... are pronic numbers. Some of the members of the class are given below:
Class name:Pronic
Data members/instance variables:
num:to store a positive integer number
Methods / Member functions:
Pronic( ):default constructor to initialize the data member with legal initial value
void acceptnum( ):to accept a positive integer number
boolean ispronic(int v):returns true if the number ‘num’ is a pronic number, otherwise returns false using recursive technique
void check( ):checks whether the given number is a pronic number by invoking the function ispronic() and displays the result with an appropriate message
Specify the class Pronic giving details of the constructor( ), void acceptnum( ), boolean ispronic(int) and void check( ). Define a main( ) function to create an object and call the functions accordingly to enable the task.
Show answer

Answer

AI
import java.util.Scanner;

class Pronic
{
    int num;

    Pronic()
    {
        num = 0;
    }

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

    boolean ispronic(int v)
    {
        return ispronic(v, 0);
    }

    boolean ispronic(int v, int n)
    {
        if (n > v)
            return false;
        else if (n * (n + 1) == v)
            return true;
        else
            return ispronic(v, n + 1);
    }

    void check()
    {
        if (ispronic(num))
            System.out.println(num + " is a Pronic number.");
        else
            System.out.println(num + " is not a Pronic number.");
    }

    public static void main(String args[])
    {
        Pronic obj = new Pronic();
        obj.acceptnum();
        obj.check();
    }
}
Explanation: ispronic(int) is the required single-argument method from the specification; it forwards to an overloaded recursive helper ispronic(v, n) which tries successive values of n starting at 0 - a pronic number satisfies num = n*(n+1) for some non-negative integer n. If n*(n+1) exceeds v (n>v) without a match, it returns false; if n*(n+1)==v it returns true; otherwise it recurses with n+1. Tested (run for real): num=12 correctly reported "12 is a Pronic number." (since 3*4=12) and num=15 correctly reported "15 is not a Pronic number."
2023 · 10 marks · ProgramOpen: Design a class NumDude to check if a given number is a Dudeney number or not…

Write the program described below.

Design a class NumDude to check if a given number is a Dudeney number or not. (A Dudeney number is a positive integer that is a perfect cube, such that the sum of its digits is equal to the cube root of the number.) Example: $5832 = (5+8+3+2)^3 = (18)^3 = 5832$ Some of the members of the class are given below:
Class name:NumDude
Data member/instance variable:
num:to store a positive integer number
Methods / Member functions:
NumDude( ):default constructor to initialise the data member with legal initial value
void input( ):to accept a positive integer number
int sumDigits(int x):returns the sum of the digits of number ‘x’ using recursive technique
void isDude( ):checks whether the given number is a Dudeney number by invoking the function sumDigits() and displays the result with an appropriate message
Specify the class NumDude giving details of the constructor( ), void input( ), int sumDigits(int) and void isDude( ). Define a main( ) function to create an object and call the functions accordingly to enable the task.
Show answer

Answer

AI
import java.util.Scanner;

class NumDude
{
    int num;   // the number to be checked

    // default constructor
    NumDude()
    {
        num = 0;
    }

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

    // returns the sum of the digits of x using recursion
    int sumDigits(int x)
    {
        if (x == 0)
            return 0;
        return (x % 10) + sumDigits(x / 10);
    }

    // checks whether num is a Dudeney number
    void isDude()
    {
        int s = sumDigits(num);
        if (s * s * s == num)
            System.out.println(num + " is a Dudeney number");
        else
            System.out.println(num + " is not a Dudeney number");
    }

    public static void main(String args[])
    {
        NumDude ob = new NumDude();
        ob.input();
        ob.isDude();
    }
}
sumDigits() adds the last digit (x % 10) to the sum of the remaining digits (x / 10) until x becomes 0. isDude() cubes that sum: if the cube equals the number, the sum is its cube root, so the number is a Dudeney number. Sample run:
Enter a positive integer: 5832
5832 is a Dudeney number
2022 · 6 marks · ProgramOpen: Design a class Toggle which toggles a word by converting all upper case…

Write the program described below.

Design a class Toggle which toggles a word by converting all upper case alphabets to lower case and vice versa. Example: The word “mOTivATe” becomes “MotIVatE” The details of the members of the class are given below: Class name: Toggle Data members/instance variables: str: stores a word newstr: stores the toggled word len: to store the length of the word Methods/Member functions: Toggle(): default constructor void readword(): to accept the word void toggle(): converts the upper case alphabets to lower case and all lower case alphabets to upper case and stores it in newstr void display(): displays the original word along with the toggled word Specify the class Toggle giving details of the constructor, void readword(), void toggle() and void display(). Define the main() function to create an object and call the functions accordingly to enable the task.
Show answer

Answer

AI
import java.util.*;
class Toggle
{
    String str, newstr;
    int len;

    Toggle()
    {
        str = "";
        newstr = "";
        len = 0;
    }

    void readword()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a word: ");
        str = sc.next();
        len = str.length();
    }

    void toggle()
    {
        newstr = "";
        for (int i = 0; i < len; i++)
        {
            char ch = str.charAt(i);
            if (Character.isUpperCase(ch))
                newstr = newstr + Character.toLowerCase(ch);
            else if (Character.isLowerCase(ch))
                newstr = newstr + Character.toUpperCase(ch);
            else
                newstr = newstr + ch;
        }
    }

    void display()
    {
        System.out.println("Original word: " + str);
        System.out.println("Toggled word: " + newstr);
    }

    public static void main(String[] args)
    {
        Toggle ob = new Toggle();
        ob.readword();
        ob.toggle();
        ob.display();
    }
}
Each character is checked and its case reversed and appended to newstr. Sample run: mOTivATe gives MotIVatE.
2022 · 6 marks · ProgramOpen: Design a class Check which checks whether a word is a palindrome or not…

Write the program described below.

Design a class Check which checks whether a word is a palindrome or not. (Palindrome words are those which spell the same from either ends). Example: MADAM, LEVEL etc. The details of the members of the class are given below: Class name: Check Data members/instance variables: wrd: stores a word len: to store the length of the word Methods/Member functions: Check(): default constructor void acceptword(): to accept the word boolean palindrome(): checks and returns ‘true’ if the word is a palindrome otherwise returns ‘false’ void display(): displays the word along with an appropriate message Specify the class Check giving details of the constructor, void acceptword(), boolean palindrome() and void display(). Define the main() function to create an object and call the functions accordingly to enable the task.
Show answer

Answer

AI
import java.util.*;
class Check
{
    String wrd;
    int len;

    Check()
    {
        wrd = "";
        len = 0;
    }

    void acceptword()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a word: ");
        wrd = sc.next();
        len = wrd.length();
    }

    boolean palindrome()
    {
        for (int i = 0; i < len / 2; i++)
            if (wrd.charAt(i) != wrd.charAt(len - 1 - i))
                return false;
        return true;
    }

    void display()
    {
        if (palindrome())
            System.out.println(wrd + " is a palindrome word");
        else
            System.out.println(wrd + " is not a palindrome word");
    }

    public static void main(String[] args)
    {
        Check ob = new Check();
        ob.acceptword();
        ob.display();
    }
}
The method palindrome() compares the characters from both ends moving towards the middle; any mismatch returns false. Sample run: MADAM gives "MADAM is a palindrome word".
2020 · 10 marks · ProgramOpen: A Special number is a number in which the sum of the factorial of its digits is…

Write the program described below.

A Special number is a number in which the sum of the factorial of its digits is equal to the number. Example: 145 ($1! + 4! + 5! = 145$). Thus, 145 is a Special number. Design a class Special to check if the given number is a Special number or not. Some of the members of the class are given below: Class name : Special Data member/instance variable: n : integer to store number Member functions/methods: Special() : default constructor void read() : to accept the number int factorial(int x) : return the factorial of a number using recursive technique boolean isSpecial() : checks for the special number by invoking the function factorial() and returns true if Special, otherwise returns false void display() : displays the result with an appropriate message Specify the class Special, giving details of the Constructor, void read(), int factorial(int), boolean isSpecial() and void display(). Define the main() function to create an object and call the member function according to enable the task.
Show answer

Answer

AI
import java.util.Scanner;

class Special
{
    int n;

    Special()
    {
        n = 0;
    }

    void read()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        n = sc.nextInt();
    }

    int factorial(int x)
    {
        if (x <= 1)
            return 1;
        return x * factorial(x - 1);
    }

    boolean isSpecial()
    {
        int sum = 0, t = n;
        while (t > 0)
        {
            sum = sum + factorial(t % 10);
            t = t / 10;
        }
        return sum == n;
    }

    void display()
    {
        if (isSpecial())
            System.out.println(n + " is a Special number");
        else
            System.out.println(n + " is not a Special number");
    }

    public static void main(String args[])
    {
        Special ob = new Special();
        ob.read();
        ob.display();
    }
}
Explanation: The constructor sets n to 0 and read() accepts the number. factorial(x) is recursive: it returns 1 when x <= 1 (base case), otherwise x * factorial(x - 1). isSpecial() extracts each digit of n with % 10 and / 10, adds the factorial of each digit and returns true if the sum equals n. display() prints an appropriate message. Tested: 145 gives 145 is a Special number (1! + 4! + 5! = 1 + 24 + 120 = 145).
2020 · 2 marks · Short answerOpen: What is the significance of the keyword ‘new’ in Java? Mention the areas where…

Answer the following in short.

What is the significance of the keyword ‘new’ in Java? Mention the areas where it is used.
Show answer

Answer

AI
The keyword 'new' is an operator that dynamically allocates memory at run time (from the heap) for an object or an array, calls the constructor to initialise it, and returns a reference to the newly created memory. Areas where it is used: 1. To create objects of a class, e.g. $Student\ s = new\ Student();$ 2. To create arrays, e.g. $int\ a[] = new\ int[10];$ 3. To create objects of library classes, e.g. $Scanner\ sc = new\ Scanner(System.in);$ 4. To create nodes of dynamic data structures such as linked lists and trees, e.g. $Node\ t = new\ Node();$
2020 · 10 marks · ProgramOpen: Design a class Convert to find the date and the month from a given day number…

Write the program described below.

Design a class Convert to find the date and the month from a given day number for a particular year. Example: If day number is 64 and the year is 2020, then the corresponding date would be: March 4, 2020 i.e. (31 + 29 + 4 = 64) Some of the members of the class are given below: Class name : Convert Data members/instance variables: n : integer to store the day number d : integer to store the day of the month (date) m : integer to store the month y : integer to store the year Methods/Member functions: Convert ( ) : constructor to initialize the data members with legal initial values void accept( ) : to accept the day number and the year void day_to_date( ) : converts the day number to its corresponding date for a particular year and stores the date in ‘d’ and the month in ‘m’ void display( ) : displays the month name, date and year Specify the class Convert giving details of the constructor( ), void accept( ), void day_to_date( ) and void display( ). Define a main( ) function to create an object and call the functions accordingly to enable the task.
Show answer

Answer

AI
import java.util.Scanner;

class Convert
{
    int n, d, m, y;

    Convert()
    {
        n = 0;
        d = 0;
        m = 0;
        y = 0;
    }

    void accept()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter day number: ");
        n = sc.nextInt();
        System.out.print("Enter year: ");
        y = sc.nextInt();
    }

    void day_to_date()
    {
        int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        if ((y % 400 == 0) || (y % 100 != 0 && y % 4 == 0))
            days[1] = 29;
        int rem = n;
        m = 0;
        while (m < 12 && rem > days[m])
        {
            rem = rem - days[m];
            m++;
        }
        d = rem;
        m = m + 1;
    }

    void display()
    {
        String mn[] = {"January", "February", "March", "April", "May", "June", "July",
                       "August", "September", "October", "November", "December"};
        System.out.println(mn[m - 1] + " " + d + ", " + y);
    }

    public static void main(String args[])
    {
        Convert ob = new Convert();
        ob.accept();
        ob.day_to_date();
        ob.display();
    }
}
Explanation: The constructor sets all data members to 0. accept() reads the day number and the year. day_to_date() first checks whether the year is a leap year (divisible by 400, or divisible by 4 but not by 100) and sets February to 29 days if so. It then subtracts the days of each month from the day number as long as the remaining number is larger than that month's days; what remains is the date d and the month is m + 1. display() prints the month name, date and year. Tested: for day number 64 and year 2020 the output is March 4, 2020, matching the example (31 + 29 + 4 = 64).
2020 · 10 marks · ProgramOpen: A class Mix has been defined to mix two words, character by character, in the…

Write the program described below.

A class Mix has been defined to mix two words, character by character, in the following manner: The first character of the first word is followed by the first character of the second word and so on. If the words are of different length, the remaining characters of the longer word are put at the end. Example: If the First word is “JUMP” and the second word is “STROLL”, then the required word will be “JSUTMRPOLL” Some of the members of the class are given below: Class name : Mix Data member/instance variable: wrd : to store a word len : to store the length of the word Member functions/methods: Mix( ) : default constructor to initialize the data members with legal initial values void feedword( ) : to accept the word in UPPER case void mix_word( Mix P, Mix Q ) : mixes the words of objects P and Q as stated above and stores the resultant word in the current object void display( ) : displays the word Specify the class Mix giving the details of the constructor( ), void feedword( ), void mix_word( Mix, Mix ) and void display( ). Define the main( ) function to create objects and call the functions accordingly to enable the task.
Show answer

Answer

AI
import java.util.Scanner;

class Mix
{
    String wrd;
    int len;

    Mix()
    {
        wrd = "";
        len = 0;
    }

    void feedword()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a word in UPPER CASE: ");
        wrd = sc.next();
        len = wrd.length();
    }

    void mix_word(Mix P, Mix Q)
    {
        String s = "";
        int min = Math.min(P.len, Q.len);
        for (int i = 0; i < min; i++)
            s = s + P.wrd.charAt(i) + Q.wrd.charAt(i);
        if (P.len > Q.len)
            s = s + P.wrd.substring(min);
        else
            s = s + Q.wrd.substring(min);
        wrd = s;
        len = s.length();
    }

    void display()
    {
        System.out.println(wrd);
    }

    public static void main(String args[])
    {
        Mix a = new Mix();
        Mix b = new Mix();
        Mix c = new Mix();
        a.feedword();
        b.feedword();
        c.mix_word(a, b);
        c.display();
    }
}
Explanation: The constructor sets wrd to an empty string and len to 0. feedword() accepts a word in upper case and stores its length. mix_word(P, Q) takes characters alternately from P and Q for as many positions as the shorter word has, then appends the remaining characters of the longer word at the end, and stores the result in the current object. display() prints the word. Tested: for JUMP and STROLL the output is JSUTMRPOLL, matching the example.
2020 · 10 marks · ProgramOpen: A class Composite contains a two dimensional array of order [m x n]. The…

Write the program described below.

A class Composite contains a two dimensional array of order [m x n]. The maximum value possible for both ‘m’ and ‘n’ is 20. Design a class Composite to fill the array with the first (m x n) composite numbers in column wise. The details of the members of the class are given below: Class name : Composite Data members/instance variables: arr[ ] [ ] : stores the composite numbers column wise m : integer to store the number of rows n : integer to store the number of columns Member functions/methods: Composite(int mm, int nn) : to initialize the size of the matrix m=mm and n=nn int isComposite(int p) : returns 1 if number is composite otherwise returns 0 void fill() : to fill the elements of the array with the first (m × n) composite numbers in column wise void display() : displays the array in a matrix form Specify the class Composite giving details of the constructor(int,int), int isComposite(int), void fill() and void display(). Define a main() function to create an object and call the functions accordingly to enable the task.
Show answer

Answer

AI
import java.util.Scanner;

class Composite
{
    int arr[][];
    int m, n;

    Composite(int mm, int nn)
    {
        m = mm;
        n = nn;
        arr = new int[m][n];
    }

    int isComposite(int p)
    {
        if (p < 4)
            return 0;
        for (int i = 2; i <= p / 2; i++)
        {
            if (p % i == 0)
                return 1;
        }
        return 0;
    }

    void fill()
    {
        int num = 3;
        for (int j = 0; j < n; j++)
        {
            for (int i = 0; i < m; i++)
            {
                num++;
                while (isComposite(num) == 0)
                    num++;
                arr[i][j] = num;
            }
        }
    }

    void display()
    {
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
                System.out.print(arr[i][j] + "\t");
            System.out.println();
        }
    }

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of rows (max 20): ");
        int r = sc.nextInt();
        System.out.print("Enter the number of columns (max 20): ");
        int c = sc.nextInt();
        Composite ob = new Composite(r, c);
        ob.fill();
        ob.display();
    }
}
Explanation: The constructor stores the order of the matrix and creates the array. isComposite(p) returns 1 if p (4 or more) has a divisor between 2 and p/2, i.e. it has more than two factors, else 0. fill() goes through the array column by column (outer loop over columns, inner loop over rows) and stores the next composite number each time, searching upward from 4. display() prints the array in matrix form. Tested: for 3 rows and 4 columns the output is 4 9 14 18 6 10 15 20 8 12 16 21 which holds the first 12 composite numbers filled column-wise.
2020 · 10 marks · ProgramOpen: Design a class BinSearch to search for a particular value in an array. Some of…

Write the program described below.

Design a class BinSearch to search for a particular value in an array. Some of the members of the class are given below: Class name : BinSearch Data members/instance variables: arr[ ] : to store integer elements n : integer to store the size of the array Member functions/methods: BinSearch(int nn) : parameterized constructor to initialize n=nn void fillarray( ) : to enter elements in the array void sort( ) : sorts the array elements in ascending order using any standard sorting technique int bin_search(int l, int u, int v) : searches for the value ‘v’ using binary search and recursive technique and returns its location if found otherwise returns -1 Define the class BinSearch giving details of the constructor( ), void fillarray( ), void sort( ) and int bin_search(int, int, int). Define the main( ) function to create an object and call the functions accordingly to enable the task.
Show answer

Answer

AI
import java.util.Scanner;

class BinSearch
{
    int arr[];
    int n;

    BinSearch(int nn)
    {
        n = nn;
        arr = new int[n];
    }

    void fillarray()
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter " + n + " elements:");
        for (int i = 0; i < n; i++)
            arr[i] = sc.nextInt();
    }

    void sort()
    {
        for (int i = 0; i < n - 1; i++)
        {
            for (int j = 0; j < n - 1 - i; j++)
            {
                if (arr[j] > arr[j + 1])
                {
                    int t = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = t;
                }
            }
        }
    }

    int bin_search(int l, int u, int v)
    {
        if (l > u)
            return -1;
        int mid = (l + u) / 2;
        if (arr[mid] == v)
            return mid;
        else if (v < arr[mid])
            return bin_search(l, mid - 1, v);
        else
            return bin_search(mid + 1, u, v);
    }

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the size of the array: ");
        int size = sc.nextInt();
        BinSearch ob = new BinSearch(size);
        ob.fillarray();
        ob.sort();
        System.out.print("Sorted array: ");
        for (int i = 0; i < size; i++)
            System.out.print(ob.arr[i] + " ");
        System.out.println();
        System.out.print("Enter the value to search: ");
        int v = sc.nextInt();
        int pos = ob.bin_search(0, size - 1, v);
        if (pos == -1)
            System.out.println(v + " not found");
        else
            System.out.println(v + " found at index " + pos);
    }
}
Explanation: The constructor stores the size and creates the array. fillarray() reads the elements. sort() arranges them in ascending order using bubble sort (binary search needs a sorted array). bin_search(l, u, v) is recursive: if l > u the value is absent and -1 is returned; otherwise it compares v with the middle element and returns mid if equal, else searches the left half (l to mid-1) or the right half (mid+1 to u). Tested: for the array 45 12 89 7 33 60 the sorted array is 7 12 33 45 60 89 and searching 33 gives index 2.
2020 · 10 marks · ProgramOpen: Design a class Sort which enables a word to be arranged in alphabetical order…

Write the program described below.

Design a class Sort which enables a word to be arranged in alphabetical order. The details of the members of the class are given below: Class name : Sort Data members/instance variables: str : stores a word len : to store the length of the word Methods/Member functions: Sort() : default constructor void readword() : to accept the word void arrange() : to arrange the word in alphabetical order using any standard sorting technique. void display() : displays the original word along with the sorted word Specify the class Sort giving details of the constructor, void readword(), void arrange() and void display(). Define the main() function to create an object and call the functions accordingly to enable the task.
Show answer

Answer

AI
import java.util.Scanner;

class Sort
{
    String str, sw;
    int len;

    Sort()
    {
        str = "";
        sw = "";
        len = 0;
    }

    void readword()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a word: ");
        str = sc.next();
        len = str.length();
    }

    void arrange()
    {
        char ch[] = str.toCharArray();
        for (int i = 0; i < len - 1; i++)
        {
            for (int j = 0; j < len - 1 - i; j++)
            {
                if (ch[j] > ch[j + 1])
                {
                    char t = ch[j];
                    ch[j] = ch[j + 1];
                    ch[j + 1] = t;
                }
            }
        }
        sw = new String(ch);
    }

    void display()
    {
        System.out.println("Original word : " + str);
        System.out.println("Sorted word   : " + sw);
    }

    public static void main(String args[])
    {
        Sort ob = new Sort();
        ob.readword();
        ob.arrange();
        ob.display();
    }
}
Explanation: The default constructor sets the words to empty strings and len to 0. readword() accepts the word and stores its length. arrange() copies the characters of the word into an array and sorts them with bubble sort, then stores the sorted characters as a String in an extra data member sw, so that the original word in str is kept and both can be displayed. display() prints the original and the sorted word. Tested: input COMPUTER gives sorted word CEMOPRTU.
2019 · 10 marks · ProgramOpen: Design a class ArmNum to check if a given number is an Armstrong number or not…

Write the program described below.

Design a class ArmNum to check if a given number is an Armstrong number or not. [A number is said to be Armstrong if sum of its digits raised to the power of length of the number is equal to the number] Example : $371 = 3^3 + 7^3 + 1^3$ $1634 = 1^4 + 6^4 + 3^4 + 4^4$ $54748 = 5^5 + 4^5 + 7^5 + 4^5 + 8^5$ Thus 371, 1634 and 54748 are all examples of Armstrong numbers. Some of the members of the class are given below: Class name : ArmNum Data members/instance variables: n : to store the number l : to store the length of the number Methods/Member functions: ArmNum (int nn) : parameterized constructor to initialize the data member n=nn int sum_pow(int i) : returns the sum of each digit raised to the power of the length of the number using recursive technique eg. 34 will return $3^2 + 4^2$ (as the length of the number is 2) void isArmstrong( ) : checks whether the given number is an Armstrong number by invoking the function sum_pow( ) and displays the result with an appropriate message Specify the class ArmNum giving details of the constructor( ), int sum_pow(int) and void isArmstrong( ). Define a main( ) function to create an object and call the functions accordingly to enable the task.
Show answer

Answer

AI
import java.util.Scanner;

class ArmNum
{
    int n;
    int l;

    ArmNum(int nn)
    {
        n = nn;
        l = String.valueOf(n).length();
    }

    int sum_pow(int i)
    {
        if (i == 0)
            return 0;
        else
        {
            int digit = i % 10;
            return (int) Math.pow(digit, l) + sum_pow(i / 10);
        }
    }

    void isArmstrong()
    {
        int s = sum_pow(n);
        if (s == n)
            System.out.println(n + " is an Armstrong number.");
        else
            System.out.println(n + " is not an Armstrong number.");
    }

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int nn = sc.nextInt();
        ArmNum obj = new ArmNum(nn);
        obj.isArmstrong();
    }
}
Explanation: the constructor stores the number n and its length l (number of digits, found via String.valueOf(n).length()). sum_pow(i) recursively strips the last digit of i at each call (i%10), raises it to the power l (the length of the original number, a fixed value throughout the recursion), and adds it to the recursive call on the remaining digits (i/10), stopping when i becomes 0. isArmstrong() compares this sum to n and prints the appropriate message. Tested (run for real): for n=371, sum_pow computes 3^3+7^3+1^3=371 and the program correctly printed "371 is an Armstrong number."
2019 · 10 marks · ProgramOpen: A class Rearrange has been defined to modify a word by bringing all the vowels…

Write the program described below.

A class Rearrange has been defined to modify a word by bringing all the vowels in the word at the beginning followed by the consonants. Example: ORIGINAL becomes OIIARGNL Some of the members of the class are given below: Class name : Rearrange Data member/instance variable: wrd : to store a word newwrd : to store the rearranged word Member functions/methods: Rearrange( ) : default constructor void readword( ) : to accept the word in UPPER case void freq_vow_con( ) : finds the frequency of vowels and consonants in the word and displays them with an appropriate message void arrange( ) : rearranges the word by bringing the vowels at the beginning followed by consonants void display( ) : displays the original word along with the rearranged word Specify the class Rearrange, giving the details of the constructor( ), void readword( ), void freq_vow_con( ), void arrange( ) and void display( ). Define the main( ) function to create an object and call the functions accordingly to enable the task.
Show answer

Answer

AI
import java.util.Scanner;

class Rearrange
{
    String wrd, newwrd;

    Rearrange()
    {
        wrd = "";
        newwrd = "";
    }

    void readword()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a word in UPPER CASE: ");
        wrd = sc.nextLine();
    }

    void freq_vow_con()
    {
        int vcount = 0, ccount = 0;
        for (int i = 0; i < wrd.length(); i++)
        {
            char ch = wrd.charAt(i);
            if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
                vcount++;
            else
                ccount++;
        }
        System.out.println("Number of vowels: " + vcount);
        System.out.println("Number of consonants: " + ccount);
    }

    void arrange()
    {
        String vowels = "";
        String consonants = "";
        for (int i = 0; i < wrd.length(); i++)
        {
            char ch = wrd.charAt(i);
            if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
                vowels = vowels + ch;
            else
                consonants = consonants + ch;
        }
        newwrd = vowels + consonants;
    }

    void display()
    {
        System.out.println("Original word   : " + wrd);
        System.out.println("Rearranged word  : " + newwrd);
    }

    public static void main(String args[])
    {
        Rearrange obj = new Rearrange();
        obj.readword();
        obj.freq_vow_con();
        obj.arrange();
        obj.display();
    }
}
Explanation: freq_vow_con() scans wrd once and counts vowels and consonants, printing both counts. arrange() scans wrd character by character, appending each vowel to a separate 'vowels' string and each consonant to a 'consonants' string (preserving their original relative order within each group), then sets newwrd = vowels + consonants so all vowels come first followed by all consonants. Tested (run for real): for wrd="ORIGINAL" the program printed "Number of vowels: 4", "Number of consonants: 4", and Rearranged word "OIIARGNL", matching the example in the question exactly.

Questions on other pages on Objects

Other Computer Science chapters