0% found this document useful (0 votes)
32 views62 pages

COMMEDIA HolidayAssignmentfor10th2024 20240917161304

Uploaded by

muthuvel0301
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views62 pages

COMMEDIA HolidayAssignmentfor10th2024 20240917161304

Uploaded by

muthuvel0301
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Dear Parents,

Greetings from FLOS Carmeli ICSE School,


Kindly find the below holiday assignment for your ward.
Take a 100 pages long un ruled book and write the following board papers
Note: Do not write the output instead write the variable description table.
Submit the assignment on or before 14th October 2024.
Thank you.

2018
Section A

Question 1

(a) Define abstraction.

Answer

Abstraction refers to the act of representing essential features without including the background details or
explanation.

(b) Differentiate between searching and sorting.

Answer

Searching Sorting

Searching means to search for a term or value Sorting means to arrange the elements of the array in
in an array. ascending or descending order.

Linear search and Binary search are examples Bubble sort and Selection sort are examples of sorting
of search techniques. techniques.

(c) Write a difference between the functions isUpperCase( ) and toUpperCase( ).

Answer

isUpperCase( ) toUpperCase( )

isUpperCase( ) function checks if a given character is toUpperCase( ) function converts a given


in uppercase or not. character to uppercase.

Its return type is boolean. Its return type is char.

(d) How are private members of a class different from public members?

Answer
private members of a class can only be accessed by other member methods of the same class whereas public
members of a class can be accessed by methods of other classes as well.

(e) Classify the following as primitive or non-primitive datatypes:

1. char
2. arrays
3. int
4. classes

Answer

1. Primitive
2. Non-Primitive
3. Primitive
4. Non-Primitive

Question 2

(a) (i) int res = 'A';


What is the value of res?

Answer

Value of res is 65 which is the ASCII code of A. As res is an int variable and we are trying to assign it the
character A so through implicit type conversion the ASCII code of A is assigned to res.

(ii) Name the package that contains wrapper classes.

Answer

java.lang

(b) State the difference between while and do while loop.

Answer

while do-while

It is an entry-controlled loop. It is an exit-controlled loop.

It is helpful in situations where numbers of iterations It is suitable when we need to display a menu
are not known. to the user.

(c) System.out.print("BEST ");


System.out.println("OF LUCK");

Choose the correct option for the output of the above statements

1. BEST OF LUCK
2. BEST
OF LUCK

Answer

Option 1 — BEST OF LUCK is the correct option.


System.out.print does not print a newline at the end of its output so the println statement begins printing on the
same line. So the output is BEST OF LUCK printed on a single line.

(d) Write the prototype of a function check which takes an integer as an argument and returns a
character.

Answer

char check(int a)

(e) Write the return data type of the following function.

1. endsWith()
2. log()

Answer

1. boolean
2. double

Question 3

(a) Write a Java expression for the following:

3x+x2a+ba+b3x+x2
Answer

Math.sqrt(3 * x + x * x) / (a + b)

(b) What is the value of y after evaluating the expression given below?

y+= ++y + y-- + --y; when int y=8

Answer

y+= ++y + y-- + --y


⇒ y = y + (++y + y-- + --y)
⇒ y = 8 + (9 + 9 + 7)
⇒ y = 8 + 25
⇒ y = 33

(c) Give the output of the following:

1. Math.floor (-4.7)
2. Math.ceil(3.4) + Math.pow(2, 3)
Answer

1. -5.0
2. 12.0

(d) Write two characteristics of a constructor.

Answer

Two characteristics of a constructor are:

1. A constructor has the same name as its class.


2. A constructor does not have a return type.

(e) Write the output for the following:


System.out.println("Incredible"+"\n"+"world");
Answer

Output of the above code is:

Incredible
world
\n is the escape sequence for newline so Incredible and world are printed on two different lines.

(f) Convert the following if else if construct into switch case

if( var==1)
System.out.println("good");
else if(var==2)
System.out.println("better");
else if(var==3)
System.out.println("best");
else
System.out.println("invalid");
Answer

switch (var) {
case 1:
System.out.println("good");
break;

case 2:
System.out.println("better");
break;

case 3:
System.out.println("best");
break;

default:
System.out.println("invalid");
}
(g) Give the output of the following string functions:

1. "ACHIEVEMENT".replace('E', 'A')
2. "DEDICATE".compareTo("DEVOTE")

Answer

1. ACHIAVAMANT
2. -18

Explanation

1. "ACHIEVEMENT".replace('E', 'A') will replace all the E's in ACHIEVEMENT with A's.
2. The first letters that are different in DEDICATE and DEVOTE are D and V respectively. So the output
will be:
ASCII code of D - ASCII code of V
⇒ 68 - 86
⇒ -18

(h) Consider the following String array and give the output

String arr[]= {"DELHI", "CHENNAI", "MUMBAI", "LUCKNOW", "JAIPUR"};


System.out.println(arr[0].length() > arr[3].length());
System.out.print(arr[4].substring(0,3));
Answer

Output of the above code is:

false
JAI

Explanation

1. arr[0] is DELHI and arr[3] is LUCKNOW. Length of DELHI is 5 and LUCKNOW is 7. As 5 > 7 is false
so the output is false.
2. arr[4] is JAIPUR. arr[4].substring(0,3) extracts the characters from index 0 till index 2 of JAIPUR so
JAI is the output.

(i) Rewrite the following using ternary operator:

if (bill > 10000 )


discount = bill * 10.0/100;
else
discount = bill * 5.0/100;
Answer

discount = bill > 10000 ? bill * 10.0/100 : bill * 5.0/100;


(j) Give the output of the following program segment and also mention how many times the loop is
executed:

int i;
for ( i = 5 ; i > 10; i ++ )
System.out.println( i );
System.out.println( i * 4 );
Answer

Output of the above code is:

20
Loop executes 0 times.

Explanation

In the loop, i is initialized to 5 but the condition of the loop is i > 10. As 5 is less than 10 so the condition of the
loop is false and it is not executed. There are no curly braces after the loop which means that the
statement System.out.println( i ); is inside the loop and the statement System.out.println( i * 4 ); is
outside the loop. Loop is not executed so System.out.println( i ); is not executed but System.out.println(
i * 4 ); being outside the loop is executed and prints the output as 20 (i * 4 ⇒ 5 * 4 ⇒ 20).
Section B

Question 4

Design a class RailwayTicket with following description:

Instance variables/data members:


String name — To store the name of the customer
String coach — To store the type of coach customer wants to travel
long mobno — To store customer’s mobile number
int amt — To store basic amount of ticket
int totalamt — To store the amount to be paid after updating the original amount

Member methods:
void accept() — To take input for name, coach, mobile number and amount.
void update() — To update the amount as per the coach selected (extra amount to be added in the amount as
follows)

Type of Coaches Amount

First_AC 700

Second_AC 500

Third_AC 250
Type of Coaches Amount

sleeper None

void display() — To display all details of a customer such as name, coach, total amount and mobile number.

Write a main method to create an object of the class and call the above member methods.

Answer

import java.util.Scanner;

public class RailwayTicket


{
private String name;
private String coach;
private long mobno;
private int amt;
private int totalamt;

private void accept() {


Scanner in = new Scanner(System.in);
System.out.print("Enter name: ");
name = in.nextLine();
System.out.print("Enter coach: ");
coach = in.nextLine();
System.out.print("Enter mobile no: ");
mobno = in.nextLong();
System.out.print("Enter amount: ");
amt = in.nextInt();
}

private void update() {


if(coach.equalsIgnoreCase("First_AC"))
totalamt = amt + 700;
else if(coach.equalsIgnoreCase("Second_AC"))
totalamt = amt + 500;
else if(coach.equalsIgnoreCase("Third_AC"))
totalamt = amt + 250;
else if(coach.equalsIgnoreCase("Sleeper"))
totalamt = amt;
}

private void display() {


System.out.println("Name: " + name);
System.out.println("Coach: " + coach);
System.out.println("Total Amount: " + totalamt);
System.out.println("Mobile number: " + mobno);
}
public static void main(String args[]) {
RailwayTicket obj = new RailwayTicket();
obj.accept();
obj.update();
obj.display();
}
}

Output

Question 5

Write a program to input a number and check and print whether it is a Pronic number or not. (Pronic number is
the number which is the product of two consecutive integers)

Examples:
12 = 3 x 4
20 = 4 x 5
42 = 6 x 7

Answer

import java.util.Scanner;
public class KboatPronicNumber
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number to check: ");
int num = in.nextInt();

boolean isPronic = false;

for (int i = 1; i <= num - 1; i++) {


if (i * (i + 1) == num) {
isPronic = true;
break;
}
}

if (isPronic)
System.out.println(num + " is a pronic number");
else
System.out.println(num + " is not a pronic number");
}
}

Output
Question 6

Write a program in Java to accept a string in lower case and change the first letter of every word to upper case.
Display the new string.

Sample input: we are in cyber world


Sample output: We Are In Cyber World

Answer

import java.util.Scanner;

public class KboatString


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a sentence:");
String str = in.nextLine();
String word = "";

for (int i = 0; i < str.length(); i++) {


if (i == 0 || str.charAt(i - 1) == ' ') {
word += Character.toUpperCase(str.charAt(i));
}
else {
word += str.charAt(i);
}
}

System.out.println(word);
}
}

Output

Question 7

Design a class to overload a function volume() as follows:

1. double volume (double R) – with radius (R) as an argument, returns the volume of sphere using the
formula.
V = 4/3 x 22/7 x R3

2. double volume (double H, double R) – with height(H) and radius(R) as the arguments, returns the
volume of a cylinder using the formula.
V = 22/7 x R2 x H

3. double volume (double L, double B, double H) – with length(L), breadth(B) and Height(H) as the
arguments, returns the volume of a cuboid using the formula.
V=LxBxH

Answer

public class KboatVolume


{
double volume(double r) {
return (4 / 3.0) * (22 / 7.0) * r * r * r;
}

double volume(double h, double r) {


return (22 / 7.0) * r * r * h;
}

double volume(double l, double b, double h) {


return l * b * h;
}

public static void main(String args[]) {


KboatVolume obj = new KboatVolume();
System.out.println("Sphere Volume = " +
obj.volume(6));
System.out.println("Cylinder Volume = " +
obj.volume(5, 3.5));
System.out.println("Cuboid Volume = " +
obj.volume(7.5, 3.5, 2));
}
}

Output

Question 8

Write a menu driven program to display the pattern as per user’s choice.

Pattern 1

ABCDE
ABCD
ABC
AB
A

Pattern 2

B
LL
UUU
EEEE

For an incorrect option, an appropriate error message should be displayed.

Answer

import java.util.Scanner;

public class KboatMenuPattern


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter 1 for pattern 1");
System.out.println("Enter 2 for Pattern 2");
System.out.print("Enter your choice: ");
int choice = in.nextInt();
switch (choice) {
case 1:
for (int i = 69; i >= 65; i--) {
for (int j = 65; j <= i; j++) {
System.out.print((char)j);
}
System.out.println();
}
break;

case 2:
String word = "BLUE";
int len = word.length();
for(int i = 0; i < len; i++) {
for(int j = 0; j <= i; j++) {
System.out.print(word.charAt(i));
}
System.out.println();
}
break;

default:
System.out.println("Incorrect choice");
break;

}
}
}

Output
Question 9

Write a program to accept name and total marks of N number of students in two single subscript
array name[] and totalmarks[].

Calculate and print:

1. The average of the total marks obtained by N number of students.


[average = (sum of total marks of all the students)/N]
2. Deviation of each student’s total marks with the average.
[deviation = total marks of a student – average]

Answer

import java.util.Scanner;

public class KboatSDAMarks


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = in.nextInt();

String name[] = new String[n];


int totalmarks[] = new int[n];
int grandTotal = 0;

for (int i = 0; i < n; i++) {


in.nextLine();
System.out.print("Enter name of student " + (i+1) + ": ");
name[i] = in.nextLine();
System.out.print("Enter total marks of student " + (i+1) + ": ");
totalmarks[i] = in.nextInt();
grandTotal += totalmarks[i];
}

double avg = grandTotal / (double)n;


System.out.println("Average = " + avg);

for (int i = 0; i < n; i++) {


System.out.println("Deviation for " + name[i] + " = "
+ (totalmarks[i] - avg));
}
}
}

Output
2023
Section A

Question 1(i)

A mechanism where one class acquires the properties of another class:

1. Polymorphism
2. Inheritance
3. Encapsulation
4. Abstraction

Answer

Inheritance

Reason — Inheritance enables new classes to receive or inherit the properties and methods of existing classes.

Question 1(ii)

Identify the type of operator &&:

1. ternary
2. unary
3. logical
4. relational

Answer

logical

Reason — Logical operators operate only on boolean operands and are used to construct complex decision-
making expressions. Logical AND && operator evaluates to true only if both of its operands are true.

Question 1(iii)

The Scanner class method used to accept words with space:

1. next()
2. nextLine()
3. Next()
4. nextString()
Answer

nextLine()

Reason — nextLine() reads the input till the end of line so it can read a full sentence including spaces.

Question 1(iv)

The keyword used to call package in the program:

1. extends
2. export
3. import
4. package

Answer

import

Reason — import keyword is used to import built-in and user-defined packages into our Java program.

Question 1(v)

What value will Math.sqrt(Math.ceil(15.3)) return?

1. 16.0
2. 16
3. 4.0
4. 5.0

Answer

4.0

Reason — Math.ceil method returns the smallest double value that is greater than or equal to the argument and
Math.sqrt method returns the square root of its argument as a double value. Thus the given expression is
evaluated as follows:

Math.sqrt(Math.ceil (15.3))
= Math.sqrt(16.0)
= 4.0

Question 1(vi)

The absence of which statement leads to fall through situation in switch case statement?

1. continue
2. break
3. return
4. System.exit(0)
Answer

break

Reason — The absence of break statement leads to fall through situation in switch case statement.

Question 1(vii)

State the type of loop in the given program segment:

for (int i = 5; i != 0; i -= 2)
System.out.println(i);

1. finite
2. infinite
3. null
4. fixed

Answer

infinite

Reason — The given loop is an example of infinite loop as for each consecutive iteration of for loop, the value
of i will be updates as follows:

Iteration Value of i Remark

1 5 Initial value of i = 5

2 3 i=5-2=3

3 1 i=3-2=1

4 -1 i = 1 - 2 = -1

5 -3 i = -1 - 2 = -3 and so on...

Since i will never be '0', the loop will execute infinitely.

Question 1(viii)

Write a method prototype name check() which takes an integer argument and returns a char:

1. char check()
2. void check (int x)
3. check (int x)
4. char check (int x)
Answer

char check (int x)

Reason — The prototype of a function is written in the given syntax:

return_type method_name(arguments)
Thus, the method has the prototype given below:

char check (int x)

Question 1(ix)

The number of values that a method can return is:

1. 1
2. 2
3. 3
4. 4

Answer

Reason — A method can return only one value.

Question 1(x)

Predict the output of the following code snippet:

String P = "20", Q ="22";


int a = Integer.parseInt(P);
int b = Integer.valueOf(Q);
System.out.println(a + " " + b);

1. 20
2. 20 22
3. 2220
4. 22

Answer

20 22

Reason — The values of strings P and Q are converted into integers using the Integer.parseInt() method and
stored in int variables a and b, respectively.
When the statement System.out.println(a + " " + b) is executed, first the operation a + " " is performed.
Here, int variable a is converted to a string and a space is concatenated to it resulting in "20 ".
After this, the operation "20 " + b is performed resulting in 20 22 which is printed as the output.

Question 1(xi)
The String class method to join two strings is:

1. concat(String)
2. <string>.joint(string)
3. concat(char)
4. Concat()

Answer

concat(String)

Reason — concat() method is used to join two strings. Its syntax is as follows:

String1.concat(String2)

Question 1(xii)

The output of the function "COMPOSITION".substring(3, 6):

1. POSI
2. POS
3. MPO
4. MPOS

Answer

POS

Reason — The substring() method returns a substring beginning from the startindex and extending to the
character at endIndex - 1. Since a string index begins at 0, the character at index 3 is 'P' and the character at
index 5 (6-1 = 5) is 'S'. Thus, "POS" is extracted.

Question 1(xiii)

int x = (int)32.8; is an example of ............... typecasting.

1. implicit
2. automatic
3. explicit
4. coercion

Answer

explicit

Reason — In explicit type conversion, the data gets converted to a type as specified by the programmer. Here,
the float value 32.8 is being converted to int type by the programmer, explicitly.

Question 1(xiv)
The code obtained after compilation is known as:

1. source code
2. object code
3. machine code
4. java byte code

Answer

java byte code

Reason — Java compiler converts Java source code into an intermediate binary code called Bytecode after
compilation.

Question 1(xv)

Missing a semicolon in a statement is what type of error?

1. Logical
2. Syntax
3. Runtime
4. No error

Answer

Syntax

Reason — Syntax Errors occur when we violate the rules of writing the statements of the programming
language. Missing a semicolon in a statement is a syntax error.

Question 1(xvi)

Consider the following program segment and select the output of the same when n = 10 :

switch(n)
{
case 10 : System.out.println(n*2);
case 4 : System.out.println(n*4); break;
default : System.out.println(n);
}

1. 20
40
2. 10
4
3. 20, 40
4. 10
10

Answer
20
40
Reason — Since n = 10, case 10 will be executed. It prints 20 (10 * 2) on the screen. Since break statement is
missing, the execution falls through to the next case. Case 4 prints 40 (10 * 4) on the screen. Now the control
finds the break statement and the control comes out of the switch statement.

Question 1(xvii)

A method which does not modify the value of variables is termed as:

1. Impure method
2. Pure method
3. Primitive method
4. User defined method

Answer

Pure method

Reason — A method which does not modify the value of variables is termed as a pure method.

Question 1(xviii)

When an object of a Wrapper class is converted to its corresponding primitive data type, it is called as ...............
.

1. Boxing
2. Explicit type conversion
3. Unboxing
4. Implicit type conversion

Answer

Unboxing

Reason — When an object of a Wrapper class is converted to its corresponding primitive data type, it is called
as unboxing.

Question 1(xix)

The number of bits occupied by the value ‘a’ are:

1. 1 bit
2. 2 bits
3. 4 bits
4. 16 bits

Answer

16 bits
Reason — A char data type occupies 2 bytes in the memory.

1 byte = 8 bits
2 bytes = 8 * 2 = 16 bits

Question 1(xx)

Method which is a part of a class rather than an instance of the class is termed as:

1. Static method
2. Non static method
3. Wrapper class
4. String method

Answer

Static method

Reason — Method which is a part of a class rather than an instance of the class is termed as Static method.

Question 2(i)

Write the Java expression for (a + b)x.

Answer

Math.pow(a + b, x)

Question 2(ii)

Evaluate the expression when the value of x = 4:

x *= --x + x++ + x
Answer

The given expression is evaluated as follows:

x *= --x + x++ + x (x = 4)
x *= 3 + x++ + x (x = 3)
x *= 3 + 3 + x (x = 4)
x *= 3 + 3 + 4 (x = 4)
x *= 10 (x = 4)
x = x * 10 (x = 4)
x = 4 * 10
x = 40

Question 2(iii)

Convert the following do…while loop to for loop:

int x = 10;
do
{
x––;
System.out.print(x);
}while (x>=1);
Answer

for(int x = 9; x >= 0; x--)


{
System.out.print(x);
}

Question 2(iv)

Give the output of the following Character class methods:

(a) Character.toUpperCase ('a')

(b) Character.isLetterOrDigit('#')

Answer

(a) Character.toUpperCase ('a')

Output

Explanation

In Java, the Character.toUpperCase(char ch) method is used to convert a given character to its uppercase
equivalent, if one exists. So, the output is uppercase 'A'.
(b) Character.isLetterOrDigit('#')

Output

false

Explanation

Character.isLetterOrDigit() method returns true if the given character is a letter or digit, else returns false.
Since, hash (#) is neither letter nor digit, the method returns false.

Question 2(v)

Rewrite the following code using the if-else statement:

int m = 400;
double ch = (m>300) ? (m / 10.0) * 2 : (m / 20.0) - 2;
Answer

int m = 400;
double ch = 0.0;
if(m > 300)
ch = (m / 10.0) * 2;
else
ch = (m / 20.0) - 2;

Question 2(vi)

Give the output of the following program segment:

int n = 4279; int d;


while(n > 0)
{ d = n % 10;
System.out.println(d);
n = n / 100;
}
Answer

Output

9
2

Explanation

Step by step explanation of the code:

1. int n = 4279; — Initializes the integer n with the value 4279.


2. int d; — Declares an integer variable d without initializing it. It will be used to store the individual
digits.

Now, let's go through the loop:

The while loop continues as long as n is greater than 0:

 d = n % 10; — This line calculates the remainder when n is divided by 10 and stores it in d. In the first
iteration, d will be 9 because the remainder of 4279 divided by 10 is 9.
 System.out.println(d); — This line prints the value of d. In the first iteration, it will print 9.
 n = n / 100; — This line performs integer division of n by 100. In the first iteration, n becomes 42.
(Remember, it is integer division so only quotient is taken and fractional part is discarded.)

The loop continues, and in the second iteration:

 d = n % 10; — d will now be 2 because the remainder of 42 divided by 10 is 2.


 System.out.println(d); — It prints 2.
 n = n / 100; — n becomes 0 because 42 divided by 100 is 0. Since n is no longer greater than 0, the
loop terminates.

Question 2(vii)

Give the output of the following String class methods:


(a) "COMMENCEMENT".lastIndexOf('M')

(b) "devote".compareTo("DEVOTE")

Answer

(a) "COMMENCEMENT".lastIndexOf('M')

Output

Explanation

The lastIndexOf('M') method searches for the last occurrence of the character 'M' in the string
"COMMENCEMENT." In this string, the last 'M' appears at the index 8, counting from 0-based indexing. So,
the method returns the index 8 as the output, indicating the position of the last 'M' in the string.
(b) "devote".compareTo("DEVOTE")

Output

32

Explanation

compareTo() method compares two strings lexicographically. It results in the difference of the ASCII codes of
the corresponding characters. The ASCII code for 'd' is 100 and the ASCII code for 'D' is 68. The difference
between their codes is 32 (100 - 68).

Question 2(viii)

Consider the given array and answer the questions given below:

int x[ ] = {4, 7, 9, 66, 72, 0, 16};

(a) What is the length of the array?

(b) What is the value in x[4]?

Answer

(a) 7

(b) 72

Question 2(ix)

Name the following:

(a) What is an instance of the class called?

(b) The method which has same name as that of the class name.
Answer

(a) Object.

(b) Constructor.

Question 2(x)

Write the value of n after execution:

char ch ='d';
int n = ch + 5;
Answer

The value of n is 105.

Explanation

1. char ch = 'd'; assigns the character 'd' to the variable ch. In ASCII, the character 'd' has a decimal
value of 100.
2. int n = ch + 5; adds 5 to the ASCII value of 'd', which is 100. So, 100 + 5 equals 105.

Therefore, the value of n will be 105.


Section B

Question 3

Design a class with the following specifications:

Class name: Student

Member variables:
name — name of student
age — age of student
mks — marks obtained
stream — stream allocated

(Declare the variables using appropriate data types)

Member methods:
void accept() — Accept name, age and marks using methods of Scanner class.
void allocation() — Allocate the stream as per following criteria:

mks stream

>= 300 Science and Computer

>= 200 and < 300 Commerce and Computer


mks stream

>= 75 and < 200 Arts and Animation

< 75 Try Again

void print() – Display student name, age, mks and stream allocated.

Call all the above methods in main method using an object.

import java.util.Scanner;

public class Student


{
private String name;
private int age;
private double mks;
private String stream;

public void accept()


{
Scanner in = new Scanner(System.in);
System.out.print("Enter student name: ");
name = in.nextLine();
System.out.print("Enter age: ");
age = in.nextInt();
System.out.print("Enter marks: ");
mks = in.nextDouble();
}

public void allocation()


{
if (mks < 75)
stream = "Try again";
else if (mks < 200)
stream = "Arts and Animation";
else if (mks < 300)
stream = "Commerce and Computer";
else
stream = "Science and Computer";
}

public void print()


{
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Marks: " + mks);
System.out.println("Stream allocated: " + stream);
}
public static void main(String args[]) {
Student obj = new Student();
obj.accept();
obj.allocation();
obj.print();
}
}

Output

Question 4

Define a class to accept 10 characters from a user. Using bubble sort technique arrange them in ascending order.
Display the sorted array and original array.

import java.util.Scanner;

public class KboatCharBubbleSort


{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
char ch[] = new char[10];
System.out.println("Enter 10 characters:");
for (int i = 0; i < ch.length; i++) {
ch[i] = in.nextLine().charAt(0);
}
System.out.println("Original Array");
for (int i = 0; i < ch.length; i++) {
System.out.print(ch[i] + " ");
}

//Bubble Sort
for (int i = 0; i < ch.length - 1; i++) {
for (int j = 0; j < ch.length - 1 - i; j++) {
if (ch[j] > (ch[j + 1])) {
char t = ch[j];
ch[j] = ch[j + 1];
ch[j + 1] = t;
}
}
}

System.out.println("\nSorted Array");
for (int i = 0; i < ch.length; i++) {
System.out.print(ch[i] + " ");
}
}
}

Output

Question 5

Define a class to overload the function print as follows:

void print() - to print the following format

1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
void print(int n) - To check whether the number is a lead number. A lead number is the one whose sum of even
digits are equal to sum of odd digits.

e.g. 3669
odd digits sum = 3 + 9 = 12
even digits sum = 6 + 6 = 12
3669 is a lead number.

import java.util.Scanner;

public class KboatMethodOverload


{
public void print()
{
for(int i = 1; i <= 5; i++)
{
for(int j = 1; j <= 4; j++)
{
System.out.print(i + " ");
}
System.out.println();
}
}

public void print(int n)


{
int d = 0;
int evenSum = 0;
int oddSum = 0;
while( n != 0)
{
d = n % 10;
if (d % 2 == 0)
evenSum += d;
else
oddSum += d;
n = n / 10;
}

if(evenSum == oddSum)
System.out.println("Lead number");
else
System.out.println("Not a lead number");
}

public static void main(String args[])


{
KboatMethodOverload obj = new KboatMethodOverload();
Scanner in = new Scanner(System.in);

System.out.println("Pattern: ");
obj.print();

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


int num = in.nextInt();
obj.print(num);
}
}

Output

Question 6

Define a class to accept a String and print the number of digits, alphabets and special characters in the string.

Example:
S = "KAPILDEV@83"
Output:
Number of digits – 2
Number of Alphabets – 8
Number of Special characters – 1

import java.util.Scanner;

public class KboatCount


{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a string:");
String str = in.nextLine();

int len = str.length();

int ac = 0;
int sc = 0;
int dc = 0;
char ch;

for (int i = 0; i < len; i++) {


ch = str.charAt(i);
if (Character.isLetter(ch))
ac++;
else if (Character.isDigit(ch))
dc++;
else if (!Character.isWhitespace(ch))
sc++;
}

System.out.println("No. of Digits = " + dc);


System.out.println("No. of Alphabets = " + ac);
System.out.println("No. of Special Characters = " + sc);

}
}

Output
Question 7

Define a class to accept values into an array of double data type of size 20. Accept a double value from user and
search in the array using linear search method. If value is found display message "Found" with its position
where it is present in the array. Otherwise display message "not found".

import java.util.Scanner;

public class KboatLinearSearch


{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);

double arr[] = new double[20];


int l = arr.length;
int i = 0;

System.out.println("Enter array elements: ");


for (i = 0; i < l; i++)
{
arr[i] = in.nextDouble();
}

System.out.print("Enter the number to search: ");


double n = in.nextDouble();

for (i = 0; i < l; i++)


{
if (arr[i] == n)
{
break;
}
}

if (i == l)
{
System.out.println("Not found");
}
else
{
System.out.println(n + " found at index " + i);
}
}
}

Output
Question 8

Define a class to accept values in integer array of size 10. Find sum of one digit number and sum of two digit
numbers entered. Display them separately.

Example:
Input: a[ ] = {2, 12, 4, 9, 18, 25, 3, 32, 20, 1}
Output:
Sum of one digit numbers : 2 + 4 + 9 + 3 + 1 = 19
Sum of two digit numbers : 12 + 18 + 25 + 32 + 20 = 107

import java.util.Scanner;

public class KboatDigitSum


{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int oneSum = 0, twoSum = 0, d = 0;
int arr[] = new int[10];
System.out.println("Enter 10 numbers");
int l = arr.length;

for (int i = 0; i < l; i++)


{
arr[i] = in.nextInt();
}

for (int i = 0; i < l; i++)


{
if(arr[i] >= 0 && arr[i] < 10 )
oneSum += arr[i];
else if(arr[i] >= 10 && arr[i] < 100 )
twoSum += arr[i];
}

System.out.println("Sum of 1 digit numbers = "+ oneSum);


System.out.println("Sum of 2 digit numbers = "+ twoSum);

}
}

Output
2024
Section A

Question 1(i)

Name the feature of java depicted in the below picture.

1. Encapsulation
2. Inheritance
3. Abstraction
4. Polymorphism

Answer

Inheritance

Reason — The given picture shows the relationship of a parent (father) and child. Just like a child inherits some
characteristics from his parents, inheritance enables new classes (derived class) to receive or inherit the
properties and methods of existing classes (base class).

Question 1(ii)

The expression which uses >= operator is known as:

1. relational
2. logical
3. arithmetic
4. assignment

Answer

relational

Reason — Relational expressions are constructed using relational operators — equal to ( == ), not equal to ( !=
), less than ( < ), less than equal to ( <= ), greater than ( > ), greater than equal to ( >= )

Question 1(iii)

Ternary operator is a:

1. logical operator
2. arithmetic operator
3. relational operator
4. conditional operator

Answer

conditional operator

Reason — Ternary operator is a conditional operator as it evaluates the given condition. Its syntax is as
follows:

condition? expression 1 : expression 2


If the condition is true then result of ternary operator is the value of expression 1. Otherwise the result is the
value of expression 2.

Question 1(iv)

When primitive data type is converted to a corresponding object of its class, it is called:

1. Boxing
2. Unboxing
3. explicit type conversion
4. implicit type conversion

Answer

Boxing

Reason — Boxing is the conversion of primitive data type into an object of its corresponding wrapper class.

Question 1(v)

The number of bytes occupied by a character array of 10 elements.

1. 20 bytes
2. 60 bytes
3. 40 bytes
4. 120 bytes

Answer

20 bytes

Reason — A char data type occupies '2' bytes in the memory. Thus, 10 char type elements occupy (10 x 2) = 20
bytes in memory.

Question 1(vi)

The method of Scanner class used to accept a double value is:

1. nextInt()
2. nextDouble()
3. next()
4. nextInteger()

Answer

nextDouble()

Reason — The nextDouble() function reads the next token entered by the user as a double value.

Question 1(vii)

Among the following which is a keyword:

1. every
2. all
3. case
4. each

Answer

case

Reason — case is a keyword. It is used to define switch case construct.

Question 1(viii)

The output of Math.round(6.6) + Math.ceil(3.4) is:

1. 9.0
2. 11.0
3. 10.0
4. 11

Answer

11.0

Reason — The given expression is evaluated as follows:


Math.round(6.6) + Math.ceil(3.4)
⇒ 7 + 4.0
⇒ 11.0

Math.round() rounds off its argument to the nearest mathematical integer and returns its value as an int or long
type. Math.ceil method returns the smallest double value that is greater than or equal to the argument and is
equal to a mathematical integer. In the addition operation, the type of result is promoted to a double as one
operand is double. Hence, the result is 11.0.

Question 1(ix)
Name the type of error, if any in the following statement:

System.out.print("HELLO")

1. logical
2. no error
3. runtime
4. syntax

Answer

syntax

Reason — The given statement is missing a terminator ( ; ) at the end. Thus, it has a syntax error.

Question 1(x)

Java statement to access the 5th element of an array is:

1. X[4]
2. X[5]
3. X[3]
4. X[0]

Answer

X[4]

Reason — Array indexes start from 0. So, X[4] refers to the 5th element of the array.

Question 1(xi)

The output of "Remarkable".substring(6) is:

1. mark
2. emark
3. marka
4. able

Answer

able

Reason — "Remarkable".substring(6) will extract a substring starting from the character at index 6 (i.e.,
7th character of the string) which is 'a' till the end of the string. Hence the output is able.

Question 1(xii)

Which of the following is the wrapper class for the data type char?
1. String
2. Char
3. Character
4. Float

Answer

Character

Reason — Character is the wrapper class for the data type char.

Question 1(xiii)

Name the package that contains wrapper classes:

1. java.lang
2. java.util
3. java.io
4. java.awt

Answer

java.lang

Reason — Wrapper classes are present in java.lang package.

Question 1(xiv)

Constructor overloading follows which principle of Object Oriented programming?

1. Inheritance
2. Polymorphism
3. Abstraction
4. Encapsulation

Answer

Polymorphism

Reason — In object-oriented programming, Polymorphism provides the means to perform a single action in
multiple different ways and constructor overloading follows Polymorphism principle of Object Oriented
programming wherein a constructor having the same name behaves differently with different arguments.

Question 1(xv)

Which of the following is a valid Integer constant:


i. 4
ii. 4.0
iii. 4.3f
iv. "four"
1. Only i
2. i and iii
3. ii and iv
4. i and ii

Answer

Only i

Reason — Integer constants represent whole number values only. Thus, 4 is an integer constant. 4.0 is a double
constant, 4.3f is a float constant while "four" is a String constant.

Question 1(xvi)

The method compareTo() returns ............... when two strings are equal and in lowercase :

1. true
2. 0
3. 1
4. false

Answer

Reason — compareTo() method compares two strings lexicographically and returns the difference between the
ASCII values of the first differing characters in the strings. Here, the strings are equal so the difference is 0.

Question 1(xvii)

Assertion (A): In Java, statements written in lower case letter or upper case letter are treated as the same.

Reason (R): Java is a case sensitive language.

1. Both Assertion (A) and Reason (R) are true and Reason (R) is a correct explanation of Assertion (A)
2. Both Assertion (A) and Reason (R) are true and Reason (R) is not a correct explanation of Assertion (A)
3. Assertion (A) is true and Reason (R) is false
4. Assertion (A) is false and Reason (R) is true

Answer

Assertion (A) is false and Reason (R) is true

Reason — In Java, statements written in lower case letter or upper case letter are treated differently as Java is a
case sensitive language.

Question 1(xviii)

Read the following text, and choose the correct answer:


A class encapsulate Data Members that contains the information necessary to represent the class and Member
methods that perform operations on the data member.

What does a class encapsulate?

1. Information and operation


2. Data members and Member methods
3. Data members and information
4. Member methods and operation

Answer

Data members and Member methods

Reason — A class encapsulates state and behavior by combining data and functions into a single unit. The state
of an object is represented by its member variables and behaviour is represented by member methods.

Question 1(xix)

Assertion (A): Call by value is known as pure method.

Reason (R): The original value of variable does not change as operation is performed on copied values.

1. Both Assertion (A) and Reason (R) are true and Reason (R) is a correct explanation of Assertion (A)
2. Both Assertion (A) and Reason (R) are true and Reason (R) is not a correct explanation of Assertion (A)
3. Assertion (A) is true and Reason (R) is false
4. Assertion (A) is false and Reason (R) is true

Answer

Both Assertion (A) and Reason (R) are true and Reason (R) is a correct explanation of Assertion (A)

Reason — Call by value is known as pure method as it does not modify the value of original variables. The
original value of variable does not change as operation is performed on copied values.

Question 1(xx)

What will be the output for:

System.out.print(Character.toLowerCase('1'));

1. 0
2. 1
3. A
4. true

Answer

1
Reason — In Java, the Character.toLowerCase(char ch) method is used to convert a given character to its
lowercase equivalent, if one exists. If the character is already in lowercase or there is no lowercase equivalent, it
will return the original character.

Question 2(i)

Write the Java expression for (p + q)2.

Answer
Math.pow((p + q) , 2)

Question 2(ii)

Evaluate the expression when the value of x = 2:

x = x++ + ++x + x
Answer

Output

10

Explanation

Initially, x = 2. The expression is calculated as follows:

x = x++ + ++x + x
x = 2 + ++x + x (x = 3)
x=2+4+x (x = 4)
x=2+4+4 (x = 4)
x = 10

Question 2(iii)

The following code segment should print "You can go out" if you have done your homework (dh) and cleaned
your room (cr). However, the code has errors. Fix the code so that it compiles and runs correctly.

boolean dh = True;
boolean cr= true;
if (dh && cr)
System.out.println("You cannot go out");
else
System.out.println("You can go out");
Answer

The corrected code is as follows:

boolean dh = true;
boolean cr= true;
if (dh && cr)
System.out.println("You can go out");
else
System.out.println("You cannot go out");

Explanation

1. boolean dh = True; — Here, True should be in lowercase as true.


2. println statements of if-else should be interchanged because if both dh (done homework) and cr (cleaned
room) are true then the person can go out.

Question 2(iv)

Sam executes the following program segment and the answer displayed is zero irrespective of any non zero
values are given. Name the error. How the program can be modified to get the correct answer?

void triangle(double b, double h)


{
double a;
a = 1/2 * b * h;
System.out.println("Area=" + a);
}
Answer

Logical error.

Modified program:

void triangle(double b, double h)


{
double a;
a = 1.0/2 * b * h;
System.out.println("Area=" + a);
}

Explanation

The statement is evaluated as follows:

a = 1/2 * b * h;
a = 0 * b * h; (1/2 being integer division gives the result as 0)
a = 0 (Since anything multiplied by 0 will be 0)

To avoid this error, we can replace '1/2' with '1.0/2'. Now the expression will be evaluated as follows:

a = 1.0/2 * b * h;
a = 0.5 * b * h; (The floating-point division will result in result as as 0.5)

This will give the correct result for the given code.

Question 2(v)
How many times will the following loop execute? What value will be returned?

int x = 2;
int y = 50;
do{
++x;
y -= x++;
}
while(x <= 10);
return y;
Answer

The loop will execute 5 times and the value returned is 15.

Explanation

Iteration X Y Remark

2 50 Initial values

1 3 47 x = 4 (3 + 1), y = 47 (50 - 3)

2 5 42 x = 6 (5 + 1), y = 42 (47 - 5)

3 7 35 x = 8 (7 + 1), y = 35 (42 - 7)

4 9 26 x = 10 (8 + 1), y = 26 (35 - 9)

5 11 15 x = 12 (11 + 1), y = 15 (26 - 11)

11 15 Condition becomes false. Loop terminates.

Question 2(vi)

Write the output of the following String methods:

(a) "ARTIFICIAL".indexOf('I')

(b) "DOG and PUPPY".trim().length()

Answer

(a)

Output
3

Explanation

indexOf() returns the index of the first occurrence of the specified character within the string or -1 if the
character is not present. First occurrence of 'I' in "ARTIFICIAL" is at index 3 (a string begins at index 0).

(b)

Output

13

Explanation

trim() removes all leading and trailing space from the string and length() returns the length of the string i.e., the
number of characters present in the string. Thus, the output is 13.

Question 2(vii)

Name any two jump statements.

Answer

Two jump statements are:

1. break statement
2. continue statement

Question 2(viii)

Predict the output of the following code snippet:

String a = "20";
String b = "23";
int p = Integer.parseInt(a);
int q = Integer.parseInt(b);
System.out.print(a + "*" + b);
Answer

Output

20*23

Explanation

Integer.parseInt() method will convert the strings a and b to their corresponding numerical integers — 20 and
23. In the statement, System.out.print(a + "*" + b); a, b, and "*" are strings so + operator concatenates them
and prints 20*23 as the output.
Question 2(ix)

When there is no explicit initialization, what are the default values set for variables in the following cases?

(a) Integer variable

(b) String variable

Answer

(a) 0

(b) null

Question 2(x)

int P[ ] = {12, 14, 16, 18};


int Q[ ] = {20, 22, 24};

Place all elements of P array and Q array in the array R one after the other.

(a) What will be the size of array R[ ] ?

(b) Write index position of first and last element?

Answer

int R[ ] = {12, 14, 16, 18, 20, 22, 24};

(a) Size of array P[ ] = 4


Size of array Q[ ] = 3
Size of array R[ ] = 7 (4 + 3).

(b) Index position of first element is 0.


Index position of last element is 6.

Section B

Question 3

Define a class called with the following specifications:

Class name: Eshop

Member variables:
String name: name of the item purchased
double price: Price of the item purchased

Member methods:
void accept(): Accept the name and the price of the item using the methods of Scanner class.
void calculate(): To calculate the net amount to be paid by a customer, based on the following criteria:
Price Discount

1000 – 25000 5.0%

25001 – 57000 7.5 %

57001 – 100000 10.0%

More than 100000 15.0 %

void display(): To display the name of the item and the net amount to be paid.

Write the main method to create an object and call the above methods.

import java.util.Scanner;
public class Eshop
{
private String name;
private double price;
private double disc;
private double amount;

public void accept() {


Scanner in = new Scanner(System.in);
System.out.print("Enter item name: ");
name = in.nextLine();
System.out.print("Enter price of item: ");
price = in.nextDouble();
}

public void calculate() {


double d = 0.0;

if (price < 1000)


d = 0.0;
else if (price <= 25000)
d = 5.0;
else if (price <= 57000)
d = 7.5;
else if (price <= 100000)
d = 10.0;
else
d = 15.0;

disc = price * d / 100.0;


amount = price - disc;

}
public void display() {
System.out.println("Item Name: " + name);
System.out.println("Net Amount: " + amount);
}

public static void main(String args[]) {


Eshop obj = new Eshop();
obj.accept();
obj.calculate();
obj.display();
}
}

Output

Question 4

Define a class to accept values in integer array of size 10. Sort them in an ascending order using selection sort
technique. Display the sorted array.

import java.util.Scanner;

public class KboatSelectionSort


{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int arr[] = new int[10];
System.out.println("Enter 10 integers: ");
for (int i = 0; i < 10; i++)
{
arr[i] = in.nextInt();
}

for (int i = 0; i < 9; i++)


{
int idx = i;
for (int j = i + 1; j < 10; j++)
{
if (arr[j] < arr[idx])
idx = j;
}

int t = arr[i];
arr[i] = arr[idx];
arr[idx] = t;
}

System.out.println("Sorted Array:");
for (int i = 0; i < 10; i++)
{
System.out.print(arr[i] + " ");
}
}
}

Output
Question 5

Define a class to accept a string and convert it into uppercase. Count and display the number of vowels in it.

Input: robotics
Output: ROBOTICS
Number of vowels: 3

import java.util.Scanner;

public class KboatCountVowels


{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter the string: ");
String str = in.nextLine();
str = str.toUpperCase();
str += " ";
int count = 0;
int len = str.length();

for (int i = 0; i < len - 1; i++)


{
char ch = str.charAt(i);
if(ch == 'A'
|| ch == 'E'
|| ch == 'I'
|| ch == 'O'
|| ch == 'U')
count++;
}

System.out.println("String : " + str);


System.out.println("Number of vowels : " + count);
}
}

Output

Question 6

Define a class to accept values into a 3 × 3 array and check if it is a special array. An array is a special array if
the sum of the even elements = sum of the odd elements.

Example:
A[ ][ ]={{ 4 ,5, 6}, { 5 ,3, 2}, { 4, 2, 5}};
Sum of even elements = 4 + 6 + 2 + 4 + 2 = 18
Sum of odd elements = 5 + 5 + 3 + 5 = 18
import java.util.Scanner;

public class KboatDDASpArr


{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int arr[][] = new int[3][3];
long evenSum = 0, oddSum = 0;
System.out.println("Enter the elements of 3 x 3 DDA: ");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
arr[i][j] = in.nextInt();
}
}

for (int i = 0; i < 3; i++) {


for (int j = 0; j < 3; j++) {
if (arr[i][j] % 2 == 0)
evenSum += arr[i][j];
else
oddSum += arr[i][j];
}
}

System.out.println("Sum of even elements = " + evenSum);


System.out.println("Sum of odd elements = " + oddSum);
if (evenSum == oddSum)
System.out.println("Special Array");
else
System.out.println("Not a Special Array");
}
}

Output
Question 7

Define a class to accept a 3 digit number and check whether it is a duck number or not.
Note: A number is a duck number if it has zero in it.

Example 1:
Input: 2083
Output: Invalid

Example 2:
Input: 103
Output: Duck number

import java.util.Scanner;

public class KboatDuckNumber


{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = in.nextInt();
int n = num;
int count = 0;

while (n != 0) {
count++;
n = n / 10;
}

if (count == 3)
{
n = num;
boolean isDuck = false;
while(n != 0)
{
if(n % 10 == 0)
{
isDuck = true;
break;
}
n = n / 10;
}

if (isDuck) {
System.out.println("Duck Number");
}
else {
System.out.println("Not a Duck Number");
}
}
else {
System.out.println("Invalid");
}
}
}

Output
Question 8

Define a class to overload the method display as follows:

void display( ): To print the following format using nested loop

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
void display(int n): To print the square root of each digit of the given number.

Example:
n = 4329
Output – 3.0
1.414213562
1.732050808
2.0

import java.util.Scanner;

public class KboatMethodOverload


{
public void display()
{
for(int i = 1; i <= 5; i++)
{
for(int j = 1; j <= i; j++)
{
System.out.print(j + " ");
}
System.out.println();
}
}

public void display(int n)


{
while( n != 0)
{
int d = n % 10;
System.out.println(Math.sqrt(d));
n = n / 10;
}
}

public static void main(String args[])


{
KboatMethodOverload obj = new KboatMethodOverload();
Scanner in = new Scanner(System.in);

System.out.println("Pattern: ");
obj.display();

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


int num = in.nextInt();
obj.display(num);

}
}

Output

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy