ICSE 2014 Sample Paper 2

Computer Applications ICSE Sample Paper 2. These are likely questions different from what has already been asked, but of similar complexity and with some minor twists. The sample papers are designed to ensure the student is able to understand and solve the questions that may come up, using similar concepts as in earlier question papers. As in earlier papers, Questions 1, 2 and 3 are compulsory, and you need to answer 4 out of the remaining 6 questions. Model answers are also provided after each question for your ready reference.

Q1. (a) Explain what you understand by the term Java Virtual Machine. [2 marks]

A1. (a) The Java Virtual Machine is an imaginary machine that can understand and execute bytecode (class files). This machine may be a computer, a mobile phone, or any other device (toaster, fridge, etc.) The JVM is enabled using something known as the Java Runtime Environment (JRE). This includes the Java interpreter (java.exe on Windows).

The JVM includes not just the Java interpreter but also a standard set of libraries. These libraries are packaged class files – that provide all the necessary functionality – which includes displaying data on the screen, connecting to a database, and so on.

Q1. (b) State true or false for each of the following statements. If false, explain why.

i) Due to function overloading, two classes in the same file can have the same name.

ii) The default constructor makes an implicit call to super() as its first statement.

iii) The 5th value in an array has an index position of 4.

iv) The package which is included by all Java programs by default is java.util.

[4 marks]

A1. (b)

i) False. Function overloading is for functions within the same class, not for classes within the same file.

ii) True.

iii) True.

iv) False. The java.lang package is included by default.

Q1. (c) Explain the meaning of static modifier for a class variable. [2 marks]

A1. (c) The static modifier makes a variable belong to the class, and not specific to an object of the class. A static variable exists when a class is loaded, even if no objects of that class exist. The value of the variable is shared across all objects of the class, and can be accessed using the class name followed by the dot and then the name of the static variable.

Q1. (d) Write a prototype of a class Circle that is a child of a class Shape. [2 marks]

A1. (d) class Circle extends Shape { … }

Q2. (a) Explain with an example what you understand by polymorphism. [4 marks]

A2. (a) Polymorphism means “many forms”. In Java, polymorphism means the ability to decide which method should be used, when we have multiple methods of the same name.

There are two types of polymorphism: compile-time polymorphism and run-time polymorphism.

Compile-time polymorphism is the same as the overloading of methods. Based on the signature (parameter list), the compiler will decide which method needs to be called.

The real power of polymorphism comes when we use “run-time polymorphism”. Here, the compiler does not decide which method gets called. Rather, at run-time, when the program is being executed, the Java interpreter will decide which method needs to be called. Run-time polymorphism is also known as dynamic binding.

Consider the example below:

abstract class Animal
{
    abstract void talk();
}
class Dog extends Animal
{
    void talk()
    {
        System.out.println("Woof!");
    }
}
class Cat extends Animal
{
    void talk()
    {
        System.out.println("Meow");
    }
}
class Test
{
    public static void main(String[] args)
    {
        Animal[] animals = new Animal[2];
        animals[0] = new Cat();
        animals[1] = new Dog();
        for(int i=0; i<animals.length; i++)
          animals[i].talk();
    }
}

At runtime, for animals[0].talk() the Cat class’ talk() method will be executed, and for animals[1].talk() the Dog class’ talk() method will get executed.

Q2. (b) Explain the importance of break inside a switch..case construct. [2 marks]

A2. (b) The break inside a switch is to prevent execution of the code belonging to the next following case from execution. The switch statement works such that once a matching case is found, all the code below that executes, until a break statement occurs, even if that code is part of a subsequent case.

Q2. (c) What do you mean by the statement: A Java String is immutable. [2 marks]

A2. (c) This means that a Java String object, once created, cannot be modified. For example, if String s = “Morning”, then, if we change to s = “Good ” + s, this will create a new String object with a value of “Good Morning”, the original one is not extended or modified.

Q2. (d) Why is a binary search more efficient that a linear search for large, sorted data sets? [2 marks]

A2. (d) Binary search starts at the central value and keeps dividing the range by half with each search. This means that the maximum number of searches before finding a result is log2N. As the data set size increases, the maximum number of searches increases in a logarithmic manner only, hence to hunt 1K values, we need 10 searches, but to hunt 1M values, we need only 20 searches, as against the linear search which can take upto N searches.

Q3. (a) What is the value of the following expressions?

i) 1 + 2 – 3 * 4 / 5

ii) 1 + 2 – 3 * (4 / 5)

[2 marks]

A3. (a)

i) 1

Explanation: 1 + 2 – 3 * 4 / 5 = 1 + 2 – 12 / 5 = 1 + 2  - 2 = 1

ii) 3

Explanation: 1 + 2 – 3 * (4 / 5) = 1 + 2 – 3 * 0 = 1 + 2 – 0 = 3

Q3. (b) What is the difference between && and || in Java? [2 marks]

A3. (b) The && operator represents logical AND operation and the || operator represents a logical OR operation.

Q3. (c) What is the difference between unary and binary operators? [2 marks]

A3. (c) A unary operator works on a single operand (e.g. x++) whereas a binary operator works on two operands (e.g. x+y)

Q3. (d) If Shape is the super class of classes Circle and Square, which of the following is true? If false, explain why:

i)

Shape s = new Circle();

ii)

Circle c = new Circle();
Shape s = c;

[2 marks]

A3. (d)

i) True – a child class can be assigned and held into a variable of the parent class.

ii) True – a reference to a child class can be reassigned to a reference to its parent class.

Q3. (e) Given that:

int[] x = new int[(int)(Math.random() * 10) + 1];

i) What is the value of x.length if Math.random() returns 0.51?

ii) What is the highest possible value that x.length can ever have?

[2 marks]

A3. (e)

i) 6

ii) 10

Q3. (f) What is the output of the following code snippet?

String s1 = "Competitive Swimming";
String s2 = "Train";
s1.replace( "Swimm", "Train" );
System.out.println( s1 );

[2 marks]

A3. (f) Competitive Swimming

Explanation: There is no change in the output. A string is immutable and hence cannot be changed. The String s1 remains the same, unless it is made to point to a different String object.

Q3. (g) What is the output of the following code snippet?

int i;
int seed = 2*(4/5);
for(i=1; i<=3; i+=2)
  seed += i;
System.out.println(seed);

[2 marks]

A3. (g) 4

Explanation: 2*(4/5) = 2*0 = 0. So, seed starts with 0. Increment is 2 in the loop. So, the loop executes with i=1 and i=3, giving a value of 4.

Q3. (h) What will the following function return if called using mystery(4)?

public static int mystery(int n)
{
    if( n==0 )
      return 0;
    else
      return n + mystery(n-1);
}

[2 marks]

A3. (h) 10

Explanation: mystery(4) = 4 + mystery(3) = 4 + 3 + mystery(2) = 7 + 2 + mystery(1) = 9 + 1 + mystery(0) = 10 + 0 = 10. This is a recursive function.

Q3. (i) What is the output of the following code snippet?

String sa = "South Africa vs New Zealand";
System.out.println( sa.lastIndexOf('A') );
System.out.println( sa.lastIndexOf('a') );
System.out.println( sa.substring(sa.indexOf('a')).indexOf('a') );
System.out.println( sa.substring(sa.indexOf('a')).indexOf('N') );

[4 marks]

A3. (i)

sample0203i

Q4. Write a menu driven program that asks the user to enter a decimal number and print its binary equivalent, or enter a binary number and print its decimal equivalent. [15 marks]

A4.

import java.util.*;
class Q4
{
    public static void main(String[] args)
    {
        char menuOption = ' '; // space
        do
        {
            menuOption = askMenuOption();
            switch(menuOption)
            {
                case 'B':
                  binary2Decimal();
                  break;
                case 'D':
                  decimal2Binary();
                  break;
                case 'X':
                  System.out.println("Exiting program. Thank you!");
                  break;
            }
        }while( menuOption != 'X' );
    }
    // ask menu option
    // if wrong option, ask again
    // return the option entered
    public static char askMenuOption()
    {
        char option = ' '; // space
        do
        {
          Scanner sc = new Scanner(System.in);
          System.out.print("Enter B: Binary to Decimal");
          System.out.print(", D: Decimal to Binary, X: Exit: ");
          option = sc.nextLine().toUpperCase().charAt(0);
          if( "BDX".indexOf(option) < 0 )
            System.out.println("Incorrect option. Try again...");
        }while( "BDX".indexOf(option) < 0 );
        return option;
    }

    // convert binary to decimal
    public static void binary2Decimal()
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a binary number: ");
        String binary = sc.nextLine().trim();
        int decimal = 0;
        int power = 0;
        int digit = 0;
        int i;
        double term;
        for(i=binary.length() - 1; i>=0; i--)
        {
            // extract the digit
            digit = Integer.parseInt(binary.substring(i, i+1));
            term = digit * Math.pow(2, power);
            decimal = decimal + (int)Math.round(term);
            power++; // for the next digit
        }
        System.out.println("Decimal: " + decimal);
    }
    // convert decimal to binary
    public static void decimal2Binary()
    {
        Scanner sc = new Scanner( System.in );
        System.out.print("Enter a decimal number: ");
        int decimal = sc.nextInt();
        String temp = sc.nextLine(); // for the trailing newline
        String binary = "";
        int remainder;
        while(decimal > 0)
        {
            remainder = decimal % 2;
            decimal = decimal / 2;
            binary = remainder + binary;
        }
        System.out.println("Binary: " + binary);
    }
}

Sample output:

sample0204

Q5. The cost of electricity for an elevator in an apartment is as follows:

Each time the elevator starts, an initial cost of Rs. 5 is incurred. For each floor the elevator moves up, the cost of electricity consumed is Rs. 2 per floor. For each floor the elevator moves down, the cost of electricity consumed is Rs. 1 per floor.

Write a program that asks the user to enter the floors of movement of the elevator starting from floor 0, until the elevator returns back to 0. Compute and print the cost of electricity consumed for the cycle of movement. [15 marks]

A5.

import java.util.*;
class Elevator
{
    int currentFloor;
    int cost;
    int nStarts, nFloorUps, nFloorDowns;
    String path; // path of elevator

    // constructor
    public Elevator()
    {
        currentFloor = 0;
        cost = 0;
        nStarts = 0;
        nFloorUps = 0;
        nFloorDowns = 0;
        path = "0";
    }

    // do one cycle of elevator movement
    public void cycle()
    {
        int previousFloor = currentFloor;
        int nextFloor;
        int floorGaps;
        do
        {
            // ask the next floor to go to
            do
            {
                nextFloor = askFloor();
                if( nextFloor == previousFloor )
                  System.out.println("Floor cannot be same as current floor. Try again...");
            }while(nextFloor == previousFloor);
            path += "-" + nextFloor;
            nStarts++;
            floorGaps = (int)Math.abs(nextFloor - previousFloor);
            if(nextFloor > previousFloor)
              nFloorUps += floorGaps;
            else
              nFloorDowns += floorGaps;
            previousFloor = nextFloor;
            currentFloor = previousFloor;
        }while( currentFloor != 0 ); // stop when 0 is reached
    }

    // ask floor number to go to
    public static int askFloor()
    {
        Scanner sc = new Scanner( System.in );
        System.out.print("Enter the floor number: ");
        int floorNo = sc.nextInt();
        String temp = sc.nextLine(); // for the trailing newline
        return floorNo;
    }

    // compute and print the cost
    public void computeCost()
    {
        cost += (nStarts * 5) + (nFloorUps * 2) + (nFloorDowns * 1);
        System.out.println("Elevator path                 : " + path);
        System.out.println("No of starts                  : " + nStarts);
        System.out.println("No of upward floor movements  : " + nFloorUps);
        System.out.println("No of downward floor movements: " + nFloorDowns);        
        System.out.println("Total cost of electricity Rs. : " + cost);
    }

    // entry point main method
    public static void main(String[] args)
    {
        Elevator e = new Elevator();
        e.cycle();
        e.computeCost();
    }
}

Sample output:

sample0205

Q6. Write a program that asks the user to keep on entering integers, until the user enters a 0. Sort the list and print in ascending order. Also print the minimum, maximum, and average values. [15 marks]

A6.

import java.util.*;
class Q6
{
    public static void main(String[] args)
    {
        // user input
        Scanner sc = new Scanner( System.in );
        String numbers = "";
        int count = 0;
        int n = 0, i, j;
        String temp;
        do
        {
            System.out.print("Enter an integer (0 to quit): ");
            n = sc.nextInt();
            temp = sc.nextLine(); // for the trailine newline
            if( n != 0 )
            {
                count++;
                if(count > 1)
                  numbers += " "; // space delimiter
                numbers += n; // add number to the end
            }
        }while( n!= 0); // exit when 0

        // create the int array and populate
        int[] arr = new int[count];
        int sum=0;
        i = 0;
        StringTokenizer st = new StringTokenizer(numbers);
        while(st.hasMoreTokens())
        {
            arr[i] = Integer.parseInt(st.nextToken());
            sum += arr[i];
            i++;
        }

        // sort the array using bubble sort
        int t; // used as temporary swapping variable
        for(i=0; i<arr.length-1; i++)
        {
            for(j=0; j<arr.length-1-i; j++)
            {
                if( arr[j] > arr[j+1] )
                {
                    // swap
                    t = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = t;
                }
            }
        }

        // print the sorted array
        System.out.print("Sorted array: ");
        for(i=0; i<arr.length; i++)
        {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
        // print min, max, average
        System.out.println("Minimum: " + arr[0]);
        System.out.println("Maximum: " + arr[arr.length-1]);        
        System.out.println("Average: " + ((double)sum) / (double)arr.length);
    }
}

Sample output:

sample0206

Q7. Define a class Shape as abstract, having an abstract method area() which has a double return type. Define two classes Rectangle and Circle that are child classes of the Shape class and which have their implementation of the area() method. The Rectangle class and Circle class should have length/breadth and radius as parameters for their respective constructors. Write a program that asks the user to enter how many shapes (an integer N), create a Shape array of size N. The user should then be asked to specify the type of the shape (Rectangle/Circle), and create an object of that type, and assign it to the Shape array variable created. At the end, print the area of each of the N shapes. [15 marks]

A7.

import java.util.*;
public class Q7
{
    public static void main(String[] args)
    {
        // user input
        Scanner sc = new Scanner(System.in);
        String temp;
        System.out.print("Enter number of shapes (N): ");
        int N = sc.nextInt();
        temp = sc.nextLine();

        // create the Shape array
        Shape[] shapes = new Shape[N];
        // populate the shapes
        int i;
        char shapeType;
        for(i=0; i<shapes.length; )
        {
            System.out.print("Enter R for Rectangle, C for Circle: ");
            shapeType = sc.nextLine().toUpperCase().charAt(0);
            switch( shapeType )
            {
                case 'R':
                  double l = askDouble("Enter length: ");
                  double b = askDouble("Enter breadth: ");
                  Rectangle rect = new Rectangle(l, b);
                  shapes[i] = rect;
                  i++;
                  break;
                case 'C':
                  double r = askDouble("Enter radius: ");
                  Circle circ = new Circle(r);
                  shapes[i] = circ;
                  i++;
                  break;
                default:
                  System.out.println("Incorrect option. Try again...");
                  break;
            }
        }

        // print the areas
        for(i=0; i<shapes.length; i++)
        {
            double area = shapes[i].area();
            System.out.println( area );
        }
    }
    // prompt user, ask to enter a double value
    // return the value entered
    public static double askDouble(String prompt)
    {
        Scanner sc = new Scanner( System.in );
        System.out.print(prompt);
        double d = sc.nextDouble();
        String temp = sc.nextLine(); // for the trailing newline
        return d;
    }
}
abstract class Shape
{
    abstract public double area();

}
class Circle extends Shape
{
    double radius;
    // constructor
    public Circle(double radius)
    {
        this.radius = radius;
    }
    // area
    public double area()
    {
        return Math.PI * Math.pow(this.radius, 2);
    }
}
class Rectangle extends Shape
{
    double length, breadth;
    // constructor
    public Rectangle(double length, double breadth)
    {
        this.length = length;
        this.breadth = breadth;
    }
    // area
    public double area()
    {
        return this.length * this.breadth;
    }
}

Sample output:

sample0207

Q8 Write a program that asks the user to enter a double value (x) and an integer value (N). Compute and print the sum of the following series:

x + x2/2! + x3/3! + … + xn/n!

[15 marks]

A8.

import java.util.*;
class Q8
{
    public static void main(String[] args)
    {
        // user input
        Scanner sc = new Scanner( System.in );
        System.out.print("Enter x and n: ");
        double x = sc.nextDouble();
        int N = sc.nextInt();
        String temp = sc.nextLine(); // for the trailing newline

        // compute the terms and the sum
        double nr, dr, term, sum=0;
        int i;
        for(i=1; i<=N; i++)
        {
            nr = Math.pow(x, i);
            dr = fact(i);
            term = nr/dr;
            sum += term;
        }

        // print the sum
        System.out.println("Sum: " + sum);
    }

    // return the factorial of the parameter passed
    public static int fact(int n)
    {
        int answer = 1;
        for(int i=2; i<=n; i++)
          answer *= i;
        return answer;
    }
}

Sample output:

sample0208

Q9. Due to rain, a cricket match is washed out. The organizers decide to play a game of chance (on the computer), of one super over. Each over has 6 deliveries, each delivery can have either 0,1, 2, 3, 4 or 6, using a random number generation logic. If a 5 occurs, it is a no-ball, and a single run results, plus an extra-delivery is to be considered. The two teams have to go through the super over each, and the team with the maximum score is the winner. Write a program that shows the super over, ball by ball, of each team, prints the team total, and declares either team 1 or team 2 as the winner. [15 marks]

A9.

class Q9
{
    public static void main(String[] args)
    {
        SuperOver team1 = new SuperOver("India");
        SuperOver team2 = new SuperOver("Australia");
        team1.playOneOver();
        team2.playOneOver();
        if( team1.score > team2.score )
          System.out.println( team1.teamName + " wins!");
        else if( team1.score < team2.score )
          System.out.println( team2.teamName + " wins!");
        else
          System.out.println( "Match is a tie!" );
    }
}
class SuperOver
{
    // instance variable
    int score;
    String teamName;
    // constructor
    public SuperOver(String teamName)
    {
        this.teamName = teamName;
        this.score = 0;
    }
    // play one over, compute the score
    public void playOneOver()
    {
        System.out.print(teamName + ": ");
        int i;
        int runs;
        boolean isNoBall;
        for(i=1; i<=6;)
        {
            isNoBall = false;
            runs = (int)(Math.random() * 7); // 0 to 6
            if(runs == 5) // noball
            {
                runs=1;
                isNoBall=true;
            }
            System.out.print(runs);
            if(isNoBall)
              System.out.print("nb");
            System.out.print(" "); // space
            score += runs; // add to team score
            if(!isNoBall)
              i++;
        }
        System.out.println("= " + score);
    }
}

Sample output:

sample0209

8 thoughts on “ICSE 2014 Sample Paper 2

  1. Dear Sir,
    The Super Over question is faaaantastic!!!!!I simply loved it.
    Regards,
    Vansh sodhi.

  2. I think there should be a separate link for the solutions. I was actually searching for a sample paper which wasn’t solved.

    1. Dear Vaishnavi Pamulapati
      Thanks for the feedback. I will take this into consideration when I come up with the newer version of this website in a few months.

      regards
      Ajay Pherwani

  3. Sir, i could not understand Q3 (i) and i have my Computer Boards exam in less than 24 Hours so if you could please reply ASAP.

    PS – This is the best computer applications website and has helped me alot. Thanks :)

    1. Dear Priyam (Q3(i))
      String sa = “South Africa vs New Zealand”;
      System.out.println( sa.lastIndexOf(‘A’) );
      System.out.println( sa.lastIndexOf(‘a’) );
      System.out.println( sa.substring(sa.indexOf(‘a’)).indexOf(‘a’) );
      System.out.println( sa.substring(sa.indexOf(‘a’)).indexOf(‘N’) );
      Answer:
      First one is 6, since the last index of uppercase ‘A’ is 6th from the left, starting with 0.
      Second one is 24, since the last index of lowercase ‘a’ is the third last occurence
      Third one, sa.indexOf(‘a’) returns an int of the first ‘a’. This is inside sa.substring() which will return a String from the first ‘a’ position now. On this String, indexOf(‘a’) will return the first ‘a’, which is the starting position of the String, and hence the answer is 0.
      In the fourth answer, the indexOf(‘a’) and the substring around it returns a String “a vs New Zealand”. Within this, indexOf(‘N’) will return the first ‘N’ which is at position 5, and hence answer is 5.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>