Prashnikaप्रश्निका

ISC Computer Science - Competency Focused Practice Questions (CISCE, August 2024) with Answers

All 75 questions of the ISC Computer Science - Competency Focused Practice Questions (CISCE, August 2024), in printed order, in full. Tap "Show answer" under a question to see its answer.

Practise these questions with filters
Q11 mark · MCQOpen: For the given code snippet: int i; for( i = 5; i>=1; i--) System.out.println(…

Choose the correct option.

For the given code snippet:
int i;
for( i = 5; i>=1; i--)
    System.out.println( );
System.out.println(i);
  • (a)Zero will be displayed as variable i has local scope with respect to the loop.
  • (b)Zero will be displayed as variable i has global scope with respect to the loop.
  • (c)Error – Undeclared variable i.
  • (d)Output will be 1.
Show answer

Answer

AI

Correct option: b

Answer: (b) Zero will be displayed as variable i has global scope with respect to the loop. The variable i is declared outside the for statement (int i; then for(i=5;...)), so its scope is the enclosing method, not just the loop body. After the loop finishes, i has been decremented to 0, and since i remains in scope, System.out.println(i) prints 0.
Q21 mark · MCQOpen: m and n are two StringBuffer objects. The method call, m.append(n) will:

Choose the correct option.

m and n are two StringBuffer objects. The method call, m.append(n) will:
  • (a)mutate object m.
  • (b)mutate object n.
  • (c)mutate both the objects m and n.
  • (d).append( ) is an accessor method so it cannot mutate any object.
Show answer

Answer

AI

Correct option: a

Answer: (a) mutate object m. StringBuffer's append(x) method modifies the StringBuffer it is called on by appending x's content to it. So m.append(n) appends n's characters onto m, mutating m; n itself is left unchanged.
Q31 mark · MCQOpen: The code snippet given below will result in: StringBuffer x = new…

Choose the correct option.

The code snippet given below will result in:
StringBuffer x = new StringBuffer("Hello");
StringBuffer y = new StringBuffer("HELLO");
System.out.println(x.equalsIgnoreCase(y));
  • (a)boolean value false
  • (b)boolean value true
  • (c)undeclared method equalsIgnoreCase(…)
  • (d)String literals mismatch.
Show answer

Answer

AI

Correct option: c

Answer: (c) undeclared method equalsIgnoreCase( ). equalsIgnoreCase( ) is a String method, not a StringBuffer method. Since x and y are StringBuffer objects, calling x.equalsIgnoreCase(y) does not compile - it is an undefined method for that class.
Q41 mark · MCQOpen: Recursion takes toll on memory. Which of the following option is the reason for…

Choose the correct option.

Recursion takes toll on memory. Which of the following option is the reason for it?
  • (a)Every recursive call is placed in a call stack memory.
  • (b)Every recursive call is resolved in Last-In-First-Out (LIFO) manner.
  • (c)Values of local variables are maintained until each of the calls are resolved.
  • (d)All of the above.
Show answer

Answer

AI

Correct option: d

Answer: (d) All of the above. Each recursive call is pushed onto the call stack (a), calls are resolved in LIFO order (b), and the local variables/parameters of each call must be kept until that call returns (c). All three together explain why recursion costs more memory than iteration.
Q51 mark · MCQOpen: If binary search technique uses recursion instead of iteration, the code: i…

Choose the correct option.

If binary search technique uses recursion instead of iteration, the code: i. will contain two base cases. ii. will contain two recursive cases. iii. when executed will lead to an exception, stack overflow. Which of the above is valid?
  • (a)i and ii
  • (b)ii and iii
  • (c)i and iii
  • (d)Only iii
Show answer

Answer

AI

Correct option: a

Answer: (a) i and ii. A recursive binary search needs two base cases - element found, and search range exhausted (low > high) - and its code contains two possible recursive calls, one for the left half and one for the right half (only one executes per call). Statement iii is false: since the search range halves each call, the recursion depth is only about log2(n), so it does not cause a stack overflow.
Q61 mark · MCQOpen: Assume int [ ] [ ] x = { {8,9} , {5,6,7},{1,2,3,4}}, what are x[0].length…

Choose the correct option.

Assume int [ ] [ ] x = { {8,9} , {5,6,7},{1,2,3,4}}, what are x[0].length, x[1].length, and x[2].length?
  • (a)2, 3 and 3
  • (b)2, 3 and 4
  • (c)3, 3 and 3
  • (d)2, 2 and 2
Show answer

Answer

AI

Correct option: b

Answer: (b) 2, 3 and 4. x[0] = {8,9} has length 2, x[1] = {5,6,7} has length 3, and x[2] = {1,2,3,4} has length 4 - each row of this jagged array can have its own length.
Q71 mark · MCQOpen: String Description StringA Password entered by the user StringB Password stored…

Choose the correct option.

StringDescription
StringAPassword entered by the user
StringBPassword stored by the system
Passwords are stored as two Strings-one is the user entered password saved in StringA, the other is a password stored by the system in StringB. If StringA must be checked with StringB, for validity, which one of the following String functions are needed to be used?
  • (a)charAt( )
  • (b)equals( )
  • (c)equalsIgnoreCase( )
  • (d)startsWith( )
Show answer

Answer

AI

Correct option: b

Answer: (b) equals( ). A password check needs an exact, case-sensitive comparison, which String's equals( ) method gives. equalsIgnoreCase( ) would wrongly accept passwords differing only in case, and charAt( )/startsWith( ) do not compare the whole string.
Q81 mark · MCQOpen: What is the outcome of the following code snippet: public class Test { public…

Choose the correct option.

What is the outcome of the following code snippet:
public class Test  
{ 
    public static void main( )  
    { 
        char [ ][ ] matrix = {{'a','b','c'},{'p','q','r'},{'x','y','z'}}; 
        for( int i=0 ; i<3 ; i++) 
            System.out.print( matrix[i] [1] + "  " ); 
    }       
}
  • (a)a b c
  • (b)a p x
  • (c)p q r
  • (d)b q y
Show answer

Answer

AI

Correct option: d

Answer: (d) b q y. matrix[i][1] picks the element at column index 1 of row i: for i=0 that is matrix[0][1]='b', for i=1 it is matrix[1][1]='q', and for i=2 it is matrix[2][1]='y', giving "b q y".
Q91 mark · MCQOpen: For the following code snippet choose the correct output: int x = 234; String…

Choose the correct option.

For the following code snippet choose the correct output:
int x = 234; 
String str = String.valueOf(x) ; 
System.out.println(str.length( )); 
System.out.println( x + x ); 
System.out.println( str + str );
  • (a)2 234234 234234
  • (b)Error
  • (c)3 234234 468
  • (d)3 468 234234
Show answer

Answer

AI

Correct option: d

Answer: (d) 3 468 234234. String.valueOf(234) gives "234", whose length( ) is 3. x + x adds the two int values numerically, giving 468. str + str concatenates the two Strings, giving "234234".
Q101 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

AI

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.
Q111 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

AI

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.
Q121 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.
Q131 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

AI

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.
Q141 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

AI

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.
Q151 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

AI

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.
Q161 mark · MCQOpen: In single inheritance, which one of the following keywords should NOT be used.

Choose the correct option.

In single inheritance, which one of the following keywords should NOT be used.
  • (a)extends
  • (b)this
  • (c)super
  • (d)implements
Show answer

Answer

AI

Correct option: d

Answer: (d) implements. Single inheritance between classes in Java uses the extends keyword, with this and super available for use inside the subclass. implements is used to implement an interface, not for single class inheritance.
Q171 mark · MCQOpen: interface A { final static int x = 5; abstract void abc( ); } interface B {…

Choose the correct option.

interface A 
{ 
    final static int x = 5; 
    abstract void abc( ); 
} 

interface B 
{ 
    final static int y = 5; 
    abstract void abc( ); 
}
Assume that class Check implements interfaces A and B, how many times the method abc( ) will be defined in class Check ?
  • (a)Twice
  • (b)Once
  • (c)Compile time error
  • (d)Runtime error
Show answer

Answer

AI

Correct option: b

Answer: (b) Once. Both interfaces A and B declare the same abstract method signature abc( ). When class Check implements both, providing one concrete definition of abc( ) satisfies the abstract method requirement of both interfaces, so it is defined only once.
Q181 mark · MCQOpen: The Central Processing Unit (CPU) scheduling follows the principle of _________…

Choose the correct option.

The Central Processing Unit (CPU) scheduling follows the principle of _________ data structure.
  • (a)Two-dimensional array
  • (b)Circular queue
  • (c)Double ended queue dequeue
  • (d)Stack
Show answer

Answer

AI

Correct option: b

Answer: (b) Circular queue. CPU scheduling (e.g. round-robin scheduling) keeps the ready processes in a queue and cycles through them in FIFO order; this ready queue is typically implemented as a circular queue so it can wrap around continuously without wasting slots.
Q191 mark · MCQOpen: For the given Binary Tree, which traversal order will arrange the elements in…

Choose the correct option.

For the given Binary Tree, which traversal order will arrange the elements in ascending order?
  • (a)Post order
  • (b)Pre order
  • (c)In order
  • (d)Postfix order
Binary Tree
Binary Tree
Show answer

Answer

AI

Correct option: c

Answer: (c) In order. The given tree (root 4, left child 2, right subtree 7 with children 5 and 8, and 8's right child 9) is a binary search tree. An in-order traversal (left, root, right) of a BST always visits the nodes in ascending order: 2, 4, 5, 7, 8, 9.
Q201 mark · MCQOpen: ___________ is called a Self-Referential Data structure.

Choose the correct option.

___________ is called a Self-Referential Data structure.
  • (a)Stack
  • (b)Circular queue
  • (c)Linked List
  • (d)Double ended queue - dequeue
Show answer

Answer

AI

Correct option: c

Answer: (c) Linked List. A linked list node contains a reference (pointer) to another node of the same type, so the structure refers to itself - this is what makes it a self-referential data structure.
Q211 mark · Assertion-reasonOpen: Recursion utilises more memory as compared to iteration.

Study the Assertion and Reason and choose the correct option.

Assertion: Recursion utilises more memory as compared to iteration.

Reason: Absence of base case leads to infinite recursion.

  • (a)Both A and R are true, and R is the correct explanation of A.
  • (b)Both A and R are true, and R is not the correct explanation of A.
  • (c)A is true, but R is false.
  • (d)A is false, but R is true.
Show answer

Answer

AI

Correct option: b

Answer: (b) Both A and R are true, but R is not the correct explanation of A. Both statements are true: recursion does use more memory than iteration because each call adds a stack frame, and a missing base case does cause infinite recursion. But R explains why recursion without a base case fails to terminate, not why recursion in general (even with a base case) uses more memory than iteration, so R does not explain A.
Q221 mark · Assertion-reasonOpen: In Boolean Algebra, dual of the Boolean expression is equal to .

Study the Assertion and Reason and choose the correct option.

Assertion: In Boolean Algebra, dual of the Boolean expression $(A+B)'.1$ is equal to $0$.

Reason: In Boolean Algebra, the complement of an OR operation is equal to the AND operation of complement of the individual variables.

  • (a)Both A and R are true, and R is the correct explanation of A.
  • (b)Both A and R are true, but R is not the correct explanation of A.
  • (c)A is true, but R is false.
  • (d)A is false, but R is true.
Show answer

Answer

AI

Correct option: d

Answer: (d) A is false, but R is true. The dual of (A+B)'.1 is formed by swapping + with . and 1 with 0: (A.B)' + 0, which simplifies to A'+B' (equivalently (A.B)') - a contingency, not the constant 0, so A is false. R correctly states De Morgan's law, (A+B)' = A'.B', so R is true.
Q231 mark · Assertion-reasonOpen: The truth table for the XOR gate shows that the output is HIGH only when an odd…

Study the Assertion and Reason and choose the correct option.

Assertion: The truth table for the XOR gate shows that the output is HIGH only when an odd number of inputs are HIGH.

Reason: The XOR gate performs addition modulo 2, thus producing a HIGH output when the number of HIGH inputs is odd.

  • (a)Both A and R are true, and R is the correct explanation of A.
  • (b)Both A and R are true, but R is not the correct explanation of A.
  • (c)A is true, but R is false.
  • (d)A is false, but R is true.
Show answer

Answer

AI

Correct option: a

Answer: (a) Both A and R are true, and R is the correct explanation of A. For a 2-input XOR gate the output is HIGH exactly when the inputs differ, i.e. exactly one input (an odd count) is HIGH, matching the assertion. This is because XOR performs addition modulo 2, which is HIGH precisely when the number of HIGH inputs is odd - exactly what the reason states, so R correctly explains A.
Q241 mark · Assertion-reasonOpen: The Equivalence expression is .

Study the Assertion and Reason and choose the correct option.

Assertion: The Equivalence expression is $p \leftrightarrow q$.

Reason: An Equivalence Statement always gives the final result as Contingencies.

  • (a)Both A and R are true, and R is the correct explanation of A.
  • (b)Both A and R are true, but R is not the correct explanation of A.
  • (c)A is true, but R is false.
  • (d)A is false, but R is true.
Show answer

Answer

AI

Correct option: c

Answer: (c) A is true, but R is false. The biconditional/equivalence of p and q is written p <-> q, so A is true. R is false as a general claim: an equivalence statement is not always a contingency - for example p <-> p is a tautology (always true) and p <-> ~p is a contradiction (always false), so equivalence statements can also be tautologies or contradictions.
Q251 mark · Assertion-reasonOpen: The contrapositive of is .

Study the Assertion and Reason and choose the correct option.

Assertion: The contrapositive of $p' \Rightarrow q$ is $q' \Rightarrow p$.

Reason: Contrapositive is the conditional statement, obtained after interchanging antecedent and consequent.

  • (a)Both A and R are true, and R is the correct explanation of A.
  • (b)Both A and R are true, but R is not the correct explanation of A.
  • (c)A is true, but R is false.
  • (d)A is false, but R is true.
Show answer

Answer

AI

Correct option: c

Answer: (c) A is true, but R is false. For p' => q, the contrapositive negates both sides and swaps them: ~q => ~(p') = q' => p, exactly as the assertion states, so A is true. R is false because it describes only interchanging the antecedent and consequent without negating them - that is the definition of the converse, not the contrapositive.
Q261 mark · Short answerOpen: Study the given two classes below and identify the error if any, in the given…

Answer the following question.

Study the given two classes below and identify the error if any, in the given code.
class Vehicle
{
    protected String colour;
    protected String registration;
    public Vehicle(String c, String r)
    {
        colour = c;
        registration = r;
    }
    public void show()
    {
        System.out.println("Colour:" + colour);
        System.out.println("Registration number:" + registration);
    }
}

class Car extends Vehicle
{
    private double weight;
    private String model;
    public Car(String model, double weight, String colour, String registration)
    {
        this.model = model;
        this.weight = weight;
        super(colour, registration);
    }
    public void show()
    {
        super.show();
        System.out.println("Car Model name = " + model);
        System.out.println("Car body weight = " + weight);
    }
}
Show answer

Answer

AI
The error is in the Car constructor: the call super(colour, registration) is not the first statement of the constructor. In Java, a call to super() must always be the first statement in a constructor, so this gives a compile time error ("call to super must be first statement in constructor").
Q271 mark · Short answerOpen: What will happen if data members of super class are made private instead of…

Answer the following question.

What will happen if data members of super class are made private instead of protected?
Show answer

Answer

AI
If the data members of the super class are made private, they become inaccessible directly in the subclass. The subclass would no longer be able to refer to colour and registration by name in its own methods; it would have to use public getter/setter (accessor/mutator) methods of the super class to access or change them.
Q281 mark · Short answerOpen: What will happen if void show( ) in subclass Car is given access specifier as…

Answer the following question.

What will happen if void show( ) in subclass Car is given access specifier as private?
Show answer

Answer

AI
Java does not allow an overriding method to reduce the visibility of the method it overrides. Since Vehicle's show() is public, making Car's show() private is not a valid override and causes a compile time error: "show() in Car cannot override show() in Vehicle; attempting to assign weaker access privileges; was public".
Q291 mark · Short answerOpen: All methods declared in the interface are abstract. Where will the body of…

Answer the following question.

All methods declared in the interface are abstract. Where will the body of these abstract methods be defined?
Show answer

Answer

AI
The body of an interface's abstract methods is defined in the class that implements the interface; that class must provide (override) the implementation for every abstract method of the interface.
Q311 mark · Short answerOpen: In the given code snippet, which feature of object-oriented programming concept…

Answer the following question.

In the given code snippet, which feature of object-oriented programming concept is being exhibited by the substring( ) method?
String s1 = "sandwich"; 
System.out.println(s1.substring(4)); 
System.out.println(s1.substring(1,4));
Show answer

Answer

AI
It exhibits method overloading (compile time/static polymorphism): the class String has two versions of substring( ) - substring(int) and substring(int, int) - with the same name but a different number of parameters.
Q321 mark · Fill inOpen: Following is a code to convert a String into Double. Fill the missing parts of…

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

Following is a code to convert a String into Double. Fill the missing parts of the code:
____ str = "15.45"; 
double d = ____ (Double.parseDouble(str));
Show answer

Answer

AI

Blanks: String; (double)

The first blank is the type of the variable holding the text, so it is String. The second blank is a type cast to double. Double.parseDouble(str) already returns a double, so the cast is harmless:
String str = "15.45";
double d = (double) (Double.parseDouble(str));
d now holds 15.45.
Q341 mark · Short answerOpen: Since a byte can represent 256 different numbers, why is its maximum value 127?

Answer the following question.

Since a byte can represent 256 different numbers, why is its maximum value 127?
Show answer

Answer

AI
A byte is stored in two's complement (signed) form, so one bit is used as the sign bit, not for magnitude. Of the 256 possible bit patterns, half (128) represent negative numbers (-128 to -1) and the other half represent zero and positive numbers (0 to 127), so the maximum positive value it can hold is 127.
Q361 mark · Case basedOpen: Ram and Hari are coder friends, who are debating effective usage of memory…

Answer the following questions.

Ram and Hari are coder friends, who are debating effective usage of memory while using variables, without compromising on precision of values. Help them on identifying the right data type to use, for the following data:
(a)[0.5]
Population of a country
(b)[0.5]
Interest rate in a bank account
Show answer

Answer (a)

AI
long (a population count can exceed the range of int, so a larger integer type is used).

Answer (b)

AI
float (a decimal value where double's extra precision is not needed, saving memory).
Q371 mark · OutputOpen: What gets printed? char [ ] set = {'*','D','5'}…

What is the output of the following code?

What gets printed?
char [ ] set = {'*','D','5'}; 
System.out.print(Character.isDigit(set[2]) + " "); 
System.out.print(Character.isWhitespace(set[0]) + " "); 
System.out.print(Character.isLetterOrDigit(set[1]));
Show answer

Answer

AI
true false true
Q381 mark · Short answerOpen: While using Wrapper classes, we do not need to import any package. Give a…

Answer the following question.

While using Wrapper classes, we do not need to import any package. Give a reason.
Show answer

Answer

AI
Wrapper classes belong to the java.lang package, and java.lang is imported into every Java program automatically by the compiler, so no explicit import statement is needed to use them.
Q391 mark · Short answerOpen: Teachers of class XII are calculating the average attendance for 3 months. The…

Answer the following question.

Teachers of class XII are calculating the average attendance for 3 months. The class attendance for 3 months is stored in double variables m1, m2, m3. TeacherA and TeacherB are using different techniques to get the average. Complete the code of TeacherA and name the technique used by him:
TeacherATeacherB
int average = (____)((m1+m2+m3)/3);int average = Math.round((m1+m2+m3)/3);
Show answer

Answer

AI
int average = (int)((m1+m2+m3)/3); TeacherA uses type casting (narrowing/explicit type conversion) - it truncates the decimal part, while TeacherB's Math.round() rounds off the value to the nearest integer.
Q401 mark · Short answerOpen: Consider the following snippet, calculate the time complexity assuming the code…

Answer the following question.

Consider the following snippet, calculate the time complexity assuming the code compiles successfully.
double m = 1, n = 1; 
for (int i = 0; i < x; i++)  
{ 
    m *= Math.random( ); 
} 
for (int j = 0; j < y; j++)  
{ 
    n *= Math.random( ); 
}
Show answer

Answer

AI
$O(x + y)$, which is linear time complexity, $O(n)$: the two for loops run one after another (not nested), taking $x$ and $y$ steps respectively, so the total number of steps grows linearly with the input sizes.
Q411 mark · Short answerOpen: “Finding the greatest common divisor (GCD) of two positive integers results in…

Answer the following question.

“Finding the greatest common divisor (GCD) of two positive integers results in the time complexity of $O(\log N)$ where $N$ is the larger number of two inputs”. Justify the statement.
Show answer

Answer

AI
The GCD (by Euclid's algorithm) is found by repeatedly replacing the larger number with the remainder of dividing it by the smaller one. Each such step reduces the larger number to less than half its previous value within at most two steps, so the number of steps needed is proportional to $\log N$, giving a time complexity of $O(\log N)$.
Q421 mark · Short answerOpen: A student had written the following method to display “Hello World” four times…

Answer the following question.

A student had written the following method to display “Hello World” four times on the output screen.
void displayMessage( ) 
{ 
    System.out.println("Hello World"); 
    System.out.println("Hello World"); 
    System.out.println("Hello World"); 
    System.out.println("Hello World"); 
}
The student modified the code later to reduce the number of lines in the code.
void displayMessage( ) 
{ 
    int i = 1; 
    while(i <= 4)  
    { 
        System.out.println("Hello World"); 
        i++; 
    } 
}
Compare the above code snippets with respect to the time complexity.
Show answer

Answer

AI
Both versions have the same time complexity, $O(1)$ (constant time): the first has 4 fixed print statements and the while loop also always executes exactly 4 times, so in both cases the number of operations does not depend on any input size and stays constant.
Q431 mark · OutputOpen: Find the output of the following snippet: void check1( ) { String x[ ] =…

What is the output of the following code?

Find the output of the following snippet:
void check1( ) 
{     
    String x[ ] = {"Kolkata", "Chennai", "Delhi"}; 
    String y[ ] = {"Kolkata", "Chennai", "Delhi"}; 
    System.out.println(x.equals(y)); 
}
Show answer

Answer

AI
false Arrays do not override equals( ), so x.equals(y) uses the default Object.equals( ), which compares object references (memory addresses), not contents; since x and y are different array objects, it returns false even though their elements are equal.
Q471 mark · Short answerOpen: String s1 = "Gujarat"; String s2 = new String("Gujarat"); String s3 = new…

Answer the following question.

String s1 = "Gujarat"; 
String s2 = new String("Gujarat"); 
String s3 = new String("Gujarat"); 
String s4 = "Gujarat";
How many String objects are created in the above snippet? Justify your answer.
Show answer

Answer

AI
3 String objects are created. s1 = "Gujarat" is a literal, placed in the String constant pool. s4 = "Gujarat" is also a literal with the same content, so it reuses the same pooled object as s1 (no new object). s2 = new String("Gujarat") and s3 = new String("Gujarat") each use the new keyword, so each creates a separate new object in the heap, even though their content is the same. So in total: 1 (pool, shared by s1 and s4) + 1 (s2) + 1 (s3) = 3 objects.
Q492 marks · Short answerOpen: Why is the lang package termed as the default package in Java?

Answer the following question.

Why is the lang package termed as the default package in Java?
Show answer

Answer

AI
The java.lang package is called the default package because it is imported automatically into every Java program by the compiler; unlike other packages, it does not need an explicit import statement to use the classes it provides (such as String, Math, Integer and the other wrapper classes).
Q502 marks · Case basedOpen: State the purpose of the following keywords in Java: package import

Answer the following questions.

State the purpose of the following keywords in Java:
(a)[1.0]
package
(b)[1.0]
import
Show answer

Answer (a)

AI
package: it groups related classes and interfaces together under one namespace, making them easier to organise, locate, reuse and avoid naming conflicts.

Answer (b)

AI
import: it is used to bring a class (or all classes) of a package into a program so that its members can be used without writing the fully qualified name each time.
Q512 marks · Case basedOpen: Given the following code snippet: package mine; public class Greetings { public…

Answer the following questions.

Given the following code snippet:
package mine; 
public class Greetings 
{ 
    public static void greet(String name) 
    { 
        System.out.println("Hello " + name + ", welcome to the world of programming"); 
    } 
} 

import java.util.*; 
import mine.*; 
public class Trial 
{ 
    public static void main() 
    { 
        Scanner sc = new Scanner(System.in); 
        System.out.println("Give your name"); 
        String n = sc.next(); 
        Greetings.greet(n); 
    } 
}
(a)[1.0]
Predict the output for n = “Abhay”;
(b)[1.0]
Explain the difference between the two statements: import java.util.*; and import mine.*;
Show answer

Answer (a)

AI
Output: Give your name Hello Abhay, welcome to the world of programming

Answer (b)

AI
import java.util.*; imports all the classes of the built-in java.util package (e.g. Scanner, StringTokenizer). import mine.*; imports all the classes of the user-defined package mine (here, the class Greetings) that the programmer created.
Q542 marks · DrawingOpen: Following is the circuit diagram of a full adder. Redraw the circuit diagram by…

Draw the following.

Following is the circuit diagram of a full adder. Redraw the circuit diagram by adding missing logic gates.

Draw: Full adder logic circuit with missing gates (i), (ii), (iii), (iv) filled in

Must show: XOR gate, AND gate, OR gate

Full adder circuit diagram
Full adder circuit diagram
Show answer

Answer

AI
A full adder circuit with A, B and C_in as inputs, and Sum and C_out as outputs. Box (i) is a 2-level XOR block computing Sum = A XOR B XOR C_in (first XOR combines A and B, second XOR combines that result with C_in). The pre-drawn AND gate, plus boxes (ii) and (iv), are the three AND gates AB, B.C_in and A.C_in (one input pair each). Box (iii) is an OR gate that combines the outputs of all three AND gates to give C_out = AB + B.C_in + A.C_in.
Diagram for this answer
Q552 marks · DrawingOpen: Draw the logic circuit diagram for the simplified form of the following…

Draw the following.

Draw the logic circuit diagram for the simplified form of the following expression: $AB'C' + AB'C + ABC$ The circuit diagram should only contain one AND, one OR and one NOT gates.

Draw: Logic circuit diagram for simplified expression AB'C' + AB'C + ABC = A(B' + C) using one AND, one OR and one NOT gate

Must show: AND gate, OR gate, NOT gate

Show answer

Answer

AI
A circuit with three inputs A, B, C. A NOT gate inverts B to give B'. An OR gate combines B' and C to give (B'+C). An AND gate combines A and (B'+C) to give the output F = A(B'+C), which equals the given expression AB'C' + AB'C + ABC.
Diagram for this answer
Q562 marks · Case basedOpen: Following method is a part of a class MyArray. int check(int m[ ], int i) { if…

Answer the following questions.

Following method is a part of a class MyArray.
int check(int m[ ], int i) 
{ 
    if (i <= 0)  
    { 
        return 0; 
    } 
    return check(m, i - 2) + m[i - 1]; 
} 

public static void main( ) 
{ 
    int m[ ] = {1, 2, 3, 4}; 
    int ans = check(m, m.length); 
    System.out.println(ans); 
}
(a)[1.0]
Predict the output of the code considering there is no compilation error. Show the working.
(b)[1.0]
Considering the if condition is changed to if(i < 0), how will it affect the output?
Show answer

Answer (a)

AI
Output: 6 Working: check(m,4) = check(m,2) + m[3] = check(m,2) + 4 check(m,2) = check(m,0) + m[1] = check(m,0) + 2 check(m,0): since i=0 <= 0, returns 0 So check(m,2) = 0 + 2 = 2, and check(m,4) = 2 + 4 = 6. ans = 6

Answer (b)

AI
With if(i < 0), the base case i=0 is no longer true (0 is not < 0), so recursion does not stop there: check(m,0) calls check(m,-2) + m[-1], and m[-1] is an invalid array index. The program throws an ArrayIndexOutOfBoundsException (index -1) instead of returning a value, so it crashes rather than printing 6.
Q572 marks · Short answerOpen: A student has written the following code. It is written to check whether a…

Answer the following question.

A student has written the following code. It is written to check whether a string is palindrome or not. However, the code is not giving the desired result when the parameter “MADAM” is passed to the method isPalindrome(). Analyse the code and find out the logical error.
public class PalindromeTesting 
{     
    public static boolean isPalindrome(String word) 
    {       
        if (word.length( ) < 1) 
        {  
            return true; 
        }  
        else if (word.charAt(0) != word.charAt(word.length( ) - 1))  
        {  
            return false; 
        }  
        else   
        {  
            return isPalindrome(word.substring(0, word.length( ) - 1)); 
        } 
    } 
}
Show answer

Answer

AI
Logical error: in the recursive call isPalindrome(word.substring(0, word.length()-1)), only the last character is dropped; the first character (already compared) is not dropped. So the next comparison compares the original first character again, but against a different (wrong) last character, giving a wrong result (isPalindrome("MADAM") incorrectly returns false). The substring should drop both ends: it should be word.substring(1, word.length()-1).
Q582 marks · Short answerOpen: Following code gives a StackOverException. public class StackOverflow { public…

Answer the following question.

Following code gives a StackOverException.
public class StackOverflow
{
    public static void main()
    {
        callMe();
    }
    public static void callMe()
    {
        callMe();
    }
}
Stack is a data structure whereas recursion is related to a method. Why does the above code give an exception with stack overflow?
Show answer

Answer

AI
Each call to callMe() creates a new activation record (return address, parameters, local variables) that is pushed onto the call stack, and since callMe() calls itself with no base/terminating condition, calls keep being pushed and none are ever popped. The stack has a fixed maximum size, and once that limit is exceeded by the endless pushes, the JVM throws a StackOverflowError (reported as a stack overflow exception).
Q592 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

AI
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.
Q602 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

AI
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().
Q612 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.

Q625 marks · Case basedOpen: At Get It All supermarket, a POS (Point of Sale) system is designed. The cart…

Answer the following questions.

At Get It All supermarket, a POS (Point of Sale) system is designed. The cart management is visible to the POS operator. The newer carts get added and once the bill payment is done the current cart gets checked out from the system. The operator has 4 options like add cart, check out cart, view cart queue and close the counter. The class Cart is created to represent the node of the linked list.
public class Cart 
{ 
    int cartNo; 
    Cart next; 
    Cart(int cartNo) 
    { 
        this.cartNo = cartNo; 
        next = null; 
    } 
}
The class POS is created to represent the POS for cart management. Observe the given code and answer the following questions.
import java.util.*; 
public class POS 
{ 
    Cart first; 
    static int count = 0; 
    static Scanner sc = new Scanner(System.in); 
    void viewQueue( ) 
    { 
        Cart temp = first; 
        boolean flag = false; 
        System.out.println("The carts at the counter are"); 
        while(temp != null)  
        {        
            System.out.println(temp.cartNo); 
            ?1? 
            ?2? 
        }  
        if(!flag) 
            System.out.println("The checkout counter is empty"); 
        else 
            System.out.println("number of carts currently=" + count); 
    } 
    void addCart()  
    { 
        System.out.print("Enter the new cart number: "); 
        int no = sc.nextInt(); 
        Cart newCart = new Cart(no); 
        if(first == null) 
            first = newCart; 
        else 
        { 
            Cart temp = first; 
            while(temp.next != null) 
                temp = temp.next;   
            temp.next = newCart; 
        } 
        count++; 
    } 
    void checkOutCart()  
    { 
        ?1? 
        System.out.println("Cart being removed =" + temp.cartNo);  
        ?2? 
        temp.next = null; 
        temp = null; 
        ?3? 
        System.out.println("Carts remaining " + count); 
    } 
}
(a)[2.0]
Write the code for the blanks given in the method void viewQueue( ).
(b)[3.0]
Mention the code for the blanks given in the method void checkOutCart( ).

No answer yet.

Q635 marks · Case basedOpen: Answer the questions based on the binary trees: Observe the following binary…

Answer the following questions.

Answer the questions based on the binary trees:
(a)[2.0]
Observe the following binary tree and identify its type. Justify your answer.
Figure for part (a)
(b)[2.0]
Observe the given tree and answer the following questions. (i) Why can the following tree not be termed as a full binary tree? (ii) What is the size of the given binary tree? (iii) Name the internal nodes of the given binary tree.
Figure for part (b)
(c)[1.0]
State any one condition for a balanced binary tree.
Show answer

Answer (a)

AI
It is a complete binary tree. Every level is completely filled except possibly the last: level 0 has A, level 1 has B and C, level 2 has all 4 possible nodes D, E, F, G, and level 3 (the last, partially-filled level) has its nodes H, I, J packed as far left as possible (H and I under D, then J under E, with nothing under F or G).

Answer (b)

AI
(i) It is not a full binary tree because node C has only one child (E) instead of exactly 0 or 2 children; a full binary tree requires every node to have either zero or two children. (ii) Size (total number of nodes) = 6 (A, B, C, F, D, E). (iii) Internal nodes (nodes with at least one child) = A, B, C.

Answer (c)

AI
A binary tree is balanced if, for every node in the tree, the heights of its left and right subtrees differ by at most 1.
Q645 marks · Case basedOpen: Consider the class definitions and answer the questions: Complete the missing…

Answer the following questions.

Consider the class definitions and answer the questions:
(a)[3.0]
Complete the missing parts of the code given below:
class SI ?1? Account     
{                            
    double sINT; 
    public SI (double sP, double sR, double sT) 
    { 
        ?2?                                           
        sINT = 0; 
    } 
    public void Interest() 
    {   
        sINT = (P * R * T) / 100;  
    } 
    public void display() 
    { 
        ?3? //invoke display( ) of base class                
        Interest(); 
        System.out.println("Simple Interest=" + sINT);      
    } 
} // class ends
(b)[2.0]
Answer the following questions, based on the above code: (i) Name the base class and derived class (ii) Write the prototype of the base class constructor.
Show answer

Answer (b)

AI
(i) Base class = Account, Derived class = SI. (ii) Prototype of the base class constructor: Account(double P, double R, double T)
Q655 marks · Case basedOpen: Fix the following keywords at the right places: extends, super, protected…

Answer the following questions.

Fix the following keywords at the right places: extends, super, protected, abstract, implements
(a)[1.0]
class D1 ______ i1, i2            
{              
}
(b)[1.0]
_________ void printInfo( );
(c)[1.0]
class S1 
{             
} 
class D2 ______ S1 
{             
}
(d)[1.0]
class S2 
{ 
    public void show( ) 
    {       
    } 
} 
class D3 extends S2 
{ 
    public void show( ) 
    { 
        ____.show( );                        
    } 
}
(e)[1.0]
// Package X
class S3 {
    ______ int data;
}

// Package Y
class D4 extends S3 {
    public void calc() {
        data = 120 * 3;
    }
}

No answer yet.

Q665 marks · Case basedOpen: Answer the following questions related to object-oriented programming: In Java…

Answer the following questions.

Answer the following questions related to object-oriented programming:
(a)[2.0]
In Java, polymorphism is exhibited in two different ways. Identify them in the code snippets given in Column A and Column B?
Column AColumn B
Shapes myShape = new Shapes(); myShape.area(); myShape.area(5); myShape.area(6.0, 1.2); myShape.area(6, 2);class Vehicle { void drive() { System.out.println("Vehicle is moving"); } } class Bus extends Vehicle { void drive() { System.out.println("Bus is running safely"); } } public static void main() { Bus b = new Bus(); b.drive(); }
(b)[1.5]
Differentiate between the keywords this and super(...) with respect to constructor.
(c)[1.5]
Base class Student and derived class ICSEStudent are illustrated as: Student $\rightarrow$ ICSEStudent. Similarly, show the classes Shapes, Triangle, TwoD_Shapes, Sphere, ThreeD_Shapes exhibiting inheritance at multi-levels, depending on the type of shapes.
Show answer

Answer (a)

AI
Column A shows compile-time (static) polymorphism / method overloading: the class Shapes has several area() methods with the same name but different parameter lists (no arguments, one int, two doubles, two ints), and the correct one is chosen at compile time based on the arguments passed. Column B shows run-time (dynamic) polymorphism / method overriding: Bus overrides Vehicle's drive() method, and calling b.drive() on a Bus object invokes Bus's version - the method that actually runs is decided at run time based on the object's actual class.

Answer (b)

AI
this(...) is used inside a constructor to call another constructor of the same class (constructor chaining within the class), and must be the first statement in the constructor. super(...) is used inside a constructor to call a constructor of the immediate base (parent) class, so the base class part of the object is initialised first; it must also be the first statement in the constructor.

Answer (c)

AI
Shapes -> TwoD_Shapes -> Triangle (one branch, for two-dimensional shapes) Shapes -> ThreeD_Shapes -> Sphere (another branch, for three-dimensional shapes) Both branches show multilevel inheritance, similar to Student -> ICSEStudent.
Q675 marks · Truth tableOpen: A student from the Electronics department is asked to design a digital alarm…

Answer the following using a truth table.

A student from the Electronics department is asked to design a digital alarm for a smart home security system for the outside area. It comprises a sensor and a digital identification (ID) card with six-digit personal identification number (PIN). The alarm is supposed to buzz if wrongful entry is attempted, either by breaking the glass window or by entering the wrong PIN. Following statements are the criteria for the alarm to buzz: • The sensor detects the door opening without scanning a digital ID card. or • The sensor detects the door opening by breaking of the door lock. or • The sensor detects the wrong pin entry thrice of the digital ID card while opening the door. The inputs are:
InputsDescription
DDoor opening
BBreaking of door lock
SScanning security card
PEntering correct six-digit pin less than three times
(In all the above cases 1 indicates Yes and 0 indicates No). Output: A – Denotes the buzz of security alarm system (1 indicates yes and 0 indicates no) Draw the truth table for the inputs and outputs given above. Write the canonical POS expression for A(D, B, S, P).

No answer yet.

Q685 marks · Case basedOpen: Given the Boolean function . Reduce the above expression by using a 4-variable…

Answer the following questions.

Given the Boolean function $F(P,Q,R,S) = \Sigma(2,3,5,7,8,10,11,12,13,15)$.
(a)[3.0]
Reduce the above expression by using a 4-variable Karnaugh map, showing the various groups (i.e. octal, quads and pairs).
(b)[2.0]
Draw the logic gate diagram for the reduced expression using NAND gate only. Assume that the variables and their complements are available as inputs.

Draw: Logic gate diagram for reduced expression using only NAND gates

Must show: NAND gates

Show answer

Answer (b)

AI
NAND-only (NAND-NAND) implementation of $F = PR'S' + QS + Q'R$: one NAND gate for each of the three product terms, and a 3-input NAND gate combining them, since $[(PR'S')' \cdot (QS)' \cdot (Q'R)']' = PR'S' + QS + Q'R$ by De Morgan's law. Variables and their complements (P, P', Q, Q', R, R', S, S') are assumed available as inputs, as stated.
Diagram for this answer
Q695 marks · Case basedOpen: Answer the following Boolean algebra questions: . Find its corresponding…

Answer the following questions.

Answer the following Boolean algebra questions:
(a)[3.0]
$f(a, b, c) = a.b' + a.c + b.c'$. Find its corresponding Cardinal and Canonical sum-of-product expression?
(b)[2.0]
If $a=1, b=0, c=1, d=0$, then write maxterm and minterm for $F(a, b, c, d)$ in canonical form?
Show answer

Answer (a)

AI
$f(a,b,c) = a.b' + a.c + b.c'$ Truth table:
abcf
0000
0010
0101
0110
1001
1011
1101
1111
Cardinal (sum-of-minterms) form: $f(a,b,c) = \Sigma(2,4,5,6,7)$ Canonical SOP: $f(a,b,c) = a'bc' + ab'c' + ab'c + abc' + abc$

Answer (b)

AI
$a=1, b=0, c=1, d=0$ gives the binary code 1010, i.e. index 10. Minterm (variable uncomplemented if its value is 1, complemented if 0): $m_{10} = a.b'.c.d'$ Maxterm (variable complemented if its value is 1, uncomplemented if 0): $M_{10} = a' + b + c' + d$
Q705 marks · Truth tableOpen: Post pandemic, to encourage the tourism industry in India, the Ministry of…

Answer the following using a truth table.

Post pandemic, to encourage the tourism industry in India, the Ministry of Tourism started a policy in which a tourist would be allowed to book a resort at a rebate, if any one of the following criteria matches. ● The tourist has an AADHAR card and has no criminal record. ● The tourist is the government employee and has repeated the resort visit in a span of six months. ● The tourist has an AADHAR card and has repeated the resort visit in a span of six months. Inputs: - A: The tourist has an AADHAR CARD - C: The tourist has a criminal record - G: The tourist is the government employee - V: The tourist has repeated the resort visit in a span of six months Output: - F: The tourist would be allowed to book the resort at rebate. [1 indicates Yes and 0 indicates No]. Draw the truth table for inputs and outputs given above and write the Cardinal Sum of product expression for $F(A, C, G, V)$.

No answer yet.

Q7110 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

AI
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.
Q7210 marks · ProgramOpen: [Programme based on Strings] Two words are called anagram of each other if both…

Write the program described below.

[Programme based on Strings] Two words are called anagram of each other if both the words contain the same letters but they are arranged in different order. Following are the three pairs of the words which are anagrams of each other. cat, act heart, earth silent, listen Design the class Anagram to input two words in lower case and check if they are anagram of each other. The member functions and data members of the class are given below: Class Name : Anagram Data members/instance variables: s1, s2 : stores the two words in lower case l1, l2 : number of character in s1 and s2 respectively Member functions : Anagram(String s1, String s2) : parameterised constructor to assign the accepted values of s1 and s2 to data member void sort(char c[]) : to sort the characters in array c[ ] in ascending order using any sorting technique boolean areAnagram(char[] str1, char[] str2) : to check if str1 and str2 are anagrams of each other and to return true or false accordingly void check() : to convert the two strings into two character arrays and to display the appropriate message as shown in the sample output by calling the method areAnagram(char[] str1, char[] str2) Specify the class Anagram giving details of the parameterised constructor, void sort(char c[ ]), boolean areAnagram(char[] str1, char[] str2) and void check( ). Create one object in the main( ) method and call all the methods appropriately.

Sample input/output

Sample input
Enter first word->earth
Enter second word->heart

Output
earth and heart are anagram of each other
Show answer

Answer

AI
import java.util.Scanner;

class Anagram
{
    String s1, s2;   // the two words in lower case
    int l1, l2;      // number of characters in s1 and s2

    // parameterised constructor
    Anagram(String s1, String s2)
    {
        this.s1 = s1;
        this.s2 = s2;
        l1 = s1.length();
        l2 = s2.length();
    }

    // sorts the characters of c[] in ascending order using bubble sort
    void sort(char c[])
    {
        int n = c.length;
        for (int i = 0; i < n - 1; i++)
            for (int j = 0; j < n - 1 - i; j++)
                if (c[j] > c[j + 1])
                {
                    char t = c[j];
                    c[j] = c[j + 1];
                    c[j + 1] = t;
                }
    }

    // checks if str1 and str2 are anagrams by sorting both and comparing
    boolean areAnagram(char[] str1, char[] str2)
    {
        if (str1.length != str2.length)
            return false;
        sort(str1);
        sort(str2);
        for (int i = 0; i < str1.length; i++)
            if (str1[i] != str2[i])
                return false;
        return true;
    }

    // converts s1 and s2 to character arrays and displays the result
    void check()
    {
        char c1[] = s1.toCharArray();
        char c2[] = s2.toCharArray();
        if (areAnagram(c1, c2))
            System.out.println(s1 + " and " + s2 + " are anagram of each other");
        else
            System.out.println(s1 + " and " + s2 + " are not anagram of each other");
    }

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter first word->");
        String s1 = sc.next();
        System.out.print("Enter second word->");
        String s2 = sc.next();
        Anagram ob = new Anagram(s1, s2);
        ob.check();
    }
}
Explanation: sort() rearranges a character array into ascending order with bubble sort; areAnagram() sorts copies of both words and returns true only if every position then matches (same length and same multiset of letters). check() converts the two stored words to char arrays and prints the appropriate message. Tested (run for real): "earth"/"heart" printed "earth and heart are anagram of each other" (matching the sample), "silent"/"listen" also correctly reported as anagrams, and "hello"/"world" was correctly reported as not anagrams.
Q7310 marks · ProgramOpen: [Recursion program] Design a class Spy to check if a number is a Spy number or…

Write the program described below.

[Recursion program] Design a class Spy to check if a number is a Spy number or not. A spy number is a number where the sum of its digits equals the product of its digits. For example, 1124 is a spy number, the sum of its digits is $1+1+2+4=8$ and the product of its digits is $1 \times 1 \times 2 \times 4=8$. Class name : Spy Data Members: num : to store the number Member methods: Spy(int nn) : initialize the data member num=nn int sumOfDigits(int i) : returns the sum of digits of num using recursive technique int prodOfDigits(int i) : returns the product of digits of num using recursive technique void check( ) : checks whether the given number is a Spy number or not by invoking the functions sumOfDigits( ) and prodOfDigits( ) and displays appropriate message Specify the class Spy giving details of the functions int sumOfDigits(int ), void check( ), int prodOfDigits(int). Assume that the data member and constructor are already defined. Define a main method to create an object and call the functions accordingly to enable the task.
Show answer

Answer

AI
class Spy
{
    int num;   // stores the number

    // constructor (assumed already defined)
    Spy(int nn)
    {
        num = nn;
    }

    // recursively returns the sum of the digits of i
    int sumOfDigits(int i)
    {
        if (i == 0)
            return 0;
        else
            return i % 10 + sumOfDigits(i / 10);
    }

    // recursively returns the product of the digits of i
    int prodOfDigits(int i)
    {
        if (i == 0)
            return 1;
        else
            return (i % 10) * prodOfDigits(i / 10);
    }

    // checks whether num is a Spy number and displays the result
    void check()
    {
        int s = sumOfDigits(num);
        int p = prodOfDigits(num);
        if (s == p)
            System.out.println(num + " is a Spy number.");
        else
            System.out.println(num + " is not a Spy number.");
    }

    public static void main(String args[])
    {
        Spy ob = new Spy(1124);
        ob.check();
    }
}
Explanation: sumOfDigits(i) and prodOfDigits(i) each recursively strip the last digit of i (i%10), combine it with the recursive result on the remaining digits (i/10), and stop at i==0 (base case 0 for the sum so the trailing digit isn't counted twice, base case 1 for the product so it doesn't zero out the result). check() compares the two and prints the appropriate message. Tested (run for real): 1124 (sum=8, product=8) was correctly reported as a Spy number, 123 (sum=6, product=6) and 9 (single digit, sum=product=9) were also correctly reported as Spy numbers, and 122 (sum=5, product=4) was correctly reported as not a Spy number.
Q7410 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

AI
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."
Q7510 marks · ProgramOpen: [Arrays] Given below is an example of a double dimensional array with unequal…

Write the program described below.

[Arrays] Given below is an example of a double dimensional array with unequal number of rows and columns. It must be arranged in such a way that the elements in the even rows are in ascending order and the elements in the odd rows are in descending order, using Insertion sort technique. The members of the class are given below: Class name : Mix_sort Data members / instance variables: a[][] : to store integers in the double dimensional array. m : to store the number of rows. n : to store the number of columns. Methods / Member functions : Mix_sort(int row, int col) : parameterised constructor to initialise the m=row, n=col and allocate memory for a[][] void input() : to enter the integer elements in a [][] void ascEven(int x[]) : arrange the elements of x[] in ascending order using Insertion sort technique. void dscOdd(int x[]) : arrange the elements of x[] in descending order using Insertion sort technique. void arrange() : to arrange the rows in even position in Ascending order using ascEven(.. ) method and rows in odd position in descending order using dscOdd(..) method. Finally store the sorted elements into a[][] void display( ) : display the original a[][] and sorted a[][] . Define the class Mix_sort with details of the constructor, void input(), void arrange(), void ascEven(int []), void dscOdd(int []) and void display( ). Define a main() function to create an object and call the functions accordingly to enable the task.

Sample input/output

Sample Input :
Row=3
Column=4
Enter the array elements
1 2 3 4
9 8 7 6
4 5 6 7

Before sort:
1   2   3   4
9   8   7   6
4   5   6   7

After sort:
4   3   2   1
6   7   8   9
7   6   5   4
Show answer

Answer

AI
import java.util.Scanner;

class Mix_sort
{
    int a[][];   // stores the integer array
    int m;       // number of rows
    int n;       // number of columns

    // parameterised constructor
    Mix_sort(int row, int col)
    {
        m = row;
        n = col;
        a = new int[m][n];
    }

    // accepts the integer elements into a[][]
    void input()
    {
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++)
                a[i][j] = sc.nextInt();
    }

    // arranges x[] in ascending order using insertion sort
    void ascEven(int x[])
    {
        for (int i = 1; i < x.length; i++)
        {
            int key = x[i];
            int j = i - 1;
            while (j >= 0 && x[j] > key)
            {
                x[j + 1] = x[j];
                j--;
            }
            x[j + 1] = key;
        }
    }

    // arranges x[] in descending order using insertion sort
    void dscOdd(int x[])
    {
        for (int i = 1; i < x.length; i++)
        {
            int key = x[i];
            int j = i - 1;
            while (j >= 0 && x[j] < key)
            {
                x[j + 1] = x[j];
                j--;
            }
            x[j + 1] = key;
        }
    }

    // sorts each row: even (1-indexed) row positions ascending, odd row positions descending
    void arrange()
    {
        for (int i = 0; i < m; i++)
        {
            int row[] = new int[n];
            for (int j = 0; j < n; j++)
                row[j] = a[i][j];
            if ((i + 1) % 2 == 0)
                ascEven(row);
            else
                dscOdd(row);
            for (int j = 0; j < n; j++)
                a[i][j] = row[j];
        }
    }

    // displays the original array, then arranges it and displays the sorted array
    void display()
    {
        System.out.println("Before sort:");
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
                System.out.print(a[i][j] + "\t");
            System.out.println();
        }
        arrange();
        System.out.println("After sort:");
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
                System.out.print(a[i][j] + "\t");
            System.out.println();
        }
    }

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Row=");
        int row = sc.nextInt();
        System.out.print("Column=");
        int col = sc.nextInt();
        Mix_sort obj = new Mix_sort(row, col);
        System.out.println("Enter the array elements");
        obj.input();
        obj.display();
    }
}
Explanation: ascEven() and dscOdd() are both plain insertion sort, just with the comparison reversed. arrange() copies each row into a temporary array, sorts it ascending if the row's 1-indexed position is even and descending if odd, then writes it back into a[][]. display() prints the array as first entered, calls arrange(), then prints the result. Tested (run for real) with the question's own 3x4 example (rows 1 2 3 4 / 9 8 7 6 / 4 5 6 7): output was exactly 'Before sort: 1 2 3 4 / 9 8 7 6 / 4 5 6 7' then 'After sort: 4 3 2 1 / 6 7 8 9 / 7 6 5 4', matching the sample in the question.

Other Computer Science papers of 2025