1.OOPs MCQ BANK
1.OOPs MCQ BANK
1.OOPs MCQ BANK
5. The feature in Java that allows a subclass to provide a specific implementation of a method that is
already defined in its superclass is called:
a) Abstraction
b) Polymorphism
c) Encapsulation
d) Inheritance
Answer: b) Polymorphism
6. Which feature in Java allows you to hide the internal details of a class and show only the
functionalities to the outside world?
a) Abstraction
b) Encapsulation
c) Inheritance
d) Polymorphism
Answer: b) Encapsulation
8. The primitive data type in Java that can store whole numbers from -128 to 127 is:
a) byte
b) short
c) int
d) long
Answer: a) byte
9. Which primitive data type is used to store floating-point numbers with single-precision?
a) float
b) double
c) decimal
d) real
Answer: a) float
10. What is the default value of the boolean data type in Java?
a) true
b) false
c) null
d) 0
Answer: b) false
3. The JVM memory area that stores method-specific data and local variables is called:
a) Heap
b) Stack
c) Program Counter Register
d) Native Method Stack
Answer: b) Stack
4. Which component of JVM is responsible for loading the required class files during runtime?
a) Class Loader
b) Bytecode Verifier
c) Just-In-Time (JIT) Compiler
d) Garbage Collector
Answer: a) Class Loader
5. The JVM memory area that stores dynamically allocated objects and arrays is called:
a) Heap
b) Stack
c) Program Counter Register
d) Native Method Stack
Answer: a) Heap
6. When does the JVM's garbage collector free up memory?
a) At the end of the program execution
b) After every method call
c) When the program encounters an error
d) When objects are no longer referenced or needed
Answer: d) When objects are no longer referenced or needed
7. The JVM instruction that holds the memory address of the currently-executing JVM instruction is
called:
a) Heap
b) Stack
c) Program Counter Register
d) Native Method Stack
Answer: c) Program Counter Register
8. Which component of JVM ensures that the bytecode does not violate Java's security rules?
a) Class Loader
b) Bytecode Verifier
c) Just-In-Time (JIT) Compiler
d) Garbage Collector
Answer: b) Bytecode Verifier
9. The JVM memory area that stores information about native methods is called:
a) Heap
b) Stack
c) Program Counter Register
d) Native Method Stack
Answer: d) Native Method Stack
3. What is the purpose of the Java Runtime Environment (JRE) in the JDK?
a) To compile Java source code
b) To run Java applications and applets
c) To debug Java programs
d) To create Java documentation
Answer: b) To run Java applications and applets
8. Which JDK tool is used to launch the Java Virtual Machine (JVM)?
a) javac
b) java
c) jar
d) jdb
Answer: b) java
3. Which section of a Java class contains the class variables and constants?
a) Method
b) Constructor
c) Static Block
d) Instance Variables
Answer: d) Instance Variables
5. Which of the following is true regarding the main method in a Java class?
a) It is mandatory in every Java class
b) It can have any name other than "main"
c) It must be defined with the "public" access modifier
d) It is called automatically when the program is executed
Answer: a) It is mandatory in every Java class
8. The access specifier used to make a method or variable accessible only within the same package is:
a) private
b) public
c) protected
d) package-private (default)
Answer: d) package-private (default)
9. Which section of a Java class contains the code that is executed when an object of the class is created?
a) Method
b) Constructor
c) Static Block
d) Instance Variables
Answer: b) Constructor
3. Which primitive data type is used to store numbers with decimal points in Java?
a) int
b) float
c) double
d) decimal
Answer: c) double
6. The boolean data type in Java can have two possible values, which are:
a) True and False
b) Yes and No
c) 0 and 1
d) On and Off
Answer: a) True and False
8. The smallest possible value that can be stored in a byte data type in Java is:
a) -128
b) 0
c) 1
d) 127
Answer: a) -128
2. Lecture: Operators
2.1 Unary, Binary, Arithmetic, Assignment, Compound, Relational, Logical, Equality
1. Which type of operator requires a single operand and is used for incrementing or decrementing a
value?
A) Unary
B) Binary
C) Arithmetic
D) Assignment
Answer: A) Unary
5. The relational operator `<=` checks whether the left operand is ___________ the right operand.
A) Greater than or equal to
B) Less than or equal to
C) Equal to
D) Not equal to
Answer: B) Less than or equal to
**2.2.1 if-else-if:**
1. The `if` statement is used to ___________.
A) Execute a block of code repeatedly
B) Make a decision based on a condition
C) Declare variables and methods
D) Perform arithmetic operations
Answer: B) Make a decision based on a condition
2. In the context of the `if-else-if` statement, which condition is evaluated if all preceding conditions
are false?
A) First `if` condition
B) Last `if` condition
C) First `else` condition
D) First `else if` condition
Answer: D) First `else if` condition
**2.2.2 switch:**
1. The `switch` statement in Java is primarily used to ___________.
A) Perform arithmetic operations
B) Execute a block of code repeatedly
C) Make decisions based on multiple conditions
D) Declare variables and methods
Answer: C) Make decisions based on multiple conditions
2. What is the purpose of the `break` statement inside a `switch` case block?
A) To terminate the program
B) To exit the loop
C) To move to the next case without executing further code
D) To clear the variable values
Answer: C) To move to the next case without executing further code
5. In a `switch` statement, what happens if there is no `break` statement after a case block?
A) The program will throw a compilation error.
B) The program will enter an infinite loop.
C) The program will execute the next case block as well.
D) The program will terminate abruptly.
Answer: C) The program will execute the next case block as well.
5. What will be the value of `result` after the following code is executed?
```java
int a =
5;
int b = 8;
int result = (a > b) ? a : b;
```
A) 5
B) 8
C) true
D) false
Answer: B) 8
4. The `for` loop can be used to iterate over which of the following data structures?
A) Arrays only
B) Lists only
C) Arrays and Lists
D) Strings only
Answer: C) Arrays and Lists
5. What will be the value of `x` after the execution of the following loop?
```java
int x = 2;
for (int i = 0; i < 5; i++) {
x *= 2;
}
```
A) 8
B) 16
C) 32
D) 64
Answer: C) 32
3. In the context of a `while` loop, what happens if the initial condition is false?
A) The loop will not be executed.
B) The loop will execute indefinitely.
C) The loop will throw an exception.
D) The loop will execute at least once.
Answer: A) The loop will not be executed.
4. The `while` loop is best used when the number of iterations is ___________.
A) Known and fixed
B) Known but variable
C) Unknown and variable
D) Zero
Answer: C) Unknown and variable
5. What will be the value of `sum` after the following loop is executed?
```java
int sum = 0;
int i = 1;
while (i <= 10) {
sum += i;
i++;
}
```
A) 45
B) 55
C) 100
D) 10
Answer: B) 55
4. What will be the value of `product` after the following loop is executed?
```java
int product = 1;
int i = 0;
do {
product *= i;
i++;
} while (i <= 5);
```
A) 0
B) 1
C) 120
D) 720
Answer: B) 1
5. The `do-while` loop is useful when you want to ensure that the loop body is executed ___________.
A) Only once
B) A fixed number of times
C) Indefinitely (loop never terminates)
D) Based on multiple conditions
Answer: A) Only once
2. Which access modifier allows a variable or method to be accessible only within its own class?
A) private
B) protected
C) public
D) package-private (default)
Answer: A) private
4. What is the return type of a method that does not return any value in Java?
A) void
B) int
C) String
D) boolean
Answer: A) void
5. In Java, a method can have ___________ with the same name, but different parameter lists.
A) Overloaded methods
B) Nested methods
C)
Recursive methods
D) Abstract methods
Answer: A) Overloaded methods
2. What happens if you try to assign a floating-point value to an integer variable in Java without
explicit casting?
A) The program will not compile.
B) The decimal part of the value will be truncated.
C) The variable will be automatically promoted to a floating-point type.
D) The program will throw a runtime exception.
Answer: A) The program will not compile.
3. Which data type is used to store floating-point numbers with a higher precision than the `float` data
type?
A) double
B) float128
C) long double
D) BigDecimal
Answer: C) long double
**2.5 Get Yourself Acquainted with Java Environment. Print Different Patterns of Asterisk (*) Using
Loops (e.g. Triangle of *).**
1. To print a right-angled triangle of asterisks (*), how many nested loops are required?
A) One
B) Two
C) Three
D) It cannot be achieved using loops
Answer: B) Two
3. To print a hollow square of asterisks (*), how many nested loops are required?
A) One
B) Two
C) Three
D) It cannot be achieved using loops
Answer: B) Two
5. The pattern of asterisks printed using loops is primarily used for ___________.
A) Debugging purposes
B) Beautifying the code
C) User input validation
D) Educational purposes
Answer: D) Educational purposes]
3. Lecture: Static Variables and Methods
**3.1 Accessing Static Variables and Methods of Different Classes:**
3. In Java, you can access a static variable without creating an instance of the class because
___________.
A) Static variables are automatically initialized to their default values
B) Static variables are always set to zero by default
C) Static variables are shared across all instances of the class
D) Static variables can only be accessed within the same class
Answer: C) Static variables are shared across all instances of the class
MyClass() {
count++;
}
}
5. The keyword used to access a static method within the same class is ___________.
A) static
B) this
C) self
D) ClassName
Answer: D) ClassName
7. Can static variables be accessed directly from an instance (object) of the class?
A) Yes, but only if the instance is not null
B) No, static variables can only be accessed using the class name
C) Yes, static variables can be accessed using both the instance and class name
D) Yes, but only if the static variable is public
Answer: C) Yes, static variables can be accessed using both the instance and class name
8. What is the difference between a static variable and an instance variable in Java?
A) Instance variables are shared among all instances of the class, while static variables are unique to
each instance.
B) Instance variables can be accessed using the class name, while static variables can only be
accessed using an instance of the class.
C) Static variables are created inside methods, while instance variables are created outside methods.
D) Instance variables are declared with the keyword "this," while static variables are declared with
the keyword "static."
Answer: A) Instance variables are shared among all instances of the class, while static variables are
unique to each instance.
5. Which of the following data types is a reference data type that allows multiple characters to be stored?
A) char
B) byte
C) int
D) String
Answer: D) String
7. What is the key difference between a reference data type and a primitive data type in Java?
A) Reference data types are larger in size compared to primitive data types.
B) Reference data types are passed by value, whereas primitive data types are passed by reference.
C) Reference data types can store data directly, while primitive data types store memory addresses of
data.
D) Reference data types represent complex objects, while primitive data types represent simple data
values.
Answer: D) Reference data types represent complex objects, while primitive data types represent
simple data values.
Person(String n) {
name = n;
}
}
4. What happens when a reference variable is assigned to another reference variable in Java?
A) The data values of both variables are exchanged.
B) Both variables will point to the same memory address (object).
C) Java throws a compilation error.
D) The data values of the second variable are copied to the first variable.
Answer: B) Both variables will point to the same memory address (object).
6. When a method is called on an object using a reference variable, the method that gets executed
depends on ___________.
A) Whether the method is static or non-static
B) The data type of the reference variable
C) The return type of the method
D) The actual type of the object being referred to
Answer: D) The actual type of the object being referred to
**3.4 Difference Between Reference Data Types and Primitive Data Types:**
1. Which of the following is a difference between primitive data types and reference data types in Java?
A) Primitive data types are created on the heap, while reference data types are created on the stack.
B) Primitive data types store actual data values, while reference data types store memory addresses of
objects.
C) Primitive data types can be used to create complex data structures, while reference data types are
limited to simple data values.
D) Primitive data types can be null, while reference data types cannot be null.
Answer: B) Primitive data types store actual data values, while reference data types store memory
addresses of objects.
3. What is a key advantage of using primitive data types over reference data types?
A) Primitive data types have more memory storage than reference data types.
B) Primitive data types can be used to create complex data structures like arrays and objects.
C) Primitive data types are faster in terms of performance compared to reference data types.
D) Primitive data types can be null, while reference data types cannot be null.
Answer: C) Primitive data types are faster in terms of performance compared to reference data types.
4. Which of the following is true about the memory allocation of primitive data types and reference
data types in Java?
A) Primitive data types are stored on the stack, while reference data types are stored on the heap.
B) Both primitive data types and reference data types are stored on the stack.
C) Primitive data types are stored on the heap, while reference data types are stored on the stack.
D) Both primitive data types and reference data types are stored on the heap.
Answer: A) Primitive data types are stored on the stack, while reference data types are stored on the
heap.
8. In Java, reference data types are ___________ in size compared to primitive data types.
A) Smaller
B) Larger
C) Equal
D) Unpredictable
Answer: B) Larger
1. What is a key difference between a reference variable and a static variable in Java?
A) A reference variable is used to store memory addresses, while a static variable is used to store
actual data values.
B) A reference variable can be accessed directly using the class name, while a static variable can only
be accessed through an instance of the class.
C) A reference variable can be declared with the "static" keyword, while a static variable cannot be
declared with the "static" keyword.
D) A reference variable can store primitive data types, while a static variable can store only reference
data types.
Answer: A) A reference variable is used to store memory addresses, while a static variable is used to
store actual data values.
Answer: a) When you want to modify the original value inside the method.
Answer: b) Any changes made to the parameter inside the method are reflected outside the method.
Answer: b) False
**4.2 Re-assigning a Reference Variable:**
1. In Java, when you re-assign a reference variable to another object, what happens to the original
object?
a) The original object is deleted from memory.
b) The original object remains unchanged.
c) The original object becomes null.
d) The original object becomes a copy of the new object.
4. In Java, when does an object become eligible for garbage collection after re-assigning its reference
variable?
a) Immediately after re-assigning the reference variable.
b) When the new object is garbage collected.
c) When there are no more references to the original object.
d) The object is never eligible for garbage collection.
Answer: a) The object becomes unreachable and eligible for garbage collection.
1. When you pass a reference variable to a method in Java, what is passed to the method?
a) The value of the object.
b) A copy of the object.
c) The memory address of the object.
d) The reference variable itself.
2. What happens to the original object when a reference variable is passed to a method?
a) The original object becomes a copy of the object inside the method.
b) Any changes made to the object inside the method are reflected outside the method.
c) The original object gets deleted from memory.
d) The original object becomes null.
Answer: b) Any changes made to the object inside the method are reflected outside the method.
Answer: a) Yes, a method can change the reference to point to a different object.
Answer: a) Declare the variable and assign it a value using the "new" keyword.
2. When initializing a reference variable of a different class, what is the type of object created?
a) An instance of the class.
b) A copy of the class.
c) A subclass of the class.
d) A superclass of the class.
Answer: a) The variable is assigned a default value based on its data type.
5. In Java, if you don't initialize a reference variable, what value does it have?
a) null
b) 0
c) "undefined"
d) The value depends on the data type of the variable.
Answer: a) null
6. Which of the following is true when initializing reference variables of different classes?
a) The reference variable can be directly assigned to a value of any data type.
b) The reference variable must be initialized in the main method.
c) The reference variable can only be initialized using a constructor.
d) The reference variable must be declared as a static variable.
3. In Java, where are local variables and method call data stored?
a) Heap memory
b) Stack memory
c) Global memory
d) Code memory
5. How is memory management different for the heap and stack memory in Java?
a) Heap memory is automatically managed by the Java Virtual Machine (JVM), while stack memory
needs manual management.
b) Stack memory is automatically managed by the JVM, while heap memory needs manual
management.
c) Both heap and stack memory require manual memory management.
d) Java does not differentiate between heap and stack memory management.
Answer: a) Heap memory is automatically managed by the Java Virtual Machine (JVM), while stack
memory needs manual management.
6. Which memory area is responsible for keeping track of method call information, local variables, and
partial results?
a) Heap memory
b) Stack memory
c) Global memory
d) Code memory
7. In Java, what happens to objects stored in the heap memory once they are no longer referenced?
a) They are automatically garbage collected to free up memory.
b) They are moved to the stack memory for faster access.
c) They become eligible for manual deletion by the programmer.
d) They remain in the heap memory indefinitely.
**4.6 Print Default Values of Static & Instance Variables for Different Data Types:**
Answer: a) 0
Answer: c) 0.0
3. For a non-static object reference variable, what is the default value when not initialized?
a) 0
b) 1
c) null
d) "undefined"
Answer: c) null
Answer: b) false
Answer: c) '\u0000'
2. Which access modifier should be used for the instance variables of the Employee class to restrict
direct access from outside the class?
a) public
b) private
c) protected
d) default (package-private)
Answer: b) private
Answer: a) By using the `new` keyword followed by the class name and constructor parameters.
4. Which method is called automatically when an object of the Employee class is instantiated?
a) run()
b) main()
c) start()
d) constructor
Answer: d) constructor
5. To compile and run the Employee class, what should the Java file be named?
a) Employee.java
b) employee.class
c) emp.class
d) emp.java
Answer: a) Employee.java
7. When creating an instance of the Employee class, what constructor parameters might you pass to set
initial values for the instance variables?
a) No parameters are needed; the constructor automatically initializes the instance variables.
b) Employee name and age.
c) Employee salary and department.
d) Employee ID and job title.
1. In Java, how do you define a reference variable that refers to an object of another class?
a) Declare the variable and assign it using the "new" keyword.
b) Use the "ref" keyword followed by the class name.
c) Declare the variable and assign it using the "instanceof" keyword.
d) Java does not allow referencing objects of other classes.
Answer: a) Declare the variable and assign it using the "new" keyword.
Answer: b) To access and utilize the methods and attributes of the referenced classes.
Answer: c) By using the reference variable followed by the method name and arguments.
4. What is the role of the "dot" operator (.) in Java when invoking an instance method on a referenced
object?
a) It creates a new object from the referenced class.
b) It calls the constructor of the referenced class.
c) It accesses the methods and attributes of the referenced object.
d) It deletes the referenced object from memory.
6. What happens if you try to invoke a non-static method on a reference variable before initializing it
with an object?
a) The program will compile, but the method will not be executed.
b) The program will throw a compilation error.
c) The program will throw a runtime exception.
d) The method will be executed, but it will return a null reference.
Answer: c) Modularity
Answer: a) The process of combining data and methods into a single unit (object).
4. Which concept in OOP allows you to create a new class based on an existing class?
a) Polymorphism
b) Inheritance
c) Encapsulation
d) Abstraction
Answer: b) Inheritance
5. Which OOP concept promotes the reusability of code and establishes a hierarchical relationship
between classes?
a) Polymorphism
b) Encapsulation
c) Abstraction
d) Inheritance
Answer: d) Inheritance
7. Which OOP concept allows you to define a blueprint for creating objects?
a) Inheritance
b) Abstraction
c) Encapsulation
d) Polymorphism
Answer: b) Abstraction
10. Which OOP concept allows a class to have multiple methods with the same name but different
parameter lists?
a) Encapsulation
b) Abstraction
c) Polymorphism
d) Inheritance
Answer: c) Polymorphism
11. What is the access specifier that allows a class member to be accessible only within the same
package?
a) private
b) protected
c) public
d) default (package-private)
Answer: d) Complexity
13. What is the term used to describe the ability of an object to take on many forms?
a) Abstraction
b) Encapsulation
c) Polymorphism
d) Inheritance
Answer: c) Polymorphism
15. Which OOP concept allows you to define a new class based on an existing class but with some
modifications or extensions?
a) Abstraction
b) Polymorphism
c) Inheritance
d) Encapsulation
Answer: c) Inheritance
**5.1 Encapsulation**
2. Which access specifier is commonly used for the getter and setter methods in encapsulation?
a) private
b) protected
c) public
d) default (package-private)
Answer: c) public
Answer: b) They provide a convenient way to access and modify the data members.
6. In encapsulation, which method is used to read the value of a private data member?
a) readValue()
b) getValue()
c) getData()
d) getVariableName()
Answer: b) getValue()
7. What is the purpose of using the "this" keyword in getter and setter methods?
a) To refer to the superclass.
b) To call the constructor of the class.
c) To refer to the current object.
d) To invoke static methods.
9. What happens if you bypass the getter and setter methods and directly access the private data
members?
a) It will
10. In encapsulation, how do you provide write-only access to a private data member?
a) By declaring the data member as public.
b) By providing a public setter method but no getter method.
c) By providing a public getter method but no setter method.
d) Java does not allow write-only access to private data members.
Answer: c) Encapsulation allows you to hide the internal implementation details of a class.
12. What is the scope of a private data member in a class that implements encapsulation?
a) It can be accessed from any class.
b) It can be accessed from subclasses only.
c) It can be accessed only within the same class.
d) It can be accessed from any class in the same package.
13. In encapsulation, what is the purpose of using the "final" keyword with a data member?
a) To prevent the data member from being accessed.
b) To make the data member read-only (constant).
c) To make the data member invisible to other classes.
d) To make the data member accessible without getter and setter methods.
15. In encapsulation, what is the role of access modifiers (e.g., private, public) for methods and data
members?
a) They define the data types for methods and data members.
b) They determine the order of execution for methods.
c) They control the visibility and accessibility of methods and data members.
d) They enforce encapsulation rules automatically.
Answer: c) They control the visibility and accessibility of methods and data members.
Answer: c) The process of acquiring the properties and behaviors of an existing class.
Answer: a) extend
5. What is the relationship between the subclass and the superclass in inheritance?
a) The subclass is a specialization of the superclass.
b) The subclass is an exact copy of the superclass.
c) The subclass is a separate entity unrelated to the superclass.
d) The subclass is a combination of multiple superclasses.
Answer: c) A method that has the same name and signature in the subclass as in the superclass.
8. Which access modifier is commonly used for the methods in a base class to allow subclasses to
override them?
a) private
b) protected
c) public
d) default (package-private)
Answer: b) protected
10. In Java, can a subclass inherit private members (data members and methods) from the superclass?
a) Yes, a subclass can inherit private members.
b) No, private members are not inherited by subclasses.
c) It depends on the access modifier used for the private members.
d) It depends on whether the superclass is abstract.
11. What happens if a subclass tries to access a private member (data member or method) of its
superclass?
a) The program will compile but throw a runtime exception.
b) The program will throw a compilation error.
c) The private member will be accessible from the subclass.
d) The superclass will automatically become a subclass.
14. In multilevel inheritance, how many levels of inheritance can a subclass have?
a) Only one level
b) Two levels
c) Three levels
d) Any number of levels
1. In hierarchical inheritance, how many classes are derived from a single base class?
a) One
b) Two
c) Multiple
d) None
Answer: b) Two
Answer: d) extends
```java
class A {
// ...
}
class B extends A {
// ...
}
class C extends A {
// ...
}
```
a) Single inheritance
b) Hierarchical inheritance
c) Multiple inheritance
d) Multilevel inheritance
Answer: c) To allow access to class members within the same package and subclasses
Answer: c) final
8. What is the process called when a subclass provides a specific implementation for a method that is
already defined in its superclass?
a) Overriding
b) Overloading
c) Inheriting
d) Encapsulating
Answer: a) Overriding
Answer: c) Overloaded methods must have the same number and types of parameters.
5. Which keyword is used to annotate a method in the superclass that can be overridden by its
subclasses?
a) this
b) abstract
c) super
d) override
Answer: d) override
6. In Java, when does the determination of which method to call happen in the case of method
overloading?
a) At compile-time
b) At runtime
c) At the time of object creation
d) When the program is executed
Answer: a) At compile-time
```java
public void display(int a, double b) {
// Method implementation
}
```
Which of the following method calls would be considered as an example of method overloading?
a) display(10, 5.0)
b) display(5.0, 10)
c) display(10, 10)
d) display(10, 10, 5.0)
2. What happens if a subclass tries to override a method in its superclass that is marked as "final"?
a) The subclass can override the final method without any issues.
b) The compiler will generate an error, and the method cannot be overridden.
c) The subclass can only override the method if it is also marked as "final."
d) The behavior is undefined, and it depends on the specific Java compiler.
Answer: b) The compiler will generate an error, and the method cannot be overridden.
3. In method overriding, what should be the relationship between the access modifiers of the
overridden method and the overriding method?
a) The access modifier of the overriding method should be less restrictive than that of the overridden
method.
b) The access modifier of the overriding method should be more restrictive than that of the
overridden method.
c) The access modifiers of both methods should be the same.
d) The access modifiers are unrelated to method overriding.
4. Which annotation is used to indicate that a method is intended to override a superclass method in
Java?
a) @override
b) @Override
c) @extend
d) @super
Answer: b) @Override
Answer: a) A single method can have multiple implementations with the same name.
6. Consider the following code:
```java
class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}
Answer: c) Overloaded methods must have the same method name but different parameters.
8. In method overloading, can two methods have the same name and parameters but different return
types?
a) Yes, it is allowed in Java.
b) No, it will result in a compilation error.
c) Only if the methods are declared in different classes.
d) Only if the methods have different access modifiers.
Answer: a) It refers to the superclass and is used to call its methods or access its properties.
```java
class Parent {
int x;
Parent(int x) {
this.x = x;
}
}
Child(int x, int y) {
super(x);
this.y = y;
}
}
```
What is the purpose of the "super(x)" statement in the Child class constructor?
Answer: b) It sets the value of x in the Parent class to the value passed in the Child class constructor.
4. In which of the following scenarios would you use the "super" keyword in Java?
a) To create a new instance of a class.
b) To call a method in the current class.
c) To call a constructor of the superclass from a subclass constructor.
d) To define a new method in a subclass.
5. What happens if the "super" keyword is not used in a subclass constructor in Java?
a) The subclass constructor will automatically call the default constructor of the superclass.
b) The compiler will generate an error, and the subclass constructor won't compile.
c) The subclass constructor will throw a runtime exception.
d) The subclass constructor will have no effect, and it won't be able to create instances of the subclass.
Answer: a) The subclass constructor will automatically call the default constructor of the superclass.
6. In Java, is it possible to use both "this" and "super" in the same constructor?
a) Yes, but only if the superclass has a parameterless constructor.
b) No, using both "this" and "super" in the same constructor is not allowed.
c) Yes, using "this" and "super" together is common when chaining constructors in a class.
d) Yes, but only if the superclass has a constructor with the same number of parameters as the
subclass.
Answer: c) Yes, using "this" and "super" together is common when chaining constructors in a class.
7. Which keyword is used to invoke a method of the superclass in a subclass, even if the subclass has
overridden that method?
a) override
b) overload
c) super
d) this
Answer: c) super
8. In Java, which keyword is used to differentiate between an instance variable of a class and a
parameter in a method with the same name?
a) final
b) new
c) this
d) super
Answer: c) this
Answer: a) Upcasting is always allowed and does not require any explicit casting.
```java
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
```java
Animal animal = new Dog();
animal.makeSound();
```
Answer: b) Downcasting can result in a loss of data if the object is not of the expected subclass type.
```java
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
What will happen when you try to compile and run the following code snippet?
```java
Animal animal = new Dog();
Cat cat = (Cat) animal;
cat.makeSound();
```
7. To avoid the risk of ClassCastException when performing downcasting in Java, you should use
which keyword?
a) instanceof
b) checkcast
c) safecast
d) convert
Answer: a) instanceof
**6.5 Create a Class Employee and Encapsulate the Data Members. Create Demo Applications to
Illustrate Different Types of Inheritance.**
Answer: c) The process of hiding the internal details of a class and providing access through methods.
3. Create a Java class named "Employee" with private data members "name," "id," and "salary." What
is the correct way to provide access to these private data members?
a) Define public methods to get and set the data members' values.
b) Declare the data members as public to allow direct access.
c) Use the "protected" access modifier to make the data members accessible to subclasses.
d) Use the "this" keyword to access the data members directly.
Answer: a) Define public methods to get and set the data members' values.
Answer: b) By preventing direct access to data members and providing controlled access through
methods.
6. Create a Java class named "Manager" that inherits from the "Employee" class. Which keyword is
used to achieve inheritance in Java?
a) extends
b) implements
c) super
d) this
Answer: a) extends
7. How can you access a method defined in the superclass from a subclass in Java?
a) By redefining the method with the same name in the subclass.
b) By using the "this" keyword to call the method.
c) By using the "super" keyword followed by the method name.
d) By casting the subclass object to the superclass type.
8. In Java, what is the default access modifier for a class member if no access modifier is specified
?
a) public
b) private
c) protected
d) package-private (default)
Answer: a) A class that cannot be instantiated and serves as a blueprint for other classes.
Answer: a) abstract
Answer: c) Yes, an abstract class can have both abstract and concrete methods.
Answer: c) An abstract class can have both static and non-static methods.
Answer: c) No, a class cannot be both abstract and final at the same time.
8. If a class extends an abstract class, what are the options regarding the abstract methods in the
subclass?
a) The subclass can choose to implement all, some, or none of the abstract methods.
b) The subclass must override all the abstract methods to provide implementations.
c) The subclass can only override the non-abstract methods from the abstract class.
d) The subclass inherits the concrete methods and cannot override the abstract methods.
Answer: a) The subclass can choose to implement all, some, or none of the abstract methods.
9. What happens if a non-abstract subclass fails to implement all the abstract methods from its abstract
superclass?
a) The subclass will inherit the abstract methods and become abstract itself.
b) The subclass will have a default implementation of the missing abstract methods.
c) The code will not compile, resulting in a compilation error.
d) The abstract methods will be automatically inherited from the Object class.
10. Can an abstract class have variables with different access modifiers (e.g., public, private, protected)
in Java?
a) Yes, but only if the variables are declared as final.
b) Yes, there are no restrictions on the access modifiers for variables in an abstract class.
c) No, all variables in an abstract class must have the same access modifier.
d) No, an abstract class cannot have any variables.
Answer: b) Yes, there are no restrictions on the access modifiers for variables in an abstract class.
Answer: a) Yes, and the subclass must implement all the abstract methods from both abstract classes.
12. What is the purpose of making an abstract class?
a) To prevent any instances of the class from being created.
b) To allow instances of the class to be created without any restrictions.
c) To ensure that the class cannot be subclassed.
d) To hide the implementation details of the class.
Answer: c) No, Java does not support multiple inheritance from abstract classes.
14. If a subclass inherits from both an abstract class and a concrete class, in which order should the
"extends" keyword be used in Java?
a) The order does not matter; the "extends" keyword can be used in any order.
b) The subclass must extend the concrete class first, followed by the abstract class.
c) The subclass must extend the abstract class first, followed by the concrete class.
d) The subclass cannot inherit from both an abstract class and a concrete class.
Answer: c) The subclass must extend the abstract class first, followed by the concrete class.
**Coding MCQs**
```java
abstract class Shape {
int sides;
void displaySides() {
System.out.println("Number of sides: " + sides);
}
}
```
a)
```java
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle.");
}
}
```
b)
```java
class Triangle extends Shape {
void draw() {
System.out.println("Drawing a triangle.");
}
void displaySides() {
System.out.println("Number of
sides: 3");
}
}
```
c)
```java
class Square extends Shape {
void displaySides() {
System.out.println("Number of sides: 4");
}
}
```
d)
```java
class Rectangle extends Shape {
void draw() {
System.out.println("Drawing a rectangle.");
}
}
```
Answer: a)
```java
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle.");
}
}
```
```java
abstract class Animal {
abstract void makeSound();
}
3. Which of the following is a valid way to declare and initialize an array of abstract class type in Java?
a)
```java
Animal[] animals = new Animal[];
```
b)
```java
Animal[] animals = new Animal[5];
```
c)
```java
Animal[] animals = { new Dog(), new Cat() };
```
d)
```java
Animal[] animals = new Animal[5] { new Dog(), new Cat() };
```
Answer: b)
```java
Animal[] animals = new Animal[5];
```
```java
abstract class Vehicle {
abstract void start();
}
a) "Car started."
b) "Bike started."
c) Compilation error due to abstract methods in the Vehicle class.
d) Runtime error due to the abstract start() method not being implemented.
```java
abstract class Fruit {
String color;
Fruit(String color) {
this.color = color;
}
void eat() {
System.out.println("Eating an apple.");
}
}
```
Which of the following is the correct way to create an instance of the Apple class?
a)
```java
Fruit apple = new Fruit("red");
```
b)
```java
Apple apple = new Apple("red");
```
c)
```java
Fruit apple = new Apple("red");
```
d)
```java
Apple apple = new Fruit("red");
```
Answer: c)
```java
Fruit apple = new Apple("red");
```
```java
abstract class Shape {
abstract void draw();
void display() {
System.out.println("Displaying shape.");
}
}
```java
Shape shape = new Circle();
shape.draw();
shape.display();
```
a) Yes, but the concrete class must override all the abstract methods from the abstract class.
b) Yes, and the concrete class inherits the implementation of the abstract methods from the abstract
class.
c) No, a concrete class cannot extend an abstract class.
d) Yes, but the concrete class can only extend an abstract class if it is in the same package.
Answer: a) Yes, but the concrete class must override all the abstract methods from the abstract class.
```java
abstract class Bird {
abstract void fly();
void makeSound() {
System.out.println("Chirp Chirp");
}
}
```java
public class Main {
public static void main(String[] args) {
Bird sparrow = new Sparrow();
Bird penguin = new Penguin();
sparrow.fly();
penguin.fly();
sparrow.makeSound();
penguin.makeSound();
}
}
```
a)
```
Sparrow flies.
Penguins cannot fly.
Chirp Chirp
Penguin sound.
```
b)
```
Sparrow flies.
Penguins cannot fly.
Penguin sound.
Penguin sound.
```
c)
```
Sparrow flies.
Penguin sound.
Chirp Chirp
Penguin sound.
```
d)
```
Sparrow flies.
Penguin sound.
Chirp Chirp
Penguins cannot fly.
```
Answer: a)
```
Sparrow flies.
Penguins cannot fly.
Chirp Chirp
Penguin sound.
```
Answer: a) interface
Answer: a) Yes, a class can extend multiple interfaces using the "extends" keyword.
6. Can an interface have variables with different access modifiers (e.g., public, private, protected) in
Java?
a) Yes, but only if the variables are declared as final.
b) Yes, there are no restrictions on the access modifiers for variables in an interface.
c) No, all variables in an interface must have the same access modifier.
d) No, an interface cannot have any variables.
Answer: b) Yes, there are no restrictions on the access modifiers for variables in an interface.
Answer: b) Yes, and the abstract class must implement all the abstract methods from the interface.
Answer: a) Yes, and the subclass must implement all the abstract methods from both interfaces.
9. What happens if a class implements an interface but fails to implement all the abstract methods
defined in that interface?
a) The class will be considered an abstract class and cannot be instantiated.
b) The class will automatically inherit the implementation of the missing methods from the Object
class.
c) The code will not compile, resulting in a compilation error.
d) The abstract methods will be implemented using default values defined in the interface.
Answer: b) To provide a default implementation for the method in case a class does not override it.
13. In Java, what is the purpose of using the "implements" keyword in a class declaration?
a) To define an abstract class.
b) To extend a superclass.
c) To specify that the class is implementing one or more interfaces.
d) To override a method from the superclass.
Answer: b) Yes, and the abstract class must implement all the abstract methods from the interface.
Answer: b) `final`
5. MCQ: Which of the following is true about the initialization of final variables?
a) Final variables must be initialized at the time of declaration.
b) Final variables can only be initialized using a constructor.
c) Final variables can be initialized anywhere in the code.
d) Final variables are automatically initialized to their default values.
7. MCQ: Which of the following modifiers can be used together with the final keyword?
a) synchronized
b) abstract
c) private
d) transient
Answer: c) private
Answer: b) One
Answer: c) To enable functional programming features like lambda expressions and method
references.
5. MCQ: Can a functional interface have more than one default method?
a) Yes, as many as needed.
b) No, it can have only one default method.
c) Yes, but only if they are marked with the `@Default` annotation.
d) No, functional interfaces cannot have default methods.
6. MCQ: How does the lambda expression in Java relate to functional interfaces?
a) Lambda expressions can only be used with functional interfaces.
b) Lambda expressions are used to define abstract classes in Java.
c) Lambda expressions are a replacement for constructors in functional interfaces.
d) Lambda expressions can be used with any Java class or interface.
Answer: c) `Supplier<T>`
2. MCQ: Can a class implement multiple interfaces that have default methods with the same signature?
a) Yes, but it will cause a compilation error.
b) No, a class cannot implement interfaces with default methods.
c) Yes, but the class must provide an implementation for the conflicting methods.
d) Yes, but only if the interfaces are in the same package.
Answer: c) Yes, but the class must provide an implementation for the conflicting methods.
3. MCQ: What is the keyword used in interfaces to allow methods to be defined only by concrete (non-
abstract) subclasses?
a) `subclass`
b) `extends`
c) `sealed`
d) `default`
Answer: c) `sealed`
Answer: c) Static methods in interfaces can be called directly using the interface name.
Answer: b) They are used to define helper methods that can be reused in default methods.
Answer: c) Static methods in interfaces are inherited by implementing classes, while regular static
methods are not.
7. MCQ: Which Java version introduced the concept of default methods in interfaces?
a) Java 5
b) Java 6
c) Java 7
d) Java 8
Answer: d) Java 8
**8.4 Arrays**
Answer: b) 0
Answer: b) `array.length`
3. MCQ: What happens when you try to access an element outside the bounds of an array?
a) The program crashes with an "ArrayIndexOutOfBoundsException."
b) The program continues execution, and the element is initialized to 0.
c) The program automatically expands the array to include the new element.
d) The program displays an error message but continues execution.
Answer: a) 0
Answer: b) No, all elements in an array must be of the same data type.
Answer: a) 9
**8.5 Enumerations**
Answer: a) `enum`
Answer: c) `enum`
7. MCQ: How do you iterate over all the constants of an enumeration in Java?
a) Using a regular `for` loop
b) Using a `foreach` loop
c) Using the `enumValues()` method
d) Using the `EnumSet` class
**8.6 Create an Array of Employee Class and Initialize Array Elements with Different Employee
Objects. Try to Understand the Number of Objects on Heap Memory When Any Array is Created.**
1. MCQ: When an array of `Employee` class is created, how many `Employee` objects are there in
memory initially?
a) One, and all array elements point to the same object.
b) The number of objects depends on the size of the array.
c) One object for each element of the array.
d) Two objects: one for the array and one for the first element.
2. MCQ: How can you access the elements of the `Employee` array named `employees` in Java?
a) `employees(index)`
b) `employees(index).getValue()`
c) `employees[index]`
d) `employees.getValue(index)`
Answer: c) `employees[index]`
3. MCQ: If an `Employee` array is declared but not initialized, how many objects are on the heap
memory?
a) None, objects are created on the heap only when the array is initialized.
b) One object for each potential element in the array, but all are `null`.
c) One object for the array, and the elements point to separate objects.
d) It depends on the default constructor of the `Employee` class.
Answer: a) None, objects are created on the heap only when the
array is initialized.
4. MCQ: How can you find the number of elements in the `employees` array in Java?
a) `employees.length()`
b) `employees.count()`
c) `employees.size()`
d) `employees.length`
Answer: d) `employees.length`
5. MCQ: What happens if you try to access an element of the `employees` array that is out of bounds?
a) The program will crash with an error message.
b) Java automatically extends the size of the array and initializes the element to `null`.
c) The program will display a warning but continue execution.
d) It depends on the compiler used.
6. MCQ: How can you initialize an `Employee` array with values in Java?
a) `Employee[] employees = new Employee {new Employee("John"), new Employee("Alice")};`
b) `Employee[] employees = new Employee[] {"John", "Alice"};`
c) `Employee[] employees = {"John", "Alice"};`
d) `Employee[] employees = new Employee[] {new Employee("John"), new Employee("Alice")};`
Answer: a) `null`
2. MCQ: Which access modifier restricts access to within the same class only?
a) `public`
b) `private`
c) `protected`
d) default (no modifier)
Answer: b) `private`
3. MCQ: What is the default access modifier for class members (variables and methods) if no modifier
is specified?
a) `public`
b) `private`
c) `protected`
d) default (package-private)
4. MCQ: Can a `protected` member of a superclass be accessed from a subclass in a different package?
a) Yes, always.
b) No, `protected` members are accessible only within the same package.
c) Yes, but only if the subclass is in the same package as the superclass.
d) Yes, but only if the subclass is in a subclassing relationship with the superclass.
Answer: c) Yes, but only if the subclass is in the same package as the superclass.
5. MCQ: Which access modifier is often used for methods that should be accessible from anywhere in
the code?
a) `public`
b) `private`
c) `protected`
d) default (no modifier)
Answer: a) `public`
6. MCQ: In Java, what is the access level of a class member if it is declared with no access modifier?
a) `public`
b) `private`
c) `protected`
d) default (package-private)
7. MCQ: Can a class member with `private` access modifier be accessed from another class?
a) Yes, it can be accessed from any class in the same package.
b) Yes, but only if the classes are in a subclassing relationship.
c) No, `private` members are accessible only within the same class.
d) Yes, but only if the member is static.
Answer: c) No, `private` members are accessible only within the same class.
Answer: a) `package`
3. MCQ: What is the convention for naming packages in Java to avoid conflicts with packages from
other developers?
a) Use all uppercase letters, e.g., `PACKAGE_NAME`.
b) Use a prefix based on the project name or the company domain, e.g., `com.company.project`.
c) Use a single letter, e.g., `p`.
d) Use a random combination of letters and numbers.
Answer: b) Use a prefix based on the project name or the company domain, e.g.,
`com.company.project`.
5. MCQ: If no package is specified at the beginning of a Java file, which package does it belong to?
a) `java.lang`
b) `java.util`
c) The file won't compile without a package declaration.
d) The default package (no package).
6. MCQ: Can two classes with the same name exist in different packages in Java?
a) Yes, but only if both classes are in the same project.
b) Yes, but the classes must have the same methods and fields.
c) No, two classes with the same name cannot exist in different packages.
d) Yes, but the classes must be in the same directory.
Answer: a) Yes, but only if both classes are in the same project.
7. MCQ: What happens if you try to use a class from another package without importing it in Java?
a) The code will not compile.
b) The code will compile, but the class will not be accessible.
c) The code will compile, and the class will be automatically imported.
d) The code will compile, but the class will be treated as if it's in the same package.
4. MCQ: Which of the following is a valid syntax for a static import statement in Java?
a) `import static java.util.*;`
b) `static import java.util.*;`
c) `import static java.util.ArrayList.*;`
d) `static import java.util.ArrayList.*;`
5. MCQ: What happens if there is a naming conflict between a static member and an instance member
in Java?
a) The instance member will take precedence, and the static member will be inaccessible.
b) The static member will take precedence, and the instance member will be inaccessible.
c) The code will not compile until the conflict is resolved.
d) Both members can be accessed using their respective class names.
Answer: a) The instance member will take precedence, and the static
6. MCQ: How are static imports different from regular imports in Java?
a) Static imports are used only for importing static members, while regular imports are used for non-
static members.
b) Static imports are used to access members without specifying the class name, while regular
imports are used to avoid naming conflicts.
c) Static imports are required for all classes used in the code, while regular imports are optional.
d) Static imports are used to import classes from other packages, while regular imports are used to
import classes from the same package.
Answer: b) Static imports are used to access members without specifying the class name, while
regular imports are used to avoid naming conflicts.
7. MCQ: Can you use static imports to import non-static members in Java?
a) Yes, but only if the non-static members are marked as `final`.
b) Yes, but only if the non-static members are marked as `protected`.
c) No, static imports are limited to importing static members only.
d) Yes, but only if the non-static members are declared in the same package as the importing class.
Answer: c) No, static imports are limited to importing static members only.
Answer: b) The process of calling one constructor from another within the same class or from a
superclass.
2. MCQ: In constructor chaining, which keyword is used to call another constructor from within a
constructor?
a) `super`
b) `this`
c) `new`
d) `chaining`
Answer: b) `this`
3. MCQ: How do you call a superclass constructor from a subclass constructor in Java?
a) `call super();`
b) `super();`
c) `invoke super();`
d) `superclass();`
Answer: b) `super();`
Answer: b) Constructor chaining is necessary when there are multiple constructors in a class.
Answer: c) It helps avoid naming conflicts between instance variables and parameters.
7. MCQ: Can constructor chaining be used to call a private constructor in the same class?
a) Yes, but only if the constructors have the same number of parameters.
b) Yes, constructor chaining can always access private constructors.
c) No, constructor chaining cannot access private constructors.
d) Yes, but only if the constructors have different access modifiers.
Answer: b) They are accessible within the same package and by subclasses in any package.
2. MCQ: Can a `protected` method in a superclass be accessed from a subclass in a different package?
a) Yes, always.
b) No, `protected` methods can only be accessed within the same package.
c) Yes, but only if the subclass is in the same package as the superclass.
d) Yes, but only if the subclass is in a subclassing relationship with the superclass.
Answer: c) Yes, but only if the subclass is in the same package as the superclass.
3. MCQ: How is the accessibility of `protected` variables different from `protected` methods in Java?
a) `protected` variables are accessible from any package, while `protected` methods are not.
b) `protected` methods are accessible from any package, while `protected` variables are not.
c) There is no difference; both `protected` variables and methods are accessible from any package.
d) `protected` variables and methods have the same accessibility within the same package but are
inaccessible outside the package.
Answer: b) `protected` methods are accessible from any package, while `protected` variables are not.
4. MCQ: Can a non-subclass, non-package class access a `protected` member of another class?
a) Yes, but only if the member is declared as `final`.
b) Yes, but only if the member is declared as `static`.
c) Yes, but only if the member is explicitly cast to the correct type.
d) No, `protected` members are accessible only by subclasses and classes in the same package.
Answer: d) No, `protected` members are accessible only by subclasses and classes in the same
package.
5. MCQ: How do you access a `protected` member from a subclass in a different package?
a) By importing the superclass package and using the `protected` member directly.
b) By using the `super` keyword followed by the `protected` member's name.
c) By casting the subclass object to the superclass type and accessing the `protected` member.
d) By using the `protected` member directly without any additional steps.
Answer: b) By using the `super` keyword followed by the `protected` member's name.
6. MCQ: What happens if you try to access a `protected` member from a non-subclass and non-package
class?
a) The code will not compile.
b) The code will compile, but the `protected` member will be inaccessible.
c) The code will compile, but the `protected` member will be `null`.
d) The code will compile, but the `protected` member will have default (package-private) access.
7. MCQ: How can you access a `protected` member of a class if you are not in a subclass or the same
package?
a) Use reflection to access the member dynamically.
b) Declare a method in the class that returns the `protected` member.
c) Change the access modifier of the member to `public`.
d) Move the accessing class to the same package as the class containing the `protected` member.
Answer: d) Move the accessing class to the same package as the class containing the `protected`
member.
10. Lecture: Garbage Collection in Java
**10.1 Requesting JVM to Run Garbage Collection**
1. MCQ: Which method can be used to request the JVM to run garbage collection in Java?
a) `System.gc()`
b) `Runtime.gc()`
c) `JVM.gc()`
d) `GarbageCollector.run()`
Answer: a) `System.gc()`
3. MCQ: Is it guaranteed that the JVM will run garbage collection immediately after `System.gc()` is
called?
a) Yes, the JVM will run garbage collection immediately.
b) No, the JVM may choose to run garbage collection at its own discretion.
c) Yes, but only if there are no active threads in the application.
d) No, the `System.gc()` method does not trigger garbage collection.
Answer: b) No, the JVM may choose to run garbage collection at its own discretion.
5. MCQ (Coding): Which data type is used to represent a reference variable that can be garbage
collected?
a) `int`
b) `String`
c) `double`
d) `Object`
Answer: d) `Object`
**10.2 Different Ways to Make Object Eligible for Garbage Collection: (Nulling a Reference Variable,
Re-assigning a Reference Variable & Island of Isolation)**
1. MCQ: How can you make an object eligible for garbage collection in Java?
a) By setting its reference variable to `null`.
b) By calling the `System.gc()` method.
c) By creating a new reference variable for the same object.
d) By reassigning its reference variable to another object.
2. MCQ (Coding): Which of the following code snippets correctly makes an object eligible for garbage
collection?
```java
// Option 1
Object obj = new Object();
obj = null;
// Option 2
Object obj = new Object();
Object obj2 = obj;
obj = null;
// Option 3
Object obj = new Object();
obj = new Object();
```
a) Option 1
b) Option 2
c) Option 3
d) None of the above
Answer: b) Option 2
3. MCQ: What is the purpose of the "Island of Isolation" in the context of garbage collection?
a) It refers to a group of objects with circular references that cannot be garbage collected.
b) It is a term used to describe objects that are not eligible for garbage collection.
c) It is a garbage collection algorithm used by the JVM.
d) It refers to a group of objects with strong references that can be garbage collected together.
Answer: a) It refers to a group of objects with circular references that cannot be garbage collected.
4. MCQ: When does an object become eligible for garbage collection if all of its references are set to
`null`?
a) Immediately after the last reference is set to `null`.
b) The object becomes eligible for garbage collection as soon as it is not reachable by any live thread.
c) The object will never be eligible for garbage collection.
d) It depends on the garbage collector's scheduling algorithm.
Answer: b) The object becomes eligible for garbage collection as soon as it is not reachable by any
live thread.
Answer: b) It marks the object as garbage, and the JVM will collect it during the next garbage
collection cycle.
```java
public class GarbageCollectionDemo {
public static void main(String[] args) {
Object obj1 = new Object();
Object obj2 = new Object();
obj1 = obj2;
obj2 = null;
System.gc();
}
}
```
Answer: c) The code will compile, and the objects will be eligible for garbage collection.
2. MCQ (Coding): Which of the following code snippets correctly demonstrates the use of the
`finalize()` method?
```java
// Option 1
public class MyClass {
// ... class code ...
// Option 3
public class MyClass {
// ... class code ...
a) Option 1
b) Option 2
c) Option 3
d) None of the above
Answer: a) Option 1
Answer: b) The `finalize()` method is automatically called when an object is garbage collected.
Answer: a) `void`
5. MCQ: What happens if an uncaught exception is thrown inside the `finalize()` method?
a) The JVM will automatically handle the exception and continue garbage collection.
b) The exception will be propagated to the calling code that triggered garbage collection.
c) The JVM will skip the `finalize()` method and proceed with garbage collection.
d) The JVM will terminate the application.
Answer: c) The JVM will skip the `finalize()` method and proceed with garbage collection.
6. MCQ: Is it recommended to use the `finalize()` method for resource cleanup in Java?
a) Yes, it is a best practice to use `finalize()` for resource cleanup.
b) No, `finalize()` is deprecated, and other approaches should be used for resource cleanup.
c) It depends on the specific use case and requirements of the application.
d) Yes, `finalize()` is the only method available for resource cleanup in Java.
Answer: b) No, `finalize()` is deprecated, and other approaches should be used for resource cleanup.
7. MCQ: What can be done inside the `finalize()` method to ensure proper resource cleanup?
a) Call the `System.gc()` method to trigger garbage collection.
b) Close open files, release network connections, or free up other resources.
c) Set the object's reference to `null`.
d) Trigger a runtime exception to indicate cleanup completion.
Answer: b) Close open files, release network connections, or free up other resources.
1. MCQ (Coding): Given the following Java classes, what will be the output of the demo application?
```java
// File: MyClass.java
public class MyClass {
public int publicVar = 10;
private int privateVar = 20;
protected int protectedVar = 30;
int defaultVar = 40;
// File: Main.java
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
```
Answer: c) The code will compile, but only public variables will be accessible and displayed.
2. MCQ: What is the output of the demo application if `Main.java` is in a different package than
`MyClass.java`?
Answer: b) The code will compile, but only public variables will be accessible and displayed.
3. MCQ: Which access modifier(s) allow a class member to be accessible from any class in any
package?
a) `public`
b) `protected`
c) `private`
d) default (package-private)
Answer: a) `public`
4. MCQ (Coding): What modification is needed in `MyClass.java
` to make the `protectedVar` accessible from the `Main` class, which is in a different package?
5. MCQ: If the `privateVar` in `MyClass.java` is changed to `protected`, what will be the output of the
demo application?
Answer: b) The code will compile, but only public and protected variables will be accessible and
displayed.
Answer: a) The code will not compile due to access modifier conflicts.
1. MCQ (Coding): Given the following Java classes in different packages, what is the output of the
demo application?
```java
// File: Package1/Grandparent.java
package Package1;
// File: Package2/Parent.java
package Package2;
import Package1.Grandparent;
// File: Main.java
import Package2.Parent;
Answer: b) The code will compile, but the output will be "This is the Parent class."
2. MCQ: What happens if the `display()` method in `Grandparent.java` is changed from `protected` to
`private`?
Answer: a) The code will not compile due to access modifier conflicts.
3. MCQ (Coding): What is the output of the demo application if `Parent.java` is modified as follows?
```java
// File: Package2/Parent.java
package Package2;
import Package1.Grandparent;
Answer: d) The code will compile, but the output will be "This is the Parent class."
4. MCQ: What type of inheritance relationship is depicted in the code between `Grandparent`, `Parent`,
and `Main` classes?
a) Single inheritance
b) Multiple inheritance
c) Multilevel inheritance
d) Hierarchical inheritance
Answer: c) Multilevel inheritance
5. MCQ (Coding): What is the output of the demo application if `Parent.java` is modified as follows?
```java
// File: Package2/Parent.java
package Package2;
import Package1.Grandparent;
Answer: d) The code will compile, and the output will be "This is the Parent class. This is the
Grandparent class."
7. MCQ: Can you implement multilevel inheritance with more than three classes in Java?
a) No, multilevel inheritance is limited to exactly three classes.
b) Yes, you can implement multilevel inheritance with any number of classes.
c) Yes, but it is limited to three levels of inheritance only.
d) Yes, but each subclass can have only one superclass.
Answer: b) Yes, you can implement multilevel inheritance with any number of classes.
1. MCQ (Coding): Given the following Java classes, what is the output of the demo application?
```java
// File: Package1/MyClass.java
package Package1;
// File: Main.java
import Package1.MyClass;
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display
();
}
}
```
a) The code will not compile because the `display()` method is not accessible.
b) The code will compile, and "This is a protected method." will be printed.
c) The code will compile, but there will be a runtime exception.
d) The code will compile, but the `display()` method will not be invoked.
Answer: a) The code will not compile because the `display()` method is not accessible.
2. MCQ: How can you access a protected method of a class outside the package in Java?
a) Use the `private` modifier instead of `protected`.
b) Use the `public` modifier instead of `protected`.
c) Move the accessing class to the same package as the class containing the protected method.
d) Use the `protected` modifier and extend the class containing the protected method.
Answer: d) Use the `protected` modifier and extend the class containing the protected method.
3. MCQ (Coding): What is the output of the demo application if `Main.java` is modified as follows?
```java
// File: Main.java
import Package1.MyClass;
Answer: c) The code will compile, and "This is a protected method." will be printed.
4. MCQ: What is the main advantage of using the `protected` access modifier in Java?
a) It allows unrestricted access to the member in any package.
b) It restricts access to the member only within the same package.
c) It allows access to the member within the same package and by subclasses in any package.
d) It allows access to the member within the same package and by subclasses in the same package.
Answer: c) It allows access to the member within the same package and by subclasses in any package.
5. MCQ (Coding): What is the output of the demo application if `Main.java` is modified as follows?
```java
// File: Main.java
import Package1.MyClass;
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
((Main)obj).display();
}
}
```
Answer: b) The code will compile, but there will be a runtime exception.
6. MCQ: Can protected members of a class be accessed using object references of the superclass?
a) Yes, it is possible to access protected members using the superclass reference.
b) No, protected members can only be accessed using subclass references.
c) Yes, but only if the superclass is in the same package as the subclass.
d) No, protected members cannot be accessed outside the package.
Answer: a) Yes, it is possible to access protected members using the superclass reference.
7. MCQ: What is the purpose of using the `protected` access modifier in Java?
a) To allow access to a member from any class in any package.
b) To restrict access to a member within the same package only.
c) To allow access to a member within the same package and by subclasses in any package.
d) To allow access to a member within the same package and by subclasses in the same package.
Answer: c) To allow access to a member within the same package and by subclasses in any package.
**10.7 Override Finalize Method to Understand the Behavior of JVM Garbage Collector.**
Answer: c) No, the `finalize()` method cannot be called directly; it is called automatically by the
JVM.
2. MCQ (Coding): Given the following Java class, what will be the output of the demo application?
```java
// File: MyClass.java
public class MyClass {
protected void finalize() {
System.out.println("The object is being garbage collected.");
}
Answer: c) The code will compile, and "The object is being garbage collected." will be printed.
Answer: b) To free up resources and perform cleanup before an object is garbage collected.
4. MCQ: When does the JVM call the `finalize()` method during garbage collection?
a) Immediately after an object is created.
b) Before the `System.gc()` method is called.
c) Before the JVM exits.
d) Before deallocating memory for an object.
5. MCQ (Coding): What is the output of the demo application if `MyClass` is modified as follows?
```java
// File: MyClass.java
public class MyClass {
protected void finalize() {
System.out.println("The object is being garbage collected.");
}
Answer: d
) The code will compile, and "The object is being garbage collected." will be printed once.
6. MCQ: Is it recommended to rely on the `finalize()` method for resource cleanup in Java?
a) Yes, it is the most efficient way to clean up resources.
b) Yes, it guarantees that resources are properly cleaned up before an object is garbage collected.
c) No, it is not guaranteed that the `finalize()` method will be called promptly by the JVM.
d) No, the `finalize()` method is deprecated and should not be used for resource cleanup.
Answer: c) No, it is not guaranteed that the `finalize()` method will be called promptly by the JVM.
7. MCQ: What happens if an uncaught exception is thrown inside the `finalize()` method?
a) The JVM will handle the exception, and the garbage collection process will continue.
b) The exception will be propagated to the calling code that triggered garbage collection.
c) The JVM will immediately terminate the application.
d) The JVM will skip the `finalize()` method and proceed with garbage collection.
Answer: d) The JVM will skip the `finalize()` method and proceed with garbage collection.
Answer: c) String
3. MCQ (Coding): Which of the following statements correctly demonstrates boxing in Java?
```java
// Option 1
int num = 42;
Integer boxedNum = new Integer(num);
// Option 2
int num = 42;
Integer boxedNum = Integer.valueOf(num);
// Option 3
Integer boxedNum = 42;
```
a) Option 1
b) Option 2
c) Option 3
d) Both Option 1 and Option 2
4. MCQ: What is the difference between autoboxing and manual boxing in Java?
a) There is no difference; both terms refer to the same process.
b) Autoboxing is done automatically by the JVM, while manual boxing is done explicitly by the
programmer.
c) Autoboxing is used for primitive data types, while manual boxing is used for reference data types.
d) Manual boxing is done automatically by the JVM, while autoboxing is done explicitly by the
programmer.
Answer: b) Autoboxing is done automatically by the JVM, while manual boxing is done explicitly by
the programmer.
5. MCQ: Can a wrapper class be null in Java?
a) Yes, all wrapper classes can be null.
b) No, wrapper classes cannot have a null value.
c) Yes, except for Boolean wrapper class, all others can be null.
d) Yes, except for Character wrapper class, all others can be null.
Answer: c) Yes, except for Boolean wrapper class, all others can be null.
7. MCQ (Coding): What is the output of the following Java code snippet?
```java
Integer num1 = 10;
Integer num2 = 10;
System.out.println(num1 == num2);
```
a) true
b) false
c) Compilation error
d) Runtime exception
Answer: a) true
1. MCQ: Which class among `String`, `StringBuffer`, and `StringBuilder` is immutable in Java?
a) String
b) StringBuffer
c) StringBuilder
d) All of them are immutable.
Answer: a) String
2. MCQ: What is the main difference between `StringBuffer` and `StringBuilder` in Java?
a) `StringBuffer` is mutable, while `StringBuilder` is immutable.
b) `StringBuffer` is faster than `StringBuilder`.
c) `StringBuffer` is synchronized, while `StringBuilder` is not.
d) `StringBuffer` is used for single-threaded applications, while `StringBuilder` is used for multi-
threaded applications.
3. MCQ (Coding): Which of the following statements correctly demonstrates appending a string in
`StringBuffer` and `StringBuilder`?
```java
// Option 1
StringBuffer sb = new StringBuffer();
sb.append("Hello");
// Option 2
StringBuilder sb = new StringBuilder();
sb.append("Hello");
// Option 3
StringBuffer sb = new StringBuffer("Hello");
```
a) Option 1
b) Option 2
c) Option 3
d) Both Option 1 and Option 2
4. MCQ: Which of the following classes is recommended to use when multiple threads are involved?
a) String
b) StringBuilder
c) StringBuffer
d) Both StringBuilder and StringBuffer can be used interchangeably.
Answer: c) StringBuffer
5. MCQ: What happens when you concatenate strings using the `+` operator in Java?
a) The original strings are modified in-place.
b) A new string object is created in memory.
c) The `String` class uses `StringBuilder` internally for concatenation.
d) The `String` class uses `StringBuffer` internally for concatenation.
6. MCQ: What is the advantage of using `StringBuilder` over `StringBuffer` when working with single-
threaded applications?
a) `StringBuilder` is faster than `StringBuffer`.
b) `StringBuilder` is immutable, so it guarantees thread-safety.
c) `StringBuilder` is more memory-efficient.
d) `StringBuilder` provides more methods for string manipulation.
7. MCQ (Coding): What is the output of the following Java code snippet?
```java
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb);
```
a) "Hello World"
b) "World Hello"
c) "Hello"
d) Compilation error
Answer: b) To store frequently used strings to conserve memory and improve performance.
2. MCQ: Which of the following statements about the string pool is true?
a) Strings created using the `new` keyword are stored in the string pool.
b) Strings created using the `new` keyword are not stored in the string pool.
c) The string pool is a separate memory area reserved for long strings.
d) The string pool is a part of the heap memory.
Answer: b) Strings created using the `new` keyword are not stored in the string pool.
3. MCQ (Coding): What is the output of the following Java code snippet?
```java
String str1 = "Java";
String str2 = "Java";
String str3 = new String("Java");
System.out
.println(str1 == str2);
System.out.println(str1 == str3);
```
a) true, true
b) true, false
c) false, true
d) false, false
4. MCQ: When does a string object get added to the string pool in Java?
a) When the string is created using the `new` keyword.
b) When the string is created using the `new` keyword and explicitly added to the pool using the
`intern()` method.
c) When the string is created using string literals.
d) When the string is created using the `new` keyword and immediately assigned to a reference
variable.
5. MCQ: How can you explicitly add a string to the string pool in Java?
a) By calling the `addToPool()` method provided by the `String` class.
b) By calling the `intern()` method on the string object.
c) By converting the string to uppercase and then assigning it to a reference variable.
d) By appending the string with another string and then assigning it to a reference variable.
Answer: b) It prevents the creation of duplicate string objects with the same content.
7. MCQ (Coding): What is the output of the following Java code snippet?
```java
String str1 = new String("Hello").intern();
String str2 = new String("Hello").intern();
System.out.println(str1 == str2);
```
a) true
b) false
c) Compilation error
d) Runtime exception
Answer: a) true
Answer: a) Converting a primitive data type into an object of the corresponding wrapper class.
2. MCQ (Coding): What is the output of the following Java code snippet?
```java
int num = 42;
Integer boxedNum = num;
System.out.println(boxedNum);
```
a) 42
b) "42"
c) Compilation error
d) Runtime exception
Answer: a) 42
Answer: b) Converting an object of the corresponding wrapper class into a primitive data type.
4. MCQ (Coding): What is the output of the following Java code snippet?
```java
Integer boxedNum = 25;
int num = boxedNum;
System.out.println(num);
```
a) 25
b) "25"
c) Compilation error
d) Runtime exception
Answer: a) 25
5. MCQ: Which of the following statements is true about boxing and unboxing in Java?
a) Boxing and unboxing are both performed automatically by the JVM.
b) Boxing is performed automatically by the JVM, but unboxing must be done explicitly by the
programmer.
c) Unboxing is performed automatically by the JVM, but boxing must be done explicitly by the
programmer.
d) Both boxing and unboxing must be done explicitly by the programmer.
Answer: a) Boxing and unboxing are both performed automatically by the JVM.
6. MCQ (Coding): What is the output of the following Java code snippet?
```java
Integer num1 = 100;
Integer num2 = 100;
System.out.println(num1 == num2);
a) true, true
b) true, false
c) false, true
d) false, false
7. MCQ: What happens if you try to unbox a `null` wrapper object in Java?
a) It will result in a runtime exception.
b) It will automatically convert to the default value of the corresponding primitive data type.
c) It will result in a compilation error.
d) It will return `null`.
1. MCQ: Which wrapper class provides the `parseXXX()` method to convert a string to a primitive data
type?
a) `Integer`
b) `Double`
c) `Character`
d) `Boolean`
Answer: a) `Integer`
2. MCQ (Coding): What is the output of the following Java code snippet?
```java
int num = Integer.parseInt("42");
System.out.println(num);
```
a) 42
b) "42"
c) Compilation error
d) Runtime exception
Answer: a) 42
3. MCQ: Which wrapper class provides the `valueOf()` method to convert a string to an object of the
corresponding wrapper class?
a) `Integer`
b) `Double`
c) `Character`
d) `Boolean`
Answer: b) `Double`
4. MCQ (Coding): What is the output of the following Java code snippet?
```java
Double value = Double.valueOf("3.14");
System.out.println(value);
```
a) 3.14
b) "3.14"
c) Compilation error
d) Runtime exception
Answer: a) 3.14
5. MCQ: Which wrapper class provides the `toString()` method to convert a primitive data type to its
corresponding string representation?
a) `Integer`
b) `Double`
c) `Character`
d) `Boolean`
Answer: d) `Boolean`
6. MCQ (Coding): What is the output of the following Java code snippet?
```java
boolean flag = true;
String str = Boolean.toString(flag);
System.out.println(str);
```
a) true
b) "true"
c) Compilation error
d) Runtime exception
Answer: b) "true"
7. MCQ: Which wrapper class provides the `compare()` method to compare two primitive values or
wrapper objects?
a) `Integer`
b) `Double`
c) `Character`
d) `Boolean`
Answer: a) `Integer`
**11.6 Create StringDemo Class and Perform Different String Manipulation Methods.**
8. MCQ (Coding): What is the output of the following Java code snippet?
```java
String str = "Java Programming";
String upperCaseStr = str.toUpperCase();
System.out.println(upperCaseStr);
```
a) "java programming"
b) "JAVA PROGRAMMING"
c) "Java Programming"
d) "Java programming"
9. MCQ: What is the purpose of the `toLowerCase()` method in the `String` class?
a) To convert the entire string to lowercase.
b) To convert the entire string to uppercase.
c) To convert the first character of the string to lowercase.
d) To convert the first character of each word in the string to lowercase.
10. MCQ (Coding): What is the output of the following Java code snippet?
```java
String str = "Hello, World!";
String lowerCaseStr = str.toLowerCase();
System.out.println(lowerCaseStr);
```
a) "HELLO, WORLD!"
b) "hello, world!"
c) "Hello, World!"
d) "hello, world!"
11. MCQ: What is the purpose of the `trim()` method in the `String` class?
a) To remove all leading and trailing whitespaces from the string.
b) To remove all leading whitespaces from the string.
c) To remove all trailing whitespaces from the string.
d) To remove all spaces from the string.
Answer: a) To remove all leading and trailing whitespaces from the string.
12. MCQ (Coding): What is the output of the following Java code snippet?
```java
String str = " Hello, World! ";
String trimmedStr = str.trim();
System.out.println(trimmedStr);
```
a) "Hello, World!"
b) "Hello, World! "
c) " Hello, World!"
d) " Hello, World! "
14. MCQ (Coding): What is the output of the following Java code snippet?
```java
String str = "Hello, World!";
String replacedStr = str.replace("l", "X");
System.out.println(replacedStr);
```
a) "HexXo, WorXd!"
b) "Hello, World!"
c) "HeXXo, WorXd!"
d) "HeXXo, WorXd!X"
15. MCQ: What is the purpose of the `startsWith()` method in the `String` class?
a) To check if the string starts with a specific character.
b) To check if the string starts with a specific substring.
c) To check if the string ends with a specific character.
d) To check if the string ends with a specific substring.
16. MCQ (Coding): What is the output of the following Java code snippet?
```java
String str = "Hello, World!";
boolean startsWithHello = str.startsWith("Hello");
boolean startsWithHi = str.startsWith("Hi");
System.out.println(startsWithHello);
System.out.println(startsWithHi);
```
a) true, false
b) false, true
c) true, true
d) false, false
17. MCQ: What is the purpose of the `endsWith()` method in the `String` class?
a) To check if the string starts with a specific character.
b) To check if the string starts with a specific substring.
c) To check if the string ends with a specific character.
d) To check if the string ends with a specific substring.
18. MCQ (Coding): What is the output of the following Java code snippet?
```java
String str = "Hello, World!";
boolean endsWithWorld = str.endsWith("World!");
boolean endsWithJava = str.endsWith("Java");
System.out.println(endsWithWorld);
System.out.println(endsWithJava);
```
a) true, false
b) false, true
c) true, true
d) false, false
19. MCQ: What is the purpose of the `contains()` method in the `String` class?
a) To check if the string contains a specific character.
b) To check if the string contains a specific substring.
c) To check if the string contains a specific word.
d) To check if the string contains any numeric digits.
20. MCQ (Coding): What is the output of the following Java code snippet?
```java
String str = "Hello, World!";
boolean containsHello = str.contains("Hello");
boolean containsHi = str.contains("Hi");
System.out.println(containsHello);
System.out.println(containsHi);
```
a) true, false
b) false, true
c) true, true
d) false, false
Answer: d) `Throwable`
2. MCQ: What is the key difference between checked and unchecked exceptions in Java?
a) Checked exceptions are explicitly handled by the programmer, while unchecked exceptions are
handled by the JVM.
b) Checked exceptions are always related to syntax or compilation errors, while unchecked
exceptions are runtime errors.
c) Checked exceptions are subclasses of `Exception`, while unchecked exceptions are subclasses of
`RuntimeException`.
d) Checked exceptions require explicit handling using try-catch or throws, while unchecked
exceptions do not.
Answer: d) Checked exceptions require explicit handling using try-catch or throws, while unchecked
exceptions do not.
3. MCQ (Coding): Which of the following statements correctly demonstrates an unchecked exception
in Java?
```java
// Option 1
int result = 10 / 0;
// Option 2
String str = null;
int length = str.length();
// Option 3
int[] arr = { 1, 2, 3 };
int value = arr[5];
```
a) Option 1
b) Option 2
c) Option 3
d) Both Option 1 and Option 3
Answer: c) Errors are critical problems that cannot be recovered, and usually, the application should
terminate.
5. MCQ: Which of the following statements about the `RuntimeException` class is true?
a) `RuntimeException` is a checked exception.
b) `RuntimeException` is an unchecked exception.
c) `RuntimeException` is an Error.
d) `RuntimeException` is a subclass of `Exception`.
Answer: c) Checked exceptions should be used only for issues that can be reasonably handled by the
calling code.
7. MCQ (Coding): What is the output of the following Java code snippet?
```java
public void performOperation() throws IOException {
// Some code that may throw an IOException
}
a) Operation successful.
b) An error occurred: (the error message)
c) Compilation error
d) Runtime exception
Answer: a) Exception propagation is the process of throwing an exception from a method to its
calling method.
2. MCQ (Coding): What will happen if an exception is thrown from a method, and the method does not
have a try-catch block to handle it?
```java
public void methodA() {
throw new RuntimeException("Exception in methodA");
}
Answer: d) The exception will propagate up the call stack until it is caught or the program terminates.
3. MCQ: What happens if an exception is not caught by any method in the call stack?
a) The program will continue to execute normally without any impact.
b) The program will terminate abruptly with an error message.
c) The JVM will handle the exception automatically.
d) The method where the exception occurred will retry the operation.
Answer: b) The program will terminate abruptly with an error message.
4. MCQ (Coding): What will be the output of the following Java code snippet?
```java
public void methodA() {
throw new ArithmeticException("Exception in methodA");
}
5. MCQ: Which of the following keywords can be used to propagate an exception explicitly?
a) `catch`
b) `throws`
c) `try`
d) `finally`
Answer: b) `throws`
6. MCQ (Coding): Which of the following method declarations correctly indicates that the method may
throw multiple exceptions?
```java
// Option 1
public void myMethod() throws IOException, NullPointerException {
// Method implementation
}
// Option 2
public void myMethod() throws Exception {
// Method implementation
}
// Option 3
public void myMethod() {
try {
// Method implementation
} catch (IOException | NullPointerException e) {
// Exception handling
}
}
```
a) Option 1
b) Option 2
c) Option 3
d) Both Option 1 and Option 2
Answer: a) Option 1
provides a way to pass information about the error from the method where it occurred to the caller.
Answer: d) It provides a way to pass information about the error from the method where it occurred
to the caller.
1. MCQ: Which keyword is used to specify a block of code where an exception may occur in Java?
a) `try`
b) `catch`
c) `finally`
d) `throws`
Answer: a) `try`
2. MCQ (Coding): What is the purpose of the `catch` block in a try-catch-finally statement?
```java
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
```
a) To define the code that will be executed if an exception of type `ExceptionType` occurs.
b) To define the code that will be executed whether an exception occurs or not.
c) To define the code that will be executed if no exception occurs.
d) To define the code that will be executed if an exception occurs, regardless of its type.
Answer: d) To define the code that will be executed if an exception occurs, regardless of its type.
Answer: b) To define the code that will be executed whether an exception occurs or not.
4. MCQ (Coding): What is the output of the following Java code snippet?
```java
public void divide(int num1, int num2) {
try {
int result = num1 / num2;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
a) Result: Infinity
Finally block executed.
b) Error: / by zero
Finally block executed.
c) Compilation error
d) Runtime exception
Answer: a) To specify the type of exceptions that the method may throw.
6. MCQ (Coding): Which of the following method declarations is correctly using the `throws` clause?
```java
// Option 1
public void myMethod() throws IOException {
// Method implementation
}
// Option 2
public void myMethod() throws Exception {
// Method implementation
}
// Option 3
public void myMethod() {
try {
// Method implementation
} catch (IOException e) {
// Exception handling
}
}
```
a) Option 1
b) Option 2
c) Option 3
d) Both Option 1 and Option 2
Answer: a) Option 1
2. MCQ (Coding): Which of the following code snippets correctly uses a multi-catch block?
```java
// Option 1
try {
// Some code that may throw exceptions
} catch (IOException | NullPointerException e) {
// Exception handling
}
// Option 2
try {
// Some code that may throw exceptions
} catch (IOException e1 | NullPointerException e2) {
// Exception handling
}
// Option 3
try {
// Some code that may throw exceptions
} catch (Exception e) {
// Exception handling
}
```
a) Option 1
b) Option 2
c) Option 3
d) Both Option 1 and Option 2
Answer: a) Option 1
3. MCQ: What happens if multiple exception types in a multi-catch block have an inheritance
relationship?
a) The code will not compile due to ambiguity.
b) The catch block will only catch exceptions of the superclass type, not the subclasses.
c) The catch block will only catch exceptions of the subclass type, not the superclass.
d) The code will compile, and the catch block will catch exceptions of both the superclass and
subclass types.
Answer: d) The code will compile, and the catch block will catch exceptions of both the superclass
and subclass types.
4. MCQ (Coding): What is the output of the following Java code snippet?
```java
try {
int[] arr = { 1, 2, 3 };
int value = arr[5];
} catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {
System.out.println("Caught: " + e.getClass().getSimpleName());
}
```
a) Caught: ArrayIndexOutOfBoundsException
b) Caught: ArithmeticException
c) Caught: Exception
d) Caught: RuntimeException
Answer: a) When the catch blocks have identical exception handling code.
6. MCQ (Coding): Which of the following code snippets will cause a compilation error?
```java
// Option 1
try {
// Some code that may throw exceptions
} catch (IOException | NullPointerException e) {
// Exception handling
// Option 2
try {
// Some code that may throw exceptions
} catch (Exception e1 | RuntimeException e2) {
// Exception handling
}
// Option 3
try {
// Some code that may throw exceptions
} catch (NullPointerException e) {
// Exception handling
} catch (IOException e) {
// Exception handling
}
```
a) Option 1
b) Option 2
c) Option 3
d) Both Option 1 and Option 2
Answer: b) Option 2
7. MCQ: What is the benefit of using a multi-catch block over separate catch blocks for each exception
type?
a) It reduces the number of catch blocks required in the code.
b) It improves the performance of exception handling.
c) It simplifies the error-handling process and makes the code more concise.
d) It allows the program to recover from any type of exception thrown.
Answer: c) It simplifies the error-handling process and makes the code more concise.
Answer: c) An exception that is defined by the programmer by extending the `Exception` class.
2. MCQ (Coding): Which of the following code snippets correctly defines a user-defined checked
exception?
```java
// Option 1
class MyCheckedException extends RuntimeException {
// Constructor and other methods
}
// Option 2
class MyCheckedException extends Exception {
// Constructor and other methods
}
// Option 3
class MyCheckedException extends Error {
// Constructor and other methods
}
```
a) Option 1
b) Option 2
c) Option 3
d) Both Option 1 and Option 2
Answer: b) Option 2
3. MCQ: What is the key difference between a checked and an unchecked user-defined exception?
a) Checked exceptions must be explicitly caught or declared with `throws`, while unchecked
exceptions do not require explicit handling.
b) Unchecked exceptions must be explicitly caught or declared with `throws`, while checked
exceptions do not require explicit handling.
c) Checked exceptions are always related to syntax or compilation errors, while unchecked
exceptions are runtime errors.
d) Checked exceptions are subclasses of `RuntimeException`, while unchecked exceptions are
subclasses of `Exception`.
Answer: a) Checked exceptions must be explicitly caught or declared with `throws`, while unchecked
exceptions do not require explicit handling.
4. MCQ (Coding): Which of the following code snippets correctly defines a user-defined unchecked
exception?
```java
// Option 1
class MyUncheckedException extends RuntimeException {
// Constructor and other methods
}
// Option 2
class MyUncheckedException extends Exception {
// Constructor and other methods
}
// Option 3
class MyUncheckedException extends Error {
// Constructor and other methods
}
```
a) Option 1
b) Option 2
c) Option 3
d) Both Option 1 and Option 2
Answer: a) Option 1
Answer: b) When you want to indicate exceptional conditions that may occur during the execution of
your code.
6. MCQ (Coding): Which of the following code snippets demonstrates the correct way to throw a user-
defined exception?
```java
// Option 1
throw new MyCheckedException("This is a checked exception.");
// Option 2
throw new MyUncheckedException("This is an unchecked exception.");
```
a) Option 1
b) Option 2
c) Both Option 1 and Option 2
d) Neither Option 1 nor Option 2
7. MCQ: What should you consider when designing custom exceptions in Java?
a) Custom exceptions should always extend the `RuntimeException` class.
b) Custom exceptions should always be defined as `final` to prevent subclassing.
c) Custom exceptions should have meaningful names that indicate the specific exceptional condition.
d) Custom exceptions should override the `getMessage()` method to provide more context about the
exception.
Answer: c) Custom exceptions should have meaningful names that indicate the specific exceptional
condition.
Answer: a) To indicate exceptional conditions that may occur during the execution of the code.
2. MCQ (Coding): Which of the following code snippets demonstrates the correct way to create a user-
defined checked exception named `CustomCheckedException`?
a) Option 1
```java
class CustomCheckedException extends RuntimeException {
public CustomCheckedException(String message) {
super(message);
}
}
```
b) Option 2
```java
class CustomCheckedException extends Exception {
public CustomCheckedException(String message) {
super(message);
}
}
```
c) Option 3
```java
class CustomCheckedException extends Error {
public CustomCheckedException(String message) {
super(message);
}
}
```
Answer: b) Option 2
Answer: a) To indicate exceptional conditions that may occur during the execution of the code.
4. MCQ (Coding): Which of the following code snippets demonstrates the correct way to create a user-
defined unchecked exception named `CustomUncheckedException`?
a) Option 1
```java
class CustomUncheckedException extends RuntimeException {
public CustomUncheckedException(String message) {
super(message);
}
}
```
b) Option
```java
class CustomUncheckedException extends Exception {
public CustomUncheckedException(String message) {
super(message);
}
}
```
c) Option 3
```java
class CustomUncheckedException extends Error {
public CustomUncheckedException(String message) {
super(message);
}
}
```
Answer: a) Option 1
5. MCQ (Coding): Write Java code to demonstrate how to use the user-defined checked exception
`CustomCheckedException` and the user-defined unchecked exception `CustomUncheckedException`
in a try-catch block.
(Note: The actual coding for this MCQ will be provided here)
```java
// Option 1
class CustomCheckedException extends Exception {
public CustomCheckedException(String message) {
super(message);
}
}
// Option 2
class CustomUncheckedException extends RuntimeException {
public CustomUncheckedException(String message) {
super(message);
}
}
a) Option 1
b) Option 2
c) Both Option 1 and Option 2
d) Neither Option 1 nor Option 2
Answer: b) User-defined exceptions allow the programmer to define exceptional conditions specific
to the application's context.
7. MCQ (Coding): Write Java code for a user-defined checked exception named
`InvalidInputException` and a user-defined unchecked exception named `DataNotFoundException`.
(Note: The actual coding for this MCQ will be provided here)
```java
class InvalidInputException extends Exception {
public InvalidInputException(String message) {
super(message);
}
}
13. Lecture:
14.
**13.1 Brief Introduction to InputStream, OutputStream, Reader and Writer Interfaces**
1. MCQ: Which Java interfaces are used for handling input operations for binary data?
a) `InputStream` and `OutputStream`
b) `Reader` and `Writer`
c) `Serializable` and `Deserialize`
d) `BufferedReader` and `BufferedWriter`
2. MCQ (Coding): What is the correct way to read data from a text file using `InputStream` in Java?
a) Option 1
```java
InputStream is = new FileInputStream("data.txt");
int data;
while ((data = is.read()) != -1) {
System.out.print((char) data);
}
is.close();
```
b) Option 2
```java
InputStream is = new InputStreamReader(new FileInputStream("data.txt"));
int data;
while ((data = is.read()) != -1) {
System.out.print((char) data);
}
is.close();
```
c) Option 3
```java
InputStream is = new FileReader("data.txt");
int data;
while ((data = is.read()) != -1) {
System.out.print((char) data);
}
is.close();
```
Answer: a) Option 1
3. MCQ: Which Java interfaces are used for handling input operations for character data?
a) `InputStream` and `OutputStream`
b) `Reader` and `Writer`
c) `Serializable` and `Deserialize`
d) `BufferedReader` and `BufferedWriter`
4. MCQ (Coding): What is the correct way to write data to a text file using `Writer` in Java?
a) Option 1
```java
Writer writer = new FileWriter("data.txt");
String data = "Hello, World!";
writer.write(data);
writer.close();
```
b) Option 2
```java
Writer writer = new BufferedWriter(new FileWriter("data.txt"));
String data = "Hello, World!";
writer.write(data);
writer.close();
```
c) Option 3
```java
Writer writer = new PrintWriter("data.txt");
String data = "Hello, World!";
writer.write(data);
writer.close();
```
Answer: b) Option 2
a) Option 1
```java
ByteBuffer buffer = new ByteBuffer();
```
b) Option 2
```java
Buffer buffer = Buffer.allocate(1024);
```
c) Option 3
```java
ByteBuffer buffer = ByteBuffer.allocate(1024);
```
Answer: c) Option 3
3. MCQ: What is the main advantage of using NIO over traditional I/O in Java?
a) NIO provides better performance for reading and writing large amounts of data.
b) NIO supports only blocking I/O, which simplifies the programming model.
c) NIO provides easier serialization and deserialization of objects.
d) NIO is compatible with older versions of Java.
Answer: a) NIO provides better performance for reading and writing large amounts of data.
4. MCQ (Coding): What is the correct way to read data from a file using NIO in Java?
a) Option 1
```java
FileChannel channel = new FileChannel("data.txt", "r");
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead = channel.read(buffer);
```
b) Option 2
```java
FileChannel channel = new FileInputStream("data.txt").getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead = channel.read(buffer);
```
c) Option 3
```java
FileChannel channel = new RandomAccessFile("data.txt", "r").getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
int bytesRead = channel.read(buffer);
```
Answer: c) Option 3
Answer: a) Serialization is used to convert a Java object into a byte stream to store it in a file or send
it over the network.
a) Option 1
```java
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.ser"));
oos.writeObject(myObject);
oos.close();
```
b) Option 2
```java
ObjectOutputStream oos = new ObjectOutputStream(new FileWriter("data.ser"));
oos.writeObject(myObject);
oos.close();
```
c) Option 3
```java
ObjectOutputStream oos = new ObjectOutputStream(new OutputStreamWriter(new
FileOutputStream("data.ser")));
oos.writeObject(myObject);
oos.close();
```
Answer: a) Option 1
Answer: b) De-serialization is used to convert a byte stream into a Java object for processing.
a) Option 1
```java
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.ser"));
MyObject myObject = (MyObject) ois.readObject();
ois.close();
```
b) Option 2
```java
ObjectInputStream ois = new ObjectInputStream(new FileReader("data.ser"));
MyObject myObject = (MyObject) ois.readObject();
ois.close();
```
c) Option 3
```java
ObjectInputStream ois = new ObjectInputStream(new InputStreamReader(new
FileInputStream("data.ser")));
MyObject myObject = (MyObject) ois.readObject();
ois.close();
```
Answer: a) Option 1
1. MCQ: What is the difference between shallow copy and deep copy in Java?
a) Shallow copy duplicates the object and its references, while deep copy creates a new object with
copies of all its internal objects.
b) Shallow copy creates a
new object with copies of all its internal objects, while deep copy duplicates the object and its
references.
c) Shallow copy and deep copy both create new objects with copies of all their internal objects.
d) Shallow copy and deep copy both duplicate the object and its references.
Answer: a) Shallow copy duplicates the object and its references, while deep copy creates a new
object with copies of all its internal objects.
2. MCQ (Coding): Which of the following code snippets demonstrates a shallow copy of an array?
```java
// Option 1
int[] sourceArray = {1, 2, 3, 4, 5};
int[] shallowCopy = sourceArray;
// Option 2
int[] sourceArray = {1, 2, 3, 4, 5};
int[] shallowCopy = new int[sourceArray.length];
System.arraycopy(sourceArray, 0, shallowCopy, 0, sourceArray.length);
// Option 3
int[] sourceArray = {1, 2, 3, 4, 5};
int[] shallowCopy = Arrays.copyOf(sourceArray, sourceArray.length);
```
a) Option 1
b) Option 2
c) Option 3
d) Both Option 1 and Option 2
Answer: a) Option 1
3. MCQ: In the context of shallow copy and deep copy, what happens to the internal objects of the
original object?
a) Shallow copy creates new instances of the internal objects, while deep copy uses the same
instances.
b) Shallow copy and deep copy both create new instances of the internal objects.
c) Shallow copy and deep copy both use the same instances of the internal objects.
d) Shallow copy creates references to the internal objects, while deep copy creates new instances of
the internal objects.
Answer: c) Shallow copy and deep copy both use the same instances of the internal objects.
4. MCQ (Coding): Which of the following code snippets demonstrates a deep copy of an array?
```java
// Option 1
int[] sourceArray = {1, 2, 3, 4, 5};
int[] deepCopy = sourceArray.clone();
// Option 2
int[] sourceArray = {1, 2, 3, 4, 5};
int[] deepCopy = Arrays.copyOf(sourceArray, sourceArray.length);
// Option 3
int[] sourceArray = {1, 2, 3, 4, 5};
int[] deepCopy = new int[sourceArray.length];
System.arraycopy(sourceArray, 0, deepCopy, 0, sourceArray.length);
```
a) Option 1
b) Option 2
c) Option 3
d) All options create shallow copies, not deep copies.
1. MCQ: What is the purpose of using the `FileInputStream` and `FileOutputStream` classes in Java?
a) They are used for reading and writing character data from and to files.
b) They are used for reading and writing binary data from and to files.
c) They are used for reading and writing data over the network.
d) They are used for creating new files in the file system.
Answer: b) They are used for reading and writing binary data from and to files.
2. MCQ: What is the purpose of using the `BufferedReader` and `BufferedWriter` classes in Java?
a) They are used for reading and writing character data from and to files.
b) They are used for reading and writing binary data from and to files.
c) They are used for reading and writing data over the network.
d) They are used for creating new files in the file system.
Answer: a) They are used for reading and writing character data from and to files.
3. MCQ: Which method is used to read a line of text from a file using `BufferedReader` in Java?
a) `readLine()`
b) `read()`
c) `readChar()`
d) `readText()`
Answer: a) `readLine()`
4. MCQ: Which method is used to write a line of text to a file using `BufferedWriter` in Java?
a) `writeLine()`
b) `write()`
c) `writeChar()`
d) `writeText()`
Answer: b) `write()`
Answer: a) Serialization is used to convert a Java object into a byte stream to store it in a file or send
it over the network.
3. MCQ: Which interface must a class implement to be eligible for serialization in Java?
a) `Serializable`
b) `SerializableObject`
c) `Serialize`
d) `SerializeObject`
Answer: a) `Serializable`
Answer: a) The `transient` keyword indicates that a variable should not be serialized.
5. MCQ (Coding): How do you de-serialize an object in Java after it has been serialized and saved to a
file?
a) Option 1
```java
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.ser"));
MyObject myObject = ois.readObject();
ois.close();
```
b) Option 2
```java
ObjectInputStream ois = new ObjectInputStream(new FileReader("data.ser"));
MyObject myObject = ois.readObject();
ois.close();
```
c) Option 3
```java
ObjectInputStream ois = new ObjectInputStream(new InputStreamReader(new
FileInputStream("data.ser")));
MyObject myObject = ois.readObject();
ois.close();
```
Answer: a) Option 1
14. Lecture: Object Class & java.util Package
**14.1 Date, DateTime, Calendar Class**
Answer: a) `Date`
2. MCQ (Coding): What is the correct way to create a `Date` object with the current date and time in
Java?
a) Option 1
```java
Date currentDate = new Date();
```
b) Option 2
```java
Date currentDate = Date.now();
```
c) Option 3
```java
Date currentDate = Date.today();
```
Answer: a) Option 1
3. MCQ: Which class should be used instead of `Date` class for representing dates and times in Java 8
and later versions?
a) `Date`
b) `DateTime`
c) `Calendar`
d) `LocalDateTime`
Answer: d) `LocalDateTime`
4. MCQ (Coding): What is the correct way to create a `LocalDateTime` object with the current date
and time in Java 8?
a) Option 1
```java
LocalDateTime currentDateTime = new LocalDateTime();
```
b) Option 2
```java
LocalDateTime currentDateTime = LocalDateTime.now();
```
c) Option 3
```java
LocalDateTime currentDateTime = LocalDateTime.today();
```
Answer: b) Option 2
**14.2 Converting Date to String and String to Date Using SimpleDateFormat Class**
1. MCQ: Which class is used to format dates into strings and parse strings back into dates in Java?
a) `DateFormatter`
b) `SimpleDateFormat`
c) `DateParser`
d) `DateTimeFormatter`
Answer: b) `SimpleDateFormat`
2. MCQ (Coding): What is the correct way to format a `Date` object into a string in Java using
`SimpleDateFormat`?
a) Option 1
```java
Date currentDate = new Date();
String formattedDate = currentDate.format("yyyy-MM-dd");
```
b) Option 2
```java
Date currentDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(currentDate);
```
c) Option 3
```java
Date currentDate = new Date();
String formattedDate = currentDate.format(new SimpleDateFormat("yyyy-MM-dd"));
```
Answer: b) Option 2
3. MCQ: What is the purpose of the `parse()` method in the `SimpleDateFormat` class?
a) It is used to parse a `Date` object into a formatted string.
b) It is used to parse a formatted string back into a `Date` object.
c) It is used to compare two `SimpleDateFormat` objects.
d) It is used to convert a `Date` object into a timestamp.
4. MCQ (Coding): What is the correct way to parse a date string into a `Date` object using
`SimpleDateFormat`?
a) Option 1
```java
String dateString = "2023-07-24";
Date date = new Date(dateString);
```
b) Option 2
```java
String dateString = "2023-07-24";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(dateString);
```
c) Option 3
```java
String dateString = "2023-07-24";
Date date = Date.parse(dateString);
```
Answer: b) Option 2
1. MCQ: In Java, what is the purpose of the `toString()` method in the `Object` class?
a) It is used to convert an object into a string representation.
b) It is used to compare two objects for equality.
c) It is used to calculate a hash code for an object.
d) It is used to check if an object is an instance of a particular class.
2. MCQ (Coding): How can you override the `toString()` method in a custom class to provide a
meaningful string representation?
a) Option 1
```java
class MyClass {
int id;
String name;
b) Option 2
```java
class MyClass {
int id;
String name;
c) Option 3
```java
class MyClass {
int id;
String name;
Answer: a) Option 1
3. MCQ: In Java, what is the purpose of the `equals()` method in the `Object` class?
a) It is used to convert an object into a string representation.
b) It is used to compare two objects for equality.
c) It is used to calculate a hash code for an object.
d) It is used to check if an object is an instance of a particular class.
4. MCQ (Coding): How can you override the `equals()` method in a custom class to provide custom
equality comparison?
a) Option 1
```java
class MyClass {
int id;
String name;
b) Option 2
```java
class MyClass {
int id;
String name;
```java
class MyClass {
int id;
String name;
Answer: a) Option 1
**14.4 Collections**
1. MCQ: In Java, which interface is the root interface of the Java Collections Framework?
a) `Collection`
b) `List`
c) `Set`
d) `Map`
Answer: a) `Collection`
2. MCQ (Coding): What is the correct way to create a list of strings in Java using the `ArrayList` class?
a) Option 1
```java
ArrayList<String> myList = new ArrayList<>();
```
b) Option 2
```java
ArrayList myList = new ArrayList<String>();
```
c) Option 3
```java
List<String> myList = new ArrayList<>();
```
Answer: c) Option 3
3.
MCQ: Which interface in the Java Collections Framework does not allow duplicate elements?
a) `Collection`
b) `List`
c) `Set`
d) `Map`
Answer: c) `Set`
4. MCQ (Coding): What is the correct way to create a set of integers in Java using the `HashSet` class?
a) Option 1
```java
HashSet<Integer> mySet = new HashSet<>();
```
b) Option 2
```java
HashSet mySet = new HashSet<Integer>();
```
c) Option 3
```java
Set<Integer> mySet = new HashSet<>();
```
Answer: a) Option 1
5. MCQ: Which interface in the Java Collections Framework is used to store key-value pairs?
a) `Collection`
b) `List`
c) `Set`
d) `Map`
Answer: d) `Map`
6. MCQ (Coding): What is the correct way to create a map of strings to integers in Java using the
`HashMap` class?
a) Option 1
```java
HashMap<String, Integer> myMap = new HashMap<>();
```
b) Option 2
```java
HashMap myMap = new HashMap<String, Integer>();
```
c) Option 3
```java
Map<String, Integer> myMap = new HashMap<>();
```
Answer: c) Option 3
15. Lecture: Introduction to Collections: Collection Hierarchy
1. MCQ: Which Java interface is used to represent a collection that maintains an ordered sequence of
elements with duplicates allowed?
a) `List`
b) `Queue`
c) `Set`
d) `Map`
Answer: a) `List`
2. MCQ (Coding): Which Java class is used to implement a list that stores elements in an array and
allows dynamic resizing?
a) Option 1
```java
ArrayList<T> myList = new ArrayList<>();
```
b) Option 2
```java
LinkedList<T> myList = new LinkedList<>();
```
c) Option 3
```java
Vector<T> myList = new Vector<>();
```
Answer: a) Option 1
3. MCQ: Which Java interface is used to represent a collection that maintains an ordered sequence of
elements with no duplicates allowed?
a) `List`
b) `Queue`
c) `Set`
d) `Map`
Answer: c) `Set`
4. MCQ (Coding): Which Java interface is used to implement a collection that stores elements in a
queue (first-in, first-out) manner?
a) Option 1
```java
List<T> myQueue = new List<>();
```
b) Option 2
```java
Queue<T> myQueue = new Queue<>();
```
c) Option 3
```java
Queue<T> myQueue = new LinkedList<>();
```
Answer: c) Option 3
5. MCQ: Which Java interface is used to represent a collection that stores key-value pairs?
a) `List`
b) `Queue`
c) `Set`
d) `Map`
Answer: d) `Map`
1. MCQ: What is the main difference between `ArrayList` and `LinkedList` in Java?
a) `ArrayList` is a resizable array-based implementation, while `LinkedList` is a doubly-linked list-
based implementation.
b) `ArrayList` allows null elements, while `LinkedList` does not allow null elements.
c) `ArrayList` is a thread-safe collection, while `LinkedList` is not thread-safe.
d) `ArrayList` allows constant-time insertion and deletion, while `LinkedList` allows constant-time
search.
2. MCQ (Coding): What is the correct way to create an `ArrayList` of strings in Java?
a) Option 1
```java
ArrayList<String> myList = new ArrayList<>();
```
b) Option 2
```java
ArrayList myList = new ArrayList<String>();
```
c) Option 3
```java
List<String> myList = new ArrayList<>();
```
Answer: a) Option 1
3. MCQ: What is the main advantage of using `LinkedList` over `ArrayList` in Java?
a) `LinkedList` allows constant-time access to elements by index.
b) `LinkedList` allows constant-time insertion and deletion.
c) `LinkedList` uses less memory compared to `ArrayList`.
d) `LinkedList` allows duplicate elements.
4. MCQ (Coding): What is the correct way to create a `LinkedList` of integers in Java?
a) Option 1
```java
LinkedList<Integer> myList = new LinkedList<>();
```
b) Option 2
```java
LinkedList myList = new LinkedList<Integer>();
```
c) Option 3
```java
List<Integer> myList = new LinkedList<>();
```
Answer: a) Option 1
1. MCQ: Which class in Java provides a thread-safe implementation of a dynamic array similar to
`ArrayList`?
a) `ArrayList`
b) `LinkedList`
c) `Vector`
d) `HashSet`
Answer: c) `Vector`
2. MCQ (Coding): What is the correct way to create a `Vector` of strings in Java?
a) Option 1
```java
Vector<String> myVector = new Vector<>();
```
b) Option 2
```java
Vector myVector = new Vector<String>();
```
c) Option 3
```java
List<String> myVector = new Vector<>();
```
Answer: a) Option 1
3. MCQ: Which method is used to insert an element at the end of a `Vector` in Java?
a) `insert()`
b) `add()`
c) `append()`
d) `push()`
Answer: b) `add()`
4. MCQ (Coding): Which method is used to delete an element at a specific index from a `Vector` in
Java?
a) `delete()`
b) `remove()`
c) `erase()`
d) `pop()`
Answer: b) `remove()`
1. MCQ: Which class in Java provides utility methods to work with collections, such as sorting,
searching, and synchronizing collections?
a) `CollectionUtils`
b) `Collections`
c) `CollectionUtil`
d) `CollectionHelper`
Answer: b) `Collections`
2. MCQ (Coding): Which method is used to sort a list of elements in ascending order using the
`Collections` class in Java?
a) Option 1
```java
Collections.sort(list);
```
b) Option 2
```java
Collections.sortList(list);
```
c) Option 3
```java
list.sort();
```
Answer: a) Option 1
3. MCQ: Which method is used to find the maximum element in a collection using the `Collections`
class in Java?
a) `Collections.max()`
b) `Collections.maximum()`
c) `Collections.findMax()`
d) `Collections.maximumElement()`
Answer: a) `Collections.max()`
1. MCQ: In Java, which interface is used to define the natural ordering of objects in a class?
a) `Comparable`
b) `Comparator`
c) `Sorting`
d) `Orderable`
Answer: a) `Comparable`
2. MCQ (Coding): How do you implement the `Comparable` interface in a custom class to define the
natural ordering?
a) Option 1
```java
class MyClass implements Comparable {
// implementation of compareTo() method
}
```
b) Option 2
```java
class MyClass implements Comparable<MyClass> {
// implementation of compareTo() method
}
```
c) Option 3
```java
class MyClass extends Comparable {
// implementation of compareTo() method
}
```
Answer: b) Option 2
3. MCQ: In Java, which interface is used to define custom sorting of objects based on different criteria?
a) `Comparable`
b) `Comparator`
c) `Sorting`
d) `Orderable`
Answer: b) `Comparator`
4. MCQ (Coding): How do you implement the `Comparator` interface in a custom class to define
custom sorting?
a) Option 1
```java
class MyComparator implements Comparator {
// implementation of compare() method
}
```
b) Option 2
```java
class MyComparator implements Comparator<MyClass> {
// implementation of compare() method
}
```
c) Option 3
```java
class MyComparator extends Comparator {
// implementation of compare() method
}
```
Answer: b) Option 2
1. MCQ: Which interface in Java is used to represent a collection that stores elements in a queue (first-
in, first-out) manner?
a) `List`
b) `Queue`
c) `Set`
d) `Map`
Answer: b) `Queue`
2. MCQ (Coding): What is the correct way to create a `Queue` of strings in Java?
a) Option 1
```java
Queue<String> myQueue = new Queue<>();
```
b) Option 2
```java
Queue myQueue = new Queue<String>();
```
c) Option 3
```java
Queue<String> myQueue = new LinkedList<>();
```
Answer: c) Option 3
**15.6 Create DateManipulator Class to Convert String to Date, Date to String and to Find Out
Number of Days Between Two Dates.**
2. MCQ: Which method is used to convert a string into a `Date` object using `SimpleDateFormat` in
Java?
a) `parse()`
b) `format()`
c) `convert()`
d) `toDate()`
Answer: a) `parse()`
3. MCQ: Which method is used to convert a `Date` object into a string using `SimpleDateFormat` in
Java?
a) `parse()`
b) `format()`
c) `convert()`
d) `toString()`
Answer: b) `format()`
4. MCQ: Which Java class is used to represent a point in time and provides methods to manipulate
dates and times?
a) `SimpleDateFormat`
b) `DateFormatter`
c) `DateTime`
d) `Calendar`
Answer: d) `Calendar`
**15.7 Create a List of Java Defined Wrapper Classes and Perform Insert/Delete/Search/Iterate/Sort
Operations.**
1. MCQ: What are the Java defined wrapper classes for primitive data types?
a) `Integer`, `Float`, `Character`, `Boolean`
b) `Byte`, `Short`, `Integer`, `Long`
c) `Float`, `Double`, `Character`, `Boolean`
d) `Byte`, `Short`, `Character`, `Boolean`
2. MCQ: Which Java wrapper class is used to store integers as objects and provides useful methods for
manipulation?
a) `Integer`
b) `Float`
c) `Character`
d) `Boolean`
Answer: a) `Integer`
3. MCQ: Which method is used to insert an element at the end of a list using the `add()` method in Java?
a) `insert()`
b) `addLast()`
c) `append()`
d) `add()`
Answer: d) `add()`
4. MCQ: Which method is used to delete an element at a specific index from a list using the `remove()`
method in Java?
a) `delete()`
b) `remove()`
c) `erase()`
d) `deleteElement()`
Answer: b) `remove()`
**15.8 Create a Collection of Employee Class and Sort Objects Using Comparable and Comparator
Interfaces.**
1. MCQ: Which interface is used to define the natural ordering of objects in a class for sorting?
a) `Comparable`
b) `Comparator`
c) `Sorting`
d) `Orderable`
Answer: a) `Comparable`
2. MCQ: Which method is used to sort a collection of objects that implement the `Comparable`
interface?
a) `sort()`
b) `Collections.sort()`
c) `sorted()`
d) `Collections.sorted()`
Answer: b) `Collections.sort()`
3. MCQ: Which interface is used to define custom sorting of objects based on different criteria?
a) `Comparable`
b) `Comparator`
c) `Sorting`
d) `Orderable`
Answer: b) `
Comparator`
4. MCQ: Which method is used to sort a collection of objects using a custom `Comparator`?
a) `sort()`
b) `Collections.sort()`
c) `sorted()`
d) `Collections.sorted()`
Answer: a) `sort()`
**15.9 Implement Queue Data Structure Using LinkedList and Queue Collection.**
1. MCQ: What is the primary difference between the `Queue` interface and the `LinkedList` class?
a) `Queue` is an interface, and `LinkedList` is a class.
b) `Queue` is a class, and `LinkedList` is an interface.
c) Both `Queue` and `LinkedList` are classes.
d) Both `Queue` and `LinkedList` are interfaces.
2. MCQ: Which interface in Java is used to represent a collection that stores elements in a queue (first-
in, first-out) manner?
a) `List`
b) `Queue`
c) `Set`
d) `Map`
Answer: b) `Queue`
a) `enqueue()`
b) `add()`
c) `insert()`
d) `push()`
Answer: a) `enqueue()`
4. MCQ: Which method is used to remove the element at the front of a queue?
a) `dequeue()`
b) `remove()`
c) `pop()`
d) `delete()`
Answer: a) `dequeue()`
1. MCQ: Which Java collection class guarantees no duplicate elements and does not maintain insertion
order?
a) `HashSet`
b) `LinkedHashSet`
c) `TreeSet`
d) `ArrayList`
Answer: a) `HashSet`
2. MCQ (Coding): How do you create a `HashSet` and add elements to it in Java?
a) Option 1
```java
HashSet<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("orange");
```
b) Option 2
```java
HashSet set = new HashSet();
set.put("apple");
set.put("banana");
set.put("orange");
```
c) Option 3
```java
HashSet<String> set = new HashSet<>();
set.append("apple");
set.append("banana");
set.append("orange");
```
Answer: a) Option 1
3. MCQ: Which Java collection class maintains insertion order, allowing elements to be retrieved in the
order they were added?
a) `HashSet`
b) `LinkedHashSet`
c) `TreeSet`
d) `ArrayList`
Answer: b) `LinkedHashSet`
4. MCQ (Coding): How do you create a `LinkedHashSet` and add elements to it in Java?
a) Option 1
```java
LinkedHashSet<String> set = new LinkedHashSet<>();
set.add("red");
set.add("green");
set.add("blue");
```
b) Option 2
```java
LinkedHashSet set = new LinkedHashSet();
set.put("red");
set.put("green");
set.put("blue");
```
c) Option 3
```java
LinkedHashSet<String> set = new LinkedHashSet<>();
set.append("red");
set.append("green");
set.append("blue");
```
Answer: a) Option 1
5. MCQ: Which Java collection class maintains elements in sorted order (natural order or custom order)
and does not allow duplicate elements?
a) `HashSet`
b) `LinkedHashSet`
c) `TreeSet`
d) `ArrayList`
Answer: c) `TreeSet`
6. MCQ (Coding): How do you create a `TreeSet` and add elements to it in Java?
a) Option 1
```java
TreeSet<String> set = new TreeSet<>();
set.add("dog");
set.add("cat");
set.add("lion");
```
b) Option 2
```java
TreeSet set = new TreeSet();
set.put("dog");
set.put("cat");
set.put("lion");
```
c) Option 3
```java
TreeSet<String> set = new TreeSet<>();
set.append("dog");
set.append("cat");
set.append("lion");
```
Answer: a) Option 1
Answer: b) It refers to collections that share the same data with other collections, but with different
views.
2. MCQ (Coding): Which method is used to create a backed `Set` from an existing `HashSet` in Java?
a) Option 1
```java
Set<String> backedSet = new HashSet<>();
backedSet.add("apple");
backedSet.add("banana");
Set<String> set = Collections.backedSet(backedSet);
```
b) Option 2
```java
HashSet<String> backedSet = new HashSet<>();
backedSet.add("apple");
backedSet.add("banana");
Set<String> set = Collections.synchronizedSet(backedSet);
```
c) Option 3
```java
HashSet<String> backedSet = new HashSet<>();
backedSet.add("apple");
backedSet.add("banana");
Set<String> set = Collections.unmodifiableSet(backedSet);
```
Answer: a) Option 1
Answer: c) Share the same data between multiple collections with different views.
4. MCQ (Coding): Which method is used to create a synchronized (thread-safe) `Set` from an existing
`HashSet` in Java?
a) Option 1
```java
Set<String> synchronizedSet = new HashSet<>();
synchronizedSet.add("apple");
synchronizedSet.add("banana");
Set<String> set = Collections.synchronizedSet(synchronizedSet);
```
b) Option 2
```java
HashSet<String> synchronizedSet = new HashSet<>();
synchronizedSet.add("apple");
synchronizedSet.add("banana");
Set<String> set = Collections.backedSet(synchronizedSet);
```
c) Option 3
```java
Set<String> synchronizedSet = new HashSet<>();
synchronizedSet.add("apple");
synchronizedSet.add("banana");
Set<String> set = Collections.unmodifiableSet(synchronizedSet);
```
Answer: a) Option 1
Answer: d) They share the same underlying data, reducing memory overhead.
6. MCQ (Coding): Which method is used to create an unmodifiable `Set` from an existing `HashSet` in
Java?
a) Option 1
```java
Set<String> unmodifiableSet = new HashSet<>();
unmodifiableSet.add("apple");
unmodifiableSet.add("banana");
Set<String> set = Collections.unmodifiableSet(unmodifiableSet);
```
b) Option 2
```java
HashSet<String> unmodifiableSet = new HashSet<>();
unmodifiableSet.add("apple");
unmodifiableSet.add("banana");
Set<String> set = Collections.synchronizedSet(unmodifiableSet);
```
c) Option 3
```java
Set<String> unmodifiableSet = new HashSet<>();
unmodifiableSet.add("apple");
unmodifiableSet.add("banana");
Set<String> set = Collections.backedSet(unmodifiableSet);
```
Answer: a) Option 1
Sure, let's continue with the MCQs for the remaining topics:
1. MCQ: Which Java collection class is synchronized and does not allow null keys or values?
a) `Hashtable`
b) `HashMap`
c) `LinkedHashMap`
d) `TreeMap`
Answer: a) `Hashtable`
2. MCQ (Coding): How do you create a `HashMap` and add key-value pairs to it in Java?
a) Option 1
```java
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
```
b) Option 2
```java
HashMap map = new HashMap();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 3);
```
c) Option 3
```java
HashMap<String, Integer> map = new HashMap<>();
map.append("apple", 1);
map.append("banana", 2);
map.append("orange", 3);
```
Answer: a) Option 1
3. MCQ: Which Java collection class maintains insertion order of keys and allows null keys and values?
a) `Hashtable`
b) `HashMap`
c) `LinkedHashMap`
d) `TreeMap`
Answer: c) `LinkedHashMap`
4. MCQ (Coding): How do you create a `LinkedHashMap` and add key-value pairs to it in Java?
a) Option 1
```java
LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
map.put("red", 1);
map.put("green", 2);
map.put("blue", 3);
```
b) Option 2
```java
LinkedHashMap map = new LinkedHashMap();
map.put("red", 1);
map.put("green", 2);
map.put("blue", 3);
```
c) Option 3
```java
LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
map.append("red", 1);
map.append("green", 2);
map.append("blue", 3);
```
Answer: a) Option 1
5. MCQ: Which Java collection class sorts keys in natural order or based on a custom comparator?
a) `Hashtable`
b) `HashMap`
c) `LinkedHashMap`
d) `TreeMap`
Answer: d) `TreeMap`
6. MCQ (Coding): How do you create a `TreeMap` and add key-value pairs to it in Java?
a) Option 1
```java
TreeMap<String, Integer> map = new TreeMap<>();
map.put("dog", 1);
map.put("cat", 2);
map.put("lion", 3);
```
b) Option 2
```java
TreeMap map = new TreeMap();
map.put("dog", 1);
map.put("cat", 2);
map.put("lion", 3);
```
c) Option 3
```java
TreeMap<String, Integer> map = new TreeMap<>();
map.append("dog", 1);
map.append("cat", 2);
map.append("lion", 3);
```
Answer: a) Option 1
Answer: c) They allow sharing the same data between multiple maps with different views.
2. MCQ (Coding): Which method is used to create a backed `Map` from an existing `HashMap` in Java?
a) Option 1
```java
Map<String, Integer> backedMap = new HashMap<>();
backedMap.put("apple", 1);
backedMap.put("banana", 2);
Map<String, Integer> map = Collections.backedMap(backedMap);
```
b) Option 2
```java
HashMap<String, Integer> backedMap = new HashMap<>();
backedMap.put("apple", 1);
backedMap.put("banana", 2);
Map<String, Integer> map = Collections.synchronizedMap(backedMap);
```
c) Option 3
```java
HashMap<String, Integer> backedMap = new HashMap<>();
backedMap.put("apple", 1);
backedMap.put("banana", 2);
Map<String, Integer> map = Collections.unmodifiableMap(backedMap);
```
Answer: a) Option 1
3. MCQ: Backed map collections are useful when you want to:
a) Create an immutable map.
b) Ensure thread safety for the map.
c) Share the same data between multiple maps with different views.
d) Ensure that keys and values are unique in the map.
Answer: c) Share the same data between multiple maps with different views.
4. MCQ (Coding): Which method is used to create a synchronized (thread-safe) `Map` from an existing
`HashMap` in Java?
a) Option 1
```java
Map<String, Integer> synchronizedMap = new HashMap<>();
synchronizedMap.put("apple", 1);
synchronizedMap.put("banana", 2);
Map<String, Integer> map = Collections.synchronizedMap(synchronizedMap);
```
b) Option 2
```java
HashMap<String, Integer> synchronizedMap = new HashMap<>();
synchronizedMap.put("apple", 1);
synchronizedMap.put("banana", 2);
Map<String, Integer> map = Collections.backedMap(synchronizedMap);
```
c) Option 3
```java
Map<String, Integer> synchronizedMap = new HashMap<>();
synchronizedMap.put("apple", 1);
synchronizedMap.put("banana", 2);
Map<String, Integer> map = Collections.unmodifiableMap(synchronizedMap);
```
Answer: a) Option 1
Answer: d) They share the same underlying data, reducing memory overhead.
6. MCQ (Coding): Which method is used to create an unmodifiable `Map` from an existing `HashMap`
in Java?
a) Option 1
```java
Map<String, Integer> unmodifiableMap = new HashMap<>();
unmodifiableMap.put("apple", 1);
unmodifiableMap.put("banana", 2);
Map<String, Integer> map = Collections.unmodifiableMap(unmodifiableMap);
```
b) Option 2
```java
HashMap<String, Integer> unmodifiableMap = new HashMap<>();
unmodifiableMap.put("apple", 1);
unmodifiableMap
.put("banana", 2);
Map<String, Integer> map = Collections.synchronizedMap(unmodifiableMap);
```
c) Option 3
```java
Map<String, Integer> unmodifiableMap = new HashMap<>();
unmodifiableMap.put("apple", 1);
unmodifiableMap.put("banana", 2);
Map<String, Integer> map = Collections.backedMap(unmodifiableMap);
```
Answer: a) Option 1
**16.4 Generics**
Answer: d) Generics allow you to create classes, interfaces, and methods that can work with different
data types.
2. MCQ (Coding): How do you declare a generic class that can work with any data type in Java?
a) Option 1
```java
class MyGenericClass<T> {
// class implementation
}
```
b) Option 2
```java
class MyGenericClass {
<T> // generic declaration
// class implementation
}
```
c) Option 3
```java
class MyGenericClass {
// class implementation
<T> // generic declaration
}
```
Answer: a) Option 1
Answer: b) Generics allow collections to work with different data types, providing type safety at
compile-time.
4. MCQ (Coding): How do you declare a generic method that can work with different data types in
Java?
a) Option 1
```java
public void myGenericMethod<T>(T obj) {
// method implementation
}
```
b) Option 2
```java
public <T> void myGenericMethod(T obj) {
// method implementation
}
```
c) Option 3
```java
public void myGenericMethod(T obj) {
// method implementation
<T> // generic declaration
}
```
Answer: b) Option 2
Answer: b) It is used to instantiate a generic class without specifying the data type.
6. MCQ (Coding): How do you instantiate a generic class with the diamond operator in Java?
a) Option 1
```java
MyGenericClass<> myObj = new MyGenericClass<>();
```
b) Option 2
```java
MyGenericClass myObj = new MyGenericClass<>();
```
c) Option 3
```java
MyGenericClass<T> myObj = new MyGenericClass<T>();
```
Answer: b) Option 2
Answer: c) Concurrent collections allow multiple threads to access and modify collections safely
without explicit synchronization.
2. MCQ (Coding): Which concurrent collection class in Java allows multiple threads to insert elements
at the beginning and end of the collection?
a) `ConcurrentList`
b) `ConcurrentMap`
c) `ConcurrentQueue`
d) `ConcurrentDeque`
Answer: d) `ConcurrentDeque`
4. MCQ (Coding): Which concurrent collection class in Java allows multiple threads to access and
modify elements in a thread-safe manner, similar to a hash table?
a) `
ConcurrentHashMap`
b) `ConcurrentHashSet`
c) `ConcurrentLinkedList`
d) `ConcurrentTreeMap`
Answer: a) `ConcurrentHashMap`
Answer: c) When you need to ensure thread safety for accessing and modifying collections from
multiple threads.
6. MCQ (Coding): Which concurrent collection class in Java allows multiple threads to access and
modify elements in a thread-safe manner, similar to a regular queue (first-in, first-out)?
a) `ConcurrentList`
b) `ConcurrentMap`
c) `ConcurrentQueue`
d) `ConcurrentDeque`
Answer: c) `ConcurrentQueue`
17. Lecture:
**17.1 Multi-Threading: Thread Class and Runnable Interface**
1. MCQ: Which of the following interfaces in Java is used for creating a thread?
a) `Runnable`
b) `Thread`
c) `Executor`
d) `Timer`
Answer: a) `Runnable`
2. MCQ (Coding): How do you create a thread using the `Thread` class in Java?
a) Option 1
```java
Thread myThread = new Thread();
myThread.start();
```
b) Option 2
```java
Thread myThread = new Thread(new Runnable() {
public void run() {
// thread logic here
}
});
myThread.start();
```
c) Option 3
```java
Thread myThread = new Thread();
myThread.run();
```
Answer: b) Option 2
a) `start()`
b) `run()`
c) `execute()`
d) `begin()`
Answer: a) `start()`
4. MCQ (Coding): How do you create a thread using the `Runnable` interface in Java?
a) Option 1
```java
Runnable myRunnable = new Runnable() {
public void run() {
// thread logic here
}
};
Thread myThread = new Thread(myRunnable);
myThread.start();
```
b) Option 2
```java
Runnable myRunnable = new Runnable() {
public void run() {
// thread logic here
}
};
myRunnable.start();
```
c) Option 3
```java
Runnable myRunnable = new Runnable() {
public void run() {
// thread logic here
}
};
myRunnable.run();
```
Answer: a) Option 1
6. MCQ (Coding): How do you define the logic for a thread using the `run()` method in Java?
a) Option 1
```java
public void run() {
// thread logic here
}
```
b) Option 2
```java
public void start() {
// thread logic here
}
```
c) Option 3
```java
public void execute() {
// thread logic here
}
```
Answer: a) Option 1
7. MCQ: Which of the following statements is true about the `Runnable` interface in Java?
a) It is a class that represents a thread.
b) It is an interface that allows a class to be executed as a thread.
c) It is a method that starts a thread.
d) It is a package that contains thread-related classes.
```java
class MyRunnable implements Runnable {
public void run() {
// thread logic here
}
}
9. MCQ: Which method is used to check if a thread is still alive and running in Java?
a) `isRunning()`
b) `isAlive()`
c) `isExecuting()`
d) `isWorking()`
Answer: b) `isAlive()`
10. MCQ (Coding): How do you check if a thread `myThread` is still alive in Java?
a) Option 1
```java
myThread.isAlive();
```
b) Option 2
```java
Thread.isAlive(myThread);
```
c) Option 3
```java
Thread.isRunning(myThread);
```
Answer: a) Option 1
1. MCQ: Which method is used to pause the execution of a thread for a specific amount of time in Java?
a) `sleep()`
b) `join()`
c) `yield()`
d) `pause()`
Answer: a) `sleep()`
2. MCQ (Coding): How do you pause the execution of a thread for 1 second using the `sleep()` method
in Java?
a) Option 1
```java
Thread.sleep(1000);
```
b) Option 2
```java
sleep(1000);
```
c) Option 3
```java
Thread.pause(1000);
```
Answer: a) Option 1
3. MCQ: Which method is used to wait for a thread to finish its execution in Java?
a) `sleep()`
b) `join()`
c) `yield()`
d) `wait()`
Answer: b) `join()`
4. MCQ (Coding): How do you make a thread `myThread` wait for another thread `otherThread` to
finish using the `join()` method in Java?
a) Option 1
```java
myThread.wait(otherThread);
```
b) Option 2
```java
myThread.join(otherThread);
```
c) Option 3
```java
otherThread.join(myThread);
```
Answer: b) Option 2
5. MCQ: Which method is used to temporarily pause the execution of a thread to give other threads a
chance to run in Java?
a) `sleep()`
b) `join()`
c) `yield()`
d) `pause()`
Answer: c) `yield()`
a thread `myThread` yield its execution to other threads using the `yield()` method in Java?
a) Option 1
```java
myThread.pause();
```
b) Option 2
```java
myThread.yield();
```
c) Option 3
```java
Thread.yield(myThread);
```
Answer: b) Option 2
a) `setPriority()`
b) `priority()`
c) `assignPriority()`
d) `setThreadPriority()`
Answer: a) `setPriority()`
8. MCQ (Coding): How do you set the priority of a thread `myThread` to the highest priority in Java?
a) Option 1
```java
myThread.setPriority(Thread.MIN_PRIORITY);
```
b) Option 2
```java
myThread.setPriority(Thread.MAX_PRIORITY);
```
c) Option 3
```java
myThread.setPriority(Thread.HIGH_PRIORITY);
```
Answer: b) Option 2
a) `getPriority()`
b) `priority()`
c) `retrievePriority()`
d) `getThreadPriority()`
Answer: a) `getPriority()`
10. MCQ (Coding): How do you get the priority of a thread `myThread` in Java?
a) Option 1
```java
myThread.getPriority();
```
b) Option 2
```java
Thread.getPriority(myThread);
```
c) Option 3
```java
myThread.priority();
```
Answer: a) Option 1
Answer: a) It is used to group threads together for easy management and control.
a) Option 1
```java
ThreadGroup group = new ThreadGroup();
```
b) Option 2
```java
ThreadGroup group = new ThreadGroup("MyGroup");
```
c) Option 3
```java
ThreadGroup group = Thread.getThreadGroup();
```
Answer: b) Option 2
3. MCQ: What is the role of the `uncaughtException()` method in the `ThreadGroup` class?
4. MCQ (Coding): How do you handle uncaught exceptions in a thread group using the
`uncaughtException()` method in Java?
a) Option 1
```java
public void uncaughtException(Thread t, Throwable e) {
// exception handling code here
}
```
b) Option 2
```java
public void handleException(Thread t, Throwable e) {
// exception handling code here
}
```
c) Option 3
```java
public void catchException(Thread t, Throwable e) {
// exception handling code here
}
```
Answer: a) Option 1
18. Lecture
**18.1 Synchronization**
a) Option 1
```java
synchronized void myMethod() {
// method logic here
}
```
b) Option 2
```java
void myMethod() {
synchronized {
// method logic here
}
}
```
c) Option 3
```java
synchronized(myMethod) {
// method logic here
}
```
Answer: a) Option 1
a) It ensures that the method can only be called by a single thread at a time.
b) It makes the method execute faster by bypassing thread synchronization.
c) It allows multiple threads to execute the method simultaneously.
d) It automatically creates new threads for the synchronized method.
Answer: a) It ensures that the method can only be called by a single thread at a time.
a) Option 1
```java
synchronized(myObject) {
// synchronized block code here
}
```
b) Option 2
```java
synchronized {
// synchronized block code here
}
```
c) Option 3
```java
myObject.synchronized {
// synchronized block code here
}
```
Answer: a) Option 1
a) Option 1
```java
synchronized static void myStaticMethod() {
// method logic here
}
```
b) Option 2
```java
static synchronized void myStaticMethod() {
// method logic here
}
```
c) Option 3
```java
synchronized void static myStaticMethod() {
// method logic here
}
```
Answer: b) Option 2
a) Option 1
```java
synchronized void setVariable(int value) {
this.variable = value;
}
```
b) Option 2
```java
void setVariable(int value) {
synchronized(this) {
this.variable = value;
}
}
```
c) Option 3
```java
synchronized(this.variable) {
this.variable = value;
}
```
Answer: b) Option 2
**18.2 Deadlock**
a) It is a situation where a thread is unable to proceed because it is waiting for a resource that is held
by another thread, and that other thread is waiting for a resource held by the first thread.
b) It is a situation where multiple threads are executing in a non-deterministic order.
c) It is a situation where a thread is unable to proceed because it is waiting for a resource that is
currently being used by another thread.
d) It is a situation where a thread is stuck in an infinite loop.
Answer: a) It is a situation where a thread is unable to proceed because it is waiting for a resource
that is held by another thread, and that other thread is waiting for a resource held by the first thread.
4. MCQ (Coding): Which Java method is used to put a thread into a waiting state until another thread
notifies it?
a) `await()`
b) `suspend()`
c) `sleep()`
d
) `wait()`
Answer: d) `wait()`
6. MCQ (Coding): Which method is used to notify a waiting thread to resume execution in Java?
a) `notify()`
b) `notifyAll()`
c) `resume()`
d) `awake()`
Answer: a) `notify()`
7. MCQ: In a deadlock situation, how can you identify which threads are involved?
Answer: c) It is used to wait for a specific condition to be met before resuming execution.
2. MCQ (Coding): Which method is used to notify a waiting thread to resume execution in Java?
a) `notify()`
b) `notifyAll()`
c) `resume()`
d) `awake()`
Answer: a) `notify()`
Answer: a) It is used to wake up all waiting threads that are waiting on the same object's monitor.
4. MCQ (Coding): How do you use the `wait()` method to wait for a specific condition to be met?
a) Option 1
```java
synchronized(waitCondition) {
while (!conditionMet) {
waitCondition.wait();
}
}
```
b) Option 2
```java
synchronized {
while (!conditionMet) {
wait();
}
}
```
c) Option 3
```java
while (!conditionMet) {
wait();
}
```
Answer: a) Option 1
5. MCQ: What happens when a thread calls the `wait()` method in Java?
a) The thread releases the lock on the object's monitor and waits until another thread notifies it.
b) The thread continues its execution without any delay.
c) The thread enters a waiting state for a specified duration.
d) The thread terminates its execution.
Answer: a) The thread releases the lock on the object's monitor and waits until another thread notifies
it.
6. MCQ (Coding): How do you use the `notifyAll()` method to wake up all waiting threads?
a) Option 1
```java
synchronized {
conditionMet = true;
notifyAll();
}
```
b) Option 2
```java
synchronized(waitCondition) {
conditionMet = true;
waitCondition.notifyAll();
}
```
c) Option 3
```java
synchronized {
conditionMet = true;
wait();
}
```
Answer: b) Option 2
7. MCQ: In which class are the `wait()`, `notify()`, and `notifyAll()` methods defined in Java?
a) `Thread`
b) `Object`
c) `Runnable`
d) `Lock
Answer: b) `Object`
8. MCQ (Coding): When do you typically use the `wait()`, `notify()`, and `notifyAll()` methods?
Answer: b) It is a problem where multiple threads consume the same input concurrently.
2. MCQ (Coding): How can you implement the producer-consumer problem in Java?
a) Option 1
```java
class Producer {
synchronized void produce() {
// producer logic here
}
}
class Consumer {
synchronized void consume() {
// consumer logic here
}
}
```
b) Option 2
```java
class Producer {
void produce() {
synchronized(this) {
// producer logic here
}
}
}
class Consumer {
void consume() {
synchronized(this) {
// consumer logic here
}
}
}
```
c) Option 3
```java
class Producer {
synchronized void produce() {
// producer logic here
}
}
class Consumer {
void consume() {
synchronized(this) {
// consumer logic here
}
}
}
```
Answer: a) Option 1
3. MCQ: What is the role of the `wait()` and `notify()` methods in the producer-consumer problem?
a) The `wait()` method is used by the producer to wait for the consumer to consume data, and the
`notify()` method is used by the consumer to notify the producer when data is available.
b) The `wait()` method is used by the consumer to wait for the producer to produce data, and the
`notify()` method is used by the producer to notify the consumer when data is available.
c) Both the `wait()` and `notify()` methods are used by the producer to wait for the consumer to
consume data.
d) Both the `wait()` and `notify()` methods are used by the consumer to wait for the producer to
produce data.
Answer: b) The `wait()` method is used by the consumer to wait for the producer to produce data, and
the `notify()` method is used by the producer to notify the consumer when data is available.
4. MCQ (Coding): How can you implement the producer-consumer problem using the `wait()` and
`notify()` methods in Java?
a) Option 1
```java
class Producer {
synchronized void produce() {
while (dataAvailable) {
wait();
}
// produce data logic here
notify();
}
}
class Consumer {
synchronized void consume() {
while (!dataAvailable) {
wait();
}
// consume data logic here
notify();
}
}
```
b) Option 2
```java
class Producer {
synchronized void produce() {
while (!dataAvailable) {
wait();
}
// produce data logic here
notifyAll();
}
}
class Consumer {
synchronized void consume() {
while (dataAvailable) {
wait();
}
// consume data logic here
notifyAll();
}
}
```
c) Option 3
```java
class Producer {
void produce() {
synchronized(this) {
while (!dataAvailable) {
this.wait();
}
// produce data logic here
this.notify();
}
}
}
class Consumer {
void consume() {
synchronized(this) {
while (dataAvailable) {
this.wait();
}
// consume data logic here
this.notify();
}
}
}
```
Answer: a) Option 1
5. MCQ: What is the purpose of using a shared buffer in the producer-consumer problem?
Answer: c) To act as a communication channel between the producer and the consumer.
6. MCQ (Coding): How do you ensure that the producer does not produce data when the buffer is full,
and the consumer does not consume data when the buffer is empty?
Answer: b) By using the `wait()` and `notify()` methods to wait for the buffer to become empty or
full.
a) Ensuring that the producer always produces data before the consumer consumes it.
b) Ensuring that the consumer always consumes data before the producer produces more.
c) Avoiding deadlock situations between the producer and consumer threads.
d) Ensuring that the producer and consumer do not access the shared buffer at the same time.
Answer: d) Ensuring that the producer and consumer do not access the shared buffer at the same time.
8. MCQ (Coding): How do you terminate the producer-consumer system in Java after a certain
condition is met?
Answer: b) By setting a shared `boolean` flag and checking it periodically in both producer and
consumer threads.
19. Lecture:
**19.1 Inner Class (Regular, Method Local, Anonymous & Static Inner Class)**
1. MCQ: Which type of inner class is defined within a method of an outer class and can only be
accessed within that method?
2. MCQ (Coding): How do you create an instance of a regular inner class in Java?
a) Option 1
```java
OuterClass.RegularInnerClass inner = new OuterClass.RegularInnerClass();
```
b) Option 2
```java
RegularInnerClass inner = new OuterClass.RegularInnerClass();
```
c) Option 3
```java
OuterClass outer = new OuterClass();
RegularInnerClass inner = outer.new RegularInnerClass();
```
Answer: c) Option 3
3. MCQ: Which type of inner class has no name and is declared and instantiated at the same time?
4. MCQ (Coding): How do you create an instance of an anonymous inner class in Java?
a) Option 1
```java
OuterClass.AnonymousInnerClass inner = new OuterClass.AnonymousInnerClass() {
// anonymous inner class implementation here
};
```
b) Option 2
```java
AnonymousInnerClass inner = new OuterClass.AnonymousInnerClass() {
// anonymous inner class implementation here
};
```
c) Option 3
```java
OuterClass outer = new OuterClass();
AnonymousInnerClass inner = outer.new AnonymousInnerClass() {
// anonymous inner class implementation here
};
```
Answer: b) Option 2
5. MCQ: Which type of inner class is declared as `static` and can be accessed without creating an
instance of the outer class?
6. MCQ (Coding): How do you create an instance of a static inner class in Java?
Answer: a) Option 1
7. MCQ: Which type of inner class can access non-final local variables of the enclosing method?
10. MCQ (Coding): Can a regular inner class contain static methods?
a) Option 1
```java
() -> {
// lambda expression body
};
```
b) Option 2
```java
() -> (
// lambda expression body
)
```
c) Option 3
```java
() => {
// lambda expression body
}
```
Answer: a) Option 1
a) (param)
b) (param1, param2)
c) param
d) [param]
Answer: c) param
4. MCQ (Coding): How do you use a lambda expression to implement a functional interface with a
single abstract method that takes two parameters?
a) Option 1
```java
(param1, param2) -> {
// lambda expression body
};
```
b) Option 2
```java
(param1, param2) => {
// lambda expression body
};
```
c) Option 3
```java
(param1, param2) -> (
// lambda expression body
)
```
Answer: a) Option 1
5. MCQ: What is the return type of a lambda expression that represents a void method?
a) `void`
b) `null`
c) `None`
d) It is inferred by the compiler.
6. MCQ (Coding): How do you use a lambda expression to implement a functional interface with a
single abstract method that returns a value?
a) Option 1
```java
() -> {
// lambda expression body
return result;
};
```
b) Option 2
```java
() => {
// lambda expression body
return result;
};
```
c) Option 3
```java
() -> (
// lambda expression body
return result;
)
```
Answer: a) Option 1
a) `Math::random`
b) `System.out::println`
c) `String::length`
d) All of the above
**19.3 Reflection**
Answer: b) The process of analyzing and modifying the runtime behavior of classes and objects.
2. MCQ (Coding): How do you obtain the `Class` object representing a class in Java?
3. MCQ: What information can be obtained from the `Class` object in Java?
4. MCQ (Coding): How do you create an instance of a class using reflection in Java?
6. MCQ (Coding): How do you set the value of a private field of a class using reflection in Java?
Answer: b) By using the `set()` method on the field object obtained from the `Class` object.
8. MCQ (Coding): What is the purpose of the `getInterfaces()` method in the `Class` class?