Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Youtube
Hide Buttons
Menu

We are apologize for the inconvenience but you need to download
more modern browser in order to be able to browse our page

Download Safari
Download Safari
Download Chrome
Download Chrome
Download Firefox
Download Firefox
Download IE 10+
Download IE 10+

2013

ICSE Computer – 2013
Q1. (a) What is meant by precedence of operators? [2 marks]
A1. (a) Precedence of operators defines the order in which the operators within an expression are executed. The order of evaluation can be modified with the help of parenthesis ( and ). For example, in the expression x = a+b*c the RHS evaluates using a+(b*c) since the * operator has a higher precedence as compared to the + operator. As another example, in the equaion x = a+b > c ? a : b, the + operator has higher precedence over the ternary operator ?: and hence the RHS evaluates to (a+b) > c ? a : b.
Q1. (b) What is a literal? [2 marks]
A1. (b) A literal is a notation for representing a fixed value in source code. It is a value that is directly represented in code. For example, in the expression “int x = 4;”, the 4 is a literal. As another example, in the example: String s = “Hello”; the “Hello” is a literal.
Q1. (c) State the Java concept that is implemented through:
i) A superclass and a subclass
ii) the act of representing essential features without including background details
[2 marks]
A1. (c)
i) Inheritance
ii) Abstraction
Q1. (d) Give a difference between constructor and a method. [2 marks]
A1. (d) A constructor has the same name as the class; the name of the method is not the same as that of the class.
A constructor does not have a return type; every method must specify a return type, and if none exists, the type void must be specified.
The calls super() and this() can be used inside a constructor, but not inside a method.
Q1. (e) What are the types of casting shown by the following examples?
i)
double x = 15.2;
int y = (int)x;
ii)
int x = 12;
long y = x;
[2 marks]
A1. (e)
i) Explicit typecast
ii) Implicit typecast
Q2. (a) Name any two wrapper classes. [2 marks]
A2. (a) Integer, Double
Q2. (b) What is the difference between break and continue statements when they occur in a loop? [2 marks]
A2. (b) The break statement stops the execution of the current loop iteration and transfers control to the statement outside the loop. The continue statement stops the execution of the current loop iteration and transfers control to the end of the loop body, for the next iteration to proceed.
Q2. (c) Write statements to show how finding the length of a character array named ch differs from finding the length of a String object str. [2 marks]
A2. (c) Length of a character array: ch.length
Length of a String array: str.length()
Example statements:
System.out.println(“Char array: ” + ch.length);
System.out.println(“String array: ” + str.length());
Q2. (d) Name the Java keyword that:
i) indicates a method has no return type
ii) Stores the address of the currently calling object
[2 marks]
A2. (d)
i) void
ii) this [Note to students: The this keyword is actually a reference to the current object, and hence it contains the address of where that object is stored. This is a tricky question, and the answer is “this”.]
Q2. (e) What is an exception? [2 marks]
A2. (e) An exception is the occurrence of something that should not normally happen. A Java method will throw an exception if it encounters a situation which it cannot handle. When an exception occurs, an object is created that contains details of the problem (exception). This object is created automatically by Java.
Some exceptions, like a divide by zero, can be avoided through careful programming.
Other exceptions, such as hard disk full, or network connection lost, cannot be avoided and nor can they be predicted.
Dealing with exceptions is known as handling the exception.
There are two types of exceptions: checked exceptions and unchecked exceptions.
Unchecked exceptions are those that do not have to be addressed (handled) by the Java program. This includes division by zero, array index out of bounds, etc. Unchecked exceptions are normally the result of bad programming (programmer bugs).
Checked exceptions are those that must be handled by the Java program. These include hard disk is full, file not found, unable to connect to database, and so on.
Q3. (a) Write Java statement to create an object mp4 of class digital. [2 marks]
A3. (a) digital mp4 = new digital();
Q3. (b) State the values stored in variables str1 and str2
String s1 = “good”; String s2 = “world matters”;
String str1 = s2.substring(5).replace(‘t’,’n’);
String str2 = s1.concat(str1);
[2 marks]
A3. (b)
str1 = ” manners” (this is a space followed by manners)
str2 = “good manners”
Q3. (c) What does a class encapsulate? [2 marks]
A3. (c) A class encapsulates the implementation details of that class. This includes the methods and the variables that are needed for the functionality of that class. Only the functionality that needs to be exposed, is exposed. The functionality that is not exposed is normally “private” to that class. Private variables can be exposed using getter (accessor) and setter (mutator) methods.
Q3. (d) Rewrite the following program segment using the if..else statement.
comm = (sale>15000)?sale*5/100:0;
[2 marks]
A3. (d)
if(sale > 15000)
comm = sale * 5 / 100;
else
comm = 0;
Q3. (e) How many times will the following loop execute? What value will be returned?
int x = 2, y = 50;
do{
++x;
y-=x++;
}while(x<=10);
return y;
[2 marks]
A3. (e)
The loop will execute 5 times. The value returned will be 15.
Explanation: x increased by 2 each iteration. It starts with 2, then 4, 6, 8, 10. So, totally it executes 5 times. The amount by which y reduces each iteration is 3, 5, 7, 9, 11, hence the value of y returned is 50-3-5-7-9-11=15.
Q3. (f) What is the data type that the following library functions return?
i) isWhitespace(char ch)
ii) Math.random()
[2 marks]
A3. (f)
i) boolean
ii) double
Q3. (g) Write a Java expression for ut + ½ ft2 [2 marks]
A3. (g)
u*t + 1.0 / 2.0 * f * t * t
Note to students: u*t + 1/2*f*t*t cannot be used, since 1/2 will give an integer of 0. Hence we use 1.0 / 2.0 instead.
Q3. (h) If int[] n = {1, 2, 3, 5, 7, 9, 13, 16} what are the values of x and y?
x=Math.pow(n[4],n[2]);
y=Math.sqrt(n[5]+n[7]);
[2 marks]
A3. (h)
x is 343.0 and y is 5.0
Q3. (i) What is the final value of ctr after the iteration process given below, executes?
int ctr = 0;
for(int i=1;i<=5;i++)
for(int j=1;j<=5;j+=2)
++ctr;
[2 marks]
A3. (i) 15
Explanation: The inner loop executes 3 times for each of the 5 iterations of the outer loop.
Q3. (j) Name the methods of the Scanner class that:
i) Is used to input an integer from standard input stream
ii) Is used to input a string data from standard input stream
[2 marks]
A3. (j)
i) nextInt()
ii) next() and nextLine()
Q4. Define a class called FruitJuice with the following description:
Instance variables/data members:
int product_code – stores the product code number
String flavour – stores the flavor of the juice. (orangle, apple, etc.)
String pack_type – stores the type of packaging (tetra-pack, bottle, etc.)
int pack_size – stores package size (200ml, 400ml, etc.)
int product_price – stores the price of the product
Member methods:
FruitJuice() – default constructor to initialize integer data members to zero and string data members to “”
void input() – to input and store the product code, flavor, pack type, pack size and product price
void discount() – to reduce the product price by 10
void display() – to display the product code, flavor, pack type, pack size and product price
[15 marks]
A4.
import java.util.*;
class FruitJuice
{
// instance variables / data members
int product_code;
String flavour;
String pack_type;
int pack_size, product_price;


// zero-argument constructor
public FruitJuice()
{
product_code = 0;
flavour = “”;
pack_type = “”;
pack_size = 0;
product_price = 0;
}


// input and store the member details
public void input()
{
product_code = askInt(“Enter the product code: “);
flavour = askString(“Enter the flavour: “);
pack_type = askString(“Enter the pack type: “);
pack_size = askInt(“Enter the pack size: “);
product_price = askInt(“Enter the product price: “);
}


// compute the discount
public void discount()
{
product_price -= 10;
}


// display the object details
public void display()
{
System.out.println(“Product code : ” + product_code);
System.out.println(“Flavour : ” + flavour);
System.out.println(“Pack type : ” + pack_type);
System.out.println(“Pack size : ” + pack_size + ” ml.”);
System.out.println(“Product price: ” + product_price + ” Rs.”);
System.out.println();
}


// utility method to ask user to enter an int
// and return the int value entered
public int askInt(String prompt)
{
Scanner sc = new Scanner( System.in );
System.out.print(prompt);
int n = sc.nextInt();
String temp = sc.nextLine(); // read the end of line
return n;
}


// utility method to ask user to enter a String
// and return the String value entered
public String askString(String prompt)
{
Scanner sc = new Scanner( System.in );
System.out.print(prompt);
String s = sc.nextLine();
return s;
}


// main method to execute the class
public static void main(String[] args)
{
FruitJuice obj = new FruitJuice();
obj.input(); // (1) ask user data for one juice
obj.display(); // (2) display
obj.discount(); // (3) compute discount
obj.display(); // (4) display discounted price
}
}


Q5. The International Standard Book Number (ISBN) is a unique numeric book identifier which is printed on every book. The ISBN is based upon a 10-digit code. The ISBN is legal if 1*digit1 + 2*digit2 + 3*digit3 + 4*digit4 + 5*digit5 + 6*digit6 + 7*digit7 + 8*digit8 + 9*digit9 + 10*digit10 is divisible by 11.
Example: For an ISBN 1401601499
Sum=1*1 + 2*4 + 0*0 + 4*1 + 5*6 + 6*0 + 7*1 + 8*4 + 9*9 + 10*9 = 253 which is divisible by 11.
Write a program to:
(i) input the ISBN code as a 10-digit number
(ii) If the ISBN is not a 10-digit number, output the message “Illegal ISBN” and terminate the program
(iii) If the number is 10-digit, extract the digits of the number and compute the sum as explained above.
If the sum is divisible by 11, output the message “Legal ISBN”. If the sum is not divisible by 11, output the message “Illegal ISBN”.
[15 marks]
A5.
import java.util.*;
class Q5
{
public static void main(String[] args)
{
// input the 10-digit ISBN number
Scanner sc = new Scanner( System.in );
System.out.print(“Enter the 10-digit ISBN number: “);
long isbn = sc.nextLong();
String temp = sc.nextLine(); // for the trailing newline


// check the length is 10, else terminate the program
String s = “” + isbn;
if( s.length() != 10 )
{
System.out.println(“Illegal ISBN”);
return; // terminate the program
}


// compute the sum of the digits
int sum = 0;
for(int i=0; i < s.length(); i++)
{
int digit = Integer.parseInt(s.substring(i, i+1));
int digitNo = i + 1;
int term = digitNo * digit;
sum += term;
}


// check if divisible by 11 and output
// an appropriate message
if( (sum%11) != 0 )
{
System.out.println(“Illegal ISBN”);
}
else

{
System.out.println(“Legal ISBN”);
}
}
}


The output over multiple executions is shown below:


Q6. Write a program that encodes a word in Piglatin. To translate word into Piglatin word, convert the word into uppercase and then place the first vowel of the original word as the start of the new word along with the remaining alphabets. The alphabets present before the vowel being shifted towards the end followed by “AY”.
Sample Input(1): London Sample Output(1): ONDONLAY
Sample Input(2): Olympics Sample Output(2): OLYMPICSAY
[15 marks]
A6.
import java.util.*;
class Q6
{
public static void main(String[] args)
{
// enter a word
Scanner sc = new Scanner( System.in );
System.out.print(“Enter a word: “);
// convert the same into uppercase as well
String word = sc.nextLine().toUpperCase();
// variable to store the Piglatin result
String piglatinWord = “”;


// find the position of the first vowel
int firstVowel = -1;
for(int i=0; (i < word.length()) && (firstVowel < 0); i++)
{
char ch = word.charAt(i);
switch(ch)

{
case ‘A’:
case ‘E’:
case ‘I’:
case ‘O’:
case ‘U’:
firstVowel = i;
break;
}
}


String part1 = “”, part2 = “”;
if(firstVowel >= 0)
{
part2 = word.substring(0, firstVowel);
part1 = word.substring(firstVowel);
}
else
{
part2 = “”;
part1 = word;
}
piglatinWord = part1 + part2 + “AY”;

System.out.println(“Output: ” + piglatinWord);
}
}
Sample output:

Q7. Write a program to input 10 integer elements in an array and sort them in descending order using bubble sort technique.
[15 marks]
A7.
import java.util.*;
class Q7
{
public static void main(String[] args)
{
// for user inputs
Scanner sc = new Scanner(System.in);
String temp = “”;


// ask array size (10 in the question)
System.out.print(“Enter the array size: “);
int n = sc.nextInt();
temp = sc.nextLine(); // for the trailing newline


// create the array of size n
int[] x = new int[n];
// fill up the array based on user input
System.out.print(“Enter the elements separated by a space: “);
for(int i=0; i < n; i++)
{
x[i] = sc.nextInt();
}
temp = sc.nextLine(); // for the trailing newline

// bubblesort the array
for(int i=0; i < (n-1); i++)
{
for(int j=0; j < (n-1-i); j++)
{
// swap if current is lower than next
// we need to move the lowest to the end
if(x[j] < x[j+1])
{
int t = x[j];
x[j] = x[j+1];
x[j+1] = t;
}
}
}

// display the sorted array
System.out.print(“Sorted array (descending): “);
for(int i=0; i < n; i++)
{
System.out.print(x[i] + ” “);
}
System.out.println();
}
}
Sample output:


Q8. Design a class to overload a function series() as follows:
(i) double series(double n) with one double argument and returns the sum of the series.
sum = 1/1 + 1/2 + 1/3 + … 1/n
(ii) double series(double a, double n) with two double arguments and returns the sum of the series.
sum = 1/a2 + 4/a5 + 7/a8 + 10/a11 … to n terms
[15 marks]
A8.
import java.util.*;
class Q8
{
// first overlaoded method
// one double argument only
public static double series(double n)
{
double sum = 0.0;
// convert n into the nearest integer
// call it terms
int terms = (int)(Math.round(n));
for(int i=1; i <= terms; i++)
{
double term = 1.0D / (double)i;
sum += term;
}
return sum;
}


// second overlaoded method
// two double arguments
public static double series(double a, double n)
{
double sum = 0.0;
// convert n into the nearest integer
// call it terms
int terms = (int)(Math.round(n));

double nr = 1.0, dr = 2.0;
for(int i=1; i <= terms; i++)
{
double term = nr / (a * dr);
sum += term;
nr += 3.0;
dr += 3.0;
}
return sum;
}


// main method to test the class
public static void main(String[] args)
{
Scanner sc = new Scanner( System.in );
System.out.print(“Enter a and n: “);
double a = sc.nextDouble();
double n = sc.nextDouble();
String temp = sc.nextLine(); // for the trailing newline
// call the 1st overloaded method
double sum1 = Q8.series(n);
System.out.println(“Sum1: ” + sum1);
// call the 2nd overloaded method
double sum2 = Q8.series(a, n);
System.out.println(“Sum2: ” + sum2);
}
}
Sample output:


Q9. Using the switch statement, write a menu driven program:
(i) To check and display whether the number input by the user is a composite number or not (A number is said to be a composite, if it has one or more than one factors excluding 1 and the number itself).
Example: 4, 6, 8, 9, …
(ii) To find the smallest digit of an integer that is input:
Sample input: 6524
Sample output: Smallest digit is 2
[15 marks]
A9.
import java.util.*;
class Q9
{
public static void main(String[] args)
{
char menuOption = ‘ ‘;
do
{
menuOption = askMenuOption();
switch(menuOption)
{
case ‘C’: // composite
doComposite();
break;
case ‘S’: // smallest digit
doSmallestDigit();
break;
case ‘X’:
System.out.println(“Quitting program. Thank you.”);
break;
default:
break;
}
}while( menuOption != ‘X’ ); // keep asking until X is entered
}


// return the menu option selected
// ensure the option is either C, S, or X
public static char askMenuOption()
{
Scanner sc = new Scanner( System.in );
char option = ‘ ‘;
do
{
System.out.print(“Enter C for Composite, S for Smallest, X for Exit: “);
option = sc.nextLine().toUpperCase().charAt(0);
if( “CSX”.indexOf(option) < 0 ) // wrong entry
{
System.out.println(“Incorrect option. Try again…”);
}
}while( “CSX”.indexOf(option) < 0 ); // if incorrect, ask again
return option;
}

// composite number checking
public static void doComposite()
{
int n = askInt(“Enter integer for Composite check: “);
int noOfFactors = 0;
for(int i=2; i < n; i++) if( (n%i) == 0 ) noOfFactors++; if(noOfFactors == 0) System.out.println(n + ” is not a composite number.”); else System.out.println(n + ” is a composite number.”); } // get the smallest digit public static void doSmallestDigit() { int n = askInt(“Enter integer for smallest digit check: “); int smallestDigit = 9; // initialize to largest digit 9 int temp = n; while(temp > 0)
{
int digit = temp % 10;
temp = temp / 10;
smallestDigit = (smallestDigit <= digit) ? smallestDigit : digit;
}
System.out.println(“Smallest digit is: ” + smallestDigit);
}
// utility function to ask the user to enter an integer
// displays the prompt passed as an argument first
// then it asks for the integer to be entered
// Eventually it returns the integer entered
public static int askInt(String prompt)
{
Scanner sc = new Scanner( System.in );
System.out.print(prompt);
int n = sc.nextInt();
String temp = sc.nextLine(); // for the trailing newline
return n;
}
}



Write a program to input the age, gender (male or female) and taxable income of a person. If the age is more than 65 years or the gender is female, display “wrong category”. If the age is less than or equal to 65 years and the gender is male, compute and display the income tax payable as per the table given above.
[15 marks]
A5.
import java.util.*;
class Q5
{
public static void main(String[] args)
{
// local variables
Scanner sc = new Scanner(System.in);
int age;
char gender;
int taxableIncome;
String temp;


// user inputs
System.out.print(“Enter the age, gender and taxable income: “);
age = sc.nextInt();
gender = sc.next().toUpperCase().charAt(0);
taxableIncome = sc.nextInt();
temp = sc.nextLine(); // for the trailing newline

// check for correctness and
if( (age > 65) || (gender != ‘M’) )
System.out.println(“wrong category”);
else // compute and display the income tax
{
double incomeTax = 0.0;
if( (taxableIncome > 160000) && (taxableIncome <= 500000) ) incomeTax = (taxableIncome – 160000)*0.1; else if( (taxableIncome > 500000) && (taxableIncome <= 800000) ) incomeTax = (taxableIncome – 500000) * 0.2 + 34000; else if( taxableIncome > 800000 )
incomeTax = (taxableIncome – 800000) * 0.3 + 94000;
System.out.println(“Income tax payable: ” + incomeTax);
}
}
}



Sample outputs from multiple iterations of the program:

Q6. Write a program to accept a string. Convert the string to uppercase. Count and output the number of double letter sequences that exist in the string.
Sample input: SHE WAS FEEDING THE LITTLE RABBIT WITH AN APPLE
Sample output: 4
[15 marks]
A6.
import java.util.*;
class Q6
{
public static void main(String[] args)
{
// user input
Scanner sc = new Scanner(System.in);
System.out.print(“Enter a sentence: “);
String sentence = sc.nextLine().toUpperCase();

// count the double letter sequences
int count = 0;
char previousChar = ‘ ‘, currentChar = ‘ ‘;
for(int i=0; i < sentence.length(); i++) { currentChar = sentence.charAt(i); // exclude spaces when checking if( (currentChar == previousChar) && (currentChar != ‘ ‘) ) { count++; } previousChar = currentChar; } // display the output System.out.println(“Number of double letter sequences: ” + count); } } Sample output: Q7. Design a class to overload a function polygon() as follows: a) void polygon(int n, char ch) – with one integer argument and one character type argument that draws a filled square of side n using the character stored in ch b) void polygon(int x, int y) – with two integer arguments that draws a filled rectangle of length x and breadth y, usign the symbol ‘@’ c) void polygon() – with no arguments that draws a filled triangle shown below. Example: i) Input value of n = 2, ch = ‘O’. Output: OO OO ii) Input value of n=2, y=5. Output: @@@@@ @@@@@ iii) Output: * ** *** [15 marks] A7. class Q7 { // overloaded function 1 public static void polygon(int n, char ch) { System.out.println(“Overloaded method #1″); for(int i=1; i <= n; i++) // n lines { printChar(ch, n); // of n characters each System.out.println(); } } // overloaded function 2 public static void polygon(int n, int y) { System.out.println(“Overloaded method #2″); for(int i=1; i <= n; i++) // n rows { printChar(‘@’,y); // each of ‘@’ y times System.out.println(); } } // overloaded function 3 public static void polygon() { System.out.println(“Overloaded method #3″); for(int i=1; i <= 3; i++) // 3 rows { printChar(‘*’, i); // each of ‘*’, i times System.out.println(); } } // utility function to print ch, n times public static void printChar(char ch, int n) { for(int i=1; i <= n; i++) System.out.print(ch); } // main method to call the 3 overloaded functions public static void main(String[] args) { Q7.polygon(2, ‘O’); Q7.polygon(2, 5); Q7.polygon(); } } Output: Q8. Using the switch statement, write a menu driven program to: i) Generate and display the first 10 terms of the Fibonacci series 0, 1, 1, 2, 3, 5, … The first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two. ii) Find the sum of the digits of an integer that is input: Sample input: 15390 Sample output: Sum of the digits = 18 For an incorrect choice, an appropriate error message should be displayed. [15 marks] A8. import java.util.*; class Q8 { public static void main(String[] args) { char menuOption = ‘ ‘; do { // Ask the menu option. If a wrong choice is entered, // display an appropriate message in the // askMenuOption() method itself. menuOption = askMenuOption(); switch(menuOption) { case ‘F’: // do Fibonacci doFibonacci(); break; case ‘S’: // do sum of the digits doSumOfDigits(); break; case ‘X’: System.out.println(“Quitting program. Thank you.”); break; default: break; } }while( menuOption != ‘X’ ); // Keep asking until X is entered } // Return the menu option selected. // If a wrong value is entered, display an appropriate // message and ask once again. public static char askMenuOption() { Scanner sc = new Scanner( System.in ); char option = ‘ ‘; do { System.out.print(“Enter F for Fibonacci, S for Sum of digits, X for Exit: “); option = sc.nextLine().toUpperCase().charAt(0); if( “FSX”.indexOf(option) < 0 ) // wrong entry { System.out.println(“Incorrect option. Try again…”); } }while( “FSX”.indexOf(option) < 0 ); // if wrong, ask again return option; } // First 10 digits of the Fibonacci series public static void doFibonacci() { int first = 0, second = 1, next; System.out.print(“Fibonacci: 0, 1″); int i; // compute 8 more values only, 0 and 1 are displayed already for(i=1; i <= 8; i++) { next = first + second; System.out.print(“, ” + next); first = second; second = next; } System.out.println(); } // Sum of digits public static void doSumOfDigits() { Scanner sc = new Scanner( System.in ); System.out.print(“Enter an integer: “); int n = sc.nextInt(); String temp = sc.nextLine(); // for the trailing newline int sum = 0; while( n > 0 )
{
int digit = n % 10;
sum += digit;
n = n / 10;
}
System.out.println(“Sum of the digits = ” + sum);
}
}
Sample output: