Oops System
Q.1 Polymorphism in OOP allows for:
A. objects to take on multiple forms
B. methods to execute concurrently
C. classes to encapsulate data and methods
D. objects to be instantiated without classes
Q.2 Which keyword is used in Java to inherit a class?
A. extends
B. implements
C. inherits
D. super
Q.3 After adding a new feature to a class, a programmer notices that creating an object of that class now throws an error.
What is the MOST likely cause?
A. The class does not have a constructor
B. The new feature conflicts with existing methods
C. There is a syntax error in the new feature
D. The class was not compiled after adding the new feature
Q.4 In the context of Java, what does the following error indicate?
java.lang.NullPointerException
A. An attempt to access a class file that does not exist
B. An attempt to use a reference that points to no location in memory
C. Incorrect syntax
D. None of the above
Q.5 A programmer attempts to compile the following Java code but encounters an error:
class MyClass { void MyClass() { } }.
What is the mistake?
A. The constructor has a return type
B. The class name is incorrect
C. The constructor is defined as a method
D. None of the above
Q.6 Identify the mistake in the following Java code snippet:
class Student {
private int score;
public static void setScore(int s) {
score = s;
}
}
A. score should not be private
B. s is not correctly passed to score
C. setScore cannot be static as it accesses an instance variable
D. None of the above
Q.7 Considering the principle of encapsulation, which option correctly makes age a private attribute and provides public getter and setter methods in a Java class?
A. private int age; public int getAge() { return age; } public void setAge(int a) { age = a; }
B. int age; public int readAge() { return age; } public void writeAge(int a) { age = a; }
C. private int age; public int age() { return age; } public void age(int a) { age = a; }
D. int age; public int getAge() { return age; } public void age(int a) { age = a; }
Q.8 Which of the following is the correct way to define a constructor in Java?
A. public void ClassName() {}
B. ClassName() {}
C. public ClassName() {}
D. constructor ClassName() {}
Q.9 What is the result of compiling and running the following code in Java?
class Counter {
private int count = 0;
void increment() {
count++;
}
int getCount() {
return count;
}
}
A. Compilation error
B. Runtime error
C. 0
D. None of the above
Q.10 Given the following Java code, what is the output?
class Box {
int width;
Box(int w) {
width = w;
}
}
public class Test {
public static void main(String[] args) {
Box myBox = new Box(5);
System.out.println(myBox.width);
}
}
A. 5
B. 0
C. Error
D. None
Q.11 Which keyword is used in Java to create a new object?
A. new
B. class
C. object
D. this
Q.12 How do objects in OOP communicate with each other?
A. Through global functions
B. By calling methods on each other
C. Using special OOP communication operators
D. By accessing each other’s memory directly
Q.13 What is the main difference between a class and an object?
A. A class is a blueprint, while an object is an instance of a class
B. A class is executable code, while an object is not
C. A class cannot exist without objects, while an object can exist without classes
D. A class is used only in object-oriented programming, while objects can be used in any programming paradigm
Q.14 Which term best describes an instance variable of a class?
A. A variable defined within a method
B. A variable accessible by all instances of a class and shared across them
C. A variable unique to each instance of a class
D. A constant value that cannot be changed
Q.15 Which of the following best describes the concept of “state” in an object?
A. The behavior the object exhibits
B. The methods the object can execute
C. The data stored within the object
D. The class from which the object is derived
Q.16 The process of creating an object from a class is known as:
A. Encapsulation
B. Instantiation
C. Inheritance
D. Abstraction
Q.17 Which of the following is a characteristic of an object?
A. Encapsulation
B. Inheritance
C. Polymorphism
D. Identity
Q.18 In the context of OOP, what does a class provide?
A. A blueprint for objects
B. A specific data type
C. A method implementation
D. A programming pattern
Q.19 What is an object in programming?
A. A piece of data
B. A runtime entity
C. A template for creating objects
D. A function
Q.20 If a class Car has a method drive() that requires no arguments, which of the following calls is correct after creating a Car object named myCar?
A. Car.drive()
B. myCar.drive()
C. drive(myCar)
D. Car().drive()
Q.21 A programmer defines a class but fails to create an instance of that class. They try to call a method of the class directly.
What type of error will occur?
A. Compilation error
B. Runtime error
C. Logical error
D. No error
Q.22 Which keyword is used to create a class in Java?
A. class
B. Class
C. object
D. Object
Q.23 What is the output of the following Python code?
class Animal:
def speak(self):
return “makes a sound”
class Dog(Animal):
def speak(self):
return “barks”
print(Dog().speak())
A. makes a sound
B. barks
C. SyntaxError
D. None
Q.24 In OOP, an “object” is:
A. An instance of a class
B. A type of data structure
C. A programming technique
D. A method definition
Q.25 The concept of hiding the internal implementation details of a class and showing only its functionality is known as:
A. Encapsulation
B. Abstraction
C. Polymorphism
D. Inheritance
Q.26 Which concept of OOP encapsulates the properties (data) and behaviors (methods) of a real-world object into a single entity?
A. Polymorphism
B. Encapsulation
C. Inheritance
D. Abstraction
Q.27 OOP aims to make software development more:
A. Error-prone
B. Flexible
C. Complicated
D. Sequential
Q.28 Which of the following is NOT a basic concept of OOP?
A. Classes
B. Objects
C. Functions
D. Inheritance
Q.29 What does OOP stand for?
A. Object-Oriented Programming
B. Objective Operation Procedure
C. Oriented Object Programming
D. Operational Object Programming
Q.30 Which principle of OOP allows for the same function to be used in different ways?
A. Inheritance
B. Polymorphism
C. Encapsulation
D. Abstraction
Q.31 How can you ensure that a class adheres to the abstraction principle by not allowing instantiation but permitting subclassing?
A. Declare the class as final
B. Declare the class as static
C. Declare the class with private constructors
D. Declare the class as abstract
Q.32 Which of the following changes will make the code below correctly encapsulate the age property?
class Person {
int age; public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
A. Change int age; to private int age;
B. Add static keyword to age
C. Remove the setter method
D. Change public methods to private
Q.33 Given the following code, identify the abstraction technique used:
abstract class Shape {
abstract void draw();
}
class Rectangle extends Shape {
void draw() {
System.out.println(“drawing rectangle”);
}
}
A. Inheritance
B. Encapsulation
C. Polymorphism
D. Abstraction
Q.34 What will be the output of the following Java code snippet?
class Encapsulate {
private int num = 10;
public int getNum() {
return num;
}
} public class Test {
public static void main(String[] args) {
Encapsulate obj = new Encapsulate();
System.out.println(obj.getNum());
}
}
A. 10
B. 0
C. Compilation error
D. Runtime error
Q.35 Which OOP feature provides a way to protect objects from unintended direct field access?
A. Inheritance
B. Polymorphism
C. Encapsulation
D. Abstraction
Q.36 What is the difference between encapsulation and abstraction?
A. Encapsulation is about hiding the details, abstraction is about showing only essential features
B. Encapsulation is a design guideline, whereas abstraction is a programming concept
C. Encapsulation deals with data, and abstraction deals with classes
D. There is no significant difference
Q.37 The process of minimizing the exposure of details from one part of a program to another is known as:
A. Encapsulation
B. Abstraction
C. Polymorphism
D. Inheritance
Q.38 How can encapsulation be achieved in a class?
A. By declaring all variables as static
B. By declaring all class methods as final
C. By making member variables private and providing public getter and setter methods
D. By using abstract classes only
Q.39 What does it mean when a class is declared as abstract?
A. The class cannot be instantiated directly and must be subclassed
B. The class does not contain any methods
C. The class is a final class and cannot have any subclasses
D. The class can only contain static methods
Q.40 In OOP, abstract methods are:
A. Methods that are fully implemented
B. Methods that are declared but not implemented
C. Methods that cannot be overridden
D. Methods that must be static
Q.41 Which keyword in Java is used to hide a class member from classes in other packages?
A. private
B. protected
C. public
D. transient
Q.42 What is the primary purpose of abstraction in OOP?
A. To speed up the execution of programs
B. To reduce code complexity and increase reusability
C. To hide the internal implementation details and only show the features to the users
D. To ensure secure data manipulation without external interference
Q.43 Which of the following best describes encapsulation?
A. Combining data and methods into a single unit
B. Breaking down a complex problem into smaller parts
C. Allowing an object to perform many forms of behavior
D. Hiding the internal state of an object from the outside world
Q.44 In a Java application utilizing interfaces, a new class implements an interface but fails to provide implementations for all declared methods.
What error will this cause?
A. NullPointerException
B. InstantiationException
C. CompilationError
D. ClassCastException
Q.45 A Java program throws a ClassCastException when casting an object of a superclass to a subclass.
What is the most probable reason?
A. The object actually belongs to another unrelated class
B. The object is of the superclass type and cannot be cast down without an explicit check
C. The subclass is abstract
D. None of the above
Q.46 After refactoring a class hierarchy, a method call on a subclass object executes the superclass method instead of the overridden method.
What is the likely cause?
A. The overridden method in the subclass is marked as private
B. The method call is statically bound
C. The subclass method does not correctly override the superclass method due to a signature mismatch
D. None of the above
Q.47 A programmer cannot access a superclass method from a subclass in Java.
What is the most likely reason?
A. The subclass does not extend the superclass
B. The method in the superclass is marked as private
C. The method in the superclass is static
D. None of the above
Q.48 Given two classes, Base and Derived, where Derived extends Base and both classes have a method show() with different implementations.
How is polymorphic behavior achieved when calling show() on a Derived object referenced by a Base type?
A. By marking show() in Base as final
B. By using the static keyword in Derived’s show() method
C. By overriding show() in Derived
D. None of the above
Q.49 What will happen if a subclass in Java tries to override a superclass method marked as final?
A. The subclass method will successfully override the superclass method
B. The compiler will generate an error
C. The superclass method will be hidden
D. None of the above
Q.50 In Java, which method signature indicates that a method is overriding a method from its superclass?
A. A method with the same name but a different return type
B. A method with the same name and parameter list as in the superclass
C. A static method with the same name as in the superclass
D. A method with the same name but different parameter types
Q.51 Given the following Java code, which principle is demonstrated?
interface Flyable {
void fly();
}
class Bird implements Flyable {
public void fly() {
System.out.println(“Bird flies”);
}
}
class Airplane implements Flyable {
public void fly() {
System.out.println(“Airplane flies”);
}
}
A. Inheritance
B. Encapsulation
C. Polymorphism
D. Abstraction
Q.52 What is the output of the following code snippet in Java?
class Animal {
public void sound() {
System.out.println(“Animal sound”);
}
}
class Dog extends Animal {
public void sound() {
System.out.println(“Bark”);
}
}
public class Test {
public static void main(String[] args) {
Animal myAnimal = new Dog();
myAnimal.sound();
}
}
A. “Animal sound”
B. “Bark”
C. Compilation error
D. None of the above
Q.53 Which feature distinguishes interfaces from abstract classes in Java?
A. Interfaces cannot have any method implementations
B. Interfaces can have only final static fields
C. Abstract classes can contain non-final methods
D. Interfaces support multiple inheritance
Q.54 When does the “diamond problem” occur in programming?
A. When multiple interfaces are implemented
B. When a class inherits from two classes with the same method
C. When multiple classes inherit from a single class
D. None of the above
Q.55 Which concept describes the ability of different classes to respond to the same method call in their own unique ways?
A. Encapsulation
B. Inheritance
C. Polymorphism
D. Composition
Q.56 To achieve polymorphism in Java, one must use:
A. Interfaces only
B. Abstract classes only
C. Either interfaces or abstract classes
D. Direct class inheritance only
Q.57 What is an “abstract class” in Java?
A. A class that cannot be instantiated and must be inherited
B. A class that can only contain abstract methods
C. A class without any implementation
D. A final class that cannot be extended
Q.58 Which of the following best describes “dynamic polymorphism”?
A. Compile-time method binding
B. The ability to create dynamic classes at runtime
C. Method overriding where method calls are resolved at runtime
D. The creation of objects at runtime
Q.59 What does the super keyword in Java do?
A. It is used to call superclass methods
B. It defines a superclass
C. It overrides a method in the superclass
D. It creates an instance of a superclass
Q.60 In the context of OOP, what is “method overriding”?
A. Defining a method in a subclass that already exists in the parent class with a different implementation
B. Increasing the visibility of a method in a subclass
C. Changing the return type of a method in a subclass
D. None of the above
Q.61 How do you handle multiple exceptions in a single catch block in Java?
A. By separating exceptions with a comma in the catch block
B. By using the | symbol between exception types in the catch block
C. By listing each exception type in its own catch block
D. By using the & symbol between exception types in the catch block
Q.62 What will be the output of the following Java code?
public class Main {
public static void main(String[] args) {
try { int divideByZero = 5 / 0;
}
catch (ArithmeticException e) {
System.out.println(“Arithmetic Exception caught”);
} finally {
System.out.println(“Finally block executed”);
}
}
}
A. Arithmetic Exception caught
B. Finally block executed
C. Arithmetic Exception caught\nFinally block executed
D. Compilation error
Q.63 What happens if a try block is followed by multiple catch blocks?
A. The first catch block executes regardless of the exception thrown
B. Only the catch block that matches the exception type is executed
C. All catch blocks are executed in the order they appear
D. None of the catch blocks are executed unless they all match the exception
Q.64 In exception handling, which block is used to execute important code such as closing connections, whether an exception occurs or not?
A. try block
B. catch block
C. finally block
D. do block
Q.65 How can a method signal to its caller that it might throw certain types of exceptions?
A. By using the Error keyword
B. By using the throw keyword in its body
C. By including an exception type in its throws clause
D. By catching the exception within the method
Q.66 What is the difference between checked and unchecked exceptions in Java?
A. Checked exceptions are caught at compile time; unchecked exceptions are caught at runtime
B. Checked exceptions are errors; unchecked exceptions are runtime exceptions
C. Checked exceptions must be declared or handled; unchecked exceptions do not need to be declared or handled
D. Checked exceptions are fatal; unchecked exceptions are not fatal
Q.67 Which keyword is used to manually throw an exception in Java?
A. throw
B. throws
C. error
D. exception
Q.68 Which statement is true about the finally block in Java?
A. It runs only if an exception is thrown
B. It always runs, regardless of whether an exception is thrown
C. It is used to throw exceptions
D. It runs only if the exception is caught
Q.69 What is an exception in Java?
A. A type of error that terminates the program
B. A runtime error that can be handled by the program
C. A compile-time error
D. An error that can only occur in development environments
Q.70 A class implements an interface but uses different method signatures than those declared in the interface.
What must be corrected?
A. Change the class’s method signatures to match the interface
B. Change the interface’s method signatures to match the class
C. Make the class methods static
D. None of the above
Q.71 If a package-private class is mistakenly accessed from outside its package, what error is generated?
A. Syntax error
B. Access control error
C. Compilation error
D. Runtime error
Q.72 A Java class fails to compile because it does not provide implementations for all methods of an implemented interface.
What is the most direct solution to this problem?
A. Make the class abstract
B. Remove the interface
C. Implement all missing methods
D. Declare the methods as private
Q.73 A developer mistakenly tries to instantiate an interface directly in Java.
What type of error will this produce?
A. Syntax error
B. Runtime error
C. Compilation error
D. Logical error
Q.74 In the context of Java interfaces, what does it mean for a method to be implicitly public?
A. The method is public by default and does not need the public keyword specified
B. The method can only be accessed within its package
C. The method must be explicitly declared as public
D. None of the above
Q.75 Which of the following correctly declares a package in a Java file?
A. package com.example;
B. package:com.example;
C. Package com.example;
D. import com.example;
Q.76 How do you make a class that is in a different package accessible to your code?
A. Declare the class as public and use the extends keyword
B. Declare the class as public and use the import statement
C. Use the package keyword
D. None of the above
Q.77 Given an interface Animal and classes Dog and Cat that implement Animal, which Java feature allows a method in a different class to accept any Animal type?
A. Overriding
B. Overloading
C. Polymorphism
D. Encapsulation
Q.78 What will be the output of the following interface and class implementation in Java?
interface Speakable {
default void speak() {
System.out.println(“Hello, World!”);
}
}
class Speaker implements Speakable {
public static void main(String[] args) {
new Speaker().speak();
}
}
A. Hello, World!
B. No output, as interfaces cannot have default methods with a body
C. A compilation error as the method is not overridden in the class
D. None of the above
Q.79 How does the protected access modifier work in the context of packages?
A. It allows access from any class within the same package or any subclass outside the package
B. It restricts access to classes within the same package only
C. It allows access from any class in any package
D. None of the above
Q.80 What advantage do packages offer in a Java application?
A. They allow classes to be reused in multiple applications
B. They prevent naming conflicts and control access
C. They increase execution speed
D. They reduce the memory usage of applications
Q.81 In Java, which keyword is used to inherit multiple interfaces?
A. extends
B. implements
C. inherits
D. uses
Q.82 What is a default method in an interface?
A. A method that is automatically invoked by default when an object is created
B. A method that provides a default implementation which can be overridden by implementing classes
C. A static method in an interface
D. A final method in an interface
Q.83 How can a class in one package access a class in another package?
A. By using the import keyword
B. By using the package keyword
C. By using the extends keyword
D. By using the implements keyword
Q.84 Which of the following statements is true about interfaces in Java?
A. An interface can contain static methods that can have a body
B. An interface can contain default methods that have a body
C. Interfaces can have constructors like classes
D. All of the above
Q.85 What is the purpose of a package in Java?
A. To provide access control mechanisms
B. To group related classes and interfaces
C. To speed up the execution time of programs
D. To serve as containers for Java applets and applications
Q.86 What is an interface in Java?
A. A class that is used to implement inheritance
B. A collection of abstract methods and static constants
C. A template for creating objects
D. A method that interfaces with the user
Q.87 A program crashes at runtime when trying to invoke a method on an object that was supposed to be fully initialized.
The likely issue is a failure in applying which concept?
A. Encapsulation leading to improper initialization
B. Abstraction leading to missing method implementations
C. Inheritance leading to overridden method issues
D. Polymorphism leading to incorrect method calls
Q.88 In attempting to refactor code for better encapsulation, a developer accidentally makes all class fields public.
What encapsulation best practice is being violated?
A. Hiding class implementation details
B. Exposing class fields directly
C. Encouraging the use of getter and setter methods
D. All of the above
Q.89 A Java class implements an interface but fails to provide concrete implementations for all interface methods, leading to a compilation error.
Which principle is not being correctly applied?
A. Inheritance
B. Encapsulation
C. Abstraction
D. Polymorphism
Q.90 A developer attempts to access a private field directly from outside its class and encounters a compilation error.
What encapsulation feature is being violated?
A. Direct access to private fields
B. Using public accessor methods
C. Improper use of static fields
D. None of the above
Q.91 Which pattern involves a request being passed along a chain of objects until one of them handles the request?
A. Chain of Responsibility
B. Command
C. State
D. Observer
Q.92 What pattern can be recognized by a structure where objects are represented as tree structures to represent part-whole hierarchies, allowing clients to treat individual objects and compositions uniformly?
A. Composite
B. Flyweight
C. Bridge
D. Prototype
Q.93 In which design pattern is a component wrapped by another component to add new behaviors and responsibilities dynamically?
A. Decorator
B. Composite
C. Adapter
D. Proxy
Q.94 Which pattern is best demonstrated by allowing different parsing strategies for an XML file and a JSON file, which can be switched at runtime?
A. Strategy
B. Observer
C. Decorator
D. Factory
Q.95 What design pattern describes an object that encapsulates how a set of objects interact?
A. Observer
B. Mediator
C. Chain of Responsibility
D. Command
Q.96 In which design pattern do objects represent operations to be performed on elements of another structure, and the visitor pattern allows new operations to be added without changing the elements on which it operates?
A. Observer
B. Strategy
C. Visitor
D. Chain of Responsibility
Q.97 Which design pattern is primarily concerned with reducing the coupling between loosely related interacting objects?
A. Mediator
B. Adapter
C. Facade
D. Bridge
Q.98 What design pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation?
A. Observer
B. Visitor
C. Iterator
D. Composite
Q.99 What is the main purpose of the Factory Method design pattern?
A. To create an instance of several derived classes
B. To ensure a class has only one instance
C. To construct complex objects step by step
D. To allow an object to alter its behavior when its internal state changes
Q.100 Which design pattern is used to create a single instance of a class throughout the application?
A. Factory Method
B. Singleton
C. Prototype
D. Builder
Q.101 Why might adding elements to a HashMap result in those elements not being retrievable even with the correct key?
A. The keys used are mutable and were modified after insertion
B. The HashMap was not properly initialized
C. The get method is called with the wrong type of key
D. The HashMap is full
Q.102 When using a HashSet, a developer notices that it contains duplicate elements.
What is a possible explanation for this behavior?
A. The equals and hashCode methods are not overridden in the elements’ class
B. The HashSet is incorrectly instantiated
C. A LinkedHashSet was used instead, which allows duplicates
D. The elements are of a type that does not support comparison
Q.103 A NullPointerException is thrown when attempting to use a sort method on a List.
What could be the cause?
A. The list is null
B. The list contains null elements
C. The comparator passed to the sort method is null
D. All of the above
Q.104 A developer finds that modifications to a List are not reflected in an iterating loop, causing ConcurrentModificationException.
What common mistake might cause this issue?
A. Modifying the list within a foreach loop iterating over it
B. Using an iterator to modify the list without calling iterator.remove()
C. Iterating over the list with a standard for loop
D. None of the above
Q.105 Given a List containing {1, 2, 3, 4, 5}, which operation transforms the list into {1, 4, 9, 16, 25} (each element squared)?
A. list.replaceAll(i -> i * i);
B. list.stream().map(i -> i * i).collect(Collectors.toList());
C. for (int i = 0; i < list.size(); i++) { list.set(i, list.get(i) * list.get(i)); }
D. All of the above
Q.106 How can you remove all null elements from a Java List?
A. list.removeAll(Collections.singleton(null));
B. while(list.contains(null)) { list.remove(null); }
C. list.filter(Objects::nonNull);
D. for (String s : list) { if (s == null) { list.remove(s); } }
Q.107 Which code snippet correctly iterates over a Map<String, Integer> and prints each key-value pair?
A. for (String key : map.keySet()) { System.out.println(key + ” – ” + map.get(key)); }
B. for (Map.Entry<string, integer=””> entry : map.entries()) { System.out.println(entry.getKey() + ” – ” + entry.getValue()); }</string,>
C. for (Map.Entry<string, integer=””> entry : map.entrySet()) { System.out.println(entry.getKey() + ” – ” + entry.getValue()); }</string,>
D. map.forEach((key, value) -> System.out.println(key + ” – ” + value));
Q.108 What will the following Java code snippet print?
List list = new ArrayList<>();
list.add(“Java”);
list.add(“Python”);
list.add(“Java”);
System.out.println(list.size());
A. 2
B. 3
C. 4
D. None of the above
Q.109 What is the primary advantage of using a LinkedHashMap over a HashMap?
A. LinkedHashMap is more efficient in terms of memory usage
B. LinkedHashMap allows lookup of values by their hash code
C. LinkedHashMap maintains insertion order of its elements
D. LinkedHashMap provides faster access and insertion times
Q.110 In Java, which collection type should you use to ensure elements are sorted in natural order?
A. HashSet
B. LinkedHashSet
C. TreeSet
D. ArrayList
Q.111 How does a HashMap in Java work internally?
A. By using arrays to store elements
B. By using a list to link keys to values
C. By hashing keys and storing entries in buckets based on hash codes
D. By organizing elements in a tree structure
Q.11 2What is the difference between List and Set interfaces in Java?
A. List allows duplicates and is ordered, while Set does not allow duplicates and is unordered
B. List is unordered and does not allow duplicates, while Set is ordered and allows duplicates
C. List and Set both allow duplicates and are ordered
D. List and Set neither allow duplicates nor are ordered
Q.113 Which interface represents a collection of objects where duplicates are not allowed?
A. List
B. Set
C. Map
D. Queue
Q.114 Which of the following is not part of the Java Collections Framework?
A. ArrayList
B. HashSet
C. HashMap
D. Array
Q.115 What is the Java Collections Framework?
A. A framework that provides an architecture to store and manipulate a group of objects
B. A framework for creating collection objects like arrays
C. A Java framework for threading and concurrency
D. A set of classes for date and time manipulation
Q.116 What must be corrected in a try block that compiles but doesn’t catch an exception it was meant to handle?
A. Ensure the exception is of the correct type that the catch block can catch
B. Move the code that does not throw the expected exception outside the try block
C. Replace the try block with a finally block
D. None of the above
Q.117 In debugging a Java program, you notice that an exception is caught, but there’s no information about where it occurred.
What is a good practice to follow in the catch block for better debugging?
A. Throw the exception again
B. Print the exception stack trace using e.printStackTrace()
C. Ignore the exception
D. Log the exception message without the stack trace
Q.118 A developer encounters a NullPointerException.
What is a common cause for this exception?
A. Trying to access a method on a reference that points to null
B. Incorrect syntax in an if-statement
C. Accessing an out-of-bounds index in an array
D. Using an uninitialized variable
Q.119 What is the result of attempting to compile and run the following code snippet?
class MyException extends Exception {}
public class Test {
public static void main(String[] args) {
try {
throw new MyException();
}
catch (MyException me) {
System.out.println(“MyException caught”);
}
catch (Exception e) {
System.out.println(“Exception caught”); }
}
}
A. MyException caught
B. Exception caught
C. Compilation error
D. Runtime error
Q.120 Consider the following code snippet:
try { // code that might throw an exception } catch (Exception e) { System.out.println(e.getMessage()); }.
What does e.getMessage() return?
A. The type of exception thrown
B. A detailed message about the exception thrown
C. The name of the class where the exception occurred
D. The stack trace of where the exception occurred
Q.121 A complex system’s unit tests are running significantly slower after adding new tests for a recently developed feature.
What might be causing the slowdown?
A. The new tests are computationally expensive
B. The tests are improperly sharing state, leading to interference
C. The setup for the new tests is overly complex
D. Excessive mocking or object creation in the new tests
Q.122 After refactoring a class, several related unit tests fail. What is the most likely cause?
A. The refactoring introduced a bug in the code
B. The tests are no longer valid due to the changes in the code
C. Both
D. Neither
Q.123 A unit test unexpectedly fails after recent changes to the codebase.
What is the first step in debugging this failure?
A. Reviewing the test’s output and stack trace for clues
B. Rewriting the test to pass
C. Skipping the test until further notice
D. None of the above
Q.124 What is a common strategy for testing a method that throws an exception under certain conditions?
A. Catching the exception in the test method and asserting its type
B. Using the assertThrows method provided by the testing framework
C. Ignoring the test case
D. None of the above
Q.125 How can you ensure that resources are properly released after a test runs in JUnit?
A. By annotating a cleanup method with @AfterEach
B. By using a try-finally block inside tests
C. By manually calling garbage collection after tests
D. By annotating with @AfterClass
Q.126 In unit testing, what is the purpose of an assertion?
A. To cause the test suite to fail if a condition is not met
B. To mark a test as incomplete or skipped
C. To document the expected behavior of a test
D. None of the above
Q.127 Which JUnit annotation is used to indicate a method should be run before each test method?
A. @BeforeClass
B. @Before
C. @BeforeEach
D. @PreTest
Q.128 How does mocking in unit testing work?
A. By changing the code at runtime to simulate different behaviors
B. By using fake objects to simulate the behavior of real objects in controlled ways
C. By removing parts of the code not relevant to the test
D. None of the above
Q.129 What does Test-Driven Development (TDD) entail?
A. Writing tests after developing the code
B. Writing tests before writing the code to be tested
C. Only writing tests for bugs that have been reported
D. None of the above
Q.130 Which of the following is NOT a characteristic of a good unit test?
A. It runs quickly
B. It requires access to external resources like a database
C. It can be run in isolation
D. It tests a single logical concept in the system
Q.131 What is the primary purpose of unit testing in software development?
A. To validate that each unit of the software performs as designed
B. To check the performance of the software under load
C. To ensure the software meets client requirements
D. To assess the software’s security features
Q.132 When debugging, you find that changes to one part of the system unexpectedly affect another part.
This is likely due to improper use of which OOP concept?
A. Encapsulation
B. Inheritance
C. Polymorphism
D. Global variables
Q.133 A complex system is experiencing issues with changing the behavior of objects at runtime dynamically.
Which OOP concept or pattern could be utilized to simplify dynamic behavior modification?
A. State pattern
B. Strategy pattern
C. Decorator pattern
D. Behavioral pattern
Q.134 Debugging a system, you notice objects are not properly cleaned up, leading to memory leaks.
Which OOP concept can help manage resources more effectively to prevent such issues?
A. Garbage collection
B. Resource management
C. Automatic memory management
D. Resource pooling
Q.135 When applying OOP principles, you encounter a situation where adding new types requires changes to existing code.
Which principle might help reduce the need for such changes?
A. Open/Closed Principle
B. Single Responsibility Principle
C. Liskov Substitution Principle
D. Dependency Inversion Principle
Q.136 What programming technique uses interfaces to expose the behavior of a class and provides a way to access its functionality through a reference?
A. Encapsulation
B. Polymorphism
C. Inversion of Control (IoC)
D. Data binding
Q.137 In the context of advanced OOP, what is aspect-oriented programming (AOP)?
A. A paradigm for modularizing cross-cutting concerns
B. A technique for separating business logic from system services
C. A strategy for enhancing code modularity
D. A method for implementing polymorphism
Q.138 How can reflection be used in Java?
A. To inspect class properties at runtime
B. To modify behavior of methods at runtime
C. To dynamically create objects
D. To invoke methods at runtime
Q.139 Given the concept of polymorphism, which Java feature allows methods to perform different operations based on the object that invokes them?
A. Method overloading
B. Method overriding
C. Dynamic method dispatch
D. Static method binding
Q.140 What is the primary purpose of the Open/Closed Principle in software design?
A. To allow software entities to be extendable
B. To prevent modification of existing code
C. To encourage modular design
D. To support polymorphism
Q.141 How do generics in Java enhance software reusability?
A. By enabling type-safe code
B. By reducing the need for casting
C. By allowing operations on various types
D. By facilitating code maintenance and readability
Q.142 What does the Liskov Substitution Principle (LSP) state?
A. Subclasses should be substitutable for their base classes
B. Objects should be replaceable with instances of their subtypes
C. Both
D. Neither
Q.143 What is the principle of “Separation of Concerns” in software engineering?
A. Dividing a program into distinct sections
B. Improving code readability and maintenance
C. Facilitating parallel development
D. Allowing easier testing and debugging
Q.144 How does the Composite design pattern work in object-oriented design?
A. It allows treating individual objects and compositions uniformly
B. It facilitates object aggregation into tree structures
C. It enables adding new components dynamically
D. It simplifies object cloning
Q.145 In OOP, what is dependency injection?
A. A design pattern where an object supplies the dependencies of another object
B. A technique for creating objects
C. A method for managing software dependencies
D. A programming paradigm for data encapsulation
Q.146 Which concept refers to a class that cannot be instantiated and is designed to be subclassed?
A. Abstract class
B. Interface
C. Singleton
D. Concrete class
Q.147 What concept allows an object to change its behavior when its internal state changes?
A. Inheritance
B. Polymorphism
C. State
D. Strategy
Q.148 A software system’s performance suffers because it creates too many heavy-weight objects.
Which design pattern could be implemented to reduce the number of objects and improve performance?
A. Singleton
B. Flyweight
C. Prototype
D. Builder
Q.149 When debugging a large system of interacting objects, it’s found that changing one object’s state requires changes to others, and the interactions are complex and hard to follow. Which design pattern can help simplify managing these interactions?
A. Observer
B. Mediator
C. Composite
D. Strategy
Q.150 A developer struggles to add new operations to objects without modifying them.
Which design pattern can simplify the addition of new operations?
A. Strategy
B. Visitor
C. Decorator
D. Singleton