..
...BACK TO HOME...
..

 

ICSE 2014 Sample Paper 1

 

Computer Applications ICSE Sample Paper 1. 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) What do you understand by WORA? [2 marks]

A1. (a) WORA = Write Once Run Anywhere. This is the promise of Java. Once a Java program is compiled, class files in bytecode are created which can be executed on any environment that implements the JRE (Java Runtime Environment), whether it is running on Linux, Android, IOS, Windows, etc.

Q1. (b) Explain two types of comments used in Java programs. [2 marks]

A1. (b)

i) Single-line comment, which starts and ends on the same line. Anything that follows the // on a line is considered a comment.

ii) Multi-line comment, which can span one or more than one line. Anything between /* and */ is considered a comment.

Q1. (c) Explain the difference between the println() and print() functions. [2 marks]

A1. (c) The println() function prints what has to be printed followed by a newline so that the next print() / println() statement starts on a new line. The print() statement does not result in a newline, and the next print() / println() statement starts from where the earlier print() statement ended.

Q1. (d) What do you understand by the term operator precedence? [2 marks]

A1. (d) Operator precedence is a set of rules that determine which part of an expression gets evaluated when. It is most useful when the parenthesis () are missing to help guide the process. According to these rules, for example, The * and / have higher priority over + and -, and + and � have higher priority over the ternary operator ?:.

Q1. (e) A java program named ABC.java has three classes defined inside it: A.java, B.java, C.java. The class A.java is a public class. Will the program compile? If yes, how many class files will be created? If no, why not? [2 marks]

A1. (e) The program will not compile. Since A.java is a public class, the name of the program file must be A.java. The program file is named ABC.java. A public class must exist in a file which has the same name as that of the class.

Q2. (a) What do you understand by wrapper class? Give an example. [2 marks]

A2. (a) Everything in Java is an object � almost. The exceptions are the 8 primitive data types such as byte, short, int, etc. Many times, it is useful to treat the primitive data type values as objects. Wrapper classes are classes that correspond to the 8 primitive data types. Automatic conversions between primitive to wrapper equivalent (boxing) and wrapper equivalent to primitive data type value (unboxing) happens in Java. The Wrapper classes also provide useful static methods, such as Integer.parseInt() and Double.parseDouble() that accept a String and return the int / double values.

An example of a wrapper class is Integer, for the primitive data type int.

Q2. (b) Differentiate between bubble sort and selection sort techniques. [2 marks]

A2. (b)

BUBBLE SORT

SELECTION SORT

Higher number of swaps

Lower number of swaps

Maximum number of swaps for large data sets is approx. n2

Maximum number of swaps for large data sets is approx. n

Less efficient for large data sets since swapping is an expensive operation

More efficient for large data sets since swapping is less that bubble sort

Swapping happens for each value check

Swapping happens once per loop iteration, since the index of the max/min value is set in the iterations

Q2. (c) Explain the difference between length() and length. [2 marks]

Q2. (c) The length() method is used on String values to compute the size of the string, whereas length is used with arrays to determine the size of the dimension of that array. For example, if String[] s = {�Hello�, �Goodbye�}; is an array of Strings, s.length is 2, and s[0].length() is 5, and s[1].length() is 7.

Q2. (d) What are the two clauses that form part of the try statement dealing with exception handling? [2 marks]

A2. (d) Two two clauses are catch and finally.

Q2. (e) Explain what you understand by signature of a function. [2 marks]

A2. (e) The signature of a function is what makes it unique from any other function in the same class. Two functions in the same class can have the same name, as long as the number and the order of the data types of those functions is different. This combination of the name of the function, the number and order of the data types, is called the signature of a function. This is useful in determining which function gets called, a process known as function overloading.

Q3. (a) Write a Java statement to create an object named apple of class Fruit. [2 marks]

A3. (a) Fruit apple = new Fruit();

Q3. (b) Write a statement that initializes a one-dimensional double array named d with the values 1, 4, 9, and 16. [2 marks]

A3. (b) double[] d = { 1.0D, 4.0D, 9.0D, 16.0D };

Q3. (c) What is the maximum value that (int)( Math.random() * 6 ); can evaluate to?

A3. (c) 5

Q3. (d) What is the return type of the following methods?

i) toUpperCase()

ii) toLowerCase()

iii) equals()

iv) compareTo()

[4 marks]

A3. (d)

i) String

ii) String

iii) boolean

iv) int

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

int x = 2;

x += x++ * x++ * x++;

System.out.println(x);

[2 marks]

A3. (e) 26

Working: 2 is added to the result due to x +=. Therefore, the expression evaluates to x = 2 + (2++*x++*x++) = 2 + (2 * 3++ * x++) = 2 + (2 * 3 * 4++) = 2 + (2 * 3 * 4) = 2 + 24 = 26.

Q3. (f) Write the statement z = (x > y) ? x : y; using if construct. [2 marks]

A3. (f)

if(x > y)

z = x;

else

z = y;

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

String s1 = "Batman and Robin";

String s2 = "The Cat wont move the cheese";

String s3 = s2.substring( s2.lastIndexOf("C"), s2.lastIndexOf("C") + 3 );

String s4 = s1.replace( "Bat", s3 + "wo" );

System.out.println( s4 );

[3 marks]

A3. (g) Catwoman and Robin

Q3. (h) What is the output if the following are invoked on the class below:

i) Q3.function(4);

ii) Q3.function();

iii) Q3.function(�A�);

class Q3

{

�� public static void function()

��� {

������� function(0);

��� }

 

��� public static void function(int x)

��� {

������� System.out.println(x);

��� }

}

[3 marks]

A3. (h)

i) 4

ii) 0

iii) 65

Q4. Define a class Point that has the following structure:

Data members / instance variables: x and y of type integer � these are the X and Y coordinated of the point

Parameterized Constructor: the data members must be initialized using a 2-argument parameterized constructor

Member methods:

display() � to display the coordinates of the Point object in (x, y) format

move(int, int) � that accepts two integer arguments and changes the x,y of the Point object by the value of the arguments passed

move(Point) � overloaded to behave similar to move(int, int) � it changes the x,y of the Point object by the x and y of the Point argument passed to it.

Call the above functions in your program.

[15 marks]

A4.

class Point

{

��� // data members

��� int x, y;

 

��� // 2-argument parameterized constructor

��� public Point(int x, int y)

��� {

������� this.x = x;

������� this.y = y;

��� }

 

��� // display

��� public void display()

��� {

������� System.out.println( "(" + x + ", " + y + ")" );

��� }

 

��� // overloaded move() #1

��� public void move(int x, int y)

��� {

������� this.x += x;

������� this.y += y;

��� }

 

��� // overloaded move() #2

��� public void move(Point p)

��� {

������� this.move(p.x, p.y);

��� }

 

��� // entry point main method

��� public static void main(String[] args)

��� {

������� Point p1 = new Point(3, 4);

������� Point p2 = new Point(5, 10);

 

������� p1.display();

������� p2.display();

������� p1.move(3, 4);

������� p1.display();

������� p1.move(p2);

������� p1.display();

��� }

}

Sample output:

sample0104

Q5. Write a program that asks the user to enter an integer (N). Create a single-dimensional array of N double values. Ask the user to enter the N double values to populate this array. Sort this array in reverse (descending) order using the selection sort method, and print the same on a single line, each element separated by a space. [15 marks]

A5.

import java.util.*;

class Q5

{

��� public static void main(String[] args)

��� {

������� // user input

������� Scanner sc = new Scanner( System.in );

������� String temp;

������� System.out.print("Enter number of elements (N): ");

������� int N = sc.nextInt();

������� temp = sc.nextLine(); // for the trailing newline

������� // create the array

������� double[] d = new double[N];

������� // populating the array

������� System.out.print("Enter the " + N + " elements: ");

������� int i, j;

������� for(i=0; i<N; i++)

������� {

����������� d[i] = sc.nextDouble();

������� }

������� temp = sc.nextLine();

 

������� // perform the selection sort

������� // in reverse order

������� int minIndex = 0;

������� double swapper;

������� for(i=0; i < (N-1); i++)

������� {

����������� minIndex = 0;

����������� for(j=1; j<=(N-1-i); j++)

����������� {

��������������� if(d[minIndex] > d[j])

����������������� minIndex = j;

����������� }

����������� // do the swap using temp variable swapper

����������� swapper = d[minIndex];

����������� d[minIndex] = d[N-1-i];

����������� d[N-1-i] = swapper;

������� }

 

������� // display the output

������� System.out.print("Sorted output: ");

������� for(i=0; i<N; i++)

��������� System.out.print(d[i] + " ");

������� System.out.println();

��� }

}

Sample output:

sample0105

Q6. A prominent builder has announced the launch of a property which starts at 4000 Rs per sft (square foot) for the 1st floor floor flat. The price per sft increases by Rs. 50 per floor up to and including the 10th floor. From the 10th floor upwards, the price per sft increases by Rs. 100 per floor. There are two types of flats: 2BHK and 3BHK. The 2BHK flats have a saleable area of 1500 sft, and the 3BHK flats have a saleable area of 2000 sft. The building has 20 floors. Write a program that prints the rate of each floor, and the cost of each type of flat for each of the floors, in the format shown below:

FLOOR NO.

RATE PER SFT.

PRICE OF 2BHK

PRICE OF 3BHK

1

2

[15 marks]

A6.

class Q6

{

��� public static void main(String[] args)

��� {

������� // set the rates array (Rs. per sft)

������� int[] rates = new int[21]; // use 1 to 20 floors

������� int i;

������� rates[1] = 4000;

������� for(i=2; i<rates.length; i++)

������� {

����������� if(i<=10)

������������� rates[i] = rates[i-1] + 50; // 2nd to 10th floors

����������� else

������������� rates[i] = rates[i-1] + 100; // 11th floor onwards

������� }

 

������� // send the header

������� System.out.println("Floor No. Rate Per SFT Price of 2BHK Price of 3BHK");

������� System.out.println("--------- ------------ ------------- -------------");

������� for(i=1; i<rates.length; i++)

������� {

����� ������printInt(i, 9+1);

����������� printInt(rates[i],12+1);

����������� printInt(rates[i]*1500,13+1);

����������� printInt(rates[i]*2000,13+1);

����������� System.out.println();

������� }

��� }

��� // utility method to print an int in a field width

��� // left padded with spaces

��� public static void printInt(int n, int width)

��� {

������� String s = "" + n;

������� int spaces = width - s.length();

������� while(spaces > 0)

������� {

����������� System.out.print(" "); // one space

����������� spaces--;

������� }

������� System.out.print(n);

��� }

}

Output:

sample0106

Q7. Write a program that asks the user to enter a sentence. Ignoring the case, print those words that occur maximum number of times in the sentence. For example:

INPUT: Is the question of why is the main method in Java called main too difficult?

OUTPUT: Maximum frequency: 3 Word(s) are: IS THE MAIN

[15 marks]

A7.

import java.util.*;

class Q7

{

��� 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();

 

������� // array to store the words and their frequency

������� // cannot exceed number of characters in the sentence

������� String[] words = new String[ sentence.length() ];

������� int[] freq = new int[words.length];

������� int wordCount = 0; // initially zero

 

������� // split into words

������� // and populate the words[] and freq[] arrays

������� String word;

������� int i;

������� boolean found;

������� int foundIndex = 0;

������� StringTokenizer st = new StringTokenizer(sentence, " .,;()?!");

������� while( st.hasMoreTokens() )

������� {

����������� word = st.nextToken();

����������� found = false;

����������� foundIndex = -1;

����������� for(i=0; i<wordCount; i++)

����������� {

��������������� if( words[i].equals( word ) )

��������������� {

������������������� found = true;

������������������� foundIndex = i;

������������ �������break;

��������������� }

����������� }

����������� if(found)

������������� freq[foundIndex]++;

����������� else

����������� {

��������������� words[wordCount] = word;

��������������� freq[wordCount] = 1;

��������������� wordCount++;

����������� }

������}

 

������� // compute the max freq

������� int maxFreq = 0;

������� for(i=0; i<wordCount; i++)

������� {

����������� maxFreq = (maxFreq < freq[i]) ? freq[i] : maxFreq;

������� }

 

������� // print words with the maxFreq occurrence

������� System.out.print("Maximum frequency: " + maxFreq + " Word(s) are: ");

������� for(i=0; i<wordCount; i++)

��������� if(freq[i] == maxFreq)

����������� System.out.print(words[i] + " ");

������� System.out.println();

��� }

}

Sample output:

sample0107

Q8. Write a menu driven program that performs the following functions (use switch..case):

i) Ask the user to enter two numbers and check if they are amicable numbers or not. A set of numbers (n1 and n2) are amicable if the sum of the proper factors of n1 is equal to n2, and the sum of the proper factors of n2 is equal to n1. A proper factor of a number is all factors of that number including 1, but not the number itself.

ii) Ask the user to enter a word, and print all 3 letter combinations of that word, including repeats, on a single line, each combination separated by spaces.

[15 marks]

A8.

import java.util.*;

class Q8

{

��� public static void main(String[] args)

��� {

������� char menuOption = ' '; // space

������� do

������� {

����������� menuOption = askMenuOption();

����������� switch(menuOption)

����������� {

��������������� case 'A':

����������������� doAmicable();

����������������� break;

��������������� case 'C':

����������������� do3LetterCombos();

����������������� break;

��������������� case 'X':

����������������� System.out.println("Exiting program. Thank you!");

����������������� break;

����������� }

������� }while( menuOption != 'X' );

��� }

��� // ask the user to enter a menu option

��� // reask if wrong option is entered

��� // return the option chosen

��� public static char askMenuOption()

��� {

������� Scanner sc = new Scanner( System.in );

������� char option = ' '; // space

������� do

������� {

����������� System.out.print("Enter A-Amicable, C-3-letter, X-Exit: ");

����������� option = sc.nextLine().toUpperCase().charAt(0);

����������� if( "ACX".indexOf(option) < 0 )

������������� System.out.println("Incorrect option. Try again...");

������� }while( "ACX".indexOf(option) < 0 );

������� return option;

��� }

��� // amicable number process

��� public static void doAmicable()

��� {

������� int n1 = askInt("Enter number n1: ");

������� int n2 = askInt("Enter number n2: ");

������� int sof1 = getSumOfFactors(n1);

������� int sof2 = getSumOfFactors(n2);

������� if( (n1 == sof2) && (n2 == sof1) )

��������� System.out.println(n1 + " and " + n2 + " are amicable numbers");

������� else

��������� System.out.println(n1 + " and " + n2 + " are not amicable numbers");

��� }

��� // ask user to enter an int

��� // display parameter 1 as the prompt

��� 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;

��� }

��� // return sum of proper factors

��� public static int getSumOfFactors(int n)

��� {

������� int i, sum=0;

������� for(i=1; i<n; i++)

��������� if( (n%i) == 0 )

��� ��������sum += i;

������� return sum;

��� }

��� // 3 letter combo

��� public static void do3LetterCombos()

��� {

������� Scanner sc = new Scanner( System.in );

������� System.out.print("Enter a word: ");

������� String word = sc.nextLine().toUpperCase();

������ int i, j, k;

������� String s1, s2, s3;

������� String combo;

������� for(i=0; i<word.length(); i++)

��������� for(j=0; j<word.length(); j++)

����������� for(k=0; k<word.length(); k++)

������������� if( (i!=j) && (j!=k) && (i!=k) )

������������� {

����������������� s1 = word.substring(i,i+1);

����������������� s2 = word.substring(j,j+1);

����������������� s3 = word.substring(k,k+1);

����������������� combo = s1 + s2 + s3;

����������������� System.out.print(combo + " ");

������������� }

������� System.out.println();

��� }

}

Sample output:

sample0108

Q9. Given that 1st Jan 2014 is a Wednesday, compute the day of Feb 28th, 2021. A year is a leap year if it is divisible by 4. There is one exception to this rule: If a year is divisible by 100, but not by 400, it is not a leap year (e.g. 2100, 2200, 2300, 2500, etc.) However, since 2400 is divisible by 400 it is a leap year. [15 marks]

A9.

class Q9

{

��� public static void main(String[] args)

��� {

������� int dd = 1, mm = 1, yyyy = 2014;

������� String[] weekDayName = { "Monday", "Tuesday",

����������� "Wednesday", "Thursday", "Friday",

����������� "Saturday", "Sunday"

������� };

������� int day = 2 ; // Wednesday

 

������� while( !( (dd == 28) && (mm == 2) && (yyyy == 2021) ) )

������� {

����������� dd++;

����������� day++;

����������� if( day == 7 )

������������� day = 0; // 0 is Monday, 6 is Sunday

����������� switch( mm )

����������� {

��������������� case 1:

��������������� case 3:

��������������� case 5:

��������������� case 7:

��������������� case 8:

��������������� case 10:

��������������� case 12:

����������������� if( dd > 31 )

����������������� {

��������������������� dd = 1;

��������������������� mm++;

��������������������� if( mm > 12 )

��������������������� {

������������������������� mm = 1;

������������������������� yyyy++;

��������������������� }

����������������� }

����������������� break;

��������������� case 4:

��������������� case 6:

��������������� case 9:

��������������� case 11:

����������������� if( dd > 30 )

����������������� {

��� ������������������dd = 1;

��������������������� mm++;

��������������������� if( mm > 12 )

��������������������� {

������������������������� mm = 1;

������������������������� yyyy++;

��������������������� }

����������������� }

����������������� break;

���� �����������case 2:

����������������� int daysInMonth = getFebDaysInMonth(yyyy);

����������������� if( dd > daysInMonth )

����������������� {

��������������������� dd = 1;

��������������������� mm++;

��������������������� if( mm > 12 )

��������������������� {

������������������������� mm = 1;

������������������������� yyyy++;

��������������������� }

����������������� }

����������������� break;�����������������

����������� }

������� }

������� System.out.println("Week day name: " + weekDayName[day]);

��� }

��� // return days on Feb of the year passed ... 28 or 29

��� public static int getFebDaysInMonth(int year)

��� {

������� if( (year%4) != 0 ) // not multiple of 4

��������� return 28;

������� // if code reaches here, year is a multiple of 4

������� if( (year%100) != 0 ) // not multiple of 100

��������� return 29; // leap year

������� // if code reaches here, year is a multiple of 100

������� if( (year%400) != 0 ) // not multiple of 400

��������� return 28;

������� return 29; // multiple of 400

��� }

}

Output:

sample0109

==========================================================================

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

=================================================================

ICSE 2014 Sample Paper 3

Computer Applications ICSE Sample Paper 3. 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 the process of compilation and execution in Java. [2 marks]

A1. (a) Assume the name of the Java program file is X.java and it contains two classes: X and Y. The compiler, on windows, is javac.exe. The command to compile is javac X.java. This will create two class files: X.class and Y.class. Assuming that the main method is in the class file X.class, the program to run is through the Java interpreter java.exe. The command is: java X. This will result in the public static void main(String[] args) method of the X.class file being executed. If this class file does not have the main() method, an error is displayed.

Q1. (b) Name two wrapper classes whose names are not the same as the names of their respective primitive data types. [2 marks]

A1. (b) Integer and Character.

Q1. (c) Explain the importance of the Scanner class. Which package does it belong to? [2 marks]

A1. (c) The Scanner class belongs to the java.util package. It is a utility class that helps us read data from an input stream, using simple methods as compared to using the slightly more elaborate and lengthy methods of the java.io package classes dealing with streams. The important methods of the java.util.Scanner class are next(), nextLine(), nextInt(), nextFloat(), nextLong(), nextDouble().

Q1. (d) Classes Car and Bus are children of the TransportVehicle class. Assuming the parent class to be abstract, write the class declarations of the 3 classes. The class TransportVehicle is public as well. Do not write contents / constructors / instance variables of the classes. Assuming that all the 3 classes are in the same Java file, what will be the name of that file?[4 marks]

A1. (d)

// File Name: TransportVehicle.java
public abstract class TransportVehicle{ ... }
class Car extends TransportVehicle { ... }
class Bus extends TransportVehicle { ... }

Since the TransportVehicle class is public, the name of the file must be TransportVehicle.java only. This is because if a class inside a file is public, the name of the file must be the name of the class. This is a requirement of Java.

Q2. (a) Mention true or false. If false, provide a reason why:

i) A subclass object can be referenced by a parent variable reference.

ii) Call to super() and this() can be made inside the same constructor.

iii) The signature of a method includes its return type.

iv) Double.parseInt() can be used to convert a decimal number entered as a String into an integer?

[4 marks]

A2. (a)

i) True.

ii) False. Inside a constructor, the call to super() or this(), if present, must be the first statement of the constructor only. Hence, they cannot both exist inside the same constructor.

iii) False. The signature of a method includes the name, the number of parameters, and the sequence of data types of those parameters. It does not include the return type of the method.

iv) False. There is no method called Double.parseInt(). Double.parseDouble() will return a double value. Integer.parseInt() will return an int value.

Q2. (b) What is sorting? Name two sorting algorithms. [2 marks]

A2. (b) Sorting is the process of arranging primitive values or objects in a certain order. Two popular sorting algorithms are bubble-sort and selection-sort.

Q2. (c) Assuming that a and b are two int values, write a Java statement to assign the minimum of these two values inside a variable named min, using the ternary operator. [2 marks]

A2. (c)

int min = (a < b) ? a : b;

Q2. (d) Explain what you understand by recursive function. Give an example. [4 marks]

A2. (d) A recursive function is a function that calls itself. Such a function needs an explicit check condition to ensure that it does not keep calling itself repeatedly. Recursion is a powerful feature that can be used to solve certain problems which would otherwise be difficult to solve, or require more lengthy programming. One of the most common examples of recursion is to compute the factorial of a number, which is shown as the example below:

public static int factorial(int n)
{
if(n == 1) // explicit exit condition
��� return 1;
return n * factorial(n-1); // recursive call
}

Q3. (a) Which of the following program snippets will compile? If no, explain why not.

i)

class Shape
{
String shape;
public Shape(String shape)
{
��� this.shape = shape;
}
}
class Circle extends Shape
{
double radius;
public Circle(double radius)
{
��� this.radius = radius;
}
}

ii)

class Shape
{
public abstract double area();
}
class Circle extends Shape
{
double radius;
public Circle(double radius)
{
��� this.radius = radius;
}
}

iii)

class Shape
{
public abstract double area();
}
class Circle extends Shape
{
double radius;
public double area()
{
��� return Math.PI * Math.pow(radius, 2);
}
}

iv)

class Shape
{
String name;
public Shape(String name)
{
��� this.name = name;
}
}
class Circle extends Shape
{
double radius;
}

[4 marks]

A3. (a)

i) Will not compile. This is because there is no call in the constructor of the child class to super() with a parameter. The Shape class has a single parameterized constructor. Since no call to super() is specified in the Circle class� constructor, Java puts in a default super(), which does not exist in the parent Shape class.

ii) Will not compile. The Circle class is a child class of Shape. Since Shape has an abstract method area(), either the Circle class should provide an implementation for the area() method, or else, the Circle class must be made abstract as well.

iii) Will compile. There is no constructor in the Circle class, so a default constructor is provided by Java. This calls super() which is OK, since the Shape class also has no constructor, and hence is given a zero-argument default constructor by Java. In the Circle class, the radius value is initialized to 0.0D automatically when an object of the class is created. The abstract method area() of the Shape classed is implemented in the Circle class, and hence this code will compile.

iv) Will not compile. The Circle class has no constructor, and so Java provides a default constructor. This constructor will have a call to super() with no arguments. But the Shape class has a single constructor that accepts a String argument, which means that there is no zero-argument constructor of the Shape class. Hence the code will not compile.

Q3. (b) Write a Java statement to create an object no of class Yes with a String parameter having value �Maybe�. [2 marks]

A3. (b)

Yes no = new Yes("Maybe");

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

class Q3c
{
��� public static void main(String[] args)
��� {
������� Dog d = new Dog("Rover");
��� }
}
abstract class Animal
{
��� Animal()
��� {
������� System.out.println("Creating an Animal");
��� }
}
class Dog extends Animal
{
��� String name;
��� Dog(String name)
��� {
������� System.out.println("Name of Dog: " + name);
������� this.name = name;
��� }
}

[4 marks]

A3. (c)

Creating an Animal
Name of Dog: Rover

Explanation: When the Dog() object is created, the Dog(String) constructor is called. The first statement here is super(), which calls the constructor of the parent Animal class, which contains the first print statement. After this, the second print statement is displayed.

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

int[][] x = { {1,2}, {3,4}, {5,6} };
int[][] y = { {1,2}, {3,4}, {5,6} };
int[][] z = new int[3][2];
int i, j;
for(i=0; i<3; i++)
for(j=0; j<2; j++)
{
��� z[i][j] = x[i][j] * y[i][j];
��� if(i==j)
����� System.out.println( z[i][j] );
}

[2 marks]

A3. (d)

1
16

Explanation: i and j are the same two times only: with values 0 and 1. When 0, the answer is x[0][0] * y[0][0] = 1 * 1 = 1. When 1, the answer is x[1][1] * y[1][1] = 4 * 4 = 16.

Q3. (e) Which of the following statements is incorrect?

i) int a[] = new int[4];
ii) int[] b = new int[4];
iii) int[][] c = new int[4];
iv) int d[][] = new int[4][];

[2 marks]

A3. (e) Statement (iii) is incorrect, since a one-dimensional array is being created and assigned to a 2-dimensional reference variable. The others will all compile.

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

int x = 4, y = 7;
double z = x*y;
if(z > x)
z = z + y/x;
else
z = z + x*y;
System.out.println(z);

[2 marks]

A3. (f) 29.0

Explanation: z is 28.0 and z+y/x = 28.0 + 7/4 = 28.0 + 1 (integer division) = 29.0

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

[2 marks]

int x = 4, y = 6;
int inc = 1;
for(int i=1; i<=3; i++, inc++, x+=inc, y+=inc)
{
��� System.out.println(x + "," + y);
}

A3. (g)

sample0303g

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

char ch1 = 'E', ch2 = '9';
System.out.println( Character.isDigit(ch1) );
System.out.println( Character.isDigit(ch2) );
System.out.println( Character.isLetter(ch1) );
System.out.println( Character.isLetter(ch2) );

[2 marks]

A3. (h)

false
true
true
false

Q4. The basic salary of school teachers is undergoing a revision. The basic salary would now be a function of the grade, the relevant experience in completed years before joining the school, and the relevant experience in completed years after joining the school. The grades can be from 1 (minimum) to 5 (maximum), and the increment per grade is 1,000 Rs in basic. The basic for grade 1 is 10,000. The increment for previous experience is 250 per year, and for current experience 500 per year. Create a class Teacher with appropriate instance variables and a parameterized constructor. Write a function to ask the details of a teacher (including the name) and then to compute and print the basic of that teacher. [15 marks]

A4.

import java.util.*;
class Q4
{
��� public static void main(String[] args)
��� {
������� Teacher t = Teacher.createTeacher();
������� t.display();
��� }
}
class Teacher
{
��� String name;
��� int grade, previous, current;
��� int basic;
 
��� // constructor
��� public Teacher(String name, int grade, int previous, int current)
��� {
������� this.name = name;
������� this.grade = grade;
������� this.previous = previous;
������� this.current = current;
������� computeBasic();
��� }
 
��� // compute the basic
��� public void computeBasic()
��� {
������� basic = 10000 + (grade - 1) * 1000;
������� basic += (previous * 250);
������� basic += (current * 500);
��� }
 
��� // display the information
��� public void display()
��� {
������� System.out.println("Name��� : " + name);
������� System.out.println("Grade�� : " + grade);
������� System.out.println("Previous: " + previous);
������� System.out.println("Current : " + current);
������� System.out.println("Basic�� : " + basic);
��� }
 
��� // factory method to create an object
��// using the inputs provided
��� public static Teacher createTeacher()
��� {
������� Scanner sc = new Scanner( System.in );
������� System.out.print("Enter name: ");
������� String name = sc.nextLine();
������� System.out.print("Enter grade, previous, current: ");
������� int grade = sc.nextInt();
������� int previous = sc.nextInt();
������� int current = sc.nextInt();
������� String temp = sc.nextLine(); // for the trailing newline
������� Teacher t = new Teacher(name, grade, previous, current);
������� return t;
��� }
}

Sample output:

sample0304

Q5. Define a class Circle that has a single instance variable radius of type double, and an instance method area() that returns the area of the circle. Write a method factory() inside the class that accepts an integer parameter (N). It should create an array of N Circle objects, asking the user to enter the radius for each of the N circles. The method should return this array to the main calling program. Loop through the array to print the radius and the area of each of the circle objects. [15 marks]

A5.

import java.util.*;
class Q5
{
��� public static void main(String[] args)
��� {
������� Scanner sc = new Scanner(System.in);
������� System.out.print("Enter how many circles (N): ");
������� int N = sc.nextInt();
������ String temp = sc.nextLine();
 
������� Circle[] circles = Circle.factory(N);
������� Circle c;
������� for(int i=0; i<circles.length; i++)
������� {
����������� c = circles[i];
����������� System.out.print("Radius: " + c.radius);
����������� System.out.println(" Area: " + c.area());
������� }
��� }
}
class Circle
{
��� double radius;
��� // constructor
��� public Circle(double r)
��� {
������� radius = r;
��� }
��� // return the area of the circle object
��� public double area()
��� {
������� return Math.PI * Math.pow(radius, 2);
��� }
��� // factory method
��� public static Circle[] factory(int N)
��� {
������� Scanner sc = new Scanner( System.in );
������� // create the array
������� Circle[] circles = new Circle[N];
������� // for each element of the array,
������� // create a circle object with the
������� // user-entered radius
������� for(int i=0; i<N; i++)
������� {
����������� System.out.print("Enter radius: ");
����������� double r = sc.nextDouble();
����������� String temp = sc.nextLine(); // for the trailine newline
����������� Circle c = new Circle(r);
����������� circles[i] = c;
������� }
������� return circles;
��� }
}

Sample output:

sample0305

Q6. Write a program that asks the user to enter an integer and print all unique two digit integers that can be formed using the digits of that number. For example, if the input is 1231, the output should be 12, 13, 11, 21, 23, 31, 32. [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 an integer: ");
������� int n = sc.nextInt();
������� String temp = sc.nextLine(); // for the trailing newline
������� String s = "" + n; // convert into a String
������� int i, j, k, number;
������� // max combos is s.length() * (s.length() - 1)
������� // make an array of that size and keep a count variable
������� int[] numbers = new int[s.length() * (s.length() - 1)];
������� int count = 0;
������� boolean found;
����� ��for(i=0; i<s.length(); i++)
��������� for(j=0; j<s.length(); j++)
����������� if(i!=j) // cannot have the same digit twice
����������� {
��������������� // the "" below is needed to prevent char addition
��������������� number = Integer.parseInt("" + s.charAt(i) + s.charAt(j));
��������������� found = false;
��������������� for(k=0; k<count; k++)
����������������� if(numbers[k] == number)
������������������� found = true; // already exists
��������������� // add to array if not found
��������������� if(!found)
����������������� numbers[count++] = number;
����������� }
������� // display the output
������� System.out.print("Combos are: ");
������� for(i=0; i<count; i++)
������� {
����������� System.out.print(numbers[i]);
����������� if(i < (count-1))
������������� System.out.print(", ");
������� }
������� System.out.println();
��� }
}

Sample output:

sample0306

Q7. Write a program that asks the user to enter N integers, sort them, and then display them with the lowest integer first, the highest integer next, the 2nd lowest integer next, the 2nd highest integer next, and so on. [15 marks]

A7.

import java.util.*;
class Q7
{
��� public static void main(String[] args)
��� {
������� // user entry
������� Scanner sc = new Scanner(System.in);
������� String temp;
������� System.out.print("How many integers (N): ");
������� int N = sc.nextInt();
������� temp = sc.nextLine(); // for the trailing newline
������� // create the int array n
������� int[] n = new int[N]; 
��������int i, j;
 
������� System.out.print("Enter " + n.length + " numbers: ");
������� for(i=0; i<n.length; i++)
������� {
����������� n[i] = sc.nextInt();
������� }
������� temp = sc.nextLine(); // for the trailing newline
 
������� // sort the array
������� int t; // temp variable for swapping
������� for(i=0; i<n.length-1; i++)
��������� for(j=0; j<n.length-1-i; j++)
����������� if(n[j] > n[j+1]) // do a swap
����������� {
��������������� t = n[j];
��������������� n[j] = n[j+1];
��������������� n[j+1] = t;
����������� }
 
������� // print in sequence suggested
������� int leftIndex = 0, rightIndex = n.length - 1;
������� for(;leftIndex<=rightIndex;leftIndex++,rightIndex--)
������� {
����������� System.out.print( n[leftIndex] + " " );
����������� // for odd sized array
����������� if( leftIndex < rightIndex ) 
��������������System.out.print( n[rightIndex] + " " );
������� }
������� System.out.println();
��� }
}

Sample outputs for odd and even number of elements:

sample0307

Q8. Write a program that asks the user to enter the values (double) of a, b, and c, and then solve for the quadratic equation ax2 + bx + c = 0. There are two answers, x1 and x2, as shown below:

term = √(b2 � 4ac)

x1 = (-b + term) / (2a)

x2 = (-b � term) / (2a)

[15 marks]

A8.

import java.util.*;
class Q8
{
��� // instance variables
��� double a, b, c;
 
��� // constructor to ask the data
��� public Q8()
��� {
������� Scanner sc = new Scanner(System.in);
������� String temp;
������� System.out.print("Enter values for a, b, c: ");
������� a = sc.nextDouble();
������� b = sc.nextDouble();
������� c = sc.nextDouble();
������� temp = sc.nextLine(); // for the trailing newline
��� }
 
��� public void solve()
��� {
������� double t = Math.pow(b, 2) - (4 * a * c);
������� if(t < 0) // if negative, cant be solved
������� {
����������� System.out.println("Cannot be solved. Negative of squareroot.");
����������� return;
������� }
������� double term = Math.sqrt(t);
������� double x1 = (-b + term) / (2 * a);
������� double x2 = (-b - term) / (2 * a);
������� System.out.println("x1=" + x1 + ", x2=" + x2);
��� }
 
��� public static void main(String[] args)
��� {
������� Q8 obj1 = new Q8();
������� obj1.solve();
������� Q8 obj2 = new Q8();
������� obj2.solve();
��}
}

Sample output:

sample0308

Q9. Write a menu driven program that allows a user to encode a word or decode a word. In order to encode a word, enter the word and an integer, and convert each character of that word into a character n later than itself. In order to decode a word, enter the encoded word and an integer, and convert each character into a character n earlier than itself. If a character loops after Z, roll it to A and continue. Similarly, if a character loops before A, roll it to Z and continue. For example, encoding �WHIZ� with 5 gives �BMNE�, and decoding �BMNE� with 5 should give �WHIZ� once again. Assume capital letters only. [15 marks]

A9.

import java.util.*;
class Q9
{
��� public static void main(String[] args)
��� {
������� char menuOption = ' '; // space
������� do
������� {
����������� menuOption = askMenuOption();
����������� switch(menuOption)
����������� {
��������������� case 'E':
����������������� encode();
����������������� break;
��������������� case 'D':
�� ���������������decode();
����������������� break;
��������������� case 'X':
����������������� System.out.println("Exiting program. Thank you!");
����������������� break;
����������� }
������� }while( menuOption != 'X' );
��� }
��� // ask menu option
��� // if incorrect, ask again
��� // return option entered
��� public static char askMenuOption()
��� {
������� Scanner sc = new Scanner(System.in);
������� char option = ' '; // space
������� do
������� {
����������� System.out.print("Enter E-encode, D-decode, X-Exit: ");
����������� option = sc.nextLine().toUpperCase().charAt(0);
����������� if("EDX".indexOf(option) < 0)
������������� System.out.println("Incorrect option. Try again...");
������� }while( "EDX".indexOf(option) < 0 );
������� return option;
��� }
��� // encode
��� public static void encode()
��� {
������� // user input
������� Scanner sc = new Scanner(System.in);
������� System.out.print("Enter a word and the integer: ");
������� String word = sc.next().toUpperCase();
������� int n = sc.nextInt();
������� String temp = sc.nextLine(); // for the trailine newline
 
������� String encodedWord = "";
������� int i;
������� char ch;
������� int offset;
������� for(i=0; i<word.length(); i++)
������� {
����������� ch = word.charAt(i);
����������� // how far away from 'A'?
����������� offset = ch - 'A';
����������� offset += n;
����������� // rotate back if beyond Z(25)
����������� offset = offset % 26;
����������� ch = (char)('A' + offset);
����������� encodedWord = encodedWord + ch;
������� }
������� System.out.println("Encoded word: " + encodedWord);
��� }
��� // decode
��� public static void decode()
��� {
������� // user input
������� Scanner sc = new Scanner(System.in);
������� System.out.print("Enter a word and the integer: ");
������� String word = sc.next().toUpperCase();
������� int n = sc.nextInt();
������� String temp = sc.nextLine(); // for the trailine newline
 
������� String decodedWord = "";
������� int i;
������� char ch;
���� ���int offset;
������� for(i=0; i<word.length(); i++)
������� {
����������� ch = word.charAt(i);
����������� // how far away from 'A'?
����������� offset = ch - 'A';
����������� offset -= n;
����������� // rotate back if before A(25)
����������� while(offset < 0)
������������� offset += 26;
����������� ch = (char)('A' + offset);
����������� decodedWord = decodedWord + ch;
������� }
������� System.out.println("Decoded word: " + decodedWord);
��� }
}

Sample output:

sample0309

================================================================================================

 

ICSE 2014 Sample Paper 4

This paper is work in progress and would be completed shortly.

Computer Applications ICSE Sample Paper 4. 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) [4 marks]

Define the term programming language. Mention 3 characteristics of a programming language.

A1. (a) A programming language is a language used to write instructions for a computer to perform.

The 3 elements (characteristics) of a programming language are:

1. A programming language has a set of words. These are known as reserved words.

2. A programming language has syntax. This defines the rules on how different parts of the program can be created. For example, the name of a variable cannot start with a number.

3. A programming language has semantics. This defines how different parts of the program can be used with each other. For example, you can multiply two numbers, but you cannot multiply a word with a number.

Q1. (b) Explain the significance of the environment variable PATH for Java programs. [2 marks]

A1. (b) The PATH environment variable is used by the operating system and not by the compiler. When we call the Java compiler (javac.exe) or the Java interpreter (java.exe), the operating system hunts for these program files to execute using the sequence of folders given in the PATH environment variable.

The CLASSPATH environment variable is used by Java programs to locate the class files / libraries needed for the program to execute. The folders within CLASSPATH are searched in sequence, and when a match is found for a class file, that class file is used.

Q1. (c) How much space is occupied by a boolean value in Java? [2 marks]

A1. (c) The space occupied by a boolean value in Java depends on the implementation of Java Virtual Machine and is not fixed to any bit/byte size. In some implementations, it may occupy one bit only, in others one byte. We cannot tell and we need not know. The boolean functionality is what is important to us.

Q1. (d) Explain what you understand by Unicode. [2 marks]

A1. (d) Unicode is a computing industry standard allowing computers to represent and manipulate characters of most of the world�s languages. The Unicode characters in Java are represented using the char data type. This data type has a size of 2 bytes (16 bits) and can hold integer numbers from 0 through 65,535. Each number represents one character of one language. For example, the number 65 represents the character �A� of the English language.

Q2. (a) Define the term expression. [2 marks]

A2. (a) An expression is a combination of values, variables, operators, and functions that get evaluated according to certain rules, and compute and return a value.

As an example, in the equation y = x + 5, the portion to the right, which is x + 5, is an expression. In this case, we have �x� as a variable, + as an operator, and �5� as a value. So, an expression is a combination of variables, operators, values, and functions.

Q2. (b) Explain what you understand by the statement: Java is a strongly typed language. [2 marks]

A2. (b) The statement means that the Java compiler expects each variable to be declared before it can be used in a program. By declaring a variable to be of a certain data type, we are telling Java what type of values can be stored in that variable.

Q2. (c) Explain two uses of the return statement. [2 marks]

Q2. (c)

1. The return statement can be used as follows:To return a value and exit from a function. As an example:

return area;

2. To exit from a function without returning a value, from a function that has void as its return type. As an example:

return;

Q2. (d) Differentiate between formal and actual parameters. [2 marks]

A2. (d) Formal parameters are the parameters as they are defined and known inside the function. Actual parameters are what is passed to the function. Actual parameters are also known as arguments.

Formal parameters

Actual parameters

Parameters defined inside the function declaration.

Actual values passed to the function. Also called arguments of the function.

Example:int area(int length)Above: length is a formal parameter

Example:int a = area( 4 );4 is the actual parameter.

Q2. (e) What is the output of the following code snippet? [2 marks]

char ch = 'A';

while( ++ch < 'D' )

{

��� System.out.println( ch++ );

}

A2. (e) The output is:

B

Explanation: Initially, ch is �A�. The condition does a pre-increment, making ch = �B�. The condition is true. The loop body executes once. When printing, ch++ means the value �B� is printed and then ch increments to �C�. Now, back to the condition once again. Here, ++ch makes the value �D�. The condition now becomes �D� < �D�, which is false, and the loop stops executing. The loop body iterates just one time.

Q3. (a)

Give the output of the following code segment when:

1.           opn = �b�

2.           opn = �x�

3.           opn = �a�

switch(opn)

{

case 'a':

System.out.println("A");

break;

case 'b':

System.out.println("B");

case 'c':

System.out.println("C");

break;

default:

System.out.println("D");

}

[3 marks]

A3. (a)

a.�������� B

�� C

b.�������� D

c.��������� A

Q3. (b)

Read the program code below. After the last statement executes:

1.           How many object references are present?

2.           How many objects have been created?

3.           How many objects are eligible for garbage collection?

Dog d1, d2, d3, d4;

d1 = new Dog();

d2 = new Dog();

d3 = d1;

d4 = d2;

d2 = new Dog();

d4 = d1;

[3 marks]

A3. (b)

1.           4 (d1, d2, d3, and d4)

2.           3 (three objects created with the new keyword)

3.           1 (the second object) [Explanation: When the last new() statement executes, d2 now points to this new object and so longer points to the Dog object it was pointing to. That Dog object was also been pointed to by d4, due to d4=d2. But the last statement of d4=d1 makes d4 also point to the object pointed to by d1. Now, the first d2 object has nothing pointing to it, and is hence eligible for garbage collection.  Another explanation: After the first 4 statements, d1 and d3 point to Object 1, and d2 and d4 point to Object 2. After the first statement, d1 and d3 continue to point to Object 1, d2 to Object 3 newly created, and d4 to Object 2. After the last statement, d4 also points to what is pointed to by d2, which is Object 3. Now, nothing points to Object 2, which becomes eligible for garbage collection.]

Q3. (c) Mention true/false against each of the statements below:

1.           An object can be created using the new keyword only.

2.           Once we no longer need an object, that object becomes automatically eligible for garbage collection.

3.           We, as programmers, can decide when the garbage collector should execute.

4.           An object reference can refer to only one object inside a program.

[4 marks]

A3. (c)

1.           True

2.           False. An object becomes eligible for garbage collection once there is no reference to that object, and not when we no longer need that object.

3.           False. The execution of the garbage collector is dependent on the implementation of the JVM.

4.           False. An object reference can refer to one object at a time. Over a period of time, the object reference can refer to different objects, one at a time.

Q3. (d) Will the following code compile? If no, why not?

class Dog

{

String name;

 

Dog( String pName )

{

��� name = pName;

}

 

Dog( String pDogsName )

{

��� name = pDogsName;

}

}

[2 marks]

A3. (d) The code will not compile. Both the constructors have one argument of data type String. Just by naming the formal parameters differently, the signature of the two constructors does not change. The signature of the two constructors is the same, which is not allowed. The compiler will not compile this.

Q3. (e) Explain why the following code will not compile.

class Dog

{

String name;

 

public Dog( String pName )

{

��� name = pName;

}

 

public static void printInfo()

{

��� System.out.println( "Name: " + name );

}

}

[2 marks]

A3. (e)  Since the printInfo() method is defined as static, it cannot access the data members of the class. This method is attempting to print the name data member, and will generate a compiler error.

Q3. (f) Explain what you understand by the term static? [2 marks]

A3. (f) Static, in Java, applies to variables and methods.

A static variable is one that belongs to a class, and not to any object of that class. It is shared across all objects of the class.

A static method is one that can be executed even without having an object of the class created. e.g. Math.sqrt(5).

A static method can access the static variables of a class, but cannot any instance variables of that class.

Q3. (g) What is a stream? [2 marks]

A3. (g) A stream is a sequence of data. It could be Unicode (character) data or binary data.

There are two types of streams: input streams and output streams.

An input stream is used to read data from a source (such as a keyboard or a file.) The main classes in Java that support all input streams are: InputStream and Reader. Both these classes are abstract.

The Reader class is used for character-based (Unicode) input streams, whereas the InputStream class is used for binary input streams.

An output stream is used by a program to write data to a destination (such as the screen, the printer, or a file.) The main classes in Java that support all output streams are: OutputStream and Writer. Both these classes are abstract.

The Writer class is used for character-based (Unicode) output streams, whereas the OutputStream class is used for binary output streams.

Q3. (h) Compare the bubble sort and the selection sort algorithms. [2 marks]

A3. (h)

Bubble sort

Selection sort

Maximum number of swaps: approximately n2

Maximum number of swaps: n (actually n-1)

Less efficient in terms of resource utilization as compared to selection sort

More efficient in terms of memory usage in terms of swaps

Takes more time since the number of swaps is more

Takes less time since the number of swaps is less

When a value needs to be changed, swap happens immediately

When a value needs to be changed, the index of the value is changed, not the value itself. At the end of each pass, one swap only needs to be done.

Q4. Define classes as follows for a game of cricket.

Class Name: Player.

Instance variables:

name � string

age � integer

runs � integer

Constructor:

Overloaded constructor 1: must accept name and age, and initialize runs and wickets to 0.

Overloaded constructor 2: must accept name, age, and runs and initialize them.

Member methods:

addRuns() � accepts an integer argument and adds this to the runs scored by the player.

display() � display the name, age, runs and wickets of a player.

Class Name: Team

Instance variables:

players � an array of 3 Player objects

name � the name of the team, string

Constructor: Single argument, which is the name of the team. In the constructor, ask the user to enter the names and ages of the 3 players and assign the 3 Player objects to the array variable players.

Member method:

play() � No arguments. Play a game of 6 balls, each with a random integer generated from 0 to 6. Do this for all 3 players, 6 balls each. Add the runs scored to each players runs. At the end, display the information of each player using the display() method defined in the Player class earlier.

Write a main method that asks the user to enter the name of the team, create the team object, play 6 balls for each of the 3 players, and print their information.

[15 marks]

A4.

import java.util.*;

class Q4

{

��� public static void main(String[] args)

��� {

������� // User input

������� Scanner sc = new Scanner(System.in);

������� String teamName;

������� System.out.print("Enter the name of the team: ");

������� teamName = sc.nextLine();

������� // Create the team object

������� Team team1 = new Team(teamName);

������� team1.play(); // play the game

��� }

}

class Player

{

��� String name;

��� int age, runs;

 

��� // Overloaded constructor 1

��� public Player(String name, int age)

��� {

������� // call the other constructor to prevent duplicate coding

������� this(name, age, 0);

��� }

��� // Overloaded constructor 2

��� public Player(String name, int age, int runs)

��� {

������� this.name = name;

������� this.age= age;

������� this.runs = runs;

��� }

 

��� public void addRuns(int r)

��� {

������� runs += r;

��� }

 

��� public void display()

��� {

������� System.out.println("Name: " + name + " (" + age + " years) " + runs + " runs.");

��� }

}

class Team

{

��� Player players[];

��� String name;

 

��� // Constructor

��� public Team(String teamName)

��� {

������� this.name = teamName;

������� players = new Player[3];

������� // ask for name and age

������� Scanner sc;�������

������� String name, temp;

������� int age, i;

������� sc = new Scanner(System.in);

������� for(i=0; i<players.length; i++)

������� {

����������� System.out.print("Enter the name of player " + (i+1) + ": ");

����������� name = sc.nextLine();

����������� System.out.print("Enter the age: ");

����������� age = sc.nextInt();

����������� temp = sc.nextLine(); // for the trailing newline

����������� Player p = new Player(name, age); // constructor 1 of Player class

����������� players[i] = p; // assign to players array of Team class

������� }

��� }

 

��� public void play()

��� {

������� int i, j;

������� // make each player bat 6 balls

��� ����for(i=0; i<players.length; i++)

������� {

����������� // 6 balls to play per player

����������� for(j=1; j <= 6; j++)

����������� {

��������������� int r = (int)(Math.random() * 7); // int from 0 to 6

��������������� players[i].addRuns(r);

����������� }

������� }

������� // display runs of each of the players

������� for(i=0; i < players.length; i++)

������� {

����������� players[i].display();

������� }

��� }

}

Sample output:

sample0404

Q5. An office building has ground floor (floor zero) and extends up to 20 floors (floor twenty). An elevator starts from the 0th floor and moves as requested by the passengers, eventually returning back to the ground floor (floor zero). Write a program that asks the passengers to enter a valid floor (0 till 20), until a final floor of 0 is reached. Count and display the number of stops as well as the path followed by the elevator. Do not accept an enter of a floor number greater than 20, and do not accept an entry of a floor number same as the current floor.

Example:

Current floor 0, enter a floor number: 4

Current floor 4, enter a floor number: 9

Current floor 9, enter a floor number: 6

Current floor 6, enter a floor number: 12

Current floor 12, enter a floor number: 22

Wrong floor entered! Enter a floor number: 12

You are already on floor 12! Enter a floor number: 3

Current floor 3, enter a floor number: 0

Current floor 0.

Number of stops: 6

Path of the elevator: 0-4-9-6-12-3-0

[15 marks]

A5.

import java.util.*;

public class Q5

{

��� public static void main(String[] args)

��� {

������� String path = "0"; // currently at floor 0

������� int currentFloor = 0;

������� int stops = 0;

������� do

������� {

����������� currentFloor = askNextFloor(currentFloor);

����������� stops++;

����������� path = path + "-" + currentFloor;

������� }while(currentFloor != 0); // exit when return back to floor 0

������� System.out.println("Number of stops: " + stops);

������� System.out.println("Path of the elevator: " + path);

��� }

 

��� // ask user to enter the next floor stop of the elevator

��� // if same as current floor, ask again

��� // if more than 20th floor, ask again

��� public static int askNextFloor(int currentFloor)

��� {

������� int nextFloor = -1;

������� Scanner sc = new Scanner(System.in);�����������

������� System.out.print("Current floor " + currentFloor + ", enter a floor number: ");

������� do

������� {

����������� nextFloor = Integer.parseInt(sc.nextLine());

����������� if(nextFloor == currentFloor)

����������� {

��������������� System.out.print("You are already on floor " + currentFloor + "! Enter a floor number: ");

��������������� nextFloor = -1;

����������� }

����������� else if( (nextFloor < 0) || (nextFloor > 20) )

����������� {

��������������� System.out.print("Wrong floor entered! Enter a floor number: ");

��������������� nextFloor = -1;

����������� }

������� }while( nextFloor == -1 );

������� return nextFloor;

��� }

 

}

Sample output:

Sample0405

Q6. Define a class Point that has two instance variables of type double: x and y, which are the coordinates of the point. Write an appropriate parameterized constructor for this class. Write a method distance() that accepts a second Point object as its argument and computes the distance between two Point objects. For example, if p1 is a Point object and p2 is another Point object, then p1.distance(p2) should return the distance between the two points. Ask the user to enter values for creating two Point objects p1 and p2, and to compute and print the distance between them.

[15 marks]

A6.

import java.util.*;

class Point

{

��� double x, y; // instance variables

��� // parameterized constructor

��� public Point(double px, double py)

��� {

������� this.x = px;

������� this.y = py;

��� }

��� // compute and return the distance between 2 Points

��� public double distance(Point p2)

��� {

������� double deltaX = this.x - p2.x;

������� double deltaY = this.y - p2.y;

������� double distance = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));

������� return distance;

��� }

��� // display the Point object as a pair of (x,y) coordinates

��� public void display()

��� {

������� System.out.print("(" + this.x + "," + this.y + ")");

��� }

��� // static method to create a Point object

��� // and then return it back.

��� // user has to enter the values of x and y

��� public static Point createPoint(String prompt)

��� {

������� Scanner sc = new Scanner( System.in );

������� System.out.println(prompt);

������� System.out.print("Enter x and y: ");

������� double x = sc.nextDouble();

������� double y = sc.nextDouble();

������� String temp = sc.nextLine(); // for the trailing newline

������� Point p = new Point(x, y);

������� return p;

��� }

��� // entry-point main method

��� public static void main(String[] args)

��� {

������� Point p1, p2;

������� p1 = Point.createPoint("Create point p1");

������� p2 = Point.createPoint("Create point p2");

������� double d = p1.distance(p2);

������� System.out.print("The distance between ");

������� p1.display();

������� System.out.print(" and ");

������� p2.display();

������� System.out.println(" is " + d);

��� }

}

Sample output:

Sample0406

Note: The createPoint() method is a static method (a factory method) that does all the work of asking the user to enter values of x and y, creating a Point object, and returning the same back. Such factory methods are considered a good programming style and you are encouraged to use this when writing code for object creation.

Q7. Define a class IceCream that has instance variables volume (integer) and flavour (String). Write an appropriate parameterized constructor for this IceCream class. Write a bite() method that reduces the remaining volume of the ice cream by 10 ml. Write a display() method that prints out the flavour and the remaining volume.

Ask the user to enter the number of IceCream objects to be created (say N). Pass this number to a static factory method createIceCreams() of the IceCream class. This method will create an array of N IceCream objects, ask the user to enter the flavour and the volume of each of these N objects, and return the same back to the caller.

Using a loop, call the bite() method 1 time on the first IceCream object of that array, 2 times on the second IceCream object of that array, and so on, calling it N times on the last IceCream object of that array.

Finally, call the display() method to display the flavour and remaining volume of each of the IceCream objects.

 

. ..............................back