0% found this document useful (0 votes)
8 views93 pages

Answers Book For Platinum Book

The document provides answers and explanations for multiple-choice questions related to Java programming concepts, including keywords, operators, data types, and control structures. It covers various topics such as inheritance, polymorphism, method declarations, and memory management. Each answer is accompanied by a brief explanation to clarify the reasoning behind the correct choice.

Uploaded by

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

Answers Book For Platinum Book

The document provides answers and explanations for multiple-choice questions related to Java programming concepts, including keywords, operators, data types, and control structures. It covers various topics such as inheritance, polymorphism, method declarations, and memory management. Each answer is accompanied by a brief explanation to clarify the reasoning behind the correct choice.

Uploaded by

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

Answer booklet of Platinum Book

Answers of MCQ
1. (b) Polymorphism
o Showing different faces.
2. (b) boolean
o Character.isWhitespace(char) returns a boolean value (true or false)
indicating whether the given character is a whitespace.
3. (c) Platform-independent
o The JVM enables Java applications to run on any machine with a JVM
installed, making Java platform-independent.
4. (a) 2 bytes
o The newline character ('\n') is stored as a Unicode character in Java,
which takes 2 bytes.
5. (d) 2.0
o Math.pow(625, 1/2) evaluates to Math.pow(625, 0) = 1, but
Math.sqrt(625) should be used instead.
Math.sqrt(169) - 14 = 13 - 14 = -1.0, and Math.abs(-1) = 1, so 1.0 + 1.0 =
2.0.
6. (c) vcr
o "java".charAt(2) gives 'v', and "script".substring(1, 3) gives "cr", so the
result is "vcr".
7. (a) extends
o The extends keyword is used to inherit a class in Java.
8. (c) 48 bytes
o A float takes 4 bytes. A one-dimensional array of 12 elements takes 12 ×
4 = 48 bytes.
9. (c) 3data
o Variable names cannot start with a digit.
10. (a) 30 20 10
o The loop starts at arr.length - 2 = 2 (value 30) and prints in reverse
order.
11. (b) Supports floating point constants
o The switch statement does not support floating-point values.
12. (d) Syntax
o "10" is a string, not an integer, so int num = "10"; causes a syntax error.
13. (c) The return type, method name, and parameter list
o A method prototype defines these attributes.
14. (a) boolean isEven(int number)
o This is a correct method declaration.
15. (c) (.)dot
o The dot (.) operator accesses class methods.
16. (c) Assertion (A) is true and Reason (R) is false
o The String class is part of java.lang, but not all Java classes belong to
java.lang by default.
17. (a) for(int i = 0; i < 10; i++)
o This is the correct for loop syntax.
18. (b) A constructor is called automatically when an object is created.

Page 1 of 93
o A constructor is invoked when an object is instantiated.
19. (a) (4) (1) (2) (3)
o The variable n must be declared first before using it.
20. (c) Assertion (A) is true and Reason (R) is false
o Method overloading does not depend on return types, only on method
parameters.
Let me know if you need further clarification! �
Here are the answers to the given MCQs:
21. (c) float
 Explanation: char is implicitly converted to int, and int is promoted to float in
the expression due to b being float.
22. (b) SimpleInterest
 Explanation: A valid class name in Java should not contain spaces, special
characters (except _ or $), or start with a digit.
23. (d) It can be invoked using an object like any other member function.
 Explanation: Constructors are automatically called when an object is
instantiated and cannot be explicitly invoked like normal methods.
24. (d) 9.7
 Explanation:
o Math.cbrt(27) → 3.0 (cube root of 27)
o Math.sqrt(169) → 13.0
o Math.max(-12.7, -14.5) → -12.7
o Math.min(13.0, -12.7) → -12.7
o 3.0 + (-12.7) = 9.7
25. (c) 109
 Explanation:
o s.charAt(1) → 'a' (1st index of "Happy New Year")
o s.lastIndexOf('a') → 109 (ASCII value of 'a' concatenated with
s.lastIndexOf('a'))
26. (c) Manual Memory Management
 Explanation: Java has automatic memory management using Garbage
Collection.
27. (a) \"
 Explanation: The escape sequence \" is used to include a double quote in a
string.
28. (b) static
 Explanation: The static keyword is used to declare class variables (shared
among all objects).
29. (b) new
 Explanation: The new keyword is used to instantiate (create) objects from a
class.
30. (c) extends
 Explanation: The extends keyword is used for inheritance in Java (to derive a
subclass from a superclass).

31. Which of the following is used to declare a constant variable?


� (b) final
Explanation: The final keyword ensures that a variable‟s value cannot be changed
after it has been assigned.

Page 2 of 93
32. What is the correct syntax to define a method that does not return a value?
� (c) void
Explanation: The void keyword is used when a method does not return any value.

33. Which of the following is used to refer to the current instance of a class?
� (b) this
Explanation: The this keyword refers to the current instance of the class and is
used to distinguish between instance variables and local variables.

34. What keyword is used to prevent a method from being overridden?


� (d) final
Explanation: When a method is declared with the final keyword, it cannot be
overridden in a subclass.

35. Which keyword is used to define a method without any implementation in


Java?

� (b) abstract
Explanation: The abstract keyword is used to declare a method without
implementation. Abstract methods must be implemented by subclasses.

36. Which keyword is used to break out of a loop?

� (b) break
Explanation: The break statement is used to exit a loop prematurely.

37. Which of the following operators is of the lowest precedence?

� (a) &&
Explanation: The logical AND (&&) has lower precedence than arithmetic operators
(+, *, %).

38. A variable can be made constant using which keyword?

� (b) final
Explanation: The final keyword makes a variable constant, meaning its value
cannot be changed after assignment.

39. A class acquiring the properties of another class is called:

Page 3 of 93
� (a) inheritance
Explanation: Inheritance is a mechanism in which a class derives properties and
behaviors from another class using the extends keyword.

40. Which of the following is a unary operator?

� (b) --
Explanation: The decrement operator (--) is a unary operator because it operates on
a single operand.

41. What will be the output of the following statement?


System.out.println(5 + 2 * 3);
Answer: (b) 11
(Multiplication () has higher precedence than addition (+), so 2 * 3 = 6, then 5 + 6
= 11.)*
42. In the given code, what is the value of X and Y?
Answer: (b) X - Actual Parameter, Y - Formal Parameter
(In the method call Compute(X), X is the actual parameter, and in the method
definition Compute(int Y), Y is the formal parameter.)
43. What is the result of the expression:
System.out.println(0.5 * 2 + 5 > 5 ? true : false);
Answer: (b) true
(0.5 * 2 = 1, then 1 + 5 = 6, and 6 > 5 is true, so the output is true.)
44. What is the maximum number of values a method can return in Java?
Answer: (a) 1
(A method in Java can return only one value at a time.)
45. Which of the following operators has the highest precedence?
Answer: (b) *
(Multiplication () has higher precedence than logical AND (&&), equality (==), and
logical OR (||).)*
46. Which of the following operators has the lowest precedence?
Answer: (c) =
(The assignment operator = has the lowest precedence in Java.)
47. Which of the following has a higher precedence?
Answer: (a) ++
(Increment operator (++) has the highest precedence among the given options.)
48. Among the following, which operator is evaluated last?
Answer: (c) ==
(Equality (==) has lower precedence than AND (&&) and modulo (%).)
49. Which operator has a lower precedence than addition (+)?
Answer: (c) ==
(Equality operator (==) has lower precedence than addition (+).)
50. Which keyword is used to define a method in Java that cannot be
overridden?
Answer: (c) final
(Methods declared as final cannot be overridden in Java.)
51. b) false

Page 4 of 93
52. b) final
53. c)
54. a) int[] arr;
55. c) 123value (Identifiers cannot start with a digit.)
56. b) new
57. a) void
58. b) == (Used for comparison.)
59. a) final (Prevents inheritance.)
60. a) Method overloading (Same method name with different parameters.)
61. (b) Polymorphism – It allows a class to have multiple forms of a method (method
overloading and method overriding).
62. (d) Abstraction – It hides implementation details and exposes only functionality.
63. (b) Method overriding – This occurs at runtime when a subclass provides a
specific implementation of a method declared in its superclass.
64. (d) Compilation – It is not a pillar of OOP. The four pillars are Inheritance,
Encapsulation, Polymorphism, and Abstraction.
65. (a) Class – A class defines the blueprint for creating objects.
66. (b) Encapsulation – It restricts direct access to an object's attributes and allows
controlled access via methods.
67. (b) Polymorphism – It enables a method to behave differently based on the object
it is acting upon.
68. (d) default – While Java has a default access level, there is no explicit "default"
keyword for access modifiers.
69. (a) Inheritance – One class acquiring the properties and behaviors of another is
called inheritance.
70. (b) && – It is the logical AND operator in Java.
Here are the answers to the questions, along with explanations for each one:

71. Which one of the following is a relational operator?


Answer: b) >
 Explanation: A relational operator compares two values. The > (greater than)
operator is used to compare two values to check if the first one is greater than
the second one. Other operators like +, *, and -- are not relational operators.

72. Which one of the following is a bitwise operator?


Answer: a) &
 Explanation: The & operator is a bitwise AND operator. It operates on the
individual bits of integers. Other options like || (logical OR), ! (logical NOT), and
/ (division) are not bitwise operators.

73. Which one of the following is a ternary operator?


Answer: b) ? :
 Explanation: The ternary operator ? : is used to evaluate a condition and
return one of two values based on that condition. It's a shorthand for an if-else
statement. The other operators &&, +, and % are not ternary operators.

74. Which one of the following is an assignment operator?


Answer: a) +=

Page 5 of 93
 Explanation: The += operator is an assignment operator that adds a value to a
variable and assigns the result back to the variable. The other options like ==,
/, and > are not assignment operators.

75. Which one is a relational operator?


Answer: a) ==
 Explanation: The == operator is used to compare two values for equality. If they
are equal, it returns true. The other options (++, +=, and --) are not relational
operators; they perform other actions like incrementing or assigning values.

76. Which of the following is an assignment operator?


Answer: c) =
 Explanation: The = operator is the basic assignment operator. It assigns the
value on the right-hand side to the variable on the left-hand side. Other options
like !=, ==, and & do not assign values.

77. Which one is a bitwise operator?


Answer: a) |
 Explanation: The | operator is a bitwise OR operator. It operates on the bits of
two integers. It returns a 1 if either of the bits is 1, otherwise 0. Other options
like &&, >, and += are not bitwise operators.

78. Which operator is used to check equality between two values?


Answer: a) ==
 Explanation: The == operator is used to check whether two values are equal. If
they are equal, it returns true; otherwise, it returns false. The = operator is for
assignment, and != checks inequality.

79. Which of the following is a conditional operator?


Answer: a) ? :
 Explanation: The ? : is the conditional (ternary) operator, which evaluates a
condition and returns one of two values based on whether the condition is true
or false. The other options (=, &, and ++) are not conditional operators.

80. Which one is an arithmetic operator?


Answer: a) +
 Explanation: The + operator is used for addition and is an arithmetic operator.
Other options like || (logical OR), == (equality check), and & (bitwise AND) are
not arithmetic operators.

81. Which one is an increment operator?


Answer: a) ++
 Explanation: The ++ operator is the increment operator, which increases the
value of a variable by 1. The -- operator is a decrement operator (decreases the
value by 1), and += is an assignment operator, not an increment operator.

82. Which of the following is a logical AND operator?


Answer: a) &&

Page 6 of 93
 Explanation: The && operator is the logical AND operator, which evaluates
whether both conditions are true. Other options like || (logical OR), ! (logical
NOT), and &= (bitwise AND assignment) are not logical AND operators.

83. What will be the output of the following expression?


Math.sqrt(144) - 12
Answer: a) 0
 Explanation: Math.sqrt(144) gives the square root of 144, which is 12. Then,
subtracting 12 from 12 results in 0.

84. Evaluate the following expression:


Math.pow(3, 3) - 27
Answer: a) 0
 Explanation: Math.pow(3, 3) calculates 3 raised to the power of 3, which is 27.
Subtracting 27 from 27 gives 0.
85. What is the result of this expression?
Math.floor(5.8) + Math.ceil(4.2)
 Math.floor(5.8) returns 5 (rounds down to the nearest integer).
 Math.ceil(4.2) returns 5 (rounds up to the nearest integer).
 So, 5 + 5 = 10.
Answer: (b) 10

86. What will be the output?


Math.abs(-50) + Math.min(5, 10)
 Math.abs(-50) returns 50 (absolute value of -50).
 Math.min(5, 10) returns 5 (smallest value between 5 and 10).
 So, 50 + 5 = 55.
Answer: (b) 55

87. Evaluate the result of this expression:


Math.max(25, 40) - Math.min(20, 15)
 Math.max(25, 40) returns 40 (largest value between 25 and 40).
 Math.min(20, 15) returns 15 (smallest value between 20 and 15).
 So, 40 - 15 = 25.
Answer: (b) 25

88. The do-while loop is an entry-controlled loop.


 False, because a do-while loop executes at least once before checking the
condition (exit-controlled loop).
Answer: (b) False

89. The if-else statement is used to iterate a block of code multiple times.
 False, because if-else is used for decision-making, not iteration. Loops (like for,
while) are used for iteration.
Answer: (b) False

90. The switch statement can work with char, int, and String types in Java.
 True, because Java supports char, int, byte, short, enum, and String in
switch statements.
Answer: (a) True

Page 7 of 93
91. The break statement terminates the innermost loop or switch statement.
 True, because the break statement stops execution inside the nearest loop or
switch block.
Answer: (a) True

92. In Java, a static variable is shared among all instances of a class.


 True, because static variables belong to the class, not an instance, so they are
shared among all objects.
Answer: (a) True

93. A constructor can have a return type.


 False, because a constructor does not have a return type, not even void.
Answer: (b) False

94. The continue statement skips the remaining code in the current iteration of
the loop and proceeds with the next iteration.
 True, because continue forces the loop to jump to the next iteration.
Answer: (a) True

95. An abstract class cannot have any implemented methods.


 False, because an abstract class can have both abstract and non-abstract
methods.
Answer: (b) False

96. Literal can be of which of these data types?


 Literals can be integer, float, boolean, char, String, etc.
 Answer: (d) all of the mentioned

97. What will be the output of the following program?


class Test {
static void main() {
int i = 1;
int j = 20;
int k = 31;
while (i < j) {
k += (i * j);
i = i * 2;
j--;
}
System.out.println("i = " + i + " j = " + j + " k = " + k);
}
}
Let's dry run the program:
i j k (calculated as k += i * j)
1 20 31 + (1 * 20) = 51
2 19 51 + (2 * 19) = 89
4 18 89 + (4 * 18) = 161

Page 8 of 93
i j k (calculated as k += i * j)
8 17 161 + (8 * 17) = 297
16 16 loop exits
Final values:
i = 16, j = 16, k = 297
Answer: (b) i = 16 j = 16 k = 297

98. What is the extension of compiled Java classes?


 Java files are compiled into bytecode with a .class extension.
Answer: (c) .class

99. Which of the following for loop declaration is not valid?


 (a) for ( int i = 99; i >= 0; i / 9 ) → Invalid, because i / 9 does not update i
properly.
 (b) for ( int i = 7; i <= 77; i += 7 ) → Valid
 (c) for ( int i = 20; i >= 2; --i ) → Valid
 (d) for ( int i = 2; i <= 20; i = 2 * i ) → Valid
Answer: (a) for ( int i = 99; i >= 0; i / 9 )

100. What is the entry point of a program in Java?


 The main() method is the entry point for Java programs.
Answer: (a) main() method

Here are the answers along with explanations for each question:
101. Output of the Java program
class array {
static void main() {
int variable[] = new int[10];
for (int i = 0; i < 10; ++i) {
variable[i] = i;
System.out.print(variable[i] + " ");
i++;
}
}
}
Analysis:
 The loop initializes i = 0 and increments it by ++i at each iteration.
 Inside the loop, variable[i] = i assigns the current i value to variable[i].
 System.out.print(variable[i] + " ") prints the value.
 i++ at the end of the loop causes an extra increment, effectively skipping every
alternate value.
Output:
02468
Correct Option: (a) 0 2 4 6 8

102. Default value for reference data types


 Reference types in Java (e.g., objects, arrays) have a default value of null.
Correct Option: (c) null

Page 9 of 93
103. Operators that can operate on a boolean variable
 && (Logical AND) �
 == (Equality check) �
 ?: (Ternary operator) �
 += (Invalid for boolean) �
Correct Option: (d) A, B & C

104. Return value of compareTo() when the invoking string is greater


 compareTo() returns:
o A positive value if the invoking string is greater.
o 0 if both are equal.
o A negative value if the invoking string is smaller.
Correct Option: (a) a value that is greater than zero

105. Correct statements about switch


 Nested switch is allowed �
 switch inside if-else is allowed �
 switch inside loops is allowed �
Correct Option: (d) All

106. Output of the loop


int cnt = 0;
while (true) {
if (cnt > 4)
break;
if (cnt == 0) {
cnt++;
continue;
}
System.out.print(cnt + ",");
cnt++;
}
Analysis:
 cnt == 0, so it increments and skips continue.
 Prints 1, 2, 3, 4 before cnt > 4 breaks the loop.
Output: 1,2,3,4,
Correct Option: (a) 1,2,3,4

107. Least restrictive access modifier


 allows access from anywhere.
Correct Option: (a)

108. Constructor Overloading


 Overloading means adding multiple constructors with different parameters.
 Minimum: 1 constructor.
Correct Option: (a) 1

109. Output of Ternary Operator


String name1 = "pen";
String name2 = "pen";

Page 10 of 93
int marks = name2.equals(name1) ? 50 : 80;
System.out.println("Marks=" + marks);
 Since name2.equals(name1) is true, marks = 50.
Output: Marks=50
Correct Option: (b) Marks=50

109. Output of the loop


class Test {
static void main() {
int i = 0;
for (i = 0; i < 10; i++)
break;
System.out.println(i);
}
}
Analysis:
 The break exits the loop immediately on the first iteration.
 i remains 0.
Output: 0
Correct Option: (b) 0

110. Execution count of the do-while loop


int x = 1, y = 10, z = 1;
do {
y--;
x++;
y -= 2;
y = z;
z++;
} while (y > 1 && z < 10);
Analysis:
 The loop executes only once before y > 1 fails.
Correct Option: (a) 1

111. Modulo operation with negative values


Expression: m % n where m = -14, n = -3
-14 % -3 = -2
Correct Option: (c) -2

112. Feature for converting primitives to wrapper classes


 Autoboxing: Converts primitive to Wrapper (e.g., int → Integer).
 Unboxing: Converts Wrapper to primitive.
Correct Option: (d) Both A and B

113. Type of error in double x; y; z;


 Syntax error because y; and z; are not declared properly.
Correct Option: (b) Syntax error

114. Parameters in method calls


 Arguments used in method calls are Actual Parameters.

Page 11 of 93
Correct Option: (a) Actual parameters

115. OOP Principle


 Polymorphism : as this picture is predicting different working profile of a
woman.
Correct Option: (d) Polymorphism
Here are the answers with explanations:
116. What feature of Java refers to the ability to define classes and create objects?
� ( a) Object-Oriented
Explanation: Java is an object-oriented programming language, which means it
allows the creation of classes and objects to structure programs in a modular way.

117. The size of a byte data type in Java is:


� ( b) 8 bits
Explanation: In Java, the byte data type is always 8 bits (1 byte) in size, storing
values from -128 to 127.

118. What is the order of precedence in the expression: a && b || !c?


� ( b) ! > && > ||
Explanation:
 ! (logical NOT) has the highest precedence.
 && (logical AND) comes next.
 || (logical OR) has the lowest precedence.
So the expression is evaluated as: a && b || (!c)

119. What keyword is used in Java to inherit a class?


� ( b) extends
Explanation: The extends keyword is used in Java for class inheritance. Example:
class Child extends Parent { }

120. The output of the following code:


System.out.println(Math.round(8.5) + Math.round(-3.5));
� ( a) 6
Explanation:
 Math.round(8.5) → 9 (rounds to the nearest integer, rounding up for .5)
 Math.round(-3.5) → -3 (rounds to the nearest integer, rounding up for .5
towards zero)
So, 9 + (-3) = 6

121. Which method can be used to compare two strings lexicographically?


� ( c) compareTo(String)
Explanation: The compareTo method compares two strings based on their Unicode
values.

122. Which of the following statements about the switch statement is false?
� ( c) The expression in a switch statement can be a long.
Explanation: The switch expression can only be byte, short, char, int, String, or
enum. It cannot be long.

Page 12 of 93
123. Which of the following is true about method overloading in Java?
� ( b) Methods can have the same name but different parameter lists.
Explanation: Method overloading means defining multiple methods with the same
name but with different parameter lists (number, type, or order of parameters).

124. What is the correct way to understand the difference between an identifier and a
keyword in Java?
� ( c) Identifiers are user-defined names, while keywords are reserved words in
Java.
Explanation: Keywords are reserved by Java and cannot be used as variable names,
while identifiers are names given to variables, methods, and classes.

125. What will be the output of the following code?


String str = "123.45";
int num = (int) Double.parseDouble(str);
System.out.println(num);
� ( a) 123
Explanation:
 Double.parseDouble("123.45") converts the string to 123.45 (double).
 (int) 123.45 truncates the decimal part, leaving 123.

126. Method prototype for the method compute which accepts two integer arguments
and returns true/false:
� ( b) boolean compute(int a, int b)
Explanation:
 A method that returns true/false must have the boolean return type.
 It should also have proper parameter declarations.

127. Which of the following statements terminates the execution of the current
method and returns control to the calling method?
� ( c) return
Explanation: The return statement exits from the current method and optionally
returns a value.

128. The default value of a reference variable is:


� ( b) null
Explanation: Reference variables (String, Arrays, Objects) default to null if not
initialized.

129. The method to check if a character is a digit is:


� ( a) Character.isDigit(char)
Explanation: Character.isDigit(char) checks if a character is a digit (0-9).

130. Assertion (A): The Math class can be used in Java programs without importing
any package.
Reason (R): The Math class belongs to the java.lang package, which is automatically
imported by default.
� ( a) Both Assertion (A) and Reason (R) are true and Reason (R) is a correct
explanation of Assertion (A).

Page 13 of 93
Explanation: java.lang is automatically imported in all Java programs, so Math
methods can be used without an explicit import.

131. *A. z = 2;
Explanation: z *= 2; correctly doubles the value of z. The given statement z =* 2;
is incorrect, as the *= operator should be used instead.
132. B. .class
Explanation: When you compile a Java source file (with a .java extension), the
output file generated is a .class file containing the bytecode.
133. B. (3) (4) (1) (2)
Explanation: The correct sequence to swap two variables using a third variable
is:
 (3) Declare the third variable (int t = 0;)
 (4) Assign the value of a to t (t = a;)
 (1) Assign the value of b to a (a = b;)
 (2) Assign the value of t to b (b = t;)
134. A. Both Assertion (A) and Reason (R) are true and Reason (R) is a
correct explanation of Assertion (A)
Explanation: void means a method does not return any value, and it is used for
methods that perform actions without returning a result.
135. A. Refers to the current object of a class.
Explanation: The this keyword is used to refer to the current instance (object) of
the class.
136. B. 60
Explanation: The numbers divisible by 20 in the array are 20 and 40. So, their
sum is 60.
137. D. for (int i = 1; ; i++) { }
Explanation: This loop lacks a termination condition, so it will run indefinitely
(infinite loop).
138. B. String
Explanation: String.valueOf(int) returns a String representing the integer value.
139. D. 0 to n-1
Explanation: In Java, array indices start from 0, so the valid index range for an
array of size n is 0 to n-1.
140. B. int multiply(int a, int b)
Explanation: The function prototype should specify the return type first (int),
followed by the method name and its parameters.
141. A. Exits the switch block and continues execution after the switch
Explanation: The break statement in a switch block exits the block and
continues execution after it.
142. B. Both Assertion (A) and Reason (R) are correct, but Reason (R) is
not the correct explanation for Assertion (A).
Explanation: An array is a collection of elements of the same type, but its size
doesn't need to be defined at the time of creation if using dynamic memory in
Java (e.g., using ArrayList).
143. A. do { } while(condition);
Explanation: The correct syntax for a do-while loop is: do { } while (condition);.
144. B. A default constructor will be automatically provided by the
compiler.

Page 14 of 93
Explanation: If no constructor is explicitly defined, the Java compiler provides a
default no-argument constructor.
145. B.
Explanation: The correct way to calculate the sum of the first n natural
numbers is by starting the loop from 1 and going up to n (inclusive).
146. A. Both Assertion (A) and Reason (R) are correct, and Reason (R) is
the correct explanation for Assertion (A).
Explanation: A function prototype in C or Java provides the function name,
return type, and parameters, and allows for type checking.
147. B. Polymorphism
149. A. boolean
Explanation: The isDigit(char) function returns a boolean indicating whether the
character is a digit or not.
150. C. Conditional
Explanation: The ?: operator is the ternary (conditional) operator in Java, which
evaluates a condition and returns one of two values based on whether the condition is
true or false.
Here are the answers with explanations for the questions:

151. What is the last index of an array containing N elements?


Answer: B. N-1
Explanation: In Java (and many other programming languages), array indices start at
0. Therefore, for an array with N elements, the indices go from 0 to N-1, and the last
index is N-1.

152. The correct term for converting an object to its corresponding data type is:
Answer: B. Unboxing
Explanation: Unboxing refers to converting an object to a corresponding data type.

153. What is the result of Math.ceil(4.2) - Math.floor(2.8)?


Answer: B. 3.0
Explanation:
 Math.ceil(4.2) returns 5.0 (rounds up to the nearest integer).
 Math.floor(2.8) returns 2.0 (rounds down to the nearest integer). So, 5.0 - 2.0 =
3.0.

154. The output of System.out.println("Java".compareTo("JAVA")); is:


Answer: C. A positive number
Explanation: The compareTo() method compares two strings lexicographically (based
on their Unicode values).

155. A member variable declared with a access specifier has visibility only in
the:
Answer: B. class
Explanation: A variable with the access modifier is only visible within the class in
which it is declared. It cannot be accessed directly outside of that class.

156. Which keyword is used to create memory dynamically?


Answer: A. new

Page 15 of 93
Explanation: In Java, the new keyword is used to dynamically allocate memory for
objects.

157. When a complete if or if-else statement is written inside another if


statement, it is known as:
Answer: B. Nested if
Explanation: A nested if is when one if or if-else statement is placed inside another if
statement.

158. What is the output of the following code?


char a = 'D';
char b = 'd';
int c = a + b;
System.out.println(c);
Answer: B. 186
Explanation: The ASCII value of 'D' is 68 and the ASCII value of 'd' is 100. So, 68 +
100 = 168. Therefore, the output is 168.

159. Expressions that have all operands of the same type are called:
Answer: A. Pure
Explanation: Expressions where all operands are of the same type are often referred to
as "pure" expressions. If operands of different types are mixed, it would be a "mixed"
expression.

160. Arrange the following data types in descending order of their size:
Answer: B. double, float, short, byte
Explanation: In Java, the size of the primitive data types is as follows:
 double is 8 bytes.
 float is 4 bytes.
 short is 2 bytes.
 byte is 1 byte.

161. Assertion (A): Polymorphism allows an object to take multiple forms.


Reason (R): In Java, polymorphism refers to hiding the implementation details of
an object, exposing the essential details to the user.
Answer: C. Assertion (A) is true, and Reason (R) is false.
Explanation: Polymorphism refers to the ability of an object to take many forms, such
as method overloading or method overriding. However, the statement in Reason (R)
about hiding implementation details refers more to encapsulation rather than
polymorphism.

162. The access specifier that gives the least accessibility is:
Answer: B.
Explanation: The access modifier restricts access to the member only within the
same class. It provides the least accessibility compared to and protected.

163. Predict the output:


int a[] = {5, 2, 8, 16, -2};
double m = Math.ceil(Math.pow(a[1], a[4]));
System.out.println(m);

Page 16 of 93
Answer: C. 0.25
Explanation:
 a[1] is 2 and a[4] is -2.
 Math.pow(2, -2) equals 0.25 (2 raised to the power of -2).
 Math.ceil(0.25) returns 1.0, so the output is 1.0.

164. Evaluate the value of a, if p = 5, q = 19:


int a = (p - q) > (q - p) ? (q - p) : (p - q);
Answer: B. 13
Explanation:
 (p - q) is 5 - 19 = -14.
 (q - p) is 19 - 5 = 14.
 Since -14 is not greater than 14, the value of a is (p - q), which is -14.

165. Which of the following is correct usage?


Answer: D. None of these
Explanation: Array declaration with negative indices is not allowed in any language
like C or Java. Arrays must have a non-negative index size.

Here are the correct answers along with explanations:


166. The “string Hello “ contains …………… characters:
� b. 9
Explanation: The string "Hello " (with a space at the end) consists of 9 characters: H, e,
l, l, o, space, and three additional characters.

167. A string in a Java program is written with….


� c. Double quotes
Explanation: In Java, strings are enclosed in double quotes (" "), whereas single quotes
(' ') are used for character literals.

168. Element a[10] is which element of the array?


� b. 11
Explanation: In Java, arrays are zero-based, meaning the first element is at index 0.
So, a[10] refers to the 11th element.

169. An array element is accessed ………….


� b. Using an index number
Explanation: In Java, elements in an array are accessed using their index number
within square brackets (array[index]).

170. The statement weight = {26,28,32,31};


� b. Assigns 28 to weight[1]
Explanation: The array elements are assigned as follows:
 weight[0] = 26
 weight[1] = 28
 weight[2] = 32
 weight[3] = 31

171. What will this code print?


int arr[] = new int[5];

Page 17 of 93
System.out.println(arr);
� d. Garbage value
Explanation: When printing an array directly, Java prints the memory reference
instead of its elements.

172. Which of the following is an advantage of Java arrays?


� d. Both a and b above
Explanation: Java arrays allow code optimization (by using loops efficiently) and
random access (elements are accessed via an index in O(1) time).

173. In Java, array elements are stored in …………… memory locations.


� b. Sequential
Explanation: Arrays in Java are stored in contiguous (sequential) memory
locations.

174. Which of the following best describes an array?


� b. Container of objects of similar types
Explanation: An array is a homogeneous data structure, meaning it stores multiple
values of the same type.

175. When does the ArrayIndexOutOfBoundsException occur?


� b. At run time
Explanation: This exception occurs when an attempt is made to access an array index
beyond its valid range at runtime.

176. What are the advantages of using arrays?


� d. It is easy to store elements of the same data type
Explanation: Arrays store elements of the same type, making operations like sorting
and searching more efficient.

177. Assuming int takes 4 bytes of memory, what is the size of int arr[15]?
� d. 60 bytes
Explanation:
Each int takes 4 bytes, so an array of 15 integers will occupy:
15 × 4 = 60 bytes

178. How many of the following are legal declarations?


char [] dog = new char[ ]; // � Incorrect, size required
char [] tiger = new char[1]; // � Correct
char [] horse = new [ ]char; // � Incorrect, syntax error
char [] cat = new [1] char; // � Incorrect, syntax error
� a. One
Explanation: Only char [] tiger = new char[1]; is correct.

179. In Java, arrays are ……………………….


� a. Objects
Explanation: Arrays in Java are objects, meaning they are stored in the heap and can
be referenced using object references.

Page 18 of 93
180. We can determine the length of an array using
� d. array.length
Explanation: The length property of an array returns the number of elements in it.
Example:
int arr[] = new int[5];
System.out.println(arr.length); // Output: 5
Here are the correct answers with explanations:
181. Write a valid statement to declare a single-dimensional array of 5 integers.
� Answer: d. None of these
Explanation:
The correct way to declare an array of 5 integers in Java is:
int arr[] = new int[5];
None of the given options are correct because:
 int arr[5] = new int[5]; is incorrect syntax in Java.
 int arr[6] = new int[6]; has an incorrect size.
 int arr[4] = new int[4]; has an incorrect size.

182. What are the starting row and column indices of the array m[3][4]?
� Answer: a. 0 and 0 respectively
Explanation:
In Java, arrays use zero-based indexing.
 A 3×4 array means 3 rows and 4 columns.
 The first row index is 0, and the first column index is 0.

183. What is printed by the below statements?


� Answer: d. None of these
Explanation:
The given statement has a syntax error. The correct way to access elements of the
array should be:
System.out.println(num[2]++ + "\t" + num[1]++ + "\t" + num[3]++ + "\t" + (num[4] -
2));
Since the provided statement uses incorrect indexing (num*2++), it will not compile.

184. From the given array y[][] = {{3,4,5},{6,7,8},{1,2,3}};, the element at y[2][2] is:
� Answer: c. 3
Explanation:
 y[2][2] refers to row index 2 and column index 2, which corresponds to 3 in the
array.

185. Write a set of statements that would find the size of the array ar[] =
{2,5,6,7,8,9,10};
� Answer: a. int len = ar.length; System.out.println(“The size of array =”+len);
Explanation:
 length is a property of arrays in Java, not a method.
 ar.length(); and ar.len; are incorrect syntax.

186. Which of the following cannot have the array type?


� Answer: d. None of these
Explanation:
Java allows arrays of integers, floats, and strings. So, all options can have array types.

Page 19 of 93
187. How many times will the given loop execute?
� Answer: b. 9
Explanation:
The loop:
for(int k=1024; k>1; k=k/2)
Executes as:
 1024 → 512 → 256 → 128 → 64 → 32 → 16 → 8 → 4 → 2
Total iterations: 9 (before k becomes 1 and the condition k > 1 fails).

188. Number of bits occupied by 65.89:


� Answer: b. 64
Explanation:
 A floating-point number (double) in Java takes 64 bits.

189. Integer i = new Integer(10); is an example of:


� Answer: a. Object assignment
Explanation:
 Integer is a wrapper class, and new Integer(10) creates an object, not
autoboxing (Integer i = 10; would be autoboxing).

190. State which access specifier is the most restrictive:


� Answer: a.
Explanation:
 restricts access to within the same class.
 protected allows access to subclasses.
 allows access from anywhere.

191. Output of Math.ceil(Math.floor(-3.7) + Math.pow(7, 1/2)):


� Answer: d. 1.0
Explanation:
Math.floor(-3.7) → -4.0
Math.pow(7, 1/2) → Math.pow(7, 0) → 1.0
-4.0 + 1.0 = -3.0
Math.ceil(-3.0) → **-3.0**
Correct answer should be -3.0, but since it's not in the options, there's a mistake in
the question.

192. Assertion (A): A constructor can be overloaded. Reason (R): Overloading


allows different constructors to be called based on parameter lists.
� Answer: a. (A) and (R) both are true
Explanation:
 Constructor overloading allows defining multiple constructors with different
parameter lists.

193. The String method, which can result in a negative integer, is:
� Answer: c. compareTo
Explanation:
 compareTo() returns a negative integer if the first string is lexicographically
smaller.

Page 20 of 93
194. Which data type can be used to store the value 123456789?
� Answer: c. long
Explanation:
 int has a max value of 2,147,483,647, which is fine, but for larger values, long
is preferred.

195. The Scanner class is a:


� Answer: b. Derived
Explanation:
 Scanner is derived from Object and Closeable.

196. Arrange the operators in order of higher precedence to lower precedence:


� Answer: c. (iv), (ii), (iii), (i)
Explanation:
 ++ (increment) → Highest
 % (modulus)
 >= (relational)
 && (logical AND) → Lowest

197. Name the type of error in int r=100/0;


� Answer: b. Runtime
Explanation:
 Division by zero causes ArithmeticException, which is a runtime error.

198. Method that accepts a string without any space is:


� Answer: a. next()
Explanation:
 next() reads a single word without spaces.
 nextLine() reads the whole line including spaces.

199. Intermediate code obtained after compilation:


� Answer: b. Byte Code
Explanation:
 Java compiles to Byte Code, which is executed by the JVM.

200. A method with many definitions is known as:


� Answer: d. Overloaded method
Explanation:
 Overloading means multiple methods with the same name but different
parameters.

201. The parameters that are passed to the method when it is invoked are called:
b. actual parameters
� Actual parameters are the values passed to a function/method at the time of calling
it. Formal parameters are the variables used to receive these values inside the method.

202. The “string Hello " contains how many characters?


d. None of the above

Page 21 of 93
� “string Hello " consists of "string" (6 letters) + " " (space 1 letter)+ "Hello" (5 letters) +
" " (space 1 letter) → Total 13 characters.

203. array[10] refers to which element in the array?


b. 11
� If an array has 10 elements, so its index or position will be 11 because index starts
from 0.

204. weight = {26,28,32,31}; assigns:


b. Assigns 28 to weight[1]
� Array indexing starts from 0:
 weight[0] = 26
 weight[1] = 28
 weight[2] = 32
 weight[3] = 31

205. When does ArrayIndexOutOfBoundsException occur?


b. At run time
� This exception occurs when accessing an index beyond array limits, which is
checked during execution.

206. Valid statement to declare a single-dimensional array of 5 integers:


d. None of these
� Correct syntax: int arr[] = new int[5];

207. Starting row and column indices of m[3][4]:


a. 0 and 0 respectively
� In Java, arrays use zero-based indexing, so the first row and column indices are
both 0.

208. Output of the given Java statement:


b. 10 5 12 10
� num[] = {3,5,10,12,18};
 num[2] = 10
 num[1] = 5
 num[3] = 12
 num[4-2] = num[2] = 10
➡ Output: 10 5 12 10

209. The second last element of an array of size 100 has index:
c. 98
� Indices range from 0 to 99. The second last element is at 98.

210. File extension for a compiled Java class file:


c. .class
� Java source files (.java) are compiled into bytecode files with .class extension.

211. Maximum number of objects that can be created from a single Java class:
d. None
� There is no predefined limit on object creation in Java.

Page 22 of 93
212. Creating an object from a class is called:
b. Instantiating
� Instantiation means creating an object from a class using new.

213. Correct statements about Java class names:


d. All the above
� Class names:
 Can start with a letter, _ or $
 Can contain numbers
 Cannot start with a number

214. Which is not a keyword in Java?


b. Boolean
� boolean (lowercase) is a keyword, but Boolean (uppercase) is a class in Java.

215. Bytecode in Java is:


a. Code generated by a Java compiler
� Java source code is compiled into bytecode (.class files) executed by the JVM.

216. "One thing in many different forms" relates to:


a. Polymorphism
� Polymorphism allows a method/class to take multiple forms.

216. To make members of class Employee accessible only within the class:
a.
� The access specifier restricts access to only within the class.

217. A bundle of similar classes is called:


a. Package
� Java packages group related classes together.

218. Code reuse is implemented by:


c. Inheritance
� Inheritance allows child classes to reuse parent class properties and methods.

219. Which are primitive data types?


a. (i) and (iii)
� Primitive types: double, char
� String and Integer are classes (non-primitive).

220. The parent class of a class is also called:


c. Both (a) and (b)
� Parent class = Base class or Super class

Here are the correct answers with explanations:


221.
Answer: b. ob.display();
Explanation: In Java, to call a method of an object, we use dot notation. Since

Page 23 of 93
display() is a method in the product class, an instance (ob) can invoke it using
ob.display();.

222.
Answer: d. (ii)
Explanation:
 _var is valid because variable names can start with an underscore _.
 var.name is invalid because . is not allowed in variable names.
 *var is invalid because * is not a valid character for variable names.
 4var is invalid because variable names cannot start with a digit.

223.
Answer: d. (ii), (iii), (i), (iv)
Explanation: The order of data type precedence in Java (highest to lowest) is:
double > float > long > int

224.
Answer: b. 25.0
Explanation:
a = 6.25, so
a * Math.pow(10,2) = 6.25 * 100 = 625
Math.sqrt(625) = 25.0

225.
Answer: a. Call by reference
Explanation: In call by reference, changes made in the function affect the original
argument.

226.
Answer: a. static
Explanation: The static keyword allows methods and variables to be accessed without
creating an object.

227.
Answer: a. JIT compiler
Explanation: The Just-In-Time (JIT) compiler converts bytecode into native machine
code for better performance.

228.
Answer: b. impure methods
Explanation: Impure methods modify the state of an object, whereas pure methods do
not change state.

229.
Answer: a. continue
Explanation: The continue statement skips the remaining loop body and jumps to the
next iteration.

230.

Page 24 of 93
Answer: b. 21
Explanation:
For x = 3:
Expression: (x++ + --x) * x-- + ++x
Breakdown:
1. x++ = 3 (Post-increment, so x becomes 4)
2. --x = 3 (Pre-decrement, so x becomes 3)
3. (3 + 3) = 6
4. x-- = 3 (Post-decrement, x becomes 2)
5. ++x = 3 (Pre-increment, x becomes 3)
Final result: 6 * 3 + 3 = 18 + 3 = 21

231.
Answer: c. Hello Brother How do you do?
I am good Explanation:
 System.out.print() does not add a new line.
 System.out.println() moves to the next line after printing.
Thus, output:
Hello Brother How do you do?
I am good

232.
Answer: b. default
Honour
Explanation:
 x = 'D', so it goes to default: case.
 The default case does not have a break, so execution falls through to case 'C'.
 Honour is printed on next line.

233.
Answer: b. Loop is executed 2 times and the output is 12
Explanation:
Loop values:
1. a = 6 → 6 % 4 != 0, so continue
2. a = 12 → 12 % 4 == 0, so break
Output: 12

234.
Answer: c. java.lang
Explanation: Wrapper classes (Integer, Double, etc.) are in java.lang package.

235.
Answer: c. java.lang
(Same as above.)

236.
Answer: b. isLetter()
Explanation: isLetter(char c) checks if the character is a letter.

237.

Page 25 of 93
Answer: b. parseInteger()
Explanation: There is no parseInteger() method in Java. The correct method is
Integer.parseInt().

238.
Answer: d. Java.lang
Explanation: String functions are in java.lang.String.

239.
Answer: d. static
Explanation: A static variable belongs to the class, not instances.

240.
Answer: c. . dot
Explanation: . is not considered a punctuator, in java it is considered as an
operator(access operator).
Here are the answers with explanations:

241. Which of the following is not mandatory in a variable declaration?


� c. an assignment
Explanation: A variable declaration requires a data type and an identifier but does not
require an assignment. You can declare a variable and assign a value later.
242. Continue statement can be used
� d. only within looping statements
Explanation: The continue statement is used to skip the remaining code in the
current iteration and proceed to the next iteration of a loop.
243. If a variable is declared final, it must include …………………. value.
� c. initial
Explanation: A final variable must be assigned a value at the time of declaration
because it cannot be changed later.
244. They represent non-graphic characters.
� c. escape sequences
Explanation: Escape sequences (e.g., \n, \t, \”) represent characters that do not have
a visual representation but affect formatting.
245. Arrange the operators in order of higher precedence to lower precedence.
� c. (iv), (ii), (iii), (i) (++, %, >=, &&)
Explanation: The order of precedence is:
1. ++ (increment operator) – Highest precedence
2. % (modulus operator)
3. >= (relational operator)
4. && (logical AND) – Lowest precedence
246. Which feature allows a program to run multiple tasks simultaneously?
� d. Multithreaded
Explanation: The multithreading feature enables concurrent execution of multiple
parts of a program.
247. Which operator has the highest precedence in the expression: x / y + z – a
%b*z
� d. % and / both answers are correct.
Explanation: Operator precedence:
1. % (modulus), / (division), * (multiplication)

Page 26 of 93
2. + (addition), - (subtraction)
Among these, % and /has the highest precedence in the given expression.
248. Order of precedence in the expression: a > d && b || !c
� b. > ! && ||
Explanation: Operator precedence:
1. > (relational)
2. ! (logical NOT)
3. && (logical AND)
4. || (logical OR)
249. Which keyword is used to declare a class?
� c. class
Explanation: The class keyword is used to define a class.
250. What keyword is used to inherit a class?
� b. extends
Explanation: The extends keyword is used for class inheritance.
251. Output of System.out.println(Math.abs(-5) + Math.pow(4, 1/2));
� b. 6.0
Explanation:
 Math.abs(-5) → 5
 Math.pow(4, 1/2) calculates 4^0, which is 1.0 (since 1/2 is integer division, it
becomes 0).
 5 + 1.0 = 6.0
252. Output of System.out.println(Math.max(5, Math.min(3, 7)) +
Math.round(2.6));
� b. 8
Explanation:
 Math.min(3, 7) → 3
 Math.max(5, 3) → 5
 Math.round(2.6) → 3
 5+3=8
253. Which method returns a boolean?
� a. equalsIgnoreCase(String)
Explanation: The equalsIgnoreCase(String) method compares two strings while
ignoring case differences and returns a boolean.
254. Which type is not allowed in a switch statement?
� c. double
Explanation: switch does not support floating-point types (double and float).
255. Which of the following is true about the switch statement?
� d. Case labels must be compile-time constants.
Explanation: case labels must be constant expressions, not variables.
256. What happens if a switch statement does not have a break after a case?
� c. The next case will be executed (fall-through).
Explanation: Without break, execution continues into the next case.
257. Which of the following statements is true about switch cases?
� d. Case labels are unique.
Explanation: Each case must have a unique constant value.
258. Correct way to declare a method?
� a. void methodName()
Explanation: The correct syntax is void methodName() { }.

Page 27 of 93
259. Output of the given Java program:
� a. 15
Explanation: The sum method returns 5 + 10 = 15.
260. Which of the following is true about method overloading?
� b. Methods can have the same name but different parameter lists.
Explanation: Method overloading allows multiple methods with the same name but
different parameters (type, number, or both).
Here are the correct answers with explanations:

261. Which of the following methods is automatically called when an object is


created?
Answer: (c) Constructor
Explanation: A constructor is a special method in Java that is automatically called
when an object is instantiated. It is used to initialize the object.

262. Which of the following constructs is NOT considered a token?


Answer: (d) Comments
Explanation: Tokens in Java include keywords, identifiers, literals, operators, and
separators. Comments are ignored by the compiler and are not considered tokens.

262. What is the correct way to understand the difference between an identifier
and a keyword?
Answer: (c) Identifiers are user-defined names, while keywords are reserved words in
Java.
Explanation: Identifiers are names given to variables, classes, and methods. Keywords
are predefined and cannot be used as identifiers.

263. Write corrections in the statement:


Answer: (c) Character.toUpperCase(ch1) + Character.toUpperCase(ch2)
Explanation: The correct method to convert a character to uppercase is
Character.toUpperCase(). The original statement had incorrect method names.

264. Which of the following statements terminates the execution of the current
method and returns control to the calling method?
Answer: (c) return
Explanation: The return statement exits the current method and passes control back
to the caller.

265. What is the effect of the continue statement in a loop?


Answer: (b) It causes the loop to skip the current iteration and continue with the next
iteration.
Explanation: continue is used to skip the remaining code in the current iteration and
move to the next iteration of the loop.

266. Which of the following statements will immediately terminate the entire
program?
Answer: (d) System.exit(0)
Explanation: System.exit(0) stops the entire Java application.

Page 28 of 93
267. The default value of a char variable is:
Answer: (d) '\u0000'
Explanation: The default value of char in Java is the null character '\u0000', which
represents an empty character.

268. The default value of a reference variable is:


Answer: (b) null
Explanation: A reference variable in Java is initialized to null by default.

269. The method to check if a character is a letter is:


Answer: (a) Character.isLetter(char)
Explanation: The Character.isLetter() method checks if a character is a letter.

270. The method to convert an int to a String is:


Answer: (a) String.valueOf(int) and (b) Integer.toString(int)
Explanation: Both methods are used to convert an int to a String.

271. Assertion (A): The Math class can be used in programs without importing
any package.
Answer: (a) Both Assertion (A) and Reason (R) are true, and Reason (R) is a correct
explanation of Assertion (A).
Explanation: The Math class belongs to the java.lang package, which is automatically
imported.

272. A developer wants to subtract 5 from a variable y. What is the correct way
to write this statement?
Answer: (d) Both A and C
Explanation: The correct ways are y -= 5; and y = y - 5;. The original y =- 5; is
incorrect.

273. __________ and __________ are the numeric wrapper classes in Java.
Answer: (c) Byte and Short
Explanation: Numeric wrapper classes in Java include Byte, Short, Integer, Long,
Float, and Double.

274. Write statements in Java to produce the following output:


Answer: (d) Both (a) and (c)
Explanation: Both System.out.println(str1.toUpperCase() + str2.toUpperCase()); and
(str1+str2).toUpperCase() produce the expected output.

275. Give the output of the following code:


Answer: (a) 740
Explanation: Integer.parseInt("670") + Integer.parseInt("70") results in 670 + 70 =
740.

276. What will be the output of the given code?


Answer: (c) 5
Explanation: x = 20 % 3 + 20 % 7 = 2 + 3 = 5.

Page 29 of 93
277. If the element 0 of an array holds a float, the rest of the pockets will be of
type:
Answer: (b) float only
Explanation: Arrays in Java are homogeneous, meaning all elements must be of the
same type.

278. Which among the following is/are the correct way(s) to create an integer
array of size 40?
Answer: (b) int []a=new int[40]
Explanation: Java does not allow negative or range-based array size declarations.

279. The second last element of an array of size 100 has index:
Answer: (c) 98
Explanation: Array indices start from 0, so the second last element is at index 98 (100
- 2).

280. Given array int marr[ ] = {101, 202, 303, 404}; the value of marr[-1+2] is:
Answer: (b) 202
Explanation: marr[-1+2] simplifies to marr[1], which is 202.

281. A statement to print the elements at odd positions


� ( b) for(int i=0;i<ar.length;i++) if (i%2!=0) System.out.println(ar[i]);
Explanation: i % 2 != 0 ensures that only odd index positions are printed. The correct
syntax for accessing array elements is ar[i].

282. Predict memory size of Arrays


� ( d) 40
Explanation: A double takes 8 bytes of memory. The array has 5 elements, so total
memory used = 5 * 8 = 40 bytes.

283. A statement to subtract 2 from each of its elements


� ( d) All of these
Explanation: All the options correctly subtract 2 from elements, though (c) modifies
only the first 5 elements.

284. A string is:


� ( b) Non-Mutable
Explanation: In Java, String is immutable, meaning once created, its value cannot be
changed.

284 (Repeated). Output of System.out.println(str.substring(4,9)+ str.indexOf(„T‟) +


str.lastIndexOf(„m‟));
� ( d) inati1821
Explanation:
 str.substring(4,9) → "inati" (characters from index 4 to 8)
 str.indexOf('T') → 18 (position of 'T')
 str.lastIndexOf('m') → 21 (last occurrence of 'm')
 Concatenation: "inati" + 18 + 21 → "inati1821"

Page 30 of 93
285. Correct statement to add 10 to a:
� (d) Both A and C
Explanation:
 a += 10; is shorthand for a = a + 10;, both are correct.
 a =+ 10; is incorrect (interpreted as a = (+10)).

286. Method parameters and overloading


� ( b) Both Assertion (A) and Reason (R) are true and Reason (R) is not a correct
explanation of Assertion (A)
Explanation: A method can have multiple parameters of the same type, but this is not
due to method overloading.

287. Return type change in method overloading


� (d) Assertion (A) is false and Reason (R) is true
Explanation: Method overloading does not allow changing only the return type; it
must have different parameters.

288. Calling a method before it is defined


� ( b) Both Assertion (A) and Reason (R) are true and Reason (R) is not a correct
explanation of Assertion (A)
� Explanation: In Java, methods can be called before their definition because Java
allows method declarations earlier in the code, but this is not the same as method
ordering being irrelevant.

289. Parameters and arguments


� (a) Both Assertion (A) and Reason (R) are true and Reason (R) is a correct
explanation of Assertion (A)
� Explanation: Parameters are used to pass values to a method and are also called
arguments.

290. Can a method return multiple values?


� ( d) Assertion (A) is false and Reason (R) is true
� Explanation: A Java method cannot return multiple values directly, but it can
return an array, object, or collection.

291. Meaning of void return type


� (a) Both Assertion (A) and Reason (R) are true and Reason (R) is a correct
explanation of Assertion (A)
� Explanation: void indicates a method does not return a value, and this is exactly
why it is used.

292. Correct way to initialize an array


� (d) int[ ] arr = new int[ ]{1, 2, 3, 4};
� Explanation: This is a valid syntax for array initialization with values. Option (a) is
also correct, but (d) is the safest explicit initialization.

293. Correct declaration of a 2D array


� (a) int[][] arr = new int[3][3];
� Explanation: This correctly declares a 3x3 2D array in Java.

Page 31 of 93
294. Accessing element in 2D array at second row and third column
� (b) arr[1][2]
� Explanation: Indexing starts from 0, so:
 First row: arr[0]
 Second row: arr[1]
 Third column: arr[1][2]

295. Output of System.out.println(arr[1][2]);


� (b) 6
� Explanation: arr[1] refers to {4, 5, 6} and arr[1][2] = 6.

296. What does charAt(int index) return?


� (b) The character at the specified index
� Explanation: charAt(index) returns the character, not its ASCII value.

297. Correct statement about Java keywords


� ( b) Keywords are reserved words in Java.
� Explanation: Java keywords cannot be used as variable names.

298. Logical error definition


� ( a) An error that occurs when the program produces incorrect output but runs
without crashing
� Explanation: Logical errors don't stop execution but cause wrong results due to
flawed logic.

299. Error in accessing arr[5] in int arr[] = new int[5];


� (c) Runtime error
� Explanation: Indexing starts from 0 to 4, so arr[5] is out of bounds, causing a
runtime exception.

300. Which is NOT a runtime error?


� (c) Missing semicolon
� Explanation: A missing semicolon is a syntax error, detected at compile-time.
Runtime errors occur only when the program runs.

301. (c) Compilation error


A misspelled keyword in Java leads to a compilation error because the Java compiler
does not recognize it as a valid syntax.
302. (c) this
The this keyword refers to the current object in a method or constructor.
303. (a) 23.78 -> 92 -> „p‟ -> false
Sizes in bytes: double (8 bytes) > int (4 bytes) > char (2 bytes) > boolean (1 byte).
304. (b) 4##7##10##12
The loop increments i before checking the condition and then again before printing.
305. (a) Inheritance
Code reuse is achieved through inheritance, where a subclass inherits properties and
behaviors from a superclass.
306. (c) 1
Expression evaluates to (5-4) > (4-5) ? (5-4)%4 : (4-5)%5, which simplifies to 1 % 4 = 1.

Page 32 of 93
307. (c) 12
Math.min(-35.83, -143.83) is -143.83, Math.abs(-143.83) is 143.83, Math.ceil(143.83) is
144, Math.sqrt(144) is 12.
308. (b) Coercion
Implicit type conversion (coercion) occurs when a lower type is converted to a higher type
automatically.
309. (a) //
Single-line comments in Java are denoted by //.
310. (d) Any number
A class can be used to create multiple objects in Java.
311. (c) Unboxing
Unboxing is converting a wrapper object to its corresponding primitive type.
312. (a) Parameter list
Constructor overloading is differentiated by different parameter lists.
313. (b) 40
The constructor sets t = 40, so when System.out.println(t1.t); executes, it prints 40.
314. (d) int a = Integer.parseInt(s);
Integer.parseInt("123") converts a string to an integer.
315. (b) java.lang
Wrapper classes belong to java.lang, which is imported by default.
316. (a) Autoboxing
Autoboxing is converting a primitive value into an object of its corresponding wrapper
class.
317. (d) isWhitespace()
Character.isWhitespace() checks if a character is a whitespace, including tab spaces.
318. (b) default
default is a reserved keyword in Java.
319. (c) To exit the method and optionally pass back a value
The return keyword exits a method and may return a value.
320. (c) 0675
Octal literals in Java start with 0, and 0675 is a valid octal number.

321. What is the output of the following code?


System.out.println(10 / 3);
Answer: (b) 3
Explanation: In Java, when both operands are integers, integer division is performed,
discarding the decimal part.

322. Which expression evaluates to true for x = 5 and y = 10?


Answer: (b) x >= 5 || y == 5
Explanation: x >= 5 is true and || (logical OR) requires at least one condition to be
true.

323. What will be the output of this code?


int a = 2, b = 3;
a = a++ + ++b;
b = ++a - b--;
System.out.println(a + " " + b);
Answer: (c) 7 2
Explanation:

Page 33 of 93
1. a = a++ + ++b → a = 2 + 4 = 6, then a becomes 3, but after assignment, it is 6.
2. b = ++a - b-- → b = 7 - 3 = 2.
Final values: a = 7, b = 2.

324. What will be the output?


System.out.println(10 + 20 + "Hello" + 30 + 40);
Answer: (c) 30Hello3040
Explanation: 10 + 20 = 30, then "30Hello" concatenates 30 and 40 as strings.

325. Identify the type of operator &&:


Answer: (c) logical
Explanation: && is a logical AND operator.

326. Type of loop?


for (int i = 5; i != 0; i -= 2)
System.out.println(i);
Answer: (b) infinite
Explanation: i decreases by 2 and never gets 0 to stop.

327. Method prototype for check() returning char with an int parameter?
Answer: (d) char check(int x)
Explanation: The correct syntax includes the return type, function name, and
parameter list.

328. Predict output:


String P = "20", Q = "22";
int a = Integer.parseInt(P);
int b = Integer.valueOf(Q);
System.out.println(a + "" + b);
Answer: (b) 20 22
Explanation: a and b are integers but "" causes concatenation.

329. String method output:


"MALAYALAM".substring("MALAYALAM".indexOf('Y'));
Answer: (d) YALAM
Explanation: indexOf('Y') gives 4, and substring(4) extracts "YALAM".

330. Value of x after execution?


char ch = 'y';
int x = ch + 10;
Answer: (b) 131
Explanation: ASCII of 'y' is 121, so 121 + 10 = 131.

331. Value of x after execution?


String x = "12" + 'A' + 20;
Answer: (a) 12A20
Explanation: 'A' ASCII value (65) is converted to a string.

332. Conversion type:


Integer a = new Integer(20);

Page 34 of 93
Answer: (a) Autoboxing
Explanation: Autoboxing converts a primitive (int) to an object (Integer).

333. Find the odd one:


Answer: (d) float
Explanation: Character, Byte, and Integer are wrapper classes, while float is a
primitive type.

334. Output of Character.isLowerCase(str.charAt(0)) &&


Character.isUpperCase(str.charAt(4))?
Answer: (c) false
Explanation: str.charAt(0) = 'M' (uppercase), so isLowerCase('M') returns false.

335. Invalid for-loop:


Answer: (a) for ( int i = 99; i >= 0; i / 9)
Explanation: i / 9 does not update i, leading to a compile-time error.

336. Output of escape sequence statement?


System.out.println("A picture is worth \t \"A thousand words.\" ");
Answer: (a) A picture is worth "A thousand words."
Explanation: \t adds a tab space, and \" prints double quotes.

337. Function prototype with char and int returning boolean?


Answer: (c) boolean check(char ch, int n)
Explanation: Correct return type and parameters.

338. Arrange primitive data types by size:


Answer: (b) byte, char, int, double
Explanation:
byte (1 byte)
char (2 bytes)
int (4 bytes)
double (8 bytes)

339. Compute Math.pow(625,1/2) + Math.sqrt(121);


Answer: (b) 12.0
Explanation: Math.pow(625,1/2) evaluates to 1.0 due to integer division.

340. Convert if-else to ternary:


Answer: (b) System.out.println(n % 2 == 0 ? "Even" : "Odd");
Explanation: ? : is the ternary conditional operator.

341. Inner loop execution count:


for(int i=1; i<=2; i++) {
for(int j=-1; j<=2; j++)
System.out.print(j);
System.out.println();
}
Answer: (b) 8 times
Explanation:

Page 35 of 93
i runs 2 times.
j runs from -1 to 2 (4 times).
2 * 4 = 8 times in total.

341. (c) declaration of parameterized constructor


abc p = new abc(5,7,9); creates an object using a constructor that takes three
parameters, meaning it's a parameterized constructor.
342. (d) ternary operator
The conditional operator is ?:, which is a ternary operator used as a
shorthand for if-else.
343. (c) boolean
The method Character.isLetterOrDigit(char) returns true or false, which is of
type boolean.
344. (a) 800 byte
A long type in Java takes 8 bytes. A long array with 100 elements takes 100 ×
8 = 800 bytes.
345. (a) 48
double takes 8 bytes. The given array has 3 rows × 2 columns = 6 elements,
so 6 × 8 = 48 bytes.
346. (c) S.charAt(6)
Java uses zero-based indexing, so the 7th element is at index 6.
347. (d) Assertion (A) is false but the Reason (R) is true
A constructor is not called like a normal method, but the reason that a
constructor is a special function without a return type is true.
348. (b) Inheritance
Simba inherits from Mufasa, just like a class inherits from another class in
Java.
349. (c) Assertion (A) is false and Reason (R) is true
Call by value is used for primitive data types, not for non-primitives.
350. (b) A constructor is called automatically when an object is created.
Constructors run automatically when an object is created.
351. (b) It is used to refer to the current object of the class.

351. The correct answer is:


(d) A method can never have the same name as the class.
Explanation:
(a) Correct: A method in Java can return any type, including void (which means it
does not return a value).
(b) Correct: A static method belongs to the class and can be called without creating
an object. Example: Math.sqrt(4).
(c) Correct: A non-static method can access both static and non-static members,
but a static method can only access static members.
(d) Incorrect: A method can have the same name as the class, but it will be treated
as a constructor, not a normal method. Constructors do not have return types, but
methods do.

352. (a) CBSE Examination


The replace() method replaces "ICSE" with "CBSE", so output is "CBSE
Examination".

Page 36 of 93
353. + 354 is a single question Ans: (a) 150
The loop adds all even numbers: 10 + 20 + 30 + 40+50 = 150.
355. (b) 6
arr[3] + arr[1] = 4 + 2 = 6.
356. (c) 20
arr[arr.length - 2] = arr[3] = 20.
357. (a) 55
Squaring each element and summing: 1² + 2² + 3² + 4² + 5² = 1 + 4 + 9 + 16 +
25 = 55.
358. (a) 4
Each element is divided by 2: arr[3] = 8 / 2 = 4.
359. (a) 40
arr[4] - arr[0] = 50 - 10 = 40.
360 & 361 is a single question (d) 6
arr[3] = 3 * 2 = 6
362. **(c) 8 times *, 7 times +++++
The loop alternates between "***" (odd) and "+++++" (even).
363. (a) for ( int i = 99; i >= 0; i / 9 )
i / 9 is incorrect, as it doesn't change i, causing an infinite loop.
364. (b) 2
case 6: y=0; falls through to case 7: y=1; and then default: y+=1; making y = 2.
365. (a) 1 3 5 7
The loop prints odd numbers and skips multiples of x=2. It stops at 8.
366. (c) double
The highest data type in the expression (double) dominates.

MCQ QUESTION PAPER COMPUTER APPLICATIONS


Answers are given at the end of each paper.

Answers of two marks :


1. Evaluate the expression
int x = 5, y = 10;
y -= x++ * ++y - --x;
System.out.println("x = " + x);
System.out.println("y = " + y);
Step-by-step evaluation:
1. x = 5, y = 10
2. ++y → y = 11
3. --x → x = 5 - 1 = 4
4. x++ * ++y - --x → 5 * 11 - 4 = 55 - 4 = 51
5. y -= 51 → y = 10 - 51 = -41
6. x was post-incremented, so x = 6
Output:
x=6
y = -41

2. Evaluate the expression

Page 37 of 93
int p = 7, q = 4;
q += --p * q++ - p--;
System.out.println("p = " + p);
System.out.println("q = " + q);
Step-by-step evaluation:
1. p = 7, q = 4
2. --p → p = 6
3. q++ → q = 4 (post-increment, so q becomes 5 after use)
4. p-- → p = 6 (post-decrement, so p becomes 5 after use)
5. q += (6 * 4 - 6) → q = 4 + (24 - 6) = 22
6. p was post-decremented, so p = 5
Output:
p=5
q = 22

3. Evaluate the expression


int m = 3, n = 8;
m += ++n - n-- + m++;
System.out.println("m = " + m);
System.out.println("n = " + n);
Step-by-step evaluation:
1. m = 3, n = 8
2. ++n → n = 9
3. n-- → n = 9 (post-decrement, so n becomes 8 after use)
4. m++ → m = 3 (post-increment, so m becomes 4 after use)
5. m += (9 - 9 + 3) → m = 3 + 3 = 6
6. n was post-decremented, so n = 8
Output:
m=6
n=8

4. Evaluate the expression


int a = 6, b = 2;
a /= b++ + ++a - --b;
System.out.println("a = " + a);
System.out.println("b = " + b);
Step-by-step evaluation:
1. a = 6, b = 2
2. b++ → b = 2 (post-increment, so b becomes 3 after use)
3. ++a → a = 7
4. --b → b = 3 - 1 = 2
5. b++ + ++a - --b = 2 + 7 - 2 = 7
6. a /= 7 → a = 6 / 7 = 0 (integer division)
Output:
a=0
b=3

5. Evaluate the expression


int x = 4, y = 7;
x = x++ - --y + ++x + y--;

Page 38 of 93
System.out.println("x = " + x);
System.out.println("y = " + y);
Step-by-step evaluation:
1. x = 4, y = 7
2. --y → y = 6
3. x++ → x = 4 (post-increment, so x becomes 5 after use)
4. ++x → x = 6
5. y-- → y = 6 (post-decrement, so y becomes 5 after use)
6. x = 4 - 6 + 6 + 6 = 10
Output:
x = 10
y=5

6. Incorrect switch statement


int score = 92;
switch(score)
{
case 90: System.out.println("Grade A"); break;
case 80: System.out.println("Grade B"); break;
case 70: System.out.println("Grade C"); break;
default: System.out.println("Grade D");
}
Error: switch does not work with ranges.
Corrected Code:
int score = 92;
if (score >= 90)
System.out.println("Grade A");
else if (score >= 80)
System.out.println("Grade B");
else if (score >= 70)
System.out.println("Grade C");
else
System.out.println("Grade D");

7. Incorrect switch for weekdays


int day = 6;
switch(day)
{
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
case 5: System.out.println("Friday"); break;
case 6:
case 7: System.out.println("Weekend"); break;
}
Correction: Group case 6 and case 7 together.

8. Incorrect switch for number classification


int number = 5;

Page 39 of 93
switch(number)
{
case 0: System.out.println("Zero"); break;
case -1: System.out.println("Negative"); break;
case 1: System.out.println("Positive"); break;
}
Error: switch cannot handle ranges.
Corrected Code:
int number = 5;
if (number > 0)
System.out.println("Positive");
else if (number < 0)
System.out.println("Negative");
else
System.out.println("Zero");

9. Incorrect switch for grades


int grade = 65;
switch(grade)
{
case 60:
case 50: System.out.println("Pass"); break;
case 40: System.out.println("Fail"); break;
}
Error: switch does not support ranges.
Corrected Code:
int grade = 65;
if (grade >= 50)
System.out.println("Pass");
else
System.out.println("Fail");

10. Incorrect switch for age groups


int age = 15;
switch(age)
{
case 0: System.out.println("Child"); break;
case 13: System.out.println("Teenager"); break;
case 20: System.out.println("Adult"); break;
}
Error: switch does not support ranges.
Corrected Code:
int age = 15;
if (age < 13)
System.out.println("Child");
else if (age >= 13 && age <= 19)
System.out.println("Teenager");
else
System.out.println("Adult");

Page 40 of 93
11. String Methods
String str1 = "Programming", str2 = "Program";
(a)
System.out.println(str1.substring(0, str2.length()));
 str2.length() is 7, so str1.substring(0, 7) gives "Program"
Output:
Program
(b)
System.out.println(str2.toUpperCase().toLowerCase());
 str2.toUpperCase() converts "Program" to "PROGRAM"
 .toLowerCase() converts it back to "program"
Output:
program

12. String Methods


String name = "Program ming";
(a)
System.out.println(name.replace("Program", "Language"));
 Replaces "Program" with "Language" in "Program ming" → "Language ming"
Output:
Language ming
(b)
System.out.println(name.substring(3).length());
 name.substring(3) gives "gram ming"
 .length() of "gram ming" is 9
Output:
9

13. String Methods


String strA = "OpenAI", strB = "openai";
(a)
System.out.println(strA.equalsIgnoreCase(strB));
 equalsIgnoreCase ignores case differences →
"OpenAI".equalsIgnoreCase("openai") → true
Output:
true
(b)
System.out.println(strA.compareTo(strB));
 "OpenAI".compareTo("openai") compares ASCII values.
 'O' (ASCII 79) vs 'o' (ASCII 111): 79 - 111 = -32
Output:
-32

14. String Methods


String phrase = " Learn ";
(a)
System.out.println(phrase.trim());
 trim() removes leading and trailing spaces, giving "Learn"
Output:

Page 41 of 93
Learn
(b)
System.out.println(phrase.length());
 " Learn " has 11 characters.
Output:
11

15. String Methods


String text1 = "Welcome", text2 = "welcome";
(a)
System.out.println(text1.equals(text2));
 "Welcome".equals("welcome") is false (case-sensitive)
Output:
false
(b)
System.out.println(text1.compareTo(text2));
 'W' (ASCII 87) vs 'w' (ASCII 119): 87 - 119 = -32
Output:
-32

16. String Methods


String word = "Hello";
(a)
System.out.println(word.charAt(4));
 charAt(4) gives 'o'
Output:
o
(b)
System.out.println(word.substring(1, 4));
 substring(1, 4) gives "ell"
Output:
ell

17. String Methods


String first = " ", second = " ";
(a)
System.out.println(first == second);
 == checks reference equality. Java may optimize "" literals, so they may refer to
the same object, returning true.
But for certainty, it's better to use .equals().
Output (may vary):
true or false (depending on optimization)
(b)
System.out.println(first.equals(second));
 equals() checks content, which is identical.
Output:
true

18. String Methods


String msg = "Coding in ";

Page 42 of 93
System.out.println(msg.indexOf('i') + msg.lastIndexOf('i'));
 "Coding in "
o indexOf('i') = 3 (first occurrence)
o lastIndexOf('i') = 9 (last occurrence)
Output:
12

19. Character and ASCII manipulation


char ch = 'E';
char chr = Character.toLowerCase(ch);
int num = (int)chr + 3;
System.out.println(chr + "\t" + (char)num);
 'E' → 'e'
 'e' ASCII = 101
 101 + 3 = 104, which is 'h'
Output:
e h

20. Predicting the loop output


int i = 5;
while (i > 0)
{
if (i % 2 == 0) {
System.out.println(i + " is even");
}
else
System.out.println(i + " is odd");
i--;
}
Error: Missing {} for if and else.
Corrected Code:
int i = 5;
while (i > 0)
{
if (i % 2 == 0) {
System.out.println(i + " is even");
} else {
System.out.println(i + " is odd");
}
i--;
}
Output:
5 is odd
4 is even
3 is odd
2 is even
1 is odd

21. Predict the output of the code

Page 43 of 93
String s = "ICSE2024";
System.out.println(s.substring(2, 5).toUpperCase());
System.out.println(s.indexOf('2'));
 s.substring(2, 5) extracts "SE2"
 .toUpperCase() doesn't change anything since it's already uppercase → "SE2"
 s.indexOf('2') finds the first occurrence of '2' in "ICSE2024" → index 4
Output:
SE2
4

22. Predict the output of the code


int[] arr = {10, 20, 30, 40, 50};
for (int i = 1; i < arr.length; i += 2)
System.out.print("a[" + i + "]=" + arr[i]);
System.out.print(i);
 i = 1 → arr[1] = 20
 i = 3 → arr[3] = 40
 i = 5 (loop terminates)
 System.out.print(i); prints 5
Output:
a[1]=20a[3]=405

23. Predict the output of the code


char ch1 = 'G', ch2 = 'g';
if (ch1 < ch2)
System.out.println("ch1 is smaller");
else
System.out.println("ch2 is smaller");
 ASCII of 'G' = 71, 'g' = 103
 'G' < 'g', so "ch1 is smaller" is printed.
Output:
ch1 is smaller

24. Predict the output of the code


char ch = 'h';
char result = (ch >= 'a' && ch <= 'z') ? Character.toUpperCase(ch) : ch;
System.out.println(result);
 'h' is lowercase, so it is converted to uppercase 'H'.
Output:
H

25. Predict the output of the code


char ch = 'Z';
char chr = Character.toLowerCase(ch);
int n = (int)chr + 1;
System.out.println((char)n + "\t" + chr);
 'Z' → 'z'
 ASCII of 'z' = 122, n = 122 + 1 = 123
 123 corresponds to '{'
Output:

Page 44 of 93
{ z

26. Predict the output of the code


for (char ch = 'A'; ch <= 'E'; ch++)
System.out.print((int)ch + "=" + ch);
 ASCII values: A=65, B=66, C=67, D=68, E=69
Output:
65=A66=B67=C68=D69=E

27. Correct the error in parsing a decimal number


String x = "30.5";
int y = Integer.parseInt(x);
double result = Math.pow(y, 2);
System.out.println(result);
Error: Integer.parseInt(x) cannot parse "30.5".
Fix: Use Double.parseDouble(x)
Corrected Code:
String x = "30.5";
double y = Double.parseDouble(x);
double result = Math.pow(y, 2);
System.out.println(result);
Output:
930.25

28. Correct the error in calculating the square root


String value = "9";
int num = Integer.parseInt(value);
int squareRoot = Math.sqrt(num);
System.out.println(squareRoot);
Error: Math.sqrt(num) returns double, but is assigned to int.
Fix: Change int to double.
Corrected Code:
String value = "9";
int num = Integer.parseInt(value);
double squareRoot = Math.sqrt(num);
System.out.println(squareRoot);
Output:
3.0

29. Correct the syntax issue in parsing a number


String number = "16";
int result = Double.parseInt(number);
System.out.println("Result is: " + result);
Error: Double.parseInt() does not exist.
Fix: Use Integer.parseInt() for integers.
Corrected Code:
String number = "16";
int result = Integer.parseInt(number);
System.out.println("Result is: " + result);
Output:

Page 45 of 93
Result is: 16

30. Correct the null error in parsing a number


String input = null;
int num = Integer.parseInt(input);
System.out.println(Math.sqrt(num));
Error: Integer.parseInt(null) throws a NullPointerException.
Fix: Ensure input is not null before parsing.
Corrected Code:
String input = "25"; // Assign a valid value
int num = Integer.parseInt(input);
System.out.println(Math.sqrt(num));
Output:
5.0

31. Analysis of Demo Class


class Demo {
int num;
Demo()
{
num = 5;
}
Demo(int n)
{
num = n;
}
void display()
{
System.out.println(num);
}
}
(i) Name the type of constructors used in the above class.
 The class uses default constructor (Demo()) and parameterized constructor
(Demo(int n)).
(ii) What is the purpose of having more than one constructor in this class?
 The purpose is constructor overloading, allowing objects to be initialized with
a default value (5) or a user-specified value (n).

32. Analysis of Rectangle Class


class Rectangle {
int length, breadth;
Rectangle() {
length = 1;
breadth = 1;
}
Rectangle(int l, int b) {
length = l;
breadth = b;
}
void area() {

Page 46 of 93
System.out.println("Area: " + (length * breadth));
}
}
(i) What is constructor overloading? Is it used in the above class? Explain.
 Constructor overloading allows multiple constructors with different
parameters.
 Yes, it is used in the Rectangle class:
o Rectangle() initializes length and breadth to 1.
o Rectangle(int l, int b) initializes them with user-specified values.
(ii) What will be the area of the rectangle if Rectangle(4, 5) is called?
 length = 4, breadth = 5
 Area = 4 × 5 = 20
Output:
Area: 20

33. Analysis of Car Class


class Car {
String name;
int speed;
Car() {
name = "Unknown";
speed = 0;
}
void display() {
System.out.println(name + " is running at " + speed + " km/h");
}
}
(i) Identify the type of constructor used in the Car class.
 A default constructor is used (Car()).
(ii) Why is it called a default constructor?
 Because it does not take parameters and assigns default values ("Unknown",
0).

34. Analysis of Box Class


class Box {
int length, breadth, height;
Box() {
length = 10;
breadth = 20;
height = 30;
}
Box(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}
void volume() {
System.out.println("Volume: " + (length * breadth * height));
}
}

Page 47 of 93
(i) Name the constructors used in the Box class.
 Default constructor (Box())
 Parameterized constructor (Box(int l, int b, int h))
(ii) Predict the output when Box(2, 3, 4) is called and volume() is invoked.
 length = 2, breadth = 3, height = 4
 Volume = 2 × 3 × 4 = 24
Output:
Volume: 24

35. Convert while to for Loop


Given while loop:
int x = 10;
while (x >= 1) {
x--;
System.out.print(x);
}
System.out.print("Bye " + x);
Equivalent for loop:
for (int x = 10; x >= 1; x--) {
System.out.print(x - 1);
}
System.out.print("Bye " + 0);

36. Convert for to do...while Loop


Given for loop:
for (int x = 10; x >= 1; x--) {
System.out.print(x);
}
System.out.print("Hello " + x);
Equivalent do...while loop:
int x = 10;
do {
System.out.print(x);
x--;
} while (x >= 1);
System.out.print("Hello " + x);

37. Convert do...while to while Loop


Given do...while loop:
int x = 10;
do {
System.out.print(x);
x--;
} while (x >= 1);
System.out.print("OK " + (++x));
Equivalent while loop:
int x = 10;
while (x >= 1) {
System.out.print(x);
x--;

Page 48 of 93
}
System.out.print("OK " + (++x));

38. Convert while to do...while Loop


Given while loop:
int x = 1;
while (x <= 10) {
System.out.print(x);
x++;
}
Equivalent do...while loop:
int x = 1;
do {
System.out.print(x);
x++;
} while (x <= 10);

39. Rewrite Ternary Operator as if-else


Given code:
int n = 150;
double result = (n < 100) ? (n + 50) : (n - 25);
Equivalent if-else statement:
int n = 150;
double result;
if (n < 100) {
result = n + 50;
} else {
result = n - 25;
}

40. Rewrite Ternary Operator as if-else


Given code:
int score = 85;
String grade = (score >= 90) ? "A" : (score >= 80) ? "B" : "C";
Equivalent if-else statement:
int score = 85;
String grade;
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else {
grade = "C";
}

Here are the answers to your questions:


31. Constructors in the Demo class
(i) The constructors used in the Demo class are:
 Default constructor (no parameters)
 Parameterized constructor (with one parameter)

Page 49 of 93
(ii) Having more than one constructor allows constructor overloading, enabling
object creation with default values or user-defined values.

32. Constructor Overloading in Rectangle class


(i) Constructor overloading is defining multiple constructors with different
parameters. Yes, it is used in the given class, allowing object creation with either
default values (length = 1, breadth = 1) or custom values.
(ii) If Rectangle(4, 5) is called, the area will be:
4×5=204 \times 5 = 20
Output: Area: 20

33. Constructor in Car class


(i) The constructor used is the default constructor (no parameters).
(ii) It is called a default constructor because it initializes member variables with
default values.

34. Constructors in Box class


(i) The constructors used are:
 Default constructor (initializes fixed values)
 Parameterized constructor (accepts custom values)
(ii) If Box(2,3,4) is called, then:
Volume=2×3×4=24Volume = 2 \times 3 \times 4 = 24
Output: Volume: 24

35. Convert while loop to for loop


for (int x = 10; x >= 1; x--)
{
System.out.print(x);
}
System.out.print("Bye " + x);

36. Convert for loop to do...while loop


int x = 10;
do
{
System.out.print(x);
x--;
} while (x >= 1);
System.out.print("Hello " + x);

37. Convert do...while loop to while loop


int x = 10;
while (x >= 1)
{
System.out.print(x);
x--;
}
System.out.print("OK " + (++x));

38. Convert while loop to do...while loop

Page 50 of 93
int x = 1;
do
{
System.out.print(x);
x++;
} while (x <= 10);

39. Rewrite using if-else


int n = 150;
double result;
if (n < 100)
result = n + 50;
else
result = n - 25;

40. Rewrite using if-else


int score = 85;
String grade;
if (score >= 90)
grade = "A";
else if (score >= 80)
grade = "B";
else
grade = "C";

41. Output of the while loop


n = 789;
while (n > 0)
{
d = n % 10; // Extract last digit
System.out.println(d);
n = n / 3; // Integer division by 3
}
Output:
9
3
1
0
The loop executes until n > 0.

42. Given array names[]


(a) Length of the array: 4
(b) Value at names[1]: "Bob"
(c) First character of names[3]: 'D'
(d) Output of System.out.println(names.length + names[2]);
4Charlie
(e) Output of System.out.println(names[1].length() + names.length);
7

43. Given array z[]

Page 51 of 93
(a) Length of array: 5
(b) Value at z[3]: 20
(c) Output of System.out.println(z[1] * 2 + z[4]);
10 * 2 + 25 = 45
(d) Reversed array: {25, 20, 15, 10, 5}
New z[0] value: 25

44. Given array letters[]


(a) Length: 5
(b) Value at letters[2]: 'C'
(c) Output of System.out.println(letters[0] + letters[3]);
65 + 68 = 133
(ASCII values of 'A' and 'D')
(d) Memory required:
5 * 2 = 10 bytes
(Each char takes 2 bytes in Java)

45. Java Keywords and Methods


(i) final
(ii) System.exit(0);
(iii) void
(iv) extends
(v) toLowerCase()
(vi) length
(vii) String
(viii) +
(ix) compareTo()
(x) System.out.print() or System.out.println()
(xi) class
(xii) break
(xiii) this()
(xiv) final
(xv) new
(xvi) this
(xvii) void

46. Difference between Autoboxing and Unboxing


 Autoboxing: Converting a primitive type into an object.
 Integer obj = 5; // int to Integer
 Unboxing: Converting an object into a primitive type.
 int num = obj; // Integer to int

47. Output of Print Statements


(i) "She said, "Java is fun!"
(ii) "Sum: 30"
(iii)
First Line
Second Line Third Line
(iv) Escape Sequence: "\t" is a tab.
(v) The value of 5 > 3 is: true

Page 52 of 93
48. Loop Execution
(i) Output:
10
15
20
25
30
(ii) Output:
1
4
(iii) Output:
2
4
6
8
10
(iv) Output:
0
2
4
(v) Output:
7
11
15
19

49. Output
Oceanis
true

50-54: 2D Arrays (Skipped due to length, let me know if needed in detail)

55. Return Types of Methods


(i) boolean
(ii) int
(iii) String
(iv) char
(v) boolean
(vi) long
(vii) double

56. Logical Operators


if (x > 5 && x > y)
System.out.println(x + y);

57. Switch Case


switch (ch) {
case 'c':
case 'C': System.out.print("COMPUTER"); break;

Page 53 of 93
case 'h':
case 'H': System.out.print("HINDI"); break;
default: System.out.print("PHYSICAL EDUCATION");
}

58. Ternary Operator


r = (n1 > n2) ? true : false;

59. Effect of continue instead of break in switch


It causes an error because continue cannot be used in a switch statement.

60. Unicode Definition


Unicode is a character encoding standard that represents characters from different
languages.
Example: \u00A9 (©) represents the copyright symbol.
Here are the answers to your questions:

Q61. Explain the need for a Java compiler.


A Java compiler translates Java source code (.java file) into bytecode (.class file), which
is executed by the Java Virtual Machine (JVM). This ensures platform independence,
security, and efficient execution.

Q62. Differentiate between K, „K‟ and "K" in Java.


 K → Not valid unless used as a variable or identifier.
 'K' → A character literal (char data type).
 "K" → A string literal (String data type).

Q63. How many types of programs can be made in Java? Define them.
1. Standalone Applications - Executed independently on a user's machine.
2. Applets - Small programs embedded in web pages.
3. Web Applications - Java Servlets and JSPs for web development.
4. Enterprise Applications - Large-scale applications using Java EE.
5. Mobile Applications - Android apps using Java.
6. Embedded Systems - Java used in IoT and smart devices.

Q64. Evaluate x+=++x*(x++-++x)% ++x, if x=4 initially.


Let's compute step-by-step:
1. ++x → 5
2. x++ → 5 (then x becomes 6)
3. ++x → 7
4. (5 - 7) = -2
5. ++x → 8
6. (-2 % 8) = -2
7. x += 5 * (-2) → x = 4 + (-10) = -6
Final value: x = -6

Q65. One-line statement to find the last occurrence of a space in string s.


int lastIndex = s.lastIndexOf(' ');

Page 54 of 93
Q66. Java feature that executes multiple operations simultaneously:
Multithreading
Java feature where lowercase and uppercase letters are different: Case Sensitivity

Q67. Difference between a boolean literal and a character literal.


 Boolean Literal: Represents true or false. Example: boolean flag = true;
 Character Literal: Represents a single character enclosed in single quotes.
Example: char ch = 'A';

Q68. Difference between syntax and logical error with example.


 Syntax Error: Error in language rules, preventing compilation.
Example: int a = "Hello"; // Type mismatch
 Logical Error: Code runs but produces incorrect output.
Example: if (a = 5) // Should be == instead of =

Q69. Output and loop execution for given code.


int a=1,b=2,i=1;
for(b=100; b>=1; b/=a)
{
a=a+2;
System.out.println(b);
}
Execution:
 b=100, a=1
 b/=1 → 100, a=3
 b/=3 → 33, a=5
 b/=5 → 6, a=7
 b/=7 → 0 (loop terminates)
Output:
100
33
6
Loop executes 3 times.

Q70. Difference between index and control variable.


 Index: Refers to position in an array. Example: arr[2] (index 2).
 Control Variable: Used in loops to control iterations. Example: for(int i=0; i<5;
i++).

Q71. Iterations and output for the given code.


double P;
for(P=1; P<=7; P +=.5)
System.out.println(P+ " "+Math.rint(P));
Output:
11
1.5 2
22
2.5 2
33
3.5 4

Page 55 of 93
44
4.5 4
55
5.5 6
66
6.5 6
77
Number of Iterations: 13

Q72. Answers:
1. Loop that executes even if the condition is false: do-while loop.
2. Access right to access superclass data in subclass of any package: protected

Q73. When is switch better than if-else?


 When there are multiple constant conditions (case values).
 When execution needs to be faster (switch uses jump tables).
Example:
switch (grade) {
case 'A': System.out.println("Excellent!"); break;
case 'B': System.out.println("Good!"); break;
default: System.out.println("Try again!");
}

Q74. Define reference variable with example.


A reference variable stores the address of an object.
Example:
String s = "Hello"; // 's' is a reference variable

Q75. Answers:
 Unary Logical Operator: !
 Feature that makes variables visible: Scope

Q76. What is an index?


An index is the position of an element in an array.
 Minimum value: 0 (first element)
 Maximum value: length-1

Q77. Two features of functions:


1. Code Reusability: Functions avoid code repetition.
2. Modularity: Functions make the program structured.

Q78. Difference between break and return


 break: Terminates loops or switch statements.
 return: Exits from a function and returns a value.

Q79. Difference between local and global variables


 Local Variable: Declared inside a function, only accessible there.
 Global Variable: Declared outside functions, accessible everywhere.
Example:
int globalVar = 10; // Global

Page 56 of 93
void func() {
int localVar = 5; // Local
}

Q80. Output of the given code


for(i=i; i<=3; i=i+1)
for(j=1; j<4; j++ )
System.out.print(j+" ");
Assuming i=1 initially:
Output:
123123123
Loop executes 3 times.

81. Difference between Class and Object Variable with Example


 Class Variable (Static Variable): It belongs to the class and is shared among
all objects of the class. It is declared using the static keyword.
 Object Variable (Instance Variable): It belongs to an instance (object) and has
a separate copy for each object.
Example:
class Example {
static int classVar = 10; // Class variable
int objVar = 20; // Object variable
}

class Test {
static void main( ) {
Example e1 = new Example();
Example e2 = new Example();

e1.objVar = 30; // Changes only for e1


Example.classVar = 50; // Changes for all objects

System.out.println(e2.objVar); // Output: 20
System.out.println(e2.classVar); // Output: 50
}
}

82. Keywords
i) return
ii) this
iii) Method or Function (Encapsulation of reusable statements)

83. Selection Sort vs Bubble Sort


 Selection Sort: Finds the smallest element in each pass and swaps it with the
current position.
 Bubble Sort: Repeatedly swaps adjacent elements if they are in the wrong
order.
Example:
int arr[] = {64, 25, 12, 22, 11};

Page 57 of 93
// Selection Sort first finds the smallest (11) and swaps with first element.

84. Polymorphism in OOP


Polymorphism allows the same function or operator to have different meanings based
on context.
Example: Method Overloading
class Demo {
void display(int a) { System.out.println(a); }
void display(String b) { System.out.println(b); }
}

85. Static vs Final Variable


 Static: Shared among all objects.
 Final: Constant, cannot be changed.
Example:
static int x = 10; // Static variable
final int y = 20; // Final variable

86. Array and Types


An array is a collection of elements of the same type stored in contiguous memory
locations.
Types:
1. One-Dimensional
2. Multi-Dimensional (2D, 3D arrays)
Example:
int arr[] = {1, 2, 3}; // One-Dimensional
int matrix[][] = {{1, 2}, {3, 4}}; // Two-Dimensional

87. Function Prototype


boolean check(String Word, String[] Warray);

88. Assigning First Five Even Numbers


int Arr[] = {2, 4, 6, 8, 10};

89. Wrapper Class


A wrapper class wraps a primitive data type into an object.
Example:
Integer obj = Integer.valueOf(10); // Wrapper class for int

90. Short Data Type Range


 Largest Value: 32767
 Smallest Value: -32768

91. Conditional Operator Statement


char result = (Str.length() % 2 != 0) ? Str.charAt(Str.length()/2) :
Str.charAt(Str.length()-1);

92. Default Values


 char: '\u0000'
 String: null

Page 58 of 93
93. Index in Java
An index represents the position of a data item in an array.
 Numbering: Starts from 0 in Java.

94. Store First Six Even Numbers Greater Than 30


int Even[] = {32, 34, 36, 38, 40, 42};

95. X[12] Representation


 X[12] represents the 13th element (0-based indexing).
 If X[12] is the last cell, the length of the array is 13.

96. Function Prototype


boolean checkValue(double[] arr, String v, int num);

97. Output of Expression


String S = "TRIMAX IS NOT BUTTERFLOW";
System.out.println(S.lastIndexOf('T') + S.substring(6, 10) + "MY AGE");
 S.lastIndexOf('T') = 14
 S.substring(6, 10) = " IS "
 Output:
14 IS MY AGE

98. Fixed Code


int mm = 80;
boolean he = true;
if (mm >= 70 && he)
System.out.println("You can play cricket");
else
System.out.println("You cannot play cricket");
Errors Fixed:
 boolcan → boolean
 !mm → mm >= 70
 Syntax errors corrected

99. Corrected Code


void triangle() {
float a;
a = (float)(2.5 * 100 / 60); // Type casting needed
System.out.println("Answer = " + a);
}
Errors Fixed:
 float a: → float a; (semicolon missing)
 Explicit type casting required

100. Loop Execution and Returned Value


int func() {
int x = 10, y = 30;
while (x < y) {
++x;

Page 59 of 93
y -= 5;
}
return y;
}
Dry Run
x = 10, y = 30
x = 11, y = 25
x = 12, y = 20
x = 13, y = 15
x = 14, y = 10 (Loop stops)
 Loop executes 4 times.
 Returns 10.

Section - B
Answers of following questions (programs)

P1: Cab Service


import java.util.*;

class CabService
{
char type;
double km, bill;

// Constructor
CabService() {
type = ' ';
km = 0.0;
bill = 0.0;
}

// Accept method
void accept() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter car type (A for AC, N for NON AC): ");
type = sc.next().charAt(0);
System.out.print("Enter kilometers traveled: ");
km = sc.nextDouble();
}

// Calculate method
void calculate()
{
if (type == 'A')
{
bill = (km <= 5)
bill =150
else
bill =150 + (km - 5) * 10;

Page 60 of 93
}
else if (type == 'N')
{
bill = (km <= 5)
bill =120
bill =120 + (km - 5) * 8;
}
}
// Display method
void display()
{
System.out.println("CAR TYPE: " + type);
System.out.println("KILOMETER TRAVELLED: " + km);
System.out.println("TOTAL BILL: Rs. " + bill);
}

static void main( )


{
CabService cab = new CabService();
cab.accept();
cab.calculate();
cab.display();
}
}

P2: Student Grade Calculator


import java.util.*;
class Student
{
int rollnum, marks;
String name, grade;

// Constructor
Student()
{
rollnum = 0;
name = "";
marks = 0;
grade = "";
}
// Accept method
void input()
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter roll number: ");
rollnum = sc.nextInt();
sc.nextLine(); // Consume newline
System.out.print("Enter name: ");
name = sc.nextLine();
System.out.print("Enter marks: ");

Page 61 of 93
marks = sc.nextInt();
}

// Compute grade
void compute() {
if (marks > 90) grade = "A";
else if (marks >= 75) grade = "B";
else if (marks >= 60) grade = "C";
else if (marks >= 40) grade = "D";
else grade = "E";
}

// Display method
void display()
{
System.out.println("Roll Number\tName\tMarks\tGrade");
System.out.println(rollnum + "\t\t" + name + "\t" + marks + "\t" + grade);
}

static void main( )


{
Student s = new Student();
s.input();
s.compute();
s.display();
}
}

P3: ATransport
import java.util.*;
class ATransport
{
String name;
int w, charge;

// Constructor
ATransport()
{
name = "";
w = 0;
charge = 0;
}
// Accept method
void accept( )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter customer name: ");
name = sc.nextLine();
System.out.print("Enter weight of parcel (kg): ");
w = sc.nextInt();

Page 62 of 93
}
// Calculate charge
void calculate( )
{
if (w <= 10)
charge = w * 25;
else if (w <= 30)
charge = (10 * 25) + ((w - 10) * 20);
else
charge = (10 * 25) + (20 * 20) + ((w - 30) * 10);
// Adding 5% surcharge
charge += (charge * 5) / 100;
}
// Print method
void print( )
{
System.out.println("Name\tWeight\tBill Amount");
System.out.println(name + "\t" + w + "\tRs. " + charge);
}

static void main( )


{
ATransport obj = new ATransport();
obj.accept();
obj.calculate();
obj.print();
}
}

P4: Grade Revision


import java.util.*;
class Grade_Revision
{
String name;
int bas, expn;
double inc, nbas;
// Constructor
Grade_Revision( )
{
name = "";
bas = expn = 0;
inc = nbas = 0.0;
}
// Accept method
void accept( )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter employee name: ");
name = sc.nextLine();
System.out.print("Enter basic salary: ");

Page 63 of 93
bas = sc.nextInt();
System.out.print("Enter years of experience: ");
expn = sc.nextInt();
}
// Calculate increment
void increment( )
{
if (expn < 3)
inc = 1000 + 0.1 * bas;
else if (expn < 5)
inc = 3000 + 0.12 * bas;
else if (expn < 10)
inc = 5000 + 0.15 * bas;
else
inc = 8000 + 0.2 * bas;
nbas = bas + inc;
}
// Display method
void display( )
{
System.out.println("Name: " + name);
System.out.println("Basic Salary: Rs. " + bas);
System.out.println("Experience: " + expn + " years");
System.out.println("Increment: Rs. " + inc);
System.out.println("New Basic Salary: Rs. " + nbas);
}

static void main( )


{
Grade_Revision emp = new Grade_Revision();
emp.accept();
emp.increment();
emp.display();
}
}

P5: Electricity Bill


import java.util.*;
class ElectricityBill
{
String name;
int units;
double billAmt;
// Accept method
void accept( )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter customer name: ");
name = sc.nextLine();
System.out.print("Enter units consumed: ");

Page 64 of 93
units = sc.nextInt();
}
// Calculate bill
void calculate( )
{
if (units <= 100)
billAmt = units * 5;
else if (units <= 300)
billAmt = (100 * 5) + ((units - 100) * 7);
else
billAmt = (100 * 5) + (200 * 7) + ((units - 300) * 10);
}

// Display method
void display( )
{
System.out.println("Name\tUnits\tBill Amount");
System.out.println(name + "\t" + units + "\tRs. " + billAmt);
}
static void main( )
{
ElectricityBill bill = new ElectricityBill();
bill.accept();
bill.calculate();
bill.display();
}
}

P6: Employee Salary Calculation


import java.util.*;
class Empl
{
int Emp_No;
String Name;
double BasicSalary, DA, HRA, TA, PF, GrossSalary;
void get( )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter Employee No: ");
Emp_No = sc.nextInt();
sc.nextLine(); // Consume newline
System.out.print("Enter Name: ");
Name = sc.nextLine();
System.out.print("Enter Basic Salary: ");
BasicSalary = sc.nextDouble();
}
void calcu( )
{
if (BasicSalary >= 20000)

Page 65 of 93
{
DA = BasicSalary * 0.53;
TA = BasicSalary * 0.12;
HRA = BasicSalary * 0.10;
PF = BasicSalary * 0.08;
}
else if (BasicSalary >= 10000)
{
DA = BasicSalary * 0.45;
TA = BasicSalary * 0.10;
HRA = BasicSalary * 0.12;
PF = BasicSalary * 0.075;
}
else
{
DA = BasicSalary * 0.40;
TA = BasicSalary * 0.08;
HRA = BasicSalary * 0.14;
PF = BasicSalary * 0.07;
}
GrossSalary = (BasicSalary + DA + TA + HRA) - PF;
}

void display( )
{
System.out.println("EMPLOYEE No.\tNAME\tGROSS SALARY");
System.out.println(Emp_No + "\t\t" + Name + "\t" + GrossSalary);
}
static void main( )
{
Empl e = new Empl();
e.get();
e.calcu();
e.display();
}
}

P7: Bubble Sort for Names


import java.util.*;
class BubbleSort
{
static void main( )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of students: ");
int n = sc.nextInt();
sc.nextLine(); // Consume newline

String names[] = new String[n];

Page 66 of 93
System.out.println("Enter names:");
for (int i = 0; i < n; i++)
names[i] = sc.nextLine();
// Bubble Sort
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
if (names[j].compareTo(names[j + 1]) > 0)
{
String temp = names[j];
names[j] = names[j + 1];
names[j + 1] = temp;
}
}
}
System.out.println("Sorted Names:");
for (int i = 0; i < n; i++)
System.out.println(name);
}
}

P8: Selection Sort for Words (Descending Order)


import java.util.*;
class SelectionSort
{
static void main( )
{
Scanner sc = new Scanner(System.in);
String words[] = new String[40];
System.out.println("Enter 40 words:");
for (int i = 0; i < 40; i++)
words[i] = sc.nextLine();
// Selection Sort (Descending Order)
for (int i = 0; i < 39; i++)
{
int maxIndex = i;
for (int j = i + 1; j < 40; j++)
{
if (words[j].compareTo(words[maxIndex]) > 0)
{
maxIndex = j;
}
}
// Swap
String temp = words[i];
words[i] = words[maxIndex];
words[maxIndex] = temp;
}

Page 67 of 93
System.out.println("Sorted Words (Descending Order):");
for (int i = 0; i <40; i++)
System.out.println(word);
}
}

P9: Searching a Name with Phone Number


import java.util.*;
class SearchPhoneBook
{
static void main( )
{
String names[] = {"Alice", "Bob", "Charlie", "David", "Eve"};
String phoneNumbers[] = {"1234567890", "9876543210", "4567891230",
"7412589630", "8529637410"};
Scanner sc = new Scanner(System.in);
System.out.print("Enter name to search: ");
String searchName = sc.nextLine();
int found = 0;

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


{
if (names[i].equalsIgnoreCase(searchName))
{
found =1;
break;
}
}

if (found==1)
System.out.println("Search Unsuccessful, Name not enlisted.");
else
System.out.println("Name: " + names[i] + ", Phone: " + phoneNumbers[i]);

}
}

P10: Finding Smallest and Largest Number with Index


import java.util.*;
class MinMaxArray
{
static void main( )
{
Scanner sc = new Scanner(System.in);
int arr[] = new int[10];
System.out.println("Enter 10 numbers:");
for (int i = 0; i < 10; i++)
arr[i] = sc.nextInt();
int min = arr[0], max = arr[0];
int minIndex = 0, maxIndex = 0;

Page 68 of 93
for (int i = 1; i < 10; i++)
{
if (arr[i] < min) {
min = arr[i];
minIndex = i;
}
if (arr[i] > max)
{
max = arr[i];
maxIndex = i;
}
}
System.out.println("Smallest Number: " + min + " at index " + minIndex);
System.out.println("Largest Number: " + max + " at index " + maxIndex);
}
}

P11: Interchange Largest and Smallest Number in an Array


import java.util.*;
class MinMax
{
static void main( )
{
Scanner sc = new Scanner(System.in);
int arr[] = new int[10];
System.out.println("Enter 10 numbers:");
for (int i = 0; i < 10; i++) {
arr[i] = sc.nextInt();
}
int minIndex = 0, maxIndex = 0;
for (int i = 1; i < 10; i++)
{
if (arr[i] < arr[minIndex])
minIndex = i;
if (arr[i] > arr[maxIndex])
maxIndex = i;
}
// Swapping the largest and smallest elements
int temp = arr[minIndex];
arr[minIndex] = arr[maxIndex];
arr[maxIndex] = temp;

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

P12: Reverse an Array


import java.util.*;

Page 69 of 93
class ReverseArray
{
static void main( )
{
Scanner sc = new Scanner(System.in);
int arr[] = new int[10];
System.out.println("Enter 10 numbers:");
for (int i = 0; i < 10; i++)
arr[i] = sc.nextInt();
// Reversing the array
for (int i = 0; i < 5; i++)
{
int temp = arr[i];
arr[i] = arr[9 - i];
arr[9 - i] = temp;
}

System.out.println("Reversed Array:");
for (int i = 0; i < 10; i++)
System.out.print(num + " ");
}
}

P13: Store Even and Odd Numbers in Separate Arrays


import java.util.*;
class EvenOdd
{
static void main( )
{
Scanner sc = new Scanner(System.in);
int arr[] = new int[20], even[] = new int[20], odd[] = new int[20];
int eIndex = 0, oIndex = 0;
System.out.println("Enter 20 numbers:");
for (int i = 0; i < 20; i++)
{
arr[i] = sc.nextInt();
if (arr[i] % 2 == 0)
even[eIndex++] = arr[i];
else
odd[oIndex++] = arr[i];
}

System.out.println("Original Array:");
for (int i = 0; i < 20; i++)
System.out.print(arr[i] + " ");

System.out.println("\nEven Numbers:");
for (int i = 0; i < eIndex; i++)
System.out.print(even[i] + " ");

Page 70 of 93
System.out.println("\nOdd Numbers:");
for (int i = 0; i < oIndex; i++)
System.out.print(odd[i] + " ");
}
}

P14: Store State-Capital Pairs and Search Using Binary Search


import java.util.*;
class StateCapital
{
static void main( )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of states: ");
int n = sc.nextInt();
sc.nextLine(); // Consume the newline

String states[] = new String[n];


String capitals[] = new String[n];

// Input state and capital names


System.out.println("Enter State and Capital:");
for (int i = 0; i < n; i++)
{
System.out.print("State " + (i + 1) + ": ");
states[i] = sc.nextLine();
System.out.print("Capital " + (i + 1) + ": ");
capitals[i] = sc.nextLine();
}

// Sorting using Bubble Sort (Ascending Order)


for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
if (states[j].compareTo(states[j + 1]) > 0)
{
// Swap states
String tempState = states[j];
states[j] = states[j + 1];
states[j + 1] = tempState;

// Swap corresponding capitals


String tempCapital = capitals[j];
capitals[j] = capitals[j + 1];
capitals[j + 1] = tempCapital;
}
}
}

Page 71 of 93
// Input state to search
System.out.print("Enter the state to search: ");
String key = sc.nextLine();

// Binary Search using Loop


int low = 0, high = n - 1, found = -1;
while (low <= high)
{
int mid = (low + high) / 2;
if (states[mid].equalsIgnoreCase(key))
{
found = mid;
break;
}
else if (states[mid].compareToIgnoreCase(key) > 0)
high = mid - 1;
else
low = mid + 1;
}
// Display result
if (found != -1)
System.out.println("Capital: " + capitals[found]);
else
System.out.println("State not found in the list.");
}
}

P15: Binary Search for a Name in a Sorted List


import java.util.Arrays;
import java.util.*;

class NameSearch {
static void main( ) {
String Names[] = {"Alex", "Brian", "Charlie", "David", "Ethan", "Frank", "George",
"Jack"};
Scanner sc = new Scanner(System.in);

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


String key = sc.nextLine();

// Binary search for the name


int low = 0, high = Names.length - 1, found = -1;
while (low <= high) {
int mid = (low + high) / 2;
if (Names[mid].equals(key)) {
found = mid;
break;
} else if (Names[mid].compareTo(key) > 0)
high = mid - 1;

Page 72 of 93
else
low = mid + 1;
}

if (found != -1)
System.out.println("Search successful");
else
System.out.println("Search element not found");
}
}

P16: Reverse Case, Replace Digits with '*'


import java.util.*;
class ReverseCase
{
static void main( )
{
String newstr=””;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
int l=str.length();
for (int i = 0; i <l; i++)
{
char x=name.charAt(i);
if (Character.isUpperCase(ch))
newstr=newstr+Character.toLowerCase(ch);
else if (Character.isLowerCase(ch))
newstr=newstr+Character.toUpperCase(ch);
else if (Character.isDigit(ch))
newstr=newstr+'*';
else
newstr=newstr+ch;
}

System.out.println("Output: " + newstr);


}
}

P17: Print Initials and Title


import java.util.*;
class NameInitials
{
static void main( )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a full name: ");
String name = sc.nextLine().trim();
int l=name.length();
char x=name.charAt(0);

Page 73 of 93
String y=name.substring(1,l-1);
char z=name.charAt(l-1);
System.out.print(x+”. ”+y+”. “+z);
}
}

P18: Reverse Case but Keep Other Characters Unchanged


import java.util.*;

class ReverseCase
{
static void main( )
{
String newstr=””;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
int l=str.length();
for (int i = 0; i <l; i++)
{
char x=name.charAt(0);
if (Character.isUpperCase(ch))
newstr=newstr+Character.toLowerCase(ch);
else if (Character.isLowerCase(ch))
newstr=newstr+Character.toUpperCase(ch);
else
newstr=newstr+ch;
}

System.out.println("Output: " + newstr);

}
}

P19: Replace Consecutive Duplicates with a Single Character


import java.util.*;
class Remove
{
static void main( )
{
Scanner sc = new Scanner(System.in);
// Accept input string
System.out.print("Enter a string: ");
String input = sc.nextLine();
String result = ""; // To store the modified string
for (int i = 0; i < input.length( ); i++)
{
// Add the first character or non-duplicate characters to the result
if (i == 0 || input.charAt(i) != input.charAt(i - 1))
result += input.charAt(i);
}

Page 74 of 93
// Display the modified string
System.out.println("Output: " + result);
}
}
P20: Shift Vowels and Consonants to Their Next Letter
import java.util.*;
class ShiftCharacters
{
static void main( )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
String vowels = "aeiouAEIOU";
String nextVowel = "eiouaEIOUA";
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
if(Character.isLetter(c))
{
if (c=‟a‟)
newstr=newstr+‟e‟;
else if (c=‟e‟)
newstr=newstr+‟i‟;
else if (c=‟i‟)
newstr=newstr+‟o‟;
else if (c=‟o‟)
newstr=newstr+‟u‟;
else if (c=‟A‟)
newstr=newstr+‟E‟;
else if (c=‟E‟)
newstr=newstr+‟I‟;
else if (c=‟I‟)
newstr=newstr+‟O‟;
else if (c=‟O‟)
newstr=newstr+‟U‟;
else if (ch == 'z')
newstr=newstr+‟b‟;
else if (ch == 'Z')
newstr=newstr+‟B‟;
else
newstr=newstr+ (char) (ch + 1); // Shift consonant to next letter
}
else
newstr=newstr+c;
}
System.out.print(newstr);
}
}

Page 75 of 93
P21: Count Double Letter Sequences
import java.util.*;

class CountDoubleLetters
{
static void main( )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine().toUpperCase();
int count = 0;
for (int i = 0; i < str.length()-1; i++)
{
if (str.charAt(i) == str.charAt(i + 1) && Character.isLetter(str.charAt(i)))
count++;
}
System.out.println("Output: " + count);

}
}

P22: Print First Letter of Each Word in Capital, Separated by Dots


import java.util.*;

class InitialsWithDots
{
static void main( )
{
String newstr=””;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine();
str=” “+str;
for (int i = 0; i <words.length; i++)
{
char c=str.charAt(i);
if(c=‟ „)
{
char c1=str.charAt(i+1);
newstr=newstr+ Character.toUpperCase( c1)+”.”;
}
}
System.out.print(newstr);
}
}

P23: Display Consecutive Characters


import java.util.*;

Page 76 of 93
class Consecutive
{
static void main( )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.nextLine().toUpperCase();
for (int i = 0; i < str.length() - 1; i++)
{
char c=str.charAt(i);
char c1=str.charAt(i + 1);
if(c==c1)
System.out.println(c+”,”+c1);
}
}

P24: Sum of Even and Odd Numbers in a 4×5 Matrix


import java.util.*;
class SumEvenOddMatrix
{
static void main( )
{
Scanner sc = new Scanner(System.in);
int[][] matrix = new int[4][5];
int evenSum = 0, oddSum = 0;

System.out.println("Enter elements of 4×5 matrix:");


for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 5; j++) {
matrix[i][j] = sc.nextInt();
if (matrix[i][j] % 2 == 0)
evenSum += matrix[i][j];
else
oddSum += matrix[i][j];
}
}

System.out.println("Input Matrix:");
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 5; j++)
System.out.print(matrix[i][j] + "\t");
System.out.println();
}

System.out.println("Sum of even numbers: " + evenSum);

Page 77 of 93
System.out.println("Sum of odd numbers: " + oddSum);
}
}

P25: Find Largest and Smallest Number in a 4×4 Matrix


import java.util.*;
class MinMaxMatrix
{
static void main( )
{
Scanner sc = new Scanner(System.in);
int[][] matrix = new int[4][4];
int min, max;

System.out.println("Enter elements of 4×4 matrix:");


for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++) {
matrix[i][j] = sc.nextInt();
}

min = max = matrix[0][0];


for (int i = 0; i < 4; i++)
{
if (matrix[i][j] < min)
min = matrix[i][j];
if (matrix[i][j] > max)
max = matrix[i][j];
}

System.out.println("Input Matrix:");
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 5; j++)
System.out.print(matrix[i][j] + "\t");
System.out.println();
}

System.out.println("Smallest number: " + min);


System.out.println("Largest number: " + max);
}
}

P26: Search a Number in 3×4 Matrix


import java.util.*;
class SearchMatrix
{
static void main( )
{
Scanner sc = new Scanner(System.in);

Page 78 of 93
int[][] matrix = new int[3][4];
System.out.println("Enter elements of 3×4 matrix:");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++) {
matrix[i][j] = sc.nextInt();
}
System.out.print("Enter number to search: ");
int num = sc.nextInt();
boolean found = false;

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


{
for (int j = 0; j < 4; j++)
{
if (val == num)
{
found = true;
break;
}
}
if(found==true)
System.out.println("Number found in the matrix")
else
System.out.println("Number not found in the matrix");
}
}

P27: Sum of Two 3×3 Matrices


import java.util.*;
class MatrixSum
{
static void main( )
{
Scanner sc = new Scanner(System.in);
int[][] A = new int[3][3], B = new int[3][3], C = new int[3][3];
System.out.println("Enter elements of first 3×3 matrix:");
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
A[i][j] = sc.nextInt();

System.out.println("Enter elements of second 3×3 matrix:");


for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
B[i][j] = sc.nextInt();

System.out.println("Sum of matrices:");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)

Page 79 of 93
{
C[i][j] = A[i][j] + B[i][j];
System.out.print(C[i][j] + "\t");
}
System.out.println();
}
}
}

P28: Sum of Elements in Various Positions in 4×4 Matrix


import java.util.*;
class MatrixPositionSum
{
static void main( )
{
Scanner sc = new Scanner(System.in);
int[][] matrix = new int[4][4];
System.out.println("Enter elements of 4×4 matrix:");
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
matrix[i][j] = sc.nextInt();

int firstRowSum = 0, lastRowSum = 0, boundarySum = 0, leftDiagSum = 0,


rightDiagSum = 0;

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


{
firstRowSum += matrix[0][i];
lastRowSum += matrix[3][i];
leftDiagSum += matrix[i][i];
rightDiagSum += matrix[i][3 - i];

for (int j = 0; j < 4; j++)


{
if (i == 0 || i == 3 || j == 0 || j == 3)
boundarySum += matrix[i][j];
}
}

System.out.println("First row sum: " + firstRowSum);


System.out.println("Last row sum: " + lastRowSum);
System.out.println("Boundary elements sum: " + boundarySum);
System.out.println("Left diagonal sum: " + leftDiagSum);
System.out.println("Right diagonal sum: " + rightDiagSum);
}
}

P29: Sum of Each Column in 4×4 Matrix


import java.util.*;
class ColumnSumMatrix

Page 80 of 93
{
static void main( )
{
Scanner sc = new Scanner(System.in);
int[][] matrix = new int[4][4];
int[] colSum = new int[4];
System.out.println("Enter elements of 4×4 matrix:");
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
{
matrix[i][j] = sc.nextInt();
colSum[j] += matrix[i][j];
}

for (int j = 0; j < 4; j++)


System.out.println("Sum of column " + (j + 1) + " = " + colSum[j]);
}
}

P30: Check for Special Number


import java.util.*;
class SpecialNumber
{
static void main( )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt(),
int sum = 0, temp = num,n;
while (temp > 0)
{
n=temp % 10);
int fact = 1;
for (int i = 1; i <= n; i++)
fact *= i;
sum += fact;
temp /= 10;
}
If (num == sum)
System.out.println(num + " is a special number");
else
System.out.println(num + " is not a special number");
}
}

P31: Check if a number is a Disarium Number


import java.util.*;
class DisariumNumber
{

Page 81 of 93
void main( )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int temp = num, sum = 0, length = String.valueOf(num).length();
while (temp > 0)
{
int digit = temp % 10;
sum += Math.pow(digit, length);
temp /= 10;
length--;
}

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

P32: Check if two numbers are Amicable Numbers


import java.util.*;
class AmicableNumbers
{
void main( )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = sc.nextInt();
System.out.print("Enter second number: ");
int num2 = sc.nextInt();
int sum1 = 0, sum2=0;
for (int i = 1; i < num1; i++)
{
if (num1 % i == 0)
sum1 += i;
}
for (int i = 1; i < num2; i++)
{
if (num2 % i == 0)
sum2 += i;
}

if (sum1== num2 && sum2 == num1)


System.out.println(num1 + " and " + num2 + " are Amicable numbers.");
else
System.out.println(num1 + " and " + num2 + " are not Amicable numbers.");
}
}

Page 82 of 93
P33: Product of Successors of Even Digits
import java.util.*;
class SuccessorProduct
{
void main( )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int product = 1, count = 0;
while (num > 0)
{
int digit = num % 10;
if (digit % 2 == 0)
{
product *= (digit + 1);
count++;
}
num /= 10;
}

if (count == 0)
product = 0; // No even digits case
System.out.println("Output: " + product);
}
}

P34: Check if a number is a Neon Number


import java.util.*;
class NeonNumber
{
void main( )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int square = num * num, sum = 0;
while (square > 0)
{
sum += square % 10;
square /= 10;
}
if (sum == num)
System.out.println(num + " is a Neon number.");
else
System.out.println(num + " is not a Neon number.");
}
}

Page 83 of 93
P35:
class OverloadCompare
{
// Compare number of digits
void compare(int a, int b)
{
int digitsA = String.valueOf(a).length();
int digitsB = String.valueOf(b).length();
if (digitsA > digitsB)
System.out.println(a);
else if (digitsB > digitsA)
System.out.println(b);
else
System.out.println("Numbers are equal");
}

// Compare ASCII values


char compare(char a, char b)
{
if (a > b) return a;
else if (b > a) return b;
else return '$';
}

// Compare string lengths


void compare(String s1, String s2)
{
if (s1.length() > s2.length())
System.out.println(s1);
else if (s2.length() > s1.length())
System.out.println(s2);
else
System.out.println("Equal String");
}
}

P36:
class OverloadHLine
{
// Print triangle with '*'
void hline(int n)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= (2 * i - 1); j++)
{
System.out.print("* ");
}
System.out.println();
}

Page 84 of 93
}

// Print horizontal line of '@'


void hline()
{
System.out.println("@@@@@@@@@@");
}

// Print pattern with given character


void hline(int n, char c)
{
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(c + " ");
}
System.out.println();
}
}
}

P37:
class OverloadSeries
{
// Single argument series: 1 + 1/2 + 1/3 + ... + 1/n
double series(double n)
{
double sum = 0;
for (double i = 1; i <= n; i++)
{
sum += 1 / i;
}
return sum;
}

// Two arguments series: 1/a + 2/a^2 + 3/a^3 + ... + n/a^n


double series(double a, double n)
{
double sum = 0;
for (double i = 1; i <= n; i++)
{
sum += i / Math.pow(a, i);
}
return sum;
}
}

P38:
class OverloadDisplay

Page 85 of 93
{
// Print pattern
void display()
{
for (int i = 5; i >= 1; i--)
{
for (int j = i; j >= 1; j--)
{
System.out.print(j + "\t");
}
System.out.println();
}
}

// Print squares of digits


void display(int n)
{
while (n > 0)
{
int digit = n % 10;
System.out.println(Math.pow(digit, 2));
n /= 10;
}
}
}

P39: Interest Calculation


import java.util.*;
class InterestCalculator
{
void main( )
{
Scanner sc = new Scanner(System.in);

System.out.println("Enter your choice (S for Simple Interest, C for Compound


Interest): ");
char choice = sc.next().charAt(0);

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


double P = sc.nextDouble();

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


double R = sc.nextDouble();

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


double T = sc.nextDouble();

switch (choice)
{

Page 86 of 93
case 'S':
double SI = (P * R * T) / 100;
System.out.println("Simple Interest: " + SI);
break;
case 'C':
System.out.print("Enter number of times interest is compounded per year:
");
int n = sc.nextInt();
double CI = P * Math.pow((1 + R / (100 * n)), n * T) - P;
System.out.println("Compound Interest: " + CI);
break;
default:
System.out.println("Invalid Choice!");
}

}
}

P40: Abundant & Duck Number


import java.util.*;
class NumberChecker
{
void main( )
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter your choice (A for Abundant, B for Duck Number): ");
char choice = sc.next().charAt(0);

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


int num = sc.nextInt();

switch (choice)
{
case 'A':
int sum = 0;
for (int i = 1; i < num; i++)
{
if (num % i == 0)
sum += i;
}
if(sum > num)
System.out.println(num +" is an Abundant Number")
else
System.out.println(num +" is NOT an Abundant Number"));
break;
case 'B':
int c=0;
while (num > 0)
{
int digit = num % 10;

Page 87 of 93
if(digit==0)
c++;
num /= 10;
}
If(c>1)
System.out.println(“It is a Duck Number”);
else
System.out.println(“It is not a Duck Number”);
}
break;
default:
System.out.println("Invalid choice!");
}
}
}

P41: Menu-driven program (Factorial & Sunny Number)


import java.util.*;
class facto
{
void main( )
{
Scanner sc = new Scanner(System.in);
System.out.println("Choose an option:\n1. Factorial\n2. Sunny Number");
int choice = sc.nextInt();
switch (choice)
{
case 1:
System.out.print("Enter a number: ");
int num = sc.nextInt();
int fact = 1;
for (int i = 1; i <= num; i++)
fact *= i;
System.out.println("Factorial: " + fact);
break;
case 2:
System.out.print("Enter a number: ");
int n = sc.nextInt();
int nextNum = n + 1;
double sqrt = Math.sqrt(nextNum);
if (sqrt == (int) sqrt)
System.out.println(n + " is a Sunny Number.");
else
System.out.println(n + " is NOT a Sunny Number.");
break;
default:
System.out.println("Invalid choice!");
}
}
}

Page 88 of 93
P42: Courier Charges Calculation
import java.util.Scanner;

class Courier
{
public static void main( )
{

Scanner in = new Scanner(System.in);

System.out.print("Enter weight of parcel: ");


double wt = in.nextDouble();

System.out.print("Enter type of booking: ");


char type = in.next().charAt(0);

double charge = 0;
if (wt <= 0)
charge = 0;
else if (wt <= 100 && type == 'O')
charge = 80;
else if (wt <= 100 && type == 'E')
charge = 100;
else if (wt <= 500 && type == 'O')
charge = 150;
else if (wt <= 500 && type == 'E')
charge = 200;
else if (wt <= 1000 && type == 'O')
charge = 210;
else if (wt <= 1000 && type == 'E')
charge = 250;
else if (wt > 1000 && type == 'O')
charge = 250;
else if (wt > 1000 && type == 'E')
charge = 300;

System.out.println("Parcel charges = " + charge);


}
}

P43: Fibonacci Series & Sum of Digits


import java.util.*;

class P43 {
static void main( ) {
Scanner sc = new Scanner(System.in);
System.out.println("Choose an option:\n1. Fibonacci Series\n2. Sum of Digits");
int choice = sc.nextInt();

Page 89 of 93
switch (choice)
{
case 1:
int a = 0, b = 1, c;
System.out.print(a + " " + b + " ");
for (int i = 3; i <=10; i++)
{
c = a + b;
System.out.print(c + " ");
a = b;
b = c;
}
System.out.println();
break;

case 2:
System.out.print("Enter a number: ");
int num = sc.nextInt(), sum = 0;
while (num > 0)
{
sum += num % 10;
num /= 10;
}
System.out.println("Sum of digits: " + sum);
break;

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

}
}

P44: Function Overloading (String Operations)


class Stron
{
void Stron(String s, char ch)
{
if (s.indexOf(ch) != -1)
System.out.println("Character found in the string.");
else
System.out.println("Character NOT found in the string.");
}

void Stron(String s)
{
for (int i = s.length(); i > 0; i--)
System.out.println(s.substring(0, i));
}

Page 90 of 93
void Stron(String s, int n)
{
System.out.println(s.substring(0, n));
}

void main( )
{
Stron obj = new Stron();
obj.Stron("OKAY", 'A');
obj.Stron("OKAY");
obj.Stron("VIBGYOR", 3);
}
}

P45: Age Group Categorization


import java.util.*;
class ageGroup
{
void main( )
{
Scanner sc = new Scanner(System.in);
int senior = 0, middle = 0, junior = 0;

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


{
System.out.print("Enter age of person " + (i + 1) + ": ");
int age = sc.nextInt();
if (age >= 60)
senior++;
else if (age > 30)
middle++;
else
junior++;
}

System.out.println("Senior citizens: " + senior);


System.out.println("Middle group: " + middle);
System.out.println("Junior group: " + junior);

}
}

P46: Fibonacci & Pell Series Sum


import java.util.*;

class Pellfib
{
void main( )
{
Scanner sc = new Scanner(System.in);

Page 91 of 93
System.out.println("Choose an option:\n1. Fibonacci Sum\n2. Pell Sum");
int choice = sc.nextInt();
System.out.print("Enter number of terms: ");
int n = sc.nextInt();

int sum = 0;
switch (choice)
{
case 1:
int a = 0, b = 1, c;
for (int i = 0; i < n; i++)
{
sum += a;
c = a + b;
a = b;
b = c;
}
break;

case 2:
int x = 0, y = 1, z;
for (int i = 0; i < n; i++)
{
sum += x;
z = 2 * y + x;
x = y;
y = z;
}
break;

default:
System.out.println("Invalid choice!");
}
System.out.println("Sum of series: " + sum);
}
}

P49: Palindrome Check


import java.util.*;

class Palin
{
void main( )
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = sc.next();String rev=””;
for(int i=0;i<s.length();i++)
{
char c=sc.charAt(i);

Page 92 of 93
rev=c+rev;
}

if (s.equalsIgnoreCase(rev))
System.out.println(s.toLowerCase());
else
System.out.println(s.toUpperCase());
}
}

P50: Binary Search for Decimal Values

import java.util.*;

class Binary
{
void main( )
{
double[] arr = {4.1, 7.8, 12.6, 18.3, 25.0, 33.7, 41.9, 50.5, 67.4, 88.1};
Scanner sc = new Scanner(System.in);
System.out.print("Enter a decimal number to search: ");
double key = sc.nextDouble();
int low = 0;

int high = arr.length - 1;


boolean found = false;
while (low <= high)
{
int mid = (low + high) / 2;
if (arr[mid] == key)
{
found = true;
break;
}
else if (arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
if (found)
System.out.println("Search successful");
else
System.out.println("Search element not found");
}
}

Page 93 of 93

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy