Saturday, August 1, 2020

2014 ICSE Computer Application Paper and Solutions




SECTION A (40 Marks)
Answer all questions from this Section

Question 1.

(a) Which of the following are valid comments? [2]
(i) /* comment */
(ii) /*comment
(iii) //comment
(iv) */ comment */

Ans. (i) and (iii) are valid comments. (i) is a multi line comment and (iii) is a single line comment.

(b) What is meant by a package? Name any two Java Application Programming Interface packages. [2]
Ans. Related classes are grouped together as a package. A package provides namespace management and access protection.
Some of the Java API packages – java.lang, java,util and java,io

(c) Name the primitive data type in Java that is:
(i) a 64-bit integer and is used when you need a range of values wider than those provided by int.
(ii) a single 16-bit Unicode character whose default value is ‘\u0000′ [2]
Ans. (i) long
(ii) char

(d) State one difference between floating point literals float and double. [2]
Ans. (i) Float requires 4 bytes of storage while double requires 8 bytes.
(ii) Float is of single precision while double is of double precision.

(e) Find the errors in the given program segment and re-write the statements correctly to assign values to an integer array. [2]

1
int a = new int( 5 );
2
for( int i=0; i<=5; i++ ) a[i]=i;
Ans. The corrected program segment is

1
int a = new int[5];
2
for( int i=0; i<=4; i++ ) a[i]=i;
Error 1: The size of an array is specified using square brackets [] and not parentheses ().
Error 2: Since the array is of length 5, the indices range from 0 to 4. The loop variable i is used as an index to the array and in the given program segment, it takes values from 0 to 5. a[4] would result in an ArrayIndexOutOfBoundsException. Therefore, the loop condition should be changed to i<=4. The given program segment creates an array of size 5 and stores numbers from 0 to 4 in the array.

Question 2.

(a) Operators with higher precedence are evaluated before operators with relatively lower precedence. Arrange the operators given below in order of higher precedence to lower precedence. [2] (i) && (ii) % (iii) >= (iv) ++
Ans. ++ , % , >= , &&

(b) Identify the statements listed below as assignment, increment, method invocation or object creation statements. [2]
(i) System.out.println(“Java”);
(ii) costPrice = 457.50;
(iii) Car hybrid = new Car();
(iv) petrolPrice++;
Ans. (i) Method Invocation – println() is a method of System.out.
(ii) Assignment – The value 457.70 is being assigned to the variable costPrice.
(iii) Object Creation – An object of type Car is created and stored in the variable hybrid.
(iv) Increment – The variable petrolPrice is incremented.

(c) Give two differences between switch statement and if-else statement. [2]
Ans. (i) Switch statement can be used to test only for equality of a particular variable with a given set of values while an if-else statement can be used for testing arbitrary boolean expressions.
(ii) If else can handle only primitive types and String while if-else can handle all data types.

(d) What is an infinite loop? Write an infinite loop statement. [2]
Ans. An infinite loop is a loop whose body executes continuously.

Infinite Loop using while:

1
while(true) {
2
}
Infinite Loop using for

1
for( ; ;){
2
}
Infinite loop using do-while

1
do {
2
} while(true);
(e) What is a constructor? When is it invoked? [2]
Ans. A constructor is a member function of a class used to perform initialization of the object. It is invoked during object creation.

Question 3.

(a) List the variables from those given below that are composite data types. [2]
(i) static int x;
(ii) arr[i] = 10;
(iii) obj.display();
(iv) boolean b;
(v) private char chr;
(vi) String str;
Ans. The primitive data types in Java are byte, short, int, long, float, double, boolean and char. All other data types – arrays, objects and interfaces – are composite data types.
(i) x is of a primitive data type
(ii) arr is variable of a composite data type of type int. i can be a variable of a primitive data type (byte, short or int) or of a composite data type (Byte, Short, Integer)
(iii) obj is a variable of a composite data type
(iv) b is a variable of a primitive data type
(v) chr is a variable of a primitive data type
(vi) str is a variable of a composite data type – String which is of class type

(b) State the output of the following program segment: [2]

1
String str1 = "great"; String str2 = "minds";
2
System.out.println(strl.substring(0,2).concat(str2.substring(l)));
3
System.out.println(("WH" + (strl.substring(2).toUpperCase())));
Ans. Output is

1
grinds
2
WHEAT
Explanation for first print statement:
strl.substring(0,2) gives “gr”
str2.substring(l) “inds”
The two on concatenation gives “grinds”
Explanation for second print statement
strl.substring(2) gives “eat”
“eat” on conversion to upper case using the function toUpperCase() results in EAT
“WH” on concatenation with “EAT” using + gives “WHEAT”

(c) What are the final values stored in variables x and y below? [2]


double a = - 6.35;

double b = 14.74;

double x = Math.abs(Math.ceil(a));

double y = Math.rint(Math.max(a,b));
Ans. Math.ceil() gives the smallest of all those integers that are greater than the input. So, Math.ceil(-6.35) gives -6.0 (not -6 as ceil returns a double value). Math.abs() gives the absolute value of the number i.e. removes negative sign, if present. So, Math.abs(-6.0) results in 6.0. So, x will be 6.0.

Math.max(-6.35, 14.74) returns 14.74. rint() returns the double value which is closest in value to the argument passed and is equal to an integer. So, Math.rint(14.74) returns 15.0. So, y will hold 15.0.

(d) Rewrite the following program segment using the if-else statements instead of the ternary operator. [2]

1
String grade = (mark >= 90) ? "A" : (mark >= 80) ? "B" : "C";
Ans.


String grade;

if(marks >= 90) {

grade = "A";

} else if( marks >= 80 ) {

grade = "B";

} else {

grade = "C";

}
(e) Give output of the following method: [2]


public static void main(String[] args) {

int a = 5;

a++;

System.out.println(a);

a -= (a--) - (--a);

System.out.println(a); }
Ans.

1
6
2
4
a++ increments a from 5 to 6. The first print statement prints the value of a which is 6.
a -= (a–) – (–a);
is equivalent to
a = a – ( (a–) – (–a) )
a = 6 – ( 6 – 4 )
a = 6 – 2
a = 4

(f) What is the data type returned by the library functions: [2]
(i) compareTo()
(ii) equals()
Ans. (i) int
(ii) boolean

(g) State the value of characteristic and mantissa when the following code is executed. [2]


String s = "4.3756";

int n = s.indexOf('.');

int characteristic = Integer.parseInt(s.substring(0,n));

int mantissa = Integer.valueOf(s.substring(n+1));
Ans. n = 1
characteristic = Integer.parseInt(s.substring(0,n)) = Integer.parseInt(“4.3756″.substring(0,1)) = Integer.parseInt(“4″) = 4
characteristic = 4
mantissa = Integer.valueOf(“4.3756″.substring(1+1)) = Integer.valueOf(“3756″) = 3756
mantissa = 3756

(h) Study the method and answer the given questions. [2]


public void sampleMethod()

{ for( int i=0; i<3 i="" p="">
{ for( int j=0; j<2 j="" p="">
{ int number = (int)(Math.random() * 10);

System.out.println(number); } } }
(i) How many times does the loop execute?
(ii) What is the range of possible values stored in the variable number?
Ans. (i) The outer loop executes 3 times ( i= 0, 1, 2) and for each execution of the outer loop, the inner loop executes two times ( j= 0, 1). So, the inner loop executes 3 * 2 = 6 times
(ii) Math.random() returns a value between 0 (inclusive) and 1 (exclusive).
Math.random() * 10 will be in the range 0 (inclusive) and 10 (exclusive)
(int)(Math.random() * 10) will be in the range 0 (inclusive) and 9 (inclusive) (only integer values)

(i) Consider the following class: [2]


public class myClass {

public static int x = 3, y = 4;

public int a = 2, b = 3; }
(i) Name the variables for which each object of the class will have its own distinct copy.
(ii) Name the variables that are common to all objects of the class.
Ans. For static variables, all objects share a common copy while for non static variable, each object gets its own copy. Therefore, the answer is
(i) a, b
(ii) x, y

(j) What will be the output when the following code segments are executed? [2]
(i)


String s = "1001";

int x = Integer.valueOf(s);

double y = Double.valueOf(s);

System.out.println("x=" +x);

System.out.println("y=" +y);
(ii)


System.out.println("The King said \"Begin at the beginning!\" to me.");
Ans. (i) s = “1001″
x = 1001
y = 1001.0
Output will be


x=1001

y=1001.0
(ii) The King said “Begin at the beginning!” to me.
\” is an escape sequence which prints ”

SECTION B (60 Marks)
Attempt any four questions from this Section.

Question 4.
Define a class named movieMagic with the following description:
Instance variables/data members:
int year – to store the year of release of a movie
String title – to store the title of the movie.
float rating – to store the popularity rating of the movie.
(minimum rating = 0.0 and maximum rating = 5.0)

Member Methods:
(i) movieMagic() Default constructor to initialize numeric data members to 0 and String data member to “”.
(ii) void accept() To input and store year, title and rating.
(iii) void display() To display the title of a movie and a message based on the rating as per the table below.

RATING MESSAGE TO BE DISPLAYED
0.0 to 2.0 Flop
2.1 to 3.4 Semi-hit
3.5 to 4.5 Hit
4.6 to 5.0 Super Hit
Write a main method to create an object of the class and call the above member methods.

Ans.
Program


import java.util.Scanner;


public class movieMagic {

    int year;

    String title;

    float rating;



    public movieMagic() {

        year = 0;

        title = "";

        rating = 0;

    }



    public void accept() {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter title: ");

        title = scanner.nextLine();

        System.out.print("Enter year: ");

        year = scanner.nextInt();

        System.out.print("Enter rating: ");

        rating = scanner.nextFloat();

    }



    public void display() {

        System.out.println("Movie Title - " + title);

        if (rating >= 0 && rating <= 2.0) {

             System.out.println("Flop");

         } else if (rating >= 2.1 && rating <= 3.4) {

             System.out.println("Semi-hit");

         } else if (rating >= 3.5 && rating <= 4.5) {

             System.out.println("Hit");

         } else if (rating >= 4.6 && rating <= 5.0) {

            System.out.println("Super Hit");

        }

    }



    public static void main(String[] args) {

        movieMagic movie = new movieMagic();

        movie.accept();

        movie.display();

    }



}
Sample Output


Enter title: Raja Rani

Enter year: 2012

Enter rating: 5.0

Movie Title - Raja Rani

Super Hit
Question 5.

A special two-digit number is such that when the sum of its digits is added to the product of its digits, the result is equal to the original two-digit number.

Example: Consider the number 59.
Sum of digits = 5 + 9 = 14
Product of its digits = 5 x 9 = 45
Sum of the sum of digits and product of digits= 14 + 45 = 59

Write a program to accept a two-digit number. Add the sum of its digits to the product of its digits. If the value is equal to the number input, output the message “Special 2-digit number” otherwise, output the message “Not a Special 2-digit number”.

Ans. We create a Scanner object and accept the input number using nextInt() method. The input is stored in the variable ‘number’. It is given in the question that the input will be a two digit number. We need to extract the two digits of the number into two variables ‘leftDigit’ and ‘rightDigit’. The left digit can be extracted by dividing the number by 10. (Note that ‘number’ is an int and the divisor 10 is an int. So, the result will be an int and not a float i.e. we obtain only the quotient as the result). The right digit can be obtained by calculating the remainder when ‘number’ is divided by 10.

Let us take an example input – number = 59.
Then, leftDigit = number / 10 = 59 / 10 = 5
rightDigit = number % 10 = 59 % 10 = 9

Once, we have the two numbers, calculating the sum and product of the digits is easy.


int sumOfDigits = rightDigit + leftDigit;

int productOfDigits = rightDigit * leftDigit;
Next, we add the two variables above and store it in a new variable.


int sumOfProductAndSum = sumOfDigits + productOfDigits;
Finally, we use if else decision statements to check if the sum of product of digits and sum of digits is same as the input number and print an appropriate message.

Program


import java.util.Scanner;



public class SpecialNumber {



    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter number: ");

        int number = scanner.nextInt();

        int rightDigit = number % 10;

        int leftDigit = number / 10;

        int sumOfDigits = rightDigit + leftDigit;

        int productOfDigits = rightDigit * leftDigit;

        int sumOfProductAndSum = sumOfDigits + productOfDigits;

        if (sumOfProductAndSum == number) {

            System.out.println("Special 2-digit number");

        } else {

            System.out.println("Not a Special 2-digit number");

        }

    }

}
Sample Outputs


Enter number: 59

Special 2-digit number

Enter number: 34

Not a Special 2-digit number

Question 6.
Write a program to assign a full path and file name as given below. Using library functions, extract and output the file path, file name and file extension separately as shown.

Input C:\Users\admin\Pictures\flower.jpg
Output Path: C:\Users\admin\Pictures\
File name: flower
Extension: jpg

Ans. We need to use the methods of the String class like indexOf(), lastIndexOf() and substring() to solve this problem.

The input String can be divided into three parts, the path, file name and extension. These three parts are separated by a backslash character and a dot as shown in the figure below.

file

So, first we need to find the indices of the backslash character and dot which separate these regions. Note that there are several backslash characters in the input but the backslash character which separates the file path from the name is the last backslash character in the String. So, we need to use the lastIndexOf() method to find the index of this backslash character. Even though in the example input, there is only one dot, folder names and file names can contain multiple dots. So, for finding the index of the dot which separates the file name and extension also, we use lastIndexOf() method. Moreover, the backslash character is written as ‘\\’ and not ‘\’ as \ is an escape character.


int indexOfLastBackslash = input.lastIndexOf('\\');

int indexOfDot = input.lastIndexOf('.');
Once, we have the indices of the backslash character and dot, we can use the substring method to extract the three parts. Substring() method takes two integer arguments – begin and end; and returns the substring formed by the characters between begin (inclusive) and end (exclusive).


String outputPath = input.substring(0, indexOfLastBackslash + 1);

String fileName = input.substring(indexOfLastBackslash + 1, indexOfDot);

String extension = input.substring(indexOfDot + 1);
Program


import java.util.Scanner;



public class FileName {



    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter file name and path: ");

        String input = scanner.nextLine();

        int indexOfLastBackslash = input.lastIndexOf('\\');

        int indexOfDot = input.lastIndexOf('.');

        String outputPath = input.substring(0, indexOfLastBackslash + 1);

        String fileName = input.substring(indexOfLastBackslash + 1, indexOfDot);

        String extension = input.substring(indexOfDot + 1);

        System.out.println("Path: " + outputPath);

        System.out.println("File Name: " + fileName);

        System.out.println("Extension: " + extension);

    }

}
Sample Output


Enter file name and path: C:\Users\admin\Pictures\flower.jpg

Path: C:\Users\admin\Pictures\

File Name: flower

Extension: jpg

Question 7.
Design a class to overload a function area() as follows:
(i) double area(double a. double b, double e) with three double arguments, returns the
area of a scalene triangle using the formula:
triangle formula 1
where
triangle formula 2
(ii) double area(int a, int b, int height) with three integer arguments, returns the area of a trapezium using the formula:
trapezium formula
(iii) double area(double diagonal1, double diagonal2) with two double arguments, returns
the area of a rhombus using the formula:
rhombus formula
Ans.


public class Area {

    public double area(double a, double b, double c) {

        double s = (a + b + c) / 2;

        double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));

        return area;

    }

    public double area(int a, int b, int height) {

        double area = 0.5 * height * (a + b);

        return area;

    }

    public double area(double diagonal1, double diagonal2) {

        double area = 0.5 * (diagonal1 * diagonal2);

        return area;

}
}
Question 8.
Using the switch statement. write a menu driven program to calculate the maturity amount of a Bank Deposit.

The user is given the following options:
(i) Term Deposit
(ii) Recurring Deposit

For option (i) accept principal(P), rare of ¡interest(r) and time period in years(n). Calculate and output the maturity amount(A) receivable using the formula
term deposit formula
For option (ii) accept Monthly Installment (P), rate of interest(r) and time period in months (n). Calculate and output the maturity amount(A) receivable using the formula
recurring deposit formula
For an incorrect option, an appropriate error message should be displayed.

Ans.


import java.util.Scanner;

public class Interest {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Menu");

        System.out.println("1. Term Deposit");

        System.out.println("2. Recurring Deposit");

        System.out.print("Enter your choice: ");

        int choice = scanner.nextInt();

        switch (choice) {

            case 1:

                System.out.print("Enter principal: ");

                int P1 = scanner.nextInt();

                System.out.print("Enter rate of interest: ");

                int r1 = scanner.nextInt();

                System.out.print("Enter period in years: ");

                int n1 = scanner.nextInt();

                double maturityAmount1 = P1 * Math.pow(1 + r1 / 100.0, n1);

                System.out.println("Maturity Amount is " + maturityAmount1);

                break;

            case 2:

                System.out.print("Enter monthly installment: ");

                int P2 = scanner.nextInt();

                System.out.print("Enter rate of interest: ");

                int r2 = scanner.nextInt();

                System.out.print("Enter period in months: ");

                int n2 = scanner.nextInt();

                double maturityAmount2 = P2 * n2 + P2 * (n2 * (n2 + 1) / 2.0) * (r2 / 100.0) * (1.0 / 12);

                System.out.println("Maturity Amount is " + maturityAmount2);

                break;

            default:

                System.out.println("Invalid choice");

        }

    }

}
Sample Outputs


Menu

1. Term Deposit

2. Recurring Deposit

Enter your choice: 1

Enter principal: 1500

Enter rate of interest: 3

Enter period in years: 5

Maturity Amount is 1738.9111114500001

Menu

1. Term Deposit

2. Recurring Deposit

Enter your choice: 2

Enter monthly installment: 300

Enter rate of interest: 1

Enter period in months: 24

Maturity Amount is 7275.0

Menu

1. Term Deposit

2. Recurring Deposit

Enter your choice: 3

Invalid choice
Question 9.
Write a program to accept the year of graduation from school as an integer value from the user. Using the Binary Search technique on the sorted array of integers given below, output the message ‘Record exists’ if the value input is located in the array. If not, output the message Record does not exist”.
(1982, 1987, 1993. 1996, 1999, 2003, 2006, 2007, 2009, 2010)

Ans.


import java.util.Scanner;

public class Search {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter year of graduation: ");

        int graduationYear = scanner.nextInt();

        int[] years = {1982, 1987, 1993, 1996, 1999, 2003, 2006, 2007, 2009, 2010};

        boolean found = false;

        int left = 0;

        int right = years.length - 1;

        while (left <= right) {

            int middle = (left + right) / 2;

            if (years[middle] == graduationYear) {

                found = true;

                break;

            } else if (years[middle] < graduationYear) {

                left = middle + 1;

            } else {

                right = middle - 1;

            }

        }

        if (found) {

            System.out.println("Record exists");

        } else {

            System.out.println("Record does not exist");

        }

    }

}
Sample Outputs


Enter year of graduation: 2007

Record exists

Enter year of graduation: 1900

Record does not exist


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner