0% found this document useful (0 votes)
130 views163 pages

Short Questions

Uploaded by

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

Short Questions

Uploaded by

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

SHORT QUESTIONS

(ii) Which statement will be executed depend upon (ii) Which statement will be executed is decided b
the output of the expression inside if statement. user.

(b) 2019
(c) Syntax error, Runtime error, Logical error
(d) boolean
True

(e)

Linear Search Binary Search

(i) Linear search works both for sorted and unsorted (i) Binary search works on sorted data (either in
data. ascending order or in descending order).

(ii) Linear search begins at the start of an array i.e. (ii) This technique divides the array in two halves
at 0th position. and the desired data item is searched in the halv

Question 3.
(a) Write a Java expression for the following : [2]
|x2+2xy|
(b) Write the return data type of the following functions : [2]
(i) startsWith( )
(ii) random( )
(r) If the value of basic=1500, what will be the value of tax after the following statement
is executed? [2]
tax = basic > 1200 ? 200 : 100;
id) Give the output of following code and mention how many times the loop will
execute ? [2]
int i;
for(i=5; i> =l;i~)
{
if(i%2 ==1)
continue;
System.out.print(i+ ”
}
(e) State a difference between call by value and call by reference. [2]
(f) Give the output of the following: [2]
Math.sqrt(Math.max(9, 16))
(g) Write the output for the following: [2]
String s1 = “phoenix”; String s2 =”

island”;
System.out.prindn (s1.substring(0).concat (s2.substring(2)));
System.out.println(s2.toUpperCase( ));
(h) Evaluate the following expression if the value ofx=2,y=3 and z=1. [2]
v=x+–z+y+ + +y
(i) String x[ ] = {“Artificial intelligence”, “IOT”, “Machine learning”, “Big data”}; [2]
Give the output of the following statements:

(i) System.out.prindn(x[3]);
(ii) System.out.prindn(x.length);
(j) What is meant by a package? Give an example. [2]
Solution................................................
(a) Math.abs((x * x) + (2 * x * y);
(b) (i) boolean
(ii) double
(c) 200
(d) 4 2
Loop will execute 5 times.

(e)

Call by Value Call by Reference

(i) In call by value the method creates its new set of (i) In call by reference, reference of the actual
variables (formal parameters) to copy the value of parameters is passed on to the method. No new
actual parameters and works with them. of variables is created.

(ii) Any change made in the formal parameter is not (ii) Any change made in the formal parameter is
reflected in the actual parameter. always reflected in the actual parameters.

(iii) Reference types like (objects, array etc.) are


(iii) Primitive data types are passed by call by value.
passed by call by reference.

(f) 4.0
(g) phoenix land
ISLAND

(h) = 2 + 0 + 3 + 4
(i) (i) Big data
(ii) 4
(j) A package is an organized collection of classes which is included in the program as
per the requirement of the program. For example java.io package is included for input
and output operations in a program. Question 1.
(a) Name any two basic principles of Object-oriented Programming.
(b) Write a difference between unary and binary operator.
(c) Name the keyword which :
(i) indicates that a method has no return type.
(ii) makes the variable as a class variable.
(d) Write the memory capacity (storage size) of short and float data type in bytes.
(e) Identify and name the following tokens :
(i) public
(ii) ‘a’
(iii) ==
(iv) {}
Solution................................................
(a) Abstraction and encapsulation are the basic principles of Object-oriented
Programming.
(b)

Unary Operators Binary Operators

(i) The operators which act upon a single operand (i) The operators which require two operands for
are called unary operators. their action are called binary operators.

(ii) They are mathematical operators and relation


(ii) They are pre-increment and post increment (+ +)
operators.

(c)
(i) void
(ii) static

(d) (i) short: 2 bytes


(ii) float: 4 bytes
(e) (i) keyword
(ii) literal
(iii) operator
(iv) separator

Question 2.
(a) Differentiate between if else if and switch-case statements. [2]
(b) Give the output of the following code : [2]
String P = “20”, Q = “19”,
int a = Integer .parselnt(P);
int b = Integer. valueOf(Q);
System.out.println(a+””+b);
(c) What are the various types of errors in Java ? [2]
(d) State the data type and value of res after the following is executed : [2]
char ch = ‘9’;
res = Character. isDigit(ch) ;
(e) What is the difference between the linear search and the binary search technique?
[2]
Solution................................................
(a)

if else if switch-case

(i) It evaluates integer, character, pointer or floating-


(i) It evaluates only character or integer value.
point type or boolean type.

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 in Sorting means to arrange the elements of the array in
an array. ascending or descending order.

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

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

Answer

isUpperCase( ) toUpperCase( )

isUpperCase( ) function checks if a given character is in toUpperCase( ) function converts a given character to
uppercase or not. 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 It is suitable when we need to display a


iterations are not known. menu 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:

3�+�2�+�a+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:

⇒ 68 - 86
ASCII code of D - ASCII code of V

⇒ -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

outside the loop is executed and prints the output as 20 (i * 4 ⇒ 5 * 4 ⇒ 20).


so System.out.println( i ); is not executed but System.out.println( i * 4 ); being

(a) What is inheritance?

Answer

Inheritance is the mechanism by which a class acquires the properties and methods of another
class.

(b) Name the operators listed below:

1. <
2. ++
3. &&
4. ?:

Answer

1. Less than operator. (It is a relational operator)


2. Increment operator. (It is an arithmetic operator)
3. Logical AND operator. (It is a logical operator)
4. Ternary operator. (It is a conditional operator)

(c) State the number of bytes occupied by char and int data types.

Answer

char occupies 2 bytes and int occupies 4 bytes.


(d) Write one difference between / and % operator.

Answer

/ operator computes the quotient whereas % operator computes the remainder.

(e) String x[] = {"SAMSUNG", "NOKIA", "SONY", "MICROMAX", "BLACKBERRY"};

Give the output of the following statements:

1. System.out.println(x[1]);
2. System.out.println(x[3].length());

Answer

1. The output of System.out.println(x[1]); is NOKIA. x[1] gives the second element


of the array x which is "NOKIA"
2. The output of System.out.println(x[3].length()); is 8. x[3].length() gives the
number of characters in the fourth element of the array x which is MICROMAX.

Question 2

(a) Name the following:

1. A keyword used to call a package in the program.


2. Any one reference data type.

Answer

1. import
2. Array

(b) What are the two ways of invoking functions?

Answer

Call by value and call by reference.

(c) State the data type and value of res after the following is executed:

char ch='t';
res= Character.toUpperCase(ch);
Answer

Data type of res is char and its value is T.

(d) Give the output of the following program segment and also mention the number of times
the loop is executed:

int a,b;
for (a = 6, b = 4; a <= 24; a = a + 6)
{
if (a%b == 0)
break;
}
System.out.println(a);
Answer

Output of the above code is 12 and loop executes 2 times.

Explanation

This dry run explains the working of the loop.

a b Remarks

6 4 1st Iteration

12 4 2nd Iteration

In 2nd iteration, as a%b becomes 0 so break statement is executed and the loop exits. Program
control comes to the println statement which prints the output as current value of a which is 12.

(e) Write the output:

char ch = 'F';
int m = ch;
m=m+5;
System.out.println(m + " " + ch);
Answer

Output of the above code is:

75 F

Explanation

The statement int m = ch; assigns the ASCII value of F (which is 70) to variable m. Adding 5 to
m makes it 75. In the println statement, the current value of m which is 75 is printed followed by
space and then value of ch which is F.

Question 3

(a) Write a Java expression for the following:


ax5 + bx3 + c

Answer
a * Math.pow(x, 5) + b * Math.pow(x, 3) + c

(b) What is the value of x1 if x=5?


x1= ++x – x++ + --x

Answer

⇒ x1 = 6 - 6 + 6
x1 = ++x – x++ + --x

⇒ x1 = 0 + 6
⇒ x1 = 6

(c) Why is an object called an instance of a class?

Answer

A class can create objects of itself with different characteristics and common behaviour. So, we
can say that an Object represents a specific state of the class. For these reasons, an Object is
called an Instance of a Class.

(d) Convert following do-while loop into for loop.

int i = 1;
int d = 5;
do {
d=d*2;
System.out.println(d);
i++ ; } while ( i<=5);
Answer

int i = 1;
int d = 5;
for (i = 1; i <= 5; i++) {
d=d*2;
System.out.println(d);
}
(e) Differentiate between constructor and function.

Answer

Constructor Function

Constructor is a block of code that Function is a group of statements that can be called at any point in the
initializes a newly created object. program using its name to perform a specific task.

Constructor has the same name as class


Function should have a different name than class name.
name.
Constructor Function

Constructor has no return type not even


Function requires a valid return type.
void.

(f) Write the output for the following:

String s="Today is Test";


System.out.println(s.indexOf('T'));
System.out.println(s.substring(0,7) + " " +"Holiday");
Answer

Output of the above code is:

0
Today i Holiday

Explanation

As the first T is present at index 0 in string s so s.indexOf('T') returns 0. s.substring(0,7)


extracts the characters from index 0 to index 6 of string s. So its result is Today i. After that println
statement prints Today i followed by a space and Holiday.
(g) What are the values stored in variables r1 and r2:

1. double r1 = Math.abs(Math.min(-2.83, -5.83));


2. double r2 = Math.sqrt(Math.floor(16.3));

Answer

1. r1 has 5.83
2. r2 has 4.0

Explanation

1. Math.min(-2.83, -5.83) returns -5.83 as -5.83 is less than -2.83. (Note that these are
negative numbers). Math.abs(-5.83) returns 5.83.
2. Math.floor(16.3) returns 16.0. Math.sqrt(16.0) gives square root of 16.0 which is 4.0.

(h) Give the output of the following code:

String A ="26", B="100";


String D=A+B+"200";
int x= Integer.parseInt(A);
int y = Integer.parseInt(B);
int d = x+y;
System.out.println("Result 1 = " + D);
System.out.println("Result 2 = " + d);
Answer

Output of the above code is:

Result 1 = 26100200
Result 2 = 126

Explanation

1. As A and B are strings so String D=A+B+"200"; joins A, B and "200" storing the
string "26100200" in D.
2. Integer.parseInt() converts strings A and B into their respective numeric values. Thus, x
becomes 26 and y becomes 100.
3. As Java is case-sensitive so D and d are treated as two different variables.
4. Sum of x and y is assigned to d. Thus, d gets a value of 126.

(i) Analyze the given program segment and answer the following questions:

for(int i=3;i<=4;i++ ) {
for(int j=2;j<i;j++ ) {
System.out.print("" ); }
System.out.println("WIN" ); }

1. How many times does the inner loop execute?


2. Write the output of the program segment.

Answer

1. Inner loop executes 3 times.


(For 1st iteration of outer loop, inner loop executes once. For 2 nd iteration of outer loop,
inner loop executes two times.)
2. Output:
WIN
WIN

(j) What is the difference between the Scanner class functions next() and nextLine()?

Answer

next() nextLine()

It reads the input only till space so it can read It reads the input till the end of line so it can read a full
only a single word. sentence including spaces.

It places the cursor in the same line after reading


It places the cursor in the next line after reading the input.
the input.
(a) Define Encapsulation.

Answer

Encapsulation is a mechanism that binds together code and the data it manipulates. It keeps them
both safe from the outside world, preventing any unauthorised access or misuse. Only member
methods, which are wrapped inside the class, can access the data and other methods.

(b) What are keywords ? Give an example.

Answer

Keywords are reserved words that have a special meaning to the Java compiler. Example: class,
public, int, etc.

(c) Name any two library packages.

Answer

Two library packages are:

1. java.io
2. java.util

(d) Name the type of error ( syntax, runtime or logical error) in each case given below:

1. Math.sqrt (36 – 45)


2. int a;b;c;

Answer

1. Runtime Error
2. Syntax Error

(e) If int x[] = { 4, 3, 7, 8, 9, 10}; what are the values of p and q ?

1. p = x.length
2. q = x[2] + x[5] * x[1]

Answer

1. 6
2. q = x[2] + x[5] * x[1]
q = 7 + 10 * 3
q = 7 + 30
q = 37

Question 2

(a) State the difference between == operator and equals() method.

Answer

equals() ==

It is a method It is a relational operator

It is used to check if the contents of two strings are It is used to check if two variables refer to the same object
same or not in memory

Example: Example:
String s1 = new String("hello"); String s1 = new String("hello");
String s2 = new String("hello"); String s2 = new String("hello");
boolean res = s1.equals(s2); boolean res = s1 == s2;
System.out.println(res); System.out.println(res);

The output of this code snippet is true as contents of The output of this code snippet is false as s1 and s2 point
s1 and s2 are the same. to different String objects.

(b) What are the types of casting shown by the following examples:

1. char c = (char) 120;


2. int x = ‘t’;

Answer

1. Explicit Cast.
2. Implicit Cast.

(c) Differentiate between formal parameter and actual parameter.

Answer

Formal parameter Actual parameter

Formal parameters appear in function definition. Actual parameters appear in function call statement.
Formal parameter Actual parameter

They represent the values received by the called They represent the values passed to the called
function. function.

(d) Write a function prototype of the following:


A function PosChar which takes a string argument and a character argument and returns an
integer value.

Answer

int PosChar(String s, char ch)

(e) Name any two types of access specifiers.

Answer

1. public
2. private

Question 3

(a) Give the output of the following string functions:

1. "MISSISSIPPI".indexOf('S') + "MISSISSIPPI".lastIndexOf('I')
2. "CABLE".compareTo("CADET")

Answer

1. 2 + 10 = 12

⇒ 66 - 68
2. ASCII Code of B - ASCII Code of D

⇒ -2

(b) Give the output of the following Math functions:

1. Math.ceil(4.2)
2. Math.abs(-4)

Answer

1. 5.0
2. 4

(c) What is a parameterized constructor ?

Answer
A Parameterised constructor receives parameters at the time of creating an object and initializes
the object with the received values.

(d) Write down java expression for:

�=�2+�2+�2T=A2+B2+C2
Answer

T = Math.sqrt(a*a + b*b + c*c)

(e) Rewrite the following using ternary operator:

if (x%2 == 0)
System.out.print("EVEN");
else
System.out.print("ODD");
Answer

System.out.print(x%2 == 0 ? "EVEN" : "ODD");


(f) Convert the following while loop to the corresponding for loop:

int m = 5, n = 10;
while (n>=1)
{
System.out.println(m*n);
n--;
}
Answer

int m = 5;
for (int n = 10; n >= 1; n--) {
System.out.println(m*n);
}
(g) Write one difference between primitive data types and composite data types.

Answer

Primitive Data Types are built-in data types defined by Java language specification whereas
Composite Data Types are defined by the programmer.

(h) Analyze the given program segment and answer the following questions:

1. Write the output of the program segment.


2. How many times does the body of the loop gets executed ?

for(int m = 5; m <= 20; m += 5)


{ if(m % 3 == 0)
break;
else
if(m % 5 == 0)
System.out.println(m);
continue;
}
Answer

Output

5
10
Loop executes 3 times.

Below dry run of the loop explains its working.

m Output Remarks

5 5 1st Iteration

5
10 2nd Iteration
10

5
15 3rd Iteration — As m % 3 becomes true, break statement exists the loop.
10

(i) Give the output of the following expression:

a+= a++ + ++a + --a + a-- ; when a = 7

Answer

⇒ a = a + (a++ + ++a + --a + a--)


a+= a++ + ++a + --a + a--

⇒ a = 7 + (7 + 9 + 8 + 8)
⇒ a = 7 + 32
⇒ a = 39

(j) Write the return type of the following library functions:

1. isLetterOrDigit(char)
2. replace(char, char)

Answer

1. boolean
2. String
Question 1

(a) What are the default values of the primitive data type int and float?

Answer

Default value of int is 0 and float is 0.0f.

(b) Name any two OOP’s principles.

Answer

1. Encapsulation
2. Inheritance

(c) What are identifiers ?

Answer

Identifiers are symbolic names given to different parts of a program such as variables, methods,
classes, objects, etc.

(d) Identify the literals listed below:

(i) 0.5 (ii) 'A' (iii) false (iv) "a"

Answer

1. Real Literal
2. Character Literal
3. Boolean Literal
4. String Literal

(e) Name the wrapper classes of char type and boolean type.

Answer

Wrapper class of char type is Character and boolean type is Boolean.

Question 2

(a) Evaluate the value of n if value of p = 5, q = 19

int n = (q – p) > (p – q) ? (q – p) : (p – q);


Answer

⇒ int n = (19 - 5) > (5 - 19) ? (19 - 5) : (5 - 19)


int n = (q – p) > (p – q) ? (q – p) : (p – q)

⇒ int n = 14 > -14 ? 14 : -14


⇒ int n = 14 [∵ 14 > -14 is true so ? : returns 14]

Final value of n is 14

(b) Arrange the following primitive data types in an ascending order of their size:

(i) char (ii) byte (iii) double (iv) int

Answer

byte, char, int, double

(c) What is the value stored in variable res given below:

double res = Math.pow ("345".indexOf('5'), 3);

Answer

Value of res is 8.0


Index of '5' in "345" is 2. Math.pow(2, 3) means 2 3 which is equal to 8

(d) Name the two types of constructors

Answer

Parameterized constructors and Non-Parameterized constructors.

(e) What are the values of a and b after the following function is executed, if the values
passed are 30 and 50:

void paws(int a, int b)


{
a=a+b;
b=a–b;
a=a–b;
System.out.println(a+ "," +b);
}
Answer

Value of a is 50 and b is 30.


Output of the code is:

50,30
Question 3

(a) State the data type and value of y after the following is executed:

char x='7';
y=Character.isLetter(x);
Answer

Data type of y is boolean and value is false. Character.isLetter() method checks if its argument is a
letter or not and as 7 is a number not a letter hence it returns false.

(b) What is the function of catch block in exception handling ? Where does it appear in a
program ?

Answer

Catch block contains statements that we want to execute in case an exception is thrown in the try
block. Catch block appears immediately after the try block in a program.

(c) State the output when the following program segment is executed:

String a ="Smartphone", b="Graphic Art";


String h=a.substring(2, 5);
String k=b.substring(8).toUpperCase();
System.out.println(h);
System.out.println(k.equalsIgnoreCase(h));
Answer

The output of the above code is:

art
true

Explanation

a.substring(2, 5) extracts the characters of string a starting from index 2 till index 4. So h contains
the string "art". b.substring(8) extracts characters of b from index 8 till the end so it returns "Art".
toUpperCase() converts it into uppercase. Thus string "ART" gets assigned to k. Values of h and k
are "art" and "ART", respectively. As both h and k differ in case only hence equalsIgnoreCase
returns true.

(d) The access specifier that gives the most accessibility is ________ and the least
accessibility is ________.

Answer

The access specifier that gives the most accessibility is public and the least accessibility
is private.

(e) (i) Name the mathematical function which is used to find sine of an angle given in
radians.
(ii) Name a string function which removes the blank spaces provided in the prefix and suffix
of a string.

Answer

(i) Math.sin() (ii) trim()

(f) (i) What will this code print ?

int arr[]=new int[5];


System.out.println(arr);

1. 0
2. value stored in arr[0]
3. 0000
4. garbage value

Answer

This code will print garbage value

(ii) Name the keyword which is used- to resolve the conflict between method parameter and
instance variables/fields.

Answer

this keyword

(g) State the package that contains the class:

1. BufferedReader
2. Scanner

Answer

1. java.io
2. java.util

(h) Write the output of the following program code:

char ch ;
int x=97;
do
{
ch=(char)x;
System.out.print(ch + " " );
if(x%10 == 0)
break;
++x;
} while(x<=100);
Answer
The output of the above code is:

a b c d

Explanation

The below table shows the dry run of the program:

x ch Output Remarks

97 a a 1st Iteration

98 b ab 2nd Iteration

99 c abc 3rd Iteration

100 d abcd 4th Iteration — As x%10 becomes true, break statement is executed and exists the loop.

(i) Write the Java expressions for:

�2+�22��2aba2+b2
Answer

(a * a + b * b) / (2 * a * b)

(j) If int y = 10 then find int z = (++y * (y++ + 5));

Answer

⇒ z = (11 * (11 + 5))


z = (++y * (y++ + 5))

⇒ z = (11 * 16)
⇒ z = 176

(a) Which of the following are valid comments ?

1. /*comment*/
2. /*comment
3. //comment
4. */comment*/

Answer

The valid comments are:

Option 1 — /*comment*/
Option 3 — //comment

(b) What is meant by a package ? Name any two java Application Programming Interface
packages.

Answer

A package is a named collection of Java classes that are grouped on the basis of their
functionality. Two java Application Programming Interface packages are:

1. java.util
2. java.io

(c) Name the primitive data type in Java that is:

1. a 64-bit integer and is used when you need a range of values wider than those
provided by int.
2. a single 16-bit Unicode character whose default value is '\u0000'.

Answer

1. long
2. char

(d) State one difference between the floating point literals float and double.

Answer

float literals double literals

float literals have a size of 32 bits so they can store a


double literals have a size of 64 bits so they can store a
fractional number with around 6-7 total digits of
fractional number with 15-16 total digits of precision.
precision.

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

int a = new int (5);


for (int i=0; i<=5; i++) a[i]=i;
Answer

Corrected Code:
int a[] = new int[5];
for (int i = 0; i < 5; i++)
a[i] = i;

Question 2

(a) Operators with higher precedence are evaluated before operators with relatively lower
precedence. Arrange the operators given below in order of higher precedence to lower
precedence:

1. &&
2. %
3. >=
4. ++

Answer

++
%
>=
&&

(b) Identify the statements listed below as assignment, increment, method invocation or
object creation statements.

1. System.out.println("Java");
2. costPrice = 457.50;
3. Car hybrid = new Car();
4. petrolPrice++;

Answer

1. Method Invocation
2. Assignment
3. Object Creation
4. Increment

(c) Give two differences between the switch statement and the if-else statement

Answer

switch if-else

switch can only test if the expression is equal to if-else can test for any boolean expression like less than, greater
any of its case constants than, equal to, not equal to, etc.
switch if-else

It is a multiple branching flow of control


It is a bi-directional flow of control statement
statement

(d) What is an infinite loop? Write an infinite loop statement.

Answer

A loop which continues iterating indefinitely and never stops is termed as infinite loop. Below is an
example of infinite loop:

for (;;)
System.out.println("Infinite Loop");
(e) What is constructor? When is it invoked?

Answer

A constructor is a member method that is written with the same name as the class name and is
used to initialize the data members or instance variables. A constructor does not have a return
type. It is invoked at the time of creating any object of the class.

Question 3

(a) List the variables from those given below that are composite data types:

1. static int x;
2. arr[i]=10;
3. obj.display();
4. boolean b;
5. private char chr;
6. String str;

Answer

The composite data types are:

 arr[i]=10;
 obj.display();
 String str;

(b) State the output of the following program segment:

String str1 = "great"; String str2 = "minds";


System.out.println(str1.substring(0,2).concat(str2.substring(1)
));
System.out.println(("WH" + (str1.substring(2).toUpperCase())));
Answer

The output of the above code is:

grinds
WHEAT
Explanation:

1. str1.substring(0,2) returns "gr". str2.substring(1) returns "inds". Due to concat both are
joined together to give the output as "grinds".
2. str1.substring(2) returns "eat". It is converted to uppercase and joined to "WH" to give the
output as "WHEAT".

(c) What are the final values stored in variable x and y below?

double a = -6.35;
double b = 14.74;
double x = Math.abs(Math.ceil(a));
double y = Math.rint(Math.max(a,b));
Answer

The final value stored in variable x is 6.0 and y is 15.0.

Explanation:

1. Math.ceil(a) gives -6.0 and Math.abs(-6.0) is 6.0.


2. Math.max(a,b) gives 14.74 and Math.rint(14.74) gives 15.0.

(d) Rewrite the following program segment using if-else statements instead of the ternary
operator:

String grade = (marks>=90)?"A": (marks>=80)? "B": "C";

Answer

String grade;
if (marks >= 90)
grade = "A";
else if (marks >= 80)
grade = "B";
else
grade = "C";
(e) Give the output of the following method:

public static void main (String [] args){


int a = 5;
a++;
System.out.println(a);
a -= (a--) - (--a);
System.out.println(a);}
Answer

Output

6
4

Explanation

1. a++ increments value of a by 1 so a becomes 6.

⇒ a = a - ((a--) - (--a))
2. a -= (a--) - (--a)

⇒ a = 6 - (6 - 4)
⇒a=6-2
⇒a=4

(f) What is the data type returned by the library functions :

1. compareTo()
2. equals()

Answer

1. int
2. boolean

(g) State the value of characteristic and mantissa when the following code is executed:

String s = "4.3756";
int n = s.indexOf('.');
int characteristic=Integer.parseInt(s.substring(0,n));
int mantissa=Integer.valueOf(s.substring(n+1));
Answer

The value of characteristic is 4 and mantissa is 3756.

Index of . in String s is 1 so variable n is initialized to 1. s.substring(0,n) gives 4. Integer.parseInt()


converts string "4" into integer 4 and this 4 is assigned to the variable characteristic.

s.substring(n+1) gives 3756 i.e. the string starting at index 2 till the end of s. Integer.valueOf()
converts string "3756" into integer 3756 and this value is assigned to the variable mantissa.

(h) Study the method and answer the given questions.

public void sampleMethod()


{ for (int i=0; i < 3; i++)
{ for (int j = 0; j<2; j++)
{int number = (int)(Math.random() * 10);
System.out.println(number); }}}
1. How many times does the loop execute?
2. What is the range of possible values stored in the variable number?

Answer

1. The loops execute 6 times.


2. The range is from 0 to 9.

(i) Consider the following class:

public class myClass {


public static int x=3, y=4;
public int a=2, b=3;}

1. Name the variables for which each object of the class will have its own distinct copy.
2. Name the variables that are common to all objects of the class.

Answer

1. a, b
2. x, y

(j) What will be the output when the following code segments are executed?

(i)

String s = "1001";
int x = Integer.valueOf(s);
double y = Double.valueOf(s);
System.out.println("x="+x);
System.out.println("y="+y);
(ii)

System.out.println("The king said \"Begin at the beginning!\"


to me.");
Answer

(i) The output of the code is:

x=1001
y=1001.0
(ii) The output of the code is:

The king said "Begin at the beginning!" to me.

(a) What is meant by precedence of operators?


Answer

Precedence of operators refers to the order in which the operators are applied to the operands in
an expression.

(b) What is a literal?

Answer

Literals are data items that are fixed data values. Java provides different types of literals like:

1. Integer Literals
2. Floating-Point Literals
3. Boolean Literals
4. Character Literals
5. String Literals
6. null Literal

(c) State the Java concept that is implemented through:

1. a superclass and a subclass.


2. the act of representing essential features without including background details.

Answer

1. Inheritance
2. Abstraction

(d) Give a difference between a constructor and a method.

Answer

Constructor has the same name as class name whereas function should have a different name
than class name.

(e) What are the types of casting shown by the following examples?

1. double x = 15.2;
int y = (int) x;
2. int x = 12;
long y = x;

Answer

1. Explicit Type Casting


2. Implicit Type Casting

Question 2

(a) Name any two wrapper classes.


Answer

Two wrapper classes are:

1. Integer
2. Character

(b) What is the difference between a break statement and a continue statement when they
occur in a loop?

Answer

When the break statement gets executed, it terminates its loop completely and control reaches to
the statement immediately following the loop. The continue statement terminates only the current
iteration of the loop by skipping rest of the statements in the body of the loop.

(c) Write statements to show how finding the length of a character array char[] differs from
finding the length of a String object str.

Answer

Java code snippet to find length of character array:

char ch[] = {'x', 'y', 'z'};


int len = ch.length
Java code snippet to find length of String object str:

String str = "Test";


int len = str.length();
(d) Name the Java keyword that:

1. indicates that a method has no return type.


2. stores the address of the currently-calling object.

Answer

1. void
2. this

(e) What is an exception?

Answer

An exception is an abnormal condition that arises in a code sequence at run time. Exceptions
indicate to a calling method that an abnormal condition has occurred.

Question 3

(a) Write a Java statement to create an object mp4 of class Digital.

Answer
Digital MP4 = new Digital();
(b) State the values stored in the variables str1 and str2:

String s1 = "good";
String s2 = "world matters";
String str1 = s2.substring(5).replace('t', 'n');
String str2 = s1.concat(str1);
Answer

Value stored in str1 is " manners" and str2 is "good manners". (Note that str1 begins with a space.)

Explanation

s2.substring(5) gives a substring from index 5 till the end of the string which is " matters". The
replace method replaces all 't' in " matters" with 'n' giving " manners". s1.concat(str1) joins
together "good" and " manners" so "good manners" is stored in str2.

(c) What does a class encapsulate?

Answer

A class encapsulates data and behavior.

(d) Rewrite the following program segment using the if..else statement:

comm = (sale > 15000)? sale * 5 / 100 : 0;


Answer

if(sale > 15000)


comm = sale * 5 / 100;
else
comm = 0;
(e) How many times will the following loop execute? What value will be returned?

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

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

(f) What is the data type that the following library functions return?

1. isWhitespace(char ch)
2. Math.random()

Answer
1. boolean
2. double

(g) Write a Java expression for:

��+12��2ut+21ft2
Answer

u * t + 1 / 2.0 * f * t * t

(h) If int n[] = {1, 2, 3, 5, 7, 9, 13, 16}, what are the values of x and y?

x = Math.pow(n[4], n[2]);
y = Math.sqrt(n[5] + n[7]);

Answer

⇒ x = Math.pow(7, 3);
x = Math.pow(n[4], n[2]);

⇒ x = 343.0;

⇒ y = Math.sqrt(9 + 16);
y = Math.sqrt(n[5] + n[7]);

⇒ y = Math.sqrt(25);
⇒ y = 5.0;

(i) What is the final value of ctr when the iteration process given below, executes?

int ctr = 0;
for(int i = 1; i <= 5; i++)
for(int j = 1; j <= 5; j += 2)
++ctr;
Answer

The final value of ctr is 15.

The outer loop executes 5 times. For each iteration of outer loop, the inner loop executes 3 times.
So the statement ++ctr; is executed a total of 5 x 3 = 15 times.

(j) Name the method of Scanner class that:

1. is used to input an integer data from the standard input stream.


2. is used to input a String data from the standard input stream.

Answer

1. nextInt()
2. nextLine()
(a) Give one example each of a primitive data type and a composite data type.

Answer

1. int
2. array

(b) Give one point of difference between unary and binary operators.

Answer

unary operators operate on a single operand whereas binary operators operate on two operands.

(c) Differentiate between call by value or pass by value and call by reference or pass by
reference.

Answer

Call by value Call by reference

Values of actual parameters are copied to formal Reference of actual parameters is passed to formal
parameters. parameters.

Changes made to formal parameters are not reflected Changes made to formal parameters are reflected back
back to actual parameters. to actual parameters.

(d) Write a Java expression for:

2��+�22as+u2
Answer

Math.sqrt(2 * a * s + u * u)

(e) Name the type of error (syntax, runtime or logical error) in each case given below:

1. Division by a variable that contains a value of zero.


2. Multiplication operator used when the operation should be division.
3. Missing semicolon.

Answer

1. Runtime error
2. Logical error
3. syntax error
Question 2

(a) Create a class with one integer instance variable. Initialize the variable using:

1. default constructor
2. parameterized constructor

Answer

class Number {
int a;

public Number() {
a = 0;
}

public Number(int x) {
a = x;
}
}
(b) Complete the code below to create an object of Scanner class:

Scanner sc = ____ Scanner(__________);

Answer

Scanner sc = new Scanner(System.in);

(c) What is an array? Write a statement to declare an integer array of 10 elements.

Answer

An array is a structure to store a number of values of the same data type in contiguous memory
locations. The following statement declares an integer array of 10 elements:

int arr[] = new int[10];

(d) Name the search or sort algorithm that:

1. Makes several passes through the array, selecting the next smallest item in the array
each time and placing it where it belongs in the array.
2. At each stage, compares the sought key value with the key value of the middle
element of the array.

Answer

1. Selection Sort
2. Binary Search

(e) Differentiate between public and private modifiers for members of a class.
Answer

public modifier makes the class members accessible both within and outside their class whereas
private modifier makes the class members accessible only within the class in which they are
declared.

Question 3

(a) What are the values of x and y when the following statements are executed?

int a = 63, b = 36;


boolean x = (a > b)? true : false;
int y = (a < b)? a : b;
Answer

Output

x = true
y = 36

Explanation

The ternary operator (a > b)? true : false returns true as its condition a > b is true so it
returns its first expression that is true.
The ternary operator (a < b)? a : b returns b as its condition a < b is false so it returns its
second expression that is b. Value of b is 36 so y also becomes 36.
(b) State the values of n and ch.

char c = 'A';
int n = c + 1;
char ch = (char)n;
Answer

Value of n is 66 and ch is B.

int n = c + 1, here due to implicit conversion, 'A' will be converted to its ASCII value 65. 1 is added
to it making the value of n 66.

char ch = (char)n, here through explicit conversion 66 is converted to its corresponding character
that is 'B' so value of ch becomes B.

(c) What will be the result stored in x after evaluating the following expression?

int x = 4;
x += (x++) + (++x) + x;
Answer

⇒ x = x + ((x++) + (++x) + x)
x += (x++) + (++x) + x

⇒ x = 4 + (4 + 6 + 6)
⇒ x = 4 + 16
⇒ x = 20

(d) Give output of the following program segment:

double x = 2.9, y = 2.5;


System.out.println(Math.min(Math.floor(x), y));
System.out.println(Math.max(Math.ceil(x), y));
Answer

Output

2.0
3.0

Explanation

Math.floor(2.9) gives 2.0. Math.min(2.0, 2.5) gives 2.0.

Math.ceil(2.9) gives 3.0. Math.max(3.0, 2.5) gives 3.0.

(e) State the output of the following program segment:

String s = "Examination";
int n = s.length();
System.out.println(s.startsWith(s.substring(5, n)));
System.out.println(s.charAt(2) == s.charAt(6));
Answer

Output

false
true

Explanation

Putting the value of n in s.substring(5, n), it becomes s.substring(5, 11). This gives "nation". As s
does not start with "nation" so s.startsWith(s.substring(5, n)) returns false.

s.charAt(2) is a and s.charAt(6) is also a so both are equal

(f) State the method that:

1. Converts a string to a primitive float data type.


2. Determines if the specified character is an uppercase character.

Answer

1. Float.parseFloat()
2. Character.isUpperCase()

(g) State the data type and values of a and b after the following segment is executed:

String s1 = "Computer", s2 = "Applications"


a = (s1.compareTo(s2));
b = (s1.equals(s2));
Answer

Data type of a is int and value is 2. Data type of b is boolean and value is false.

(h) What will the following code output:

String s = "malayalam";
System.out.println(s.indexOf('m'));
System.out.println(s.lastIndexOf('m'));
Answer

Output

0
8

Explanation

The first m appears at index 0 and the last m appears at index 8.

(i) Rewrite the following program segment using while instead of for statement.

int f = 1, i;
for(i = 1; i <= 5; i++){
f *= i;
System.out.println(f);
}
Answer

int f = 1, i;
while (i <= 5) {
f *= i;
System.out.println(f);
i++;
}
(j) In the program given below, state the name and the value of the:

1. method argument or argument variable


2. class variable
3. local variable
4. instance variable
class MyClass{
static int x = 7;
int y = 2;
public static void main(String args[]){
MyClass obj = new MyClass();
System.out.println(x);
obj.sampleMethod(5);
int a = 6;
System.out.println(a);
}
void sampleMethod(int n){
System.out.println(n);
System.out.println(y);
}
}
Answer

1. Method argument/Argument variable is n


2. Class variable is x
3. Local variable is a
4. Instance variable is y

Question 1

(a) What is the difference between an object and a class?

Answer

A class is a blue print that represents a set of objects that share common characteristics and
behaviour whereas an object is a specific instance of a class having a specific identity, specific
characteristics and specific behaviour.

(b) What does the token 'keyword' refer to in the context of Java? Give an example for
keyword.

Answer

Keywords are reserved words that have a special meaning for the Java compiler. Java compiler
reserves these words for its own use so Keywords cannot be used as identifiers. An example of
keyword is class.

(c) State the difference between entry controlled loop and exit controlled loop.
Answer

Entry controlled loop Exit controlled loop

It checks the condition at the time of entry. Only It checks the condition after executing its body. If the condition
if the condition is true, the program control is true, loop will perform the next iteration otherwise program
enters the body of the loop. control will move out of the loop.

Loop does not execute at all if the condition is


The loop executes at least once even if the condition is false.
false.

Example: for and while loops Example: do-while loop

(d) What are the two ways of invoking functions?

Answer

Two ways of invoking functions are:

1. Pass by value.
2. Pass by reference.

(e) What is the difference between / and % operators?

Answer

/ %

Division operator Modulus operator

Returns the quotient of division operation Returns the remainder of division operation

Example: int a = 5 / 2; Here a will get the value of 2 Example: int b = 5 % 2; Here b will get the value of 1
which is the quotient of this division operation which is the remainder of this division operation

Question 2

(a) State the total size in bytes, of the arrays a[4] of char data type and p[4] of float data
type.

Answer
Size of char a[4] is 4 × 2 = 8 Bytes.
Size of float p[4] is 4 × 4 = 16 Bytes.

(b) (i) Name the package that contains Scanner class.


(ii) Which unit of the class gets called, when the object of the class is created?

Answer

(i) java.util
(ii) Constructor

(c) Give the output of the following:

String n = "Computer Knowledge";


String m = "Computer Applications";
System.out.println(n.substring(0, 8).concat(m.substring(9)));
System.out.println(n.endsWith("e"));
Answer

Output

ComputerApplications
true

Explanation

n.substring(0,8) returns the substring of n starting at index 0 till 7 (i.e. 8 - 1 = 7) which is


"Computer". m.substring(9) returns the substring of m starting at index 9 till the end of the string
which is "Applications". concat() method joins "Computer" and "Applications" together to give the
output as ComputerApplications.

(d) Write the output of the following:

1. System.out.println(Character.isUpperCase('R'));
2. System.out.println(Character.toUpperCase('j'));

Answer

1. true
2. J

(e) What is the role of keyword void in declaring functions?

Answer

The keyword 'void' signifies that the function doesn't return a value to the calling function.
Question 3

(a) Analyze the following program segment and determine how many times the loop will be
executed and what will be the output of the program segment?

int p = 200;
while(true){
if(p < 100)
break;
p = p - 20;
}
System.out.println(p);
Answer

Output

80
The loop executes 6 times

Explanation

p Remarks

200 Initial Value

180 1st Iteration

160 2nd Iteration

140 3rd Iteration

120 4th Iteration

100 5th Iteration

80 6th Iteration. Now p < 100 becomes true so break statement is executed terminating the loop.

(b) What will be the output of the following code?

(i)

int k = 5, j = 9;
k += k++ - ++j + k;
System.out.println("k = " + k);
System.out.println("j = " + j);
(ii)

double b = -15.6;
double a = Math.rint(Math.abs(b));
System.out.println("a = " + a);
Answer

(i)

Output

k = 6
j = 10

Explanation

⇒ k = 5 + (5 - 10 + 6)
k += k++ - ++j + k

⇒k=5+1
⇒k=6

++j increments j to 10

(ii)

Output

16.0

Explanation

Math.abs(-15.6) gives 15.6. Math.rint(15.6) gives 16.0.

(c) Explain the concept of constructor overloading with an example.

Answer

Constructor overloading is a technique in Java through which a class can have more than one
constructor with different parameter lists. The different constructors of the class are differentiated
by the compiler using the number of parameters in the list and their types. For example, the
Rectangle class below has two constructors:

class Rectangle {
int length;
int breadth;

//Constructor 1
public Rectangle() {
length = 0;
breadth = 0;
}

//Constructor 2
public Rectangle(int l, int b) {
length = l;
breadth = b;
}

public static void main(String[] args) {


//Constructor 1 called
Rectangle obj1 = new Rectangle();

//Constructor 2 called
Rectangle obj2 = new Rectangle(10, 15);
}
}
(d) Give the prototype of a function search which receives a sentence 'sent' and word 'w'
and returns 1 or 0.

Answer

int search(String sent, String w)

(e) Write an expression in Java for:

�=5�3+2��+�z=x+y5x3+2y
Answer

z = (5 * x * x * x + 2 * y) / (x + y)

(f) Write a statement each to perform the following tasks on a string:

1. Find and display the position of the last space in a string s.


2. Convert a number stored in a string variable x to double data type.

Answer

1. System.out.println(s.lastIndexOf(" "));
2. double num = Double.parseDouble(x);

(g) Name the keyword that:

1. informs that an error has occurred in an input/output operation.


2. distinguishes between instance variable and class variable.
Answer

1. throws IOException
2. static

(h) What are library classes? Give an example.

Answer

Java Library classes are a set of predefined classes in the form of packages that are provided to
the programmer as part of Java installation. Library classes simplify the job of programmers by
providing built-in methods for common and non-trivial tasks like taking input from user, displaying
output to user, etc. For example, System class in java.lang package of Java Library classes
provides the print() and println() methods for displaying output to user.

(i) Write one difference between Linear Search and Binary Search.

Answer

Linear search works on unsorted as well as sorted arrays whereas Binary search works on only
sorted arrays.

a) Define the term Bytecode.

Answer

Java compiler converts Java source code into an intermediate binary code called Bytecode.
Bytecode can't be executed directly on the processor. It needs to be converted into Machine Code
first.

(b) What do you understand by type conversion? How is implicit conversion different from
explicit conversion?

Answer

The process of converting one predefined type into another is called type conversion. In an implicit
conversion, the result of a mixed mode expression is obtained in the higher most data type of the
variables without any intervention by the user. For example:

int a = 10;
float b = 25.5f, c;
c = a + b;
In case of explicit type conversion, the data gets converted to a type as specified by the
programmer. For example:

int a = 10;
double b = 25.5;
float c = (float)(a + b);
(c) Name two jump statements and their use.

Answer

break statement, it is used to jump out of a switch statement or a loop. continue statement, it is
used to skip the current iteration of the loop and start the next iteration.

(d) What is Exception? Name two exception handling blocks.

Answer

An exception is an event, which occurs during the execution of a program, that disrupts the normal
flow of the program's instructions. Two exception handling blocks are try and catch.

(e) Write two advantages of using functions in a program.

Answer

1. Methods help to manage the complexity of the program by dividing a bigger complex task
into smaller, easily understood tasks.
2. Methods help with code reusability.

Question 2

(a) State the purpose and return data type of the following String functions:

1. indexOf()
2. compareTo()

Answer

1. indexOf() returns the index within the string of the first occurrence of the specified
character or -1 if the character is not present. Its return type is int.
2. compareTo() compares two strings lexicographically. Its return type is int.

(b) What is the result stored in x, after evaluating the following expression?

int x = 5;
x = x++ * 2 + 3 * --x;
Answer

⇒x=5*2+3*5
x = x++ * 2 + 3 * --x

⇒ x = 10 + 15
⇒ x = 25

(c) Differentiate between static and non-static data members.

Answer
Static Data Members Non-Static Data Members

They are declared using keyword 'static'. They are declared without using keyword 'static'.

All objects of a class share the same copy of Static Each object of the class gets its own copy of Non-Static data
data members. members.

They can be accessed using the class name or object. They can be accessed only through an object of the class.

(d) Write the difference between length and length().

Answer

length length()

length is an attribute i.e. a data member of array. length() is a member method of String class.

It gives the length of an array i.e. the number of elements stored It gives the number of characters present in a
in an array. string.

(e) Differentiate between private and protected visibility modifiers.

Answer

Private members are only accessible inside the class in which they are defined and they cannot be
inherited by derived classes. Protected members are also only accessible inside the class in which
they are defined but they can be inherited by derived classes.

Question 3

(a) What do you understand by the term data abstraction? Explain with an example.

Answer

Data Abstraction refers to the act of representing essential features without including the
background details or explanations. A Switchboard is an example of Data Abstraction. It hides all
the details of the circuitry and current flow and provides a very simple way to switch ON or OFF
electrical appliances.

(b)(i) What will be the output of the following code?

int m = 2;
int n = 15;
for(int i = 1; i < 5; i++);
m++;
--n;
System.out.println("m = " + m);
System.out.println("n = " + n);
Answer

Output

m=6
n=14

Explanation

As there are no curly braces after the for loop so only the statement m++; is inside the loop. Loop
executes 4 times so m becomes 6. The next statement --n; is outside the loop so it is executed
only once and n becomes 14.
(b)(ii) What will be the output of the following code?

char x = 'A';
int m;
m = (x == 'a')? 'A' : 'a';
System.out.println("m = " + m);
Answer

Output

m = 97

Explanation

The condition x == 'a' is false as X has the value of 'A'. So, the ternary operator returns 'a' that is
assigned to m. But m is an int variable not a char variable. So, through implicit conversion Java
converts 'a' to its numeric ASCII value 97 and that gets assigned to m.

(c) Analyze the following program segment and determine how many times the loop will be
executed and what will be the output of the program segment.

int k = 1, i = 2;
while(++i < 6)
k *= i;
System.out.println(k);
Answer

Output

60
Explanation

This table shows the change in values of i and k as while loop iterates:

i k Remarks

2 1 Initial values

3 3 1st Iteration

4 12 2nd Iteration

5 60 3rd Iteration

6 60 Once i becomes 6, condition is false and loop stops iterating.

Notice that System.out.println(k); is not inside while loop. As there are no curly braces so
only the statement k *= i; is inside the loop. The statement System.out.println(k); is
outside the while loop, it is executed once and prints value of k which is 60 to the console.
(d) Give the prototype of a function check which receives a character ch and an integer n
and returns true or false.

Answer

boolean check(char ch, int n)

(e) State two features of a constructor.

Answer

1. A constructor has the same name as that of the class.


2. A constructor has no return type, not even void.

(f) Write a statement each to perform the following task on a string:

1. Extract the second-last character of a word stored in the variable wd.


2. Check if the second character of a string str is in uppercase.

Answer

1. char ch = wd.charAt(wd.length() - 2);


2. boolean res = Character.isUpperCase(str.charAt(1));

(g) What will the following function return when executed?

1. Math.max(-17, -19)
2. Math.ceil(7.8)

Answer

1. -17
2. 8.0

(h)(i) Why is an object called an instance of a class?

Answer

A class can create objects of itself with different characteristics and common behaviour. So, we
can say that an Object represents a specific state of the class. For these reasons, an Object is
called an Instance of a Class.

(h)(ii) What is the use of the keyword import?

Answer

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

BROAD QUESTIONS
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

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
Define a class named BookFair with the following description:
Instance variables/Data members:
String Bname — stores the name of the book
double price — stores the price of the book

Member methods:
(i) BookFair() — Default constructor to initialize data members
(ii) void Input() — To input and store the name and the price of the book.
(iii) void calculate() — To calculate the price after discount. Discount is calculated based on the
following criteria.

Price Discount

Less than or equal to ₹1000 2% of price

More than ₹1000 and less than or equal to ₹3000 10% of price

More than ₹3000 15% of price

(iv) void display() — To display the name and price of the book after discount.

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

Answer

import java.util.Scanner;

public class BookFair


{
private String bname;
private double price;

public BookFair() {
bname = "";
price = 0.0;
}

public void input() {


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

public void calculate() {


double disc;
if (price <= 1000)
disc = price * 0.02;
else if (price <= 3000)
disc = price * 0.1;
else
disc = price * 0.15;

price -= disc;
}

public void display() {


System.out.println("Book Name: " + bname);
System.out.println("Price after discount: " + price);
}

public static void main(String args[]) {


BookFair obj = new BookFair();
obj.input();
obj.calculate();
obj.display();
}
}
Output

Question 5

Using the switch statement, write a menu driven program for the following:

(i) To print the Floyd’s triangle [Given below]

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

(b) To display the following pattern:


I
IC
ICS
ICSE

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


Answer

import java.util.Scanner;

public class KboatPattern


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 for Floyd's triangle");
System.out.println("Type 2 for an ICSE pattern");

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


int ch = in.nextInt();

switch (ch) {
case 1:
int a = 1;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(a++ + "\t");
}
System.out.println();
}
break;

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

default:
System.out.println("Incorrect Choice");
}
}
}
Output
Question 6

Special words are those words which start and end with the same letter.
Example: EXISTENCE, COMIC, WINDOW
Palindrome words are those words which read the same from left to right and vice-versa.
Example: MALYALAM, MADAM, LEVEL, ROTATOR, CIVIC
All palindromes are special words but all special words are not palindromes.

Write a program to accept a word. Check and display whether the word is a palindrome or only a
special word or none of them.

Answer

import java.util.Scanner;

public class KboatSpecialPalindrome


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = in.next();
str = str.toUpperCase();
int len = str.length();

if (str.charAt(0) == str.charAt(len - 1)) {


boolean isPalin = true;
for (int i = 1; i < len / 2; i++) {
if (str.charAt(i) != str.charAt(len - 1 - i)) {
isPalin = false;
break;
}
}

if (isPalin) {
System.out.println("Palindrome");
}
else {
System.out.println("Special");
}
}
else {
System.out.println("Neither Special nor
Palindrome");
}

}
}
Output
Question 7

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

(i) void sumSeries(int n, double x): with one integer argument and one double argument to find
and display the sum of the series given below:

�=�1−�2+�3−�4+�5... ... ... �� � �����s=1x−2x+3x−4x


+5x... ... ... to n terms
(ii) void sumSeries(): to find and display the sum of the following series:

�=1+(1×2)+(1×2×3)+... ... ... +(1×2×3×4... ... ... ×20)s=1+(1×2)+(1


×2×3)+... ... ... +(1×2×3×4... ... ... ×20)
Answer

public class KboatOverload


{
void sumSeries(int n, double x) {
double sum = 0;
for (int i = 1; i <= n; i++) {
double t = x / i;
if (i % 2 == 0)
sum -= t;
else
sum += t;
}
System.out.println("Sum = " + sum);
}

void sumSeries() {
long sum = 0, term = 1;
for (int i = 1; i <= 20; i++) {
term *= i;
sum += term;
}
System.out.println("Sum=" + sum);
}
}

Output
Question 8

Write a program to accept a number and check and display whether it is a Niven number or not.
(Niven number is that number which is divisible by its sum of digits.).

Example:
Consider the number 126. Sum of its digits is 1 + 2 + 6 = 9 and 126 is divisible by 9.

Answer

import java.util.Scanner;

public class KboatNivenNumber


{
public void checkNiven() {
Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int num = in.nextInt();
int orgNum = num;

int digitSum = 0;

while (num != 0) {
int digit = num % 10;
num /= 10;
digitSum += digit;
}
/*
* digitSum != 0 check prevents
* division by zero error for the
* case when users gives the number
* 0 as input
*/
if (digitSum != 0 && orgNum % digitSum == 0)
System.out.println(orgNum + " is a Niven number");
else
System.out.println(orgNum + " is not a Niven
number");
}
}

Output

Question 9

Write a program to initialize the seven Wonders of the World along with their locations in two
different arrays. Search for a name of the country input by the user. If found, display the name of
the country along with its Wonder, otherwise display "Sorry not found!".
Seven Wonders:
CHICHEN ITZA, CHRIST THE REDEEMER, TAJ MAHAL, GREAT WALL OF CHINA, MACHU
PICCHU, PETRA, COLOSSEUM

Locations:
MEXICO, BRAZIL, INDIA, CHINA, PERU, JORDAN, ITALY

Examples:
Country name: INDIA
Output: TAJ MAHAL

Country name: USA


Output: Sorry Not found!

Answer

import java.util.Scanner;

public class Kboat7Wonders


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

String wonders[] = {"CHICHEN ITZA", "CHRIST THE


REDEEMER", "TAJMAHAL",
"GREAT WALL OF CHINA", "MACHU PICCHU", "PETRA",
"COLOSSEUM"};

String locations[] = {"MEXICO", "BRAZIL", "INDIA",


"CHINA", "PERU", "JORDAN",
"ITALY"};

Scanner in = new Scanner(System.in);


System.out.print("Enter country: ");
String c = in.nextLine();
int i;

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


if (locations[i].equals(c)) {
System.out.println(locations[i] + " - " +
wonders[i]);
break;
}
}

if (i == locations.length)
System.out.println("Sorry Not Found!");
}
}
Output
Define a class called ParkingLot with the following description:

Instance variables/data members:


int vno — To store the vehicle number.
int hours — To store the number of hours the vehicle is parked in the parking lot.
double bill — To store the bill amount.

Member Methods:
void input() — To input and store the vno and hours.
void calculate() — To compute the parking charge at the rate of ₹3 for the first hour or part
thereof, and ₹1.50 for each additional hour or part thereof.
void display() — To display the detail.

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

Answer

import java.util.Scanner;

public class ParkingLot


{
private int vno;
private int hours;
private double bill;

public void input() {


Scanner in = new Scanner(System.in);
System.out.print("Enter vehicle number: ");
vno = in.nextInt();
System.out.print("Enter hours: ");
hours = in.nextInt();
}

public void calculate() {


if (hours <= 1)
bill = 3;
else
bill = 3 + (hours - 1) * 1.5;
}

public void display() {


System.out.println("Vehicle number: " + vno);
System.out.println("Hours: " + hours);
System.out.println("Bill: " + bill);
}

public static void main(String args[]) {


ParkingLot obj = new ParkingLot();
obj.input();
obj.calculate();
obj.display();
}
}

Output

Question 5

Write two separate programs to generate the following patterns using iteration (loop) statements:

(a)

*
* #
* # *
* # * #
* # * # *
(b)

54321
5432
543
54
5

Answer

public class KboatPattern


{
public static void main(String args[]) {
for (int i = 1; i <=5; i++) {
for (int j = 1; j <= i; j++) {
if (j % 2 == 0)
System.out.print("# ");
else
System.out.print("* ");
}
System.out.println();
}
}
}

Output

public class KboatPattern


{
public static void main(String args[]) {
for (int i = 1; i <=5; i++) {
for (int j = 5; j >= i; j--) {
System.out.print(j + " ");
}
System.out.println();
}
}
}

Output

Question 6

Write a program to input and store roll numbers, names and marks in 3 subjects of n number of
students in five single dimensional arrays and display the remark based on average marks as
given below:

Average Marks Remark

85 — 100 Excellent

75 — 84 Distinction

60 — 74 First Class
Average Marks Remark

40 — 59 Pass

Less than 40 Poor

Answer

import java.util.Scanner;

public class KboatAvgMarks


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

Scanner in = new Scanner(System.in);


System.out.print("Enter number of students: ");
int n = in.nextInt();

int rollNo[] = new int[n];


String name[] = new String[n];
int s1[] = new int[n];
int s2[] = new int[n];
int s3[] = new int[n];
double avg[] = new double[n];

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


System.out.println("Enter student " + (i+1) + "
details:");
System.out.print("Roll No: ");
rollNo[i] = in.nextInt();
in.nextLine();
System.out.print("Name: ");
name[i] = in.nextLine();
System.out.print("Subject 1 Marks: ");
s1[i] = in.nextInt();
System.out.print("Subject 2 Marks: ");
s2[i] = in.nextInt();
System.out.print("Subject 3 Marks: ");
s3[i] = in.nextInt();
avg[i] = (s1[i] + s2[i] + s3[i]) / 3.0;
}
System.out.println("Roll No\tName\tRemark");
for (int i = 0; i < n; i++) {
String remark;
if (avg[i] < 40)
remark = "Poor";
else if (avg[i] < 60)
remark = "Pass";
else if (avg[i] < 75)
remark = "First Class";
else if (avg[i] < 85)
remark = "Distinction";
else
remark = "Excellent";
System.out.println(rollNo[i] + "\t"
+ name[i] + "\t"
+ remark);
}
}
}

Output
Question 7

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

1. void Joystring(String s, char ch1, char ch2) with one string argument and two character
arguments that replaces the character argument ch1 with the character argument ch2 in
the given String s and prints the new string.
Example:
Input value of s = "TECHNALAGY"
ch1 = 'A'
ch2 = 'O'
Output: "TECHNOLOGY"
2. void Joystring(String s) with one string argument that prints the position of the first space
and the last space of the given String s.
Example:
Input value of s = "Cloud computing means Internet based computing"
Output:
First index: 5
Last Index: 36
3. void Joystring(String s1, String s2) with two string arguments that combines the two strings
with a space between them and prints the resultant string.
Example:
Input value of s1 = "COMMON WEALTH"
Input value of s2 = "GAMES"
Output: COMMON WEALTH GAMES

(Use library functions)

Answer

public class KboatStringOverload


{
public void joystring(String s, char ch1, char ch2) {
String newStr = s.replace(ch1, ch2);
System.out.println(newStr);
}

public void joystring(String s) {


int f = s.indexOf(' ');
int l = s.lastIndexOf(' ');
System.out.println("First index: " + f);
System.out.println("Last index: " + l);
}

public void joystring(String s1, String s2) {


String newStr = s1.concat(" ").concat(s2);
System.out.println(newStr);
}

public static void main(String args[]) {


KboatStringOverload obj = new KboatStringOverload();
obj.joystring("TECHNALAGY", 'A', 'O');
obj.joystring("Cloud computing means Internet based
computing");
obj.joystring("COMMON WEALTH", "GAMES");
}
}

Output

Question 8

Write a program to input twenty names in an array. Arrange these names in descending order of
letters, using the bubble sort technique.

Answer

import java.util.Scanner;

public class KboatArrangeNames


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
String names[] = new String[20];
System.out.println("Enter 20 names:");
for (int i = 0; i < names.length; i++) {
names[i] = in.nextLine();
}

//Bubble Sort
for (int i = 0; i < names.length - 1; i++) {
for (int j = 0; j < names.length - 1 - i; j++) {
if (names[j].compareToIgnoreCase(names[j + 1])
< 0) {
String temp = names[j + 1];
names[j + 1] = names[j];
names[j] = temp;
}
}
}

System.out.println("\nSorted Names");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}
}
}
Output
Question 9

Using switch statement, write a menu driven program to:


(i) To find and display all the factors of a number input by the user ( including 1 and the excluding
the number itself).
Example:
Sample Input : n = 15
Sample Output : 1, 3, 5

(ii) To find and display the factorial of a number input by the user (the factorial of a non-negative
integer n, denoted by n!, is the product of all integers less than or equal to n.)
Example:
Sample Input : n = 5
Sample Output : 5! = 1*2*3*4*5 = 120

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

Answer

import java.util.Scanner;

public class KboatMenu


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Factors of number");
System.out.println("2. Factorial of number");
System.out.print("Enter your choice: ");
int choice = in.nextInt();
int num;

switch (choice) {
case 1:
System.out.print("Enter number: ");
num = in.nextInt();
for (int i = 1; i < num; i++) {
if (num % i == 0) {
System.out.print(i + " ");
}
}
System.out.println();
break;

case 2:
System.out.print("Enter number: ");
num = in.nextInt();
int f = 1;
for (int i = 1; i <= num; i++)
f *= i;
System.out.println("Factorial = " + f);
break;

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

Output
Define a class named movieMagic with the following description:

Data Members Purpose

int year To store the year of release of a movie

String title To store the title of the movie

To store the popularity rating of the movie


float rating
(minimum rating=0.0 and maximum rating=5.0)

Member
Purpose
Methods

movieMagic() Default constructor to initialize numeric data members to 0 and String data member to "".

void accept() To input and store year, title and rating

To display the title of the movie and a message based on the rating as per the table given
void display()
below

Ratings Table

Rating Message to be displayed

0.0 to 2.0 Flop

2.1 to 3.4 Semi-Hit

3.5 to 4.4 Hit

4.5 to 5.0 Super-Hit

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

Answer

import java.util.Scanner;
public class movieMagic
{
private int year;
private String title;
private float rating;

public movieMagic() {
year = 0;
title = "";
rating = 0.0f;
}

public void accept() {


Scanner in = new Scanner(System.in);
System.out.print("Enter Title of Movie: ");
title = in.nextLine();
System.out.print("Enter Year of Movie: ");
year = in.nextInt();
System.out.print("Enter Rating of Movie: ");
rating = in.nextFloat();
}

public void display() {


String message = "Invalid Rating";
if (rating <= 2.0f)
message = "Flop";
else if (rating <= 3.4f)
message = "Semi-Hit";
else if (rating <= 4.4f)
message = "Hit";
else if (rating <= 5.0f)
message = "Super-Hit";

System.out.println(title);
System.out.println(message);
}

public static void main(String args[]) {


movieMagic obj = new movieMagic();
obj.accept();
obj.display();
}
}
Output

Question 5

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

Example: Consider the number 59.


Sum of digits = 5 + 9 = 14
Product of digits = 5 * 9 = 45
Sum of the sum of digits and product of digits = 14 + 45 = 59

Write a program to accept a two-digit number. Add the sum of its digits to the product of its digits.
If the value is equal to the number input, then display the message "Special two—digit number"
otherwise, display the message "Not a special two-digit number".

Answer

import java.util.Scanner;

public class KboatSpecialNumber


{
public void checkNumber() {

Scanner in = new Scanner(System.in);

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


int orgNum = in.nextInt();
int num = orgNum;
int count = 0, digitSum = 0, digitProduct = 1;

while (num != 0) {
int digit = num % 10;
num /= 10;
digitSum += digit;
digitProduct *= digit;
count++;
}

if (count != 2)
System.out.println("Invalid input, please enter a
2-digit number");
else if ((digitSum + digitProduct) == orgNum)
System.out.println("Special 2-digit number");
else
System.out.println("Not a special 2-digit number");

}
}
Output

Question 6

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

Input
C:\Users\admin\Pictures\flower.jpg

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

Answer

import java.util.Scanner;

public class KboatFilepathSplit


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter full path: ");
String filepath = in.next();

char pathSep = '\\';


char dotSep = '.';

int pathSepIdx = filepath.lastIndexOf(pathSep);


System.out.println("Path:\t\t" + filepath.substring(0,
pathSepIdx));

int dotIdx = filepath.lastIndexOf(dotSep);


System.out.println("File Name:\t" +
filepath.substring(pathSepIdx + 1, dotIdx));

System.out.println("Extension:\t" +
filepath.substring(dotIdx + 1));
}
}

Output
Question 7

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

1. double area (double a, double b, double c) with three double arguments, returns the area
of a scalene triangle using the formula:
area = √(s(s-a)(s-b)(s-c))
where s = (a+b+c) / 2
2. double area (int a, int b, int height) with three integer arguments, returns the area of a
trapezium using the formula:
area = (1/2)height(a + b)
3. double area (double diagonal1, double diagonal2) with two double arguments, returns the
area of a rhombus using the formula:
area = 1/2(diagonal1 x diagonal2)

Answer

import java.util.Scanner;

public class KboatOverload


{
double area(double a, double b, double c) {
double s = (a + b + c) / 2;
double x = s * (s-a) * (s-b) * (s-c);
double result = Math.sqrt(x);
return result;
}

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


double result = (1.0 / 2.0) * height * (a + b);
return result;
}

double area (double diagonal1, double diagonal2) {


double result = 1.0 / 2.0 * diagonal1 * diagonal2;
return result;
}
}

Output

Question 8

Using the switch statement, write a menu driven program to calculate the maturity amount of a
Bank Deposit.
The user is given the following options:

1. Term Deposit
2. Recurring Deposit

For option 1, accept principal (P), rate of interest(r) and time period in years(n). Calculate and
output the maturity amount(A) receivable using the formula:

A = P[1 + r / 100] n

For option 2, accept Monthly Installment (P), rate of interest (r) and time period in months (n).
Calculate and output the maturity amount (A) receivable using the formula:

A = P x n + P x (n(n+1) / 2) x r / 100 x 1 / 12

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

Answer

import java.util.Scanner;

public class KboatBankDeposit


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 for Term Deposit");
System.out.println("Type 2 for Recurring Deposit");
System.out.print("Enter your choice: ");
int ch = in.nextInt();
double p = 0.0, r = 0.0, a = 0.0;
int n = 0;

switch (ch) {
case 1:
System.out.print("Enter Principal: ");
p = in.nextDouble();
System.out.print("Enter Interest Rate: ");
r = in.nextDouble();
System.out.print("Enter time in years: ");
n = in.nextInt();
a = p * Math.pow(1 + r / 100, n);
System.out.println("Maturity amount = " + a);
break;

case 2:
System.out.print("Enter Monthly Installment: ");
p = in.nextDouble();
System.out.print("Enter Interest Rate: ");
r = in.nextDouble();
System.out.print("Enter time in months: ");
n = in.nextInt();
a = p * n + p * ((n * (n + 1)) / 2) * (r / 100) *
(1 / 12.0);
System.out.println("Maturity amount = " + a);
break;

default:
System.out.println("Invalid choice");
}
}
}

Output
Question 9

Write a program to accept the year of graduation from school as an integer value from the user.
Using the binary search technique on the sorted array of integers given below, output the message
"Record exists" if the value input is located in the array. If not, output the message "Record does
not exist".
Sample Input:

n[0] n[1] n[2] n[3] n[4] n[5] n[6] n[7] n[8] n[9]

1982 1987 1993 1996 1999 2003 2006 2007 2009 2010

Answer

import java.util.Scanner;

public class KboatGraduationYear


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n[] = {1982, 1987, 1993, 1996, 1999, 2003, 2006,
2007, 2009, 2010};

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


int year = in.nextInt();

int l = 0, h = n.length - 1, idx = -1;


while (l <= h) {
int m = (l + h) / 2;
if (n[m] == year) {
idx = m;
break;
}
else if (n[m] < year) {
l = m + 1;
}
else {
h = m - 1;
}
}

if (idx == -1)
System.out.println("Record does not exist");
else
System.out.println("Record exists");
}
}

Output
Question 4

Define a class called Library with the following description:

Instance Variables/Data Members:


int accNum — stores the accession number of the book.
String title — stores the title of the book.
String author — stores the name of the author.

Member methods:

1. void input() — To input and store the accession number, title and author.
2. void compute() — To accept the number of days late, calculate and display the fine
charged at the rate of Rs. 2 per day.
3. void display() — To display the details in the following format:

Accession Number Title Author


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

Answer

import java.util.Scanner;

public class Library


{
private int accNum;
private String title;
private String author;

void input() {
Scanner in = new Scanner(System.in);
System.out.print("Enter book title: ");
title = in.nextLine();
System.out.print("Enter author: ");
author = in.nextLine();
System.out.print("Enter accession number: ");
accNum = in.nextInt();
}

void compute() {
Scanner in = new Scanner(System.in);
System.out.print("Enter number of days late: ");
int days = in.nextInt();
int fine = days * 2;
System.out.println("Fine = Rs." + fine);
}

void display() {
System.out.println("Accession Number\tTitle\tAuthor");
System.out.println(accNum + "\t\t" + title + "\t" +
author);
}

public static void main(String args[]) {


Library obj = new Library();
obj.input();
obj.display();
obj.compute();
}
}

Output
Question 5

Given below is a hypothetical table showing rates of income tax for male citizens below the age of
65 years:

Taxable income (TI) in ₹ Income Tax in ₹

Does not exceed Rs. 1,60,000 Nil

Is greater than Rs. 1,60,000 and less than or equal to Rs. 5,00,000. (TI - 1,60,000) x 10%

Is greater than Rs. 5,00,000 and less than or equal to Rs. 8,00,000 [(TI - 5,00,000) x 20%] + 34,000

Is greater than Rs. 8,00,000 [(TI - 8,00,000) x 30%] + 94,000

Write a program to input the age, gender (male or female) and Taxable Income of a person.

If the age is more than 65 years or the gender is female, display “wrong category”. If the age is
less than or equal to 65 years and the gender is male, compute and display the income tax
payable as per the table given above.

Answer

import java.util.Scanner;

public class KboatIncomeTax


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Gender(male/female): ");
String gender = in.nextLine();
System.out.print("Enter Age: ");
int age = in.nextInt();
System.out.print("Enter Taxable Income: ");
double ti = in.nextDouble();
double tax = 0.0;

if (age > 65 || gender.equalsIgnoreCase("female")) {


System.out.print("Wrong Category");
}
else {
if (ti <= 160000)
tax = 0;
else if (ti <= 500000)
tax = (ti - 160000) * 10 / 100;
else if (ti <= 800000)
tax = 34000 + ((ti - 500000) * 20 / 100);
else
tax = 94000 + ((ti - 800000) * 30 / 100);

System.out.println("Tax Payable: " + tax);


}
}
}

Output
Question 6

Write a program to accept a string. Convert the string into upper case letters. Count and output the
number of double letter sequences that exist in the string.
Sample Input: "SHE WAS FEEDING THE LITTLE RABBIT WITH AN APPLE"
Sample Output: 4

Answer

import java.util.Scanner;

public class KboatLetterSeq


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

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


if (str.charAt(i) == str.charAt(i + 1))
count++;
}

System.out.println("Double Letter Sequence Count = " +


count);
}
}

Output

Question 7

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

1. void polygon(int n, char ch) — with one integer and one character type argument to draw a
filled square of side n using the character stored in ch.
2. void polygon(int x, int y) — with two integer arguments that draws a filled rectangle of
length x and breadth y, using the symbol '@'.
3. void polygon() — with no argument that draws a filled triangle shown below:

Example:

1. Input value of n=2, ch = 'O'


Output:
OO
OO
2. Input value of x = 2, y = 5
Output:
@@@@@
@@@@@
3. Output:
*
**
***

Answer

public class KboatPolygon


{
public void polygon(int n, char ch) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(ch);
}
System.out.println();
}
}

public void polygon(int x, int y) {


for (int i = 1; i <= x; i++) {
for (int j = 1; j <= y; j++) {
System.out.print('@');
}
System.out.println();
}
}

public void polygon() {


for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= i; j++) {
System.out.print('*');
}
System.out.println();
}
}

public static void main(String args[]) {


KboatPolygon obj = new KboatPolygon();
obj.polygon(2, 'o');
System.out.println();
obj.polygon(2, 5);
System.out.println();
obj.polygon();
}
}

Output

Question 8

Using a switch statement, write a menu driven program to:


(a) Generate and display the first 10 terms of the Fibonacci series
0, 1, 1, 2, 3, 5
The first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the
previous two.
(b) Find the sum of the digits of an integer that is input.
Sample Input: 15390
Sample Output: Sum of the digits = 18
For an incorrect choice, an appropriate error message should be displayed.

Answer

import java.util.Scanner;

public class KboatFibonacciNDigitSum


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("1. Fibonacci Series");
System.out.println("2. Sum of digits");
System.out.print("Enter your choice: ");
int ch = in.nextInt();

switch (ch) {
case 1:
int a = 0, b = 1;
System.out.print(a + " " + b);
for (int i = 3; i <= 10; i++) {
int term = a + b;
System.out.print(" " + term);
a = b;
b = term;
}
break;

case 2:
System.out.print("Enter number: ");
int num = in.nextInt();
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
System.out.println("Sum of Digits " + " = " + sum);
break;

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

Question 9

Write a program to accept the names of 10 cities in a single dimensional string array and their
STD (Subscribers Trunk Dialling) codes in another single dimension integer array. Search for the
name of a city input by the user in the list. If found, display "Search Successful" and print the name
of the city along with its STD code, or else display the message "Search unsuccessful, no such
city in the list".
Answer

import java.util.Scanner;

public class KboatStdCodes


{
public static void main(String args[]) {
final int SIZE = 10;
Scanner in = new Scanner(System.in);
String cities[] = new String[SIZE];
String stdCodes[] = new String[SIZE];
System.out.println("Enter " + SIZE +
" cities and their STD codes:");

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


System.out.print("Enter City Name: ");
cities[i] = in.nextLine();
System.out.print("Enter its STD Code: ");
stdCodes[i] = in.nextLine();
}

System.out.print("Enter name of city to search: ");


String city = in.nextLine();

int idx;
for (idx = 0; idx < SIZE; idx++) {
if (city.compareToIgnoreCase(cities[idx]) == 0) {
break;
}
}

if (idx < SIZE) {


System.out.println("Search Successful");
System.out.println("City: " + cities[idx]);
System.out.println("STD Code: " + stdCodes[idx]);
}
else {
System.out.println("Search Unsuccessful");
}
}
}

Output
Define a class called 'Mobike' with the following specifications:

Data Members Purpose

int bno To store the bike number

int phno To store the phone number of the customer

String name To store the name of the customer

int days To store the number of days the bike is taken on rent

int charge To calculate and store the rental charge

Member Methods Purpose

void input() To input and store the details of the customer

void compute() To compute the rental charge

void display() To display the details in the given format

The rent for a mobike is charged on the following basis:

Days Charge

For first five days ₹500 per day

For next five days ₹400 per day

Rest of the days ₹200 per day

Output:

Bike No. Phone No. Name No. of days Charge


xxxxxxx xxxxxxxx xxxx xxx xxxxxx
Answer

import java.util.Scanner;
public class Mobike
{
private int bno;
private int phno;
private int days;
private int charge;
private String name;

public void input() {


Scanner in = new Scanner(System.in);
System.out.print("Enter Customer Name: ");
name = in.nextLine();
System.out.print("Enter Customer Phone Number: ");
phno = in.nextInt();
System.out.print("Enter Bike Number: ");
bno = in.nextInt();
System.out.print("Enter Number of Days: ");
days = in.nextInt();
}

public void compute() {


if (days <= 5)
charge = days * 500;
else if (days <= 10)
charge = (5 * 500) + ((days - 5) * 400);
else
charge = (5 * 500) + (5 * 400) + ((days - 10) *
200);
}

public void display() {


System.out.println("Bike No.\tPhone No.\tName\tNo. of
days \tCharge");
System.out.println(bno + "\t" + phno + "\t" + name + "\
t" + days
+ "\t" + charge);
}

public static void main(String args[]) {


Mobike obj = new Mobike();
obj.input();
obj.compute();
obj.display();
}
}
Output

Question 5

Write a program to input and sort the weight of ten people. Sort and display them in descending
order using the selection sort technique.

Answer

import java.util.Scanner;

public class KboatSelectionSort


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
double weightArr[] = new double[10];
System.out.println("Enter weights of 10 people: ");
for (int i = 0; i < 10; i++) {
weightArr[i] = in.nextDouble();
}

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


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

double t = weightArr[i];
weightArr[i] = weightArr[idx];
weightArr[idx] = t;
}

System.out.println("Sorted Weights Array:");


for (int i = 0; i < 10; i++) {
System.out.print(weightArr[i] + " ");
}
}
}
Output

Question 6

Write a program to input a number and print whether the number is a special number or not.

(A number is said to be a special number, if the sum of the factorial of the digits of the number is
same as the original number).

Example:
145 is a special number, because 1! + 4! + 5! = 1 + 24 + 120 = 145.
(Where ! stands for factorial of the number and the factorial value of a number is the product of all
integers from 1 to that number, example 5! = 1 * 2 * 3 * 4 * 5 = 120)

Answer

import java.util.Scanner;

public class KboatSpecialNum


{
public static int fact(int y) {
int f = 1;
for (int i = 1; i <= y; i++) {
f *= i;
}
return f;
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
System.out.print("Enter number: ");
int num = in.nextInt();

int t = num;
int sum = 0;
while (t != 0) {
int d = t % 10;
sum += fact(d);
t /= 10;
}

if (sum == num)
System.out.println(num + " is a special number");
else
System.out.println(num + " is not a special
number");

}
}

Output
Question 7

Write a program to accept a word and convert it into lower case, if it is in upper case. Display the
new word by replacing only the vowels with the letter following it.
Sample Input: computer
Sample Output: cpmpvtfr

Answer

import java.util.Scanner;

public class KboatVowelReplace


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a word: ");
String str = in.nextLine();
str = str.toLowerCase();
String newStr = "";
int len = str.length();

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


char ch = str.charAt(i);

if (str.charAt(i) == 'a' ||
str.charAt(i) == 'e' ||
str.charAt(i) == 'i' ||
str.charAt(i) == 'o' ||
str.charAt(i) == 'u') {

char nextChar = (char)(ch + 1);


newStr = newStr + nextChar;

}
else {
newStr = newStr + ch;
}
}

System.out.println(newStr);
}
}
Output

Question 8

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

1. void compare(int, int) — to compare two integers values and print the greater of the two
integers.
2. void compare(char, char) — to compare the numeric value of two characters and print with
the higher numeric value.
3. void compare(String, String) — to compare the length of the two strings and print the
longer of the two.

Answer

import java.util.Scanner;

public class KboatCompare


{
public void compare(int a, int b) {

if (a > b) {
System.out.println(a);
}
else {
System.out.println(b);
}
}

public void compare(char a, char b) {


int x = (int)a;
int y = (int)b;

if (x > y) {
System.out.println(a);
}
else {
System.out.println(b);
}

public void compare(String a, String b) {

int l1 = a.length();
int l2 = b.length();

if (l1 > l2) {


System.out.println(a);
}
else {
System.out.println(b);
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
KboatCompare obj = new KboatCompare();

System.out.print("Enter first integer: ");


int n1 = in.nextInt();
System.out.print("Enter second integer: ");
int n2 = in.nextInt();
obj.compare(n1, n2);

System.out.print("Enter first character: ");


char c1 = in.next().charAt(0);
System.out.print("Enter second character: ");
char c2 = in.next().charAt(0);
in.nextLine();
obj.compare(c1, c2);

System.out.print("Enter first string: ");


String s1 = in.nextLine();
System.out.print("Enter second string: ");
String s2 = in.nextLine();
obj.compare(s1, s2);
}
}

Output

Question 9

Write a menu driven program to perform the following tasks by using Switch case statement:

(a) To print the series:


0, 3, 8, 15, 24, ............ to n terms. (value of 'n' is to be an input by the user)

(b) To find the sum of the series:


S = (1/2) + (3/4) + (5/6) + (7/8) + ........... + (19/20)

Answer

import java.util.Scanner;
public class KboatSeriesMenu
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 to print series");
System.out.println("0, 3, 8, 15, 24,....to n terms");
System.out.println();
System.out.println("Type 2 to find sum of series");
System.out.println("(1/2) + (3/4) + (5/6) + (7/8) +....
+ (19/20)");
System.out.println();
System.out.print("Enter your choice: ");
int choice = in.nextInt();

switch (choice) {
case 1:
System.out.print("Enter n: ");
int n = in.nextInt();
for (int i = 1; i <= n; i++)
System.out.print(((i * i) - 1) + " ");
System.out.println();
break;

case 2:
double sum = 0;
for (int i = 1; i <= 19; i = i + 2)
sum += i / (double)(i + 1);
System.out.println("Sum = " + sum);
break;

default:
System.out.println("Incorrect Choice");
break;
}
}
}
Output
A private Cab service company provides service within the city at the following rates:

AC CAR NON AC CAR

Upto 5 KM ₹150/- ₹120/-


AC CAR NON AC CAR

Beyond 5 KM ₹10/- PER KM ₹08/- PER KM

Design a class CabService with the following description:

Member variables /data members:

String car_type — To store the type of car (AC or NON AC)

double km — To store the kilometer travelled

double bill — To calculate and store the bill amount

Member methods:

CabService() — Default constructor to initialize data members. String data members to '' ''
and double data members to 0.0.

void accept() — To accept car_type and km (using Scanner class only).

void calculate() — To calculate the bill as per the rules given above.

void display() — To display the bill as per the following format:

CAR TYPE:
KILOMETER TRAVELLED:
TOTAL BILL:

Create an object of the class in the main method and invoke the member methods.

Answer

import java.util.Scanner;

public class CabService


{
String car_type;
double km;
double bill;

public CabService() {
car_type = "";
km = 0.0;
bill = 0.0;
}
public void accept() {
Scanner in = new Scanner(System.in);
System.out.print("Enter car type: ");
car_type = in.nextLine();
System.out.print("Enter kilometer: ");
km = in.nextDouble();
}

public void calculate() {


if (km <= 5) {
if (car_type.equals("AC"))
bill = 150;
else
bill = 120;
}
else {
if (car_type.equals("AC"))
bill = 150 + 10 * (km - 5);
else
bill = 120 + 8 * (km - 5);
}
}

public void display() {


System.out.println("Car Type: " + car_type);
System.out.println("Kilometer Travelled: " + km);
System.out.println("Total Bill: " + bill);
}

public static void main(String args[]) {


CabService obj = new CabService();
obj.accept();
obj.calculate();
obj.display();
}
}
Output

Question 5

Write a program to search for an integer value input by the user in the list given below
using linear search technique. If found display "Search Successful" and print the index of
the element in the array, otherwise display "Search Unsuccessful".

{75, 86, 90, 45, 31, 50, 36, 60, 12, 47}

Answer

import java.util.Scanner;

public class KboatLinearSearch


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

int arr[] = {75, 86, 90, 45, 31, 50, 36, 60, 12, 47};
int l = arr.length;
int i = 0;

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


int n = in.nextInt();

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


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

if (i == l) {
System.out.println("Search Unsuccessful");
}
else {
System.out.println("Search Successful");
System.out.println(n + " present at index " + i);
}
}
}

Output
Question 6

An Abundant number is a number for which the sum of its proper factors is greater than the
number itself. Write a program to input a number and check and print whether it is an
Abundant number or not.

Example:

Consider the number 12.

Factors of 12 = 1, 2, 3, 4, 6 Sum of factors = 1 + 2 + 3 + 4 + 6 = 16

As 16 > 12 so 12 is an Abundant number.

Answer

import java.util.Scanner;

public class KboatAbundantNumber


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

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


if (n % i == 0)
sum += i;
}

if (sum > n)
System.out.println(n + " is an abundant number");
else
System.out.println(n + " is not an abundant
number");
}
}

Output
Question 7

Design a class to overload a method Number() as follows:

(i) void Number(int num, int d) — To count and display the frequency of a digit in a number.

Example:

num = 2565685
d=5
Frequency of digit 5 = 3

(ii) void Number(int n1) — To find and display the sum of even digits of a number.

Example:

n1 = 29865
Sum of even digits = 2 + 8 + 6 = 16

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

Answer

public class Overload


{
void Number(int num, int d) {
int f = 0;

while (num != 0) {
int x = num % 10;
if (x == d) {
f++;
}
num /= 10;
}

System.out.println("Frequency of digit " + d + " = " +


f);
}

void Number(int n1) {


int s = 0;

while (n1 != 0) {
int x = n1 % 10;
if (x % 2 == 0) {
s = s + x;
}
n1 /= 10;
}

System.out.println("Sum of even digits = " + s);


}

public static void main(String args[]) {


Overload obj = new Overload();
obj.Number(2565685, 5);
obj.Number(29865);
}
}
Output

Question 8

Write a menu driven program to perform the following operations as per user’s choice:

(i) To print the value of c=a²+2ab, where a varies from 1.0 to 20.0 with increment of 2.0 and
b=3.0 is a constant.

(ii) To display the following pattern using for loop:

A
AB
ABC
ABCD
ABCDE

Display proper message for an invalid choice.

Answer

import java.util.Scanner;

public class KboatMenu


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 for Value of c");
System.out.println("Type 2 for pattern");
System.out.print("Enter your choice: ");

int choice = in.nextInt();

switch (choice) {
case 1:
final double b = 3.0;
for (int a = 1; a <= 20; a += 2) {
double c = Math.pow(a, 2) + 2 * a * b;
System.out.println("Value of c when a is "
+ a + " = " + c);
}
break;

case 2:
for (char i = 'A'; i <= 'E'; i++) {
for (char j = 'A'; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
break;

default:
System.out.println("INVALID CHOICE");
}
}
}
Output
Question 9

Write a program to input integer elements into an array of size 20 and perform the following
operations:
1. Display largest number from the array.
2. Display smallest number from the array.
3. Display sum of all the elements of the array

Answer

import java.util.Scanner;

public class KboatSDAMinMaxSum


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int arr[] = new int[20];
System.out.println("Enter 20 numbers:");
for (int i = 0; i < 20; i++) {
arr[i] = in.nextInt();
}
int min = arr[0], max = arr[0], sum = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] < min)
min = arr[i];

if (arr[i] > max)


max = arr[i];

sum += arr[i];
}

System.out.println("Largest Number = " + max);


System.out.println("Smallest Number = " + min);
System.out.println("Sum = " + sum);
}
}
Output
Question 4

Define a class named Customer with the following description:

Instance variables /Data members:

String cardName — Name of the card holder.

long cardNo — Card Number.

char cardType — Type of card, 'P' for Platinum, 'G' for Gold, 'S' for Silver.

double purchaseAmount — The amount of purchase done on card.

double cashback — The amount of cashback received.

Member methods:

Customer(String name, long num, char type, double amt) — Parameterised constructor to
initialize all data members.

void compute() — To compute the cashback based on purchase amount as follows:

1. For Silver ('S'), 2% of purchase amount


2. For Gold ('G'), 5% of purchase amount
3. For Platinum ('P'), 8% of purchase amount

void display() — To display the details in the below format:

Card Holder Name:


Card Number:
Purchase Amount:
Cashback:

Write a main method to input the card details from the user then create object of the class
and call the member methods with the provided details.

Answer

import java.util.Scanner;

public class Customer


{
String cardName;
long cardNo;
char cardType;
double purchaseAmount;
double cashback;
public Customer(String name,
long num,
char type,
double amt) {
cardName = name;
cardNo = num;
cardType = type;
purchaseAmount = amt;
cashback = 0;
}

void compute() {
switch (cardType) {
case 'S':
cashback = 2.0 * purchaseAmount / 100.0;
break;

case 'G':
cashback = 5.0 * purchaseAmount / 100.0;
break;

case 'P':
cashback = 8.0 * purchaseAmount / 100.0;
break;

default:
System.out.println("INVALID CARD TYPE");
}
}

void display() {
System.out.println("Card Holder Name: " + cardName);
System.out.println("Card Number: " + cardNo);
System.out.println("Purchase Amount: " +
purchaseAmount);
System.out.println("Cashback: " + cashback);
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
System.out.println("Enter Card Holder Name:");
String n = in.nextLine();
System.out.println("Enter Card Number:");
long no = in.nextLong();
System.out.println("Enter Card Type:");
char t = in.next().charAt(0);
System.out.println("Enter Purchase Amount:");
double a = in.nextDouble();

Customer obj = new Customer(n, no, t, a);


obj.compute();
obj.display();
}
}

Output
Question 5

Using switch-case statement write a menu driven program for the following:

1. To display the pattern given below:


A
BC
DEF
GHIJ
KLMNO

2. To display the sum of the series given below:


1/1! + 3/3! + 5/5! + ..... + n/n!

Answer

import java.util.Scanner;

public class KboatMenu


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Type 1 for Pattern");
System.out.println("Type 2 for Series");
System.out.print("Enter your choice: ");
int choice = in.nextInt();
switch (choice) {
case 1:
char ch = 'A';
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(ch + " ");
ch++;
}
System.out.println();
}
break;

case 2:
System.out.print("Enter n: ");
int n = in.nextInt();
double s = 0;
for (int i = 1; i <= n; i++) {
double f = 1;
for (int j = 1; j <= i; j++) {
f *= j;
}
double t = i / f;
s += t;
}
System.out.println("Series Sum = " + s);
break;

default:
System.out.println("Incorrect Choice");
}
}
}

Output
Question 6

Write a program to input and store roll number and total marks of 20 students. Using
Bubble Sort technique generate a merit list. Print the merit list in two columns containing
roll number and total marks in the below format:

Roll No. Total Marks


... ...
... ...
... ...

Answer

import java.util.Scanner;

public class MeritList


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = 20;
int rollNum[] = new int[n];
int marks[] = new int[n];
for (int i = 0; i < n; i++) {
System.out.print("Enter Roll Number: ");
rollNum[i] = in.nextInt();
System.out.print("Enter marks: ");
marks[i] = in.nextInt();
}

//Bubble Sort
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (marks[j] < marks[j + 1]) {
int t = marks[j];
marks[j] = marks[j+1];
marks[j+1] = t;

t = rollNum[j];
rollNum[j] = rollNum[j+1];
rollNum[j+1] = t;
}
}
}

System.out.println("Roll No.\t\tTotal Marks");


for (int i = 0; i < n; i++) {
System.out.println(rollNum[i] + "\t\t" + marks[i]);
}
}
}
Output
Question 7

Write a class with the name Area using function overloading that computes the area of a
parallelogram, a rhombus and a trapezium.

Formula:

Area of a parallelogram (pg) = base * ht

Area of a rhombus (rh) = (1/2) * d1 * d2


(where, d1 and d2 are the diagonals)

Area of a trapezium (tr) = (1/2) * ( a + b) * h


(where a and b are the parallel sides, h is the perpendicular distance between the parallel
sides)

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

Answer

import java.util.Scanner;

public class Area


{
public double area(double base, double height) {
double a = base * height;
return a;
}

public double area(double c, double d1, double d2) {


double a = c * d1 * d2;
return a;
}

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


double x = c * (a + b) * h;
return x;
}

public static void main(String args[]) {


Scanner in = new Scanner(System.in);
Area obj = new Area();

System.out.print("Enter base of parallelogram: ");


double base = in.nextDouble();
System.out.print("Enter height of parallelogram: ");
double ht = in.nextDouble();
System.out.println("Area of parallelogram = " +
obj.area(base, ht));

System.out.print("Enter first diagonal of rhombus: ");


double d1 = in.nextDouble();
System.out.print("Enter second diagonal of rhombus: ");
double d2 = in.nextDouble();
System.out.println("Area of rhombus = " + obj.area(0.5,
d1, d2));

System.out.print("Enter first parallel side of


trapezium: ");
double a = in.nextDouble();
System.out.print("Enter second parallel side of
trapezium: ");
double b = in.nextDouble();
System.out.print("Enter height of trapezium: ");
double h = in.nextDouble();
System.out.println("Area of trapezium = " +
obj.area(0.5, a, b, h));
}
}
Output

Question 8

Write a program to print the sum of negative numbers, sum of positive even numbers and
sum of positive odd numbers from a list of numbers entered by the user. The list terminates
when the user enters a zero.

Answer

import java.util.Scanner;

public class KboatNumberSum


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int nSum = 0, eSum = 0, oSum = 0;
System.out.println("Enter Numbers:");
while (true) {
int n = in.nextInt();

if (n == 0) {
break;
}

if (n < 0) {
nSum += n;
}
else if (n % 2 == 0) {
eSum += n;
}
else {
oSum += n;
}
}

System.out.println("Negative No. Sum = " + nSum);


System.out.println("Positive Even No. Sum = " + eSum);
System.out.println("Positive Odd No. Sum = " + oSum);
}
}
Output

Question 9

Write a program to take a number from the user as input. Find and print the largest digit
of the number.

Example:

Sample Input: 748623


Largest digit: 8

Answer

import java.util.Scanner;

public class KboatLargestDigit


{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter Number: ");
int n = in.nextInt();
int l = -1;
while (n != 0) {
int d = n % 10;
if (d > l)
l = d;
n /= 10;
}
System.out.println("Largest Digit = " + l);
}
}

Output

You might also like