✅ [Java Basics] – 25 Real Questions & Answers
1. What is Java and why is it called platform-independent? Answer: Java is a high-level, object-oriented programming language developed by Sun Microsystems. It is called platform-independent because Java code is compiled into bytecode, which can be executed on any platform that has a Java Virtual Machine (JVM), allowing the same code to run anywhere.
2. What is the difference between JDK, JRE, and JVM? Answer:
- JDK (Java Development Kit): Tools for developing Java applications (includes JRE + development tools).
- JRE (Java Runtime Environment): Provides runtime environment (includes JVM + standard libraries).
- JVM (Java Virtual Machine): Executes Java bytecode.
3. Explain the concept of object-oriented programming in Java. Answer: Java is based on OOP principles:
- Encapsulation: Binding data and methods.
- Inheritance: One class inherits from another.
- Polymorphism: One interface, many forms.
- Abstraction: Hiding internal details.
4. What are the different types of memory used by JVM? Answer:
- Heap Memory: Stores objects.
- Stack Memory: Stores method calls and local variables.
- Method Area: Stores class-level data.
- Program Counter Register: Tracks execution line.
- Native Method Stack: Supports native (non-Java) methods.
5. What is the difference between a class and an object in Java? Answer:
- A class is a blueprint for creating objects.
- An object is an instance of a class that contains actual values.
6. What is a constructor in Java? Answer: A constructor is a special method used to initialize objects. It has the same name as the class and no return type. It can be overloaded but not inherited.
7. What is the purpose of the main()
method in Java?
Answer:
It is the entry point for standalone Java applications. Signature:
public static void main(String[] args)
8. What are the primitive data types in Java?
Answer:
There are 8: byte
, short
, int
, long
, float
, double
, char
, and boolean
.
9. What is the difference between ==
and .equals()
?
Answer:
-
==
compares references (memory location). -
.equals()
compares object content (can be overridden).
10. What is the this
keyword in Java?
Answer:
It refers to the current object. It’s used to resolve ambiguity between instance variables and parameters or invoke other constructors.
11. What is method overloading in Java? Answer: When two or more methods in the same class have the same name but different parameters (type, number, or order).
12. What is method overriding? Answer: A subclass provides a specific implementation for a method that is already defined in its parent class.
13. What are static methods and variables? Answer:
- Static variable: Shared among all objects.
- Static method: Can be called without object; belongs to class.
14. What is the final keyword in Java? Answer: It can be used with:
- Variables: Constant value.
- Methods: Cannot be overridden.
- Classes: Cannot be inherited.
15. What is the difference between break
and continue
?
Answer:
-
break
: Terminates the loop. -
continue
: Skips the current iteration and moves to the next.
16. What are wrapper classes in Java?
Answer:
They provide object representations of primitive data types, e.g., Integer
, Double
, Character
.
17. What is autoboxing and unboxing in Java? Answer:
-
Autoboxing: Converting primitive to wrapper (e.g.,
int
→Integer
). -
Unboxing: Wrapper to primitive (e.g.,
Integer
→int
).
18. What is the default value of primitive data types in Java? Answer:
-
int
→ 0,float
→ 0.0,boolean
→ false,char
→ ‘\u0000’, reference types → null.
19. What is a package in Java?
Answer:
A namespace that organizes classes and interfaces. Example: java.util
, java.io
.
20. What is an interface in Java? Answer: A contract that classes implement. Contains abstract methods (Java 8+ allows default and static methods).
21. What is the difference between an interface and an abstract class? Answer:
- Abstract Class: Can have both abstract and concrete methods.
- Interface: Only abstract methods (prior to Java 8), no constructors or state.
22. What is type casting in Java? Answer: Changing the data type from one to another:
-
Implicit (widening):
int
→float
. -
Explicit (narrowing):
double
→int
.
23. What is the role of the instanceof
operator?
Answer:
It checks if an object is an instance of a specific class or subclass:
if(obj instanceof String) { ... }
24. What is the purpose of the import
statement?
Answer:
It allows access to classes from other packages:
import java.util.Scanner;
25. How do you compile and run a Java program from the command line? Answer:
javac MyProgram.java
java MyProgram
✅ [Java OOPS] – 25 Real Questions & Answers
1. What is Object-Oriented Programming (OOP)? Answer: OOP is a programming paradigm based on the concept of objects, which can contain data (fields) and code (methods). Java uses four main OOP principles: Encapsulation, Inheritance, Polymorphism, and Abstraction.
2. What is encapsulation in Java? Answer: Encapsulation is the practice of hiding internal data and only exposing it via public methods (getters/setters). It enhances security and modularity.
3. What is inheritance in Java?
Answer:
Inheritance allows one class (child/subclass) to acquire the properties and behavior of another class (parent/superclass) using the extends
keyword.
4. What is polymorphism in Java? Answer: Polymorphism allows one interface to be used for a general class of actions. It is of two types:
- Compile-time (method overloading)
- Runtime (method overriding)
5. What is abstraction in Java? Answer: Abstraction means hiding implementation details and showing only essential features. It’s achieved using abstract classes and interfaces.
6. What is an abstract class? Answer: An abstract class cannot be instantiated. It can have both abstract (no body) and concrete (with body) methods. Used when base functionality is shared but needs customization.
7. What is the difference between an interface and an abstract class? Answer:
- Interface: No constructors, all methods are abstract (until Java 7); can have default/static methods (Java 8+).
- Abstract class: Can have constructors, fields, and method implementations.
8. Can Java support multiple inheritance? Answer: Java does not support multiple inheritance with classes to avoid ambiguity. But it supports it using interfaces.
9. What is method overloading? Answer: Method overloading allows multiple methods with the same name but different parameters in the same class.
10. What is method overriding? Answer: Method overriding occurs when a subclass provides a specific implementation for a method already defined in its superclass.
11. What is the difference between overloading and overriding? Answer:
- Overloading: Same class, compile-time, different method signatures.
- Overriding: Subclass modifies superclass method, runtime polymorphism.
12. What is the purpose of the super
keyword?
Answer:
- Access superclass constructor:
super()
- Access superclass methods/fields overridden in subclass.
13. What is the final
keyword in the context of OOP?
Answer:
- Final variable: constant.
- Final method: cannot be overridden.
- Final class: cannot be extended.
14. What is a constructor, and how is it different from a method? Answer: A constructor initializes an object and has no return type. A method defines behavior and has a return type. Constructor name = class name.
15. What is constructor overloading? Answer: It is the ability to define multiple constructors with different parameter lists in a class.
16. What are default and parameterized constructors? Answer:
- Default constructor: No parameters.
- Parameterized constructor: Takes arguments to initialize fields.
17. What is the use of instanceof
in OOP?
Answer:
It checks if an object belongs to a specific class or subclass:
if (obj instanceof Employee) { ... }
18. Can a constructor be private in Java? Answer: Yes. Used in Singleton Pattern or to prevent instantiation from outside the class.
19. What is dynamic method dispatch? Answer: It’s the process where the call to an overridden method is resolved at runtime, enabling runtime polymorphism.
20. What is the difference between IS-A and HAS-A relationships? Answer:
- IS-A: Inheritance (Dog IS-A Animal).
- HAS-A: Composition (Car HAS-A Engine).
21. Can we override static methods? Answer: No. Static methods are class-level and resolved at compile-time, not runtime.
22. Can we override private methods? Answer: No. Private methods are not visible to subclasses, hence cannot be overridden.
23. What happens if a subclass constructor does not call super()
?
Answer:
The compiler automatically inserts a no-arg super()
call if not explicitly specified. If the superclass doesn’t have a no-arg constructor, compilation fails.
24. What is an inner class in Java? Answer: A class defined within another class. Types:
- Static nested class
- Non-static inner class
- Local inner class
- Anonymous inner class
25. What is the object class in Java?
Answer:
All classes in Java implicitly extend the Object
class. It provides default methods like toString()
, equals()
, hashCode()
, clone()
, and finalize()
.
✅ [Java IO] – 25 Real Questions & Answers
1. What is Java I/O?
Answer:
Java I/O (Input/Output) is a set of APIs used to read data from input sources (keyboard, files, network) and write data to output destinations (console, files, network). It includes packages like java.io
, java.nio
, and java.util.Scanner
.
2. What is the difference between byte streams and character streams? Answer:
-
Byte Streams: Handle binary data (e.g.,
FileInputStream
,FileOutputStream
). -
Character Streams: Handle character data (e.g.,
FileReader
,FileWriter
). Useful for text files with character encoding.
3. What is InputStream
and OutputStream
in Java?
Answer:
-
InputStream
: Abstract class for reading raw byte data. -
OutputStream
: Abstract class for writing byte data. Common implementations:FileInputStream
,BufferedOutputStream
.
4. What is Reader
and Writer
in Java?
Answer:
-
Reader
: Abstract class for reading character streams. -
Writer
: Abstract class for writing character streams. Examples:BufferedReader
,PrintWriter
.
5. What is the use of BufferedReader
and BufferedWriter
?
Answer:
They buffer the input/output to improve efficiency by reducing I/O operations with the underlying system.
6. What is the role of File
class in Java?
Answer:
The java.io.File
class represents the pathname of a file or directory and provides methods to create, delete, and check file/directory properties.
7. How do you read a file in Java using BufferedReader
?
Answer:
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
8. What is the purpose of FileInputStream
and FileOutputStream
?
Answer:
Used for reading/writing raw binary data (images, audio files, etc.) from/to a file.
9. What are DataInputStream
and DataOutputStream
?
Answer:
They are used to read/write Java primitive data types in a portable way using binary streams.
10. How do you write to a file using FileWriter
?
Answer:
FileWriter fw = new FileWriter("output.txt");
fw.write("Hello, World!");
fw.close();
11. What is serialization in Java?
Answer:
Serialization is the process of converting an object into a byte stream to save it to a file or transmit it. The object must implement Serializable
.
12. How do you serialize an object in Java? Answer:
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser"));
out.writeObject(myObject);
out.close();
13. What is deserialization in Java?
Answer:
The reverse of serialization—converting a byte stream back into a Java object using ObjectInputStream
.
14. What is the transient
keyword in serialization?
Answer:
It marks a field to be skipped during serialization. It won’t be persisted in the byte stream.
15. What happens if a superclass is not serializable but the subclass is? Answer: Only the fields of the subclass are serialized. Superclass fields must be initialized via a constructor during deserialization.
16. What is the PrintWriter
class used for?
Answer:
It’s used to write formatted text to a file or output stream. Supports methods like println()
, print()
, etc.
17. What is the difference between flush()
and close()
?
Answer:
-
flush()
: Forces any buffered output to be written. -
close()
: Closes the stream and also flushes it.
18. How do you read a file using Scanner
?
Answer:
Scanner sc = new Scanner(new File("file.txt"));
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
sc.close();
19. What is the purpose of PushbackReader
and PushbackInputStream
?
Answer:
They allow characters/bytes to be pushed back into the stream, useful in parsers for lookahead operations.
20. How do you check if a file exists in Java? Answer:
File file = new File("data.txt");
if (file.exists()) {
System.out.println("File found!");
}
21. What is RandomAccessFile
in Java?
Answer:
Allows read and write at random positions in a file. Supports seek()
to move the file pointer.
22. What exception must be handled during file I/O?
Answer:
IOException
must be caught or declared using throws
.
23. How can you create directories in Java? Answer:
new File("folder").mkdir();
new File("parent/child").mkdirs(); // creates nested dirs
24. How do you delete a file in Java? Answer:
File file = new File("file.txt");
file.delete();
25. What is NIO in Java? How is it different from IO?
Answer:
NIO (New I/O) uses channels and buffers for non-blocking, high-performance I/O operations. It’s faster and scalable compared to traditional java.io
.
✅ [Java Utils (java.util package)] – 25 Real Questions & Answers
1. What is the java.util
package in Java?
Answer:
java.util
is a core utility package that contains data structures, date/time utilities, collections framework classes, and helper classes like Scanner
, Random
, and Arrays
.
2. What is the Scanner
class used for?
Answer:
Scanner
is used to read input from various sources like the console, files, or strings using methods like next()
, nextLine()
, nextInt()
, etc.
3. How do you generate random numbers in Java?
Answer:
Using the Random
class:
Random rand = new Random();
int num = rand.nextInt(100); // 0 to 99
4. What is the purpose of the Date
class?
Answer:
Date
represents a specific instant in time. It is used for date/time manipulation, but mostly deprecated in favor of java.time
.
5. What is the Calendar
class in Java?
Answer:
An abstract class that provides methods to convert between time and calendar fields (like YEAR, MONTH). Use Calendar.getInstance()
to get the current date/time.
6. What is the Arrays
utility class?
Answer:
Provides static methods to operate on arrays: sorting, searching, filling, copying, and printing:
Arrays.sort(arr);
Arrays.toString(arr);
7. What is the difference between ArrayList
and LinkedList
?
Answer:
-
ArrayList
: Backed by array; faster for random access. -
LinkedList
: Doubly-linked list; better for frequent insert/delete operations.
8. How do you sort an array in Java using Arrays
?
Answer:
int[] arr = {5, 2, 9};
Arrays.sort(arr);
9. What is the use of Collections
utility class?
Answer:
Provides static methods to work on collections: sort()
, reverse()
, shuffle()
, min()
, max()
, frequency()
.
10. How do you reverse a list in Java? Answer:
Collections.reverse(myList);
11. What is the difference between Collections
and Collection
?
Answer:
-
Collection
: An interface (root of Collection framework). -
Collections
: A utility class with static helper methods.
12. How do you shuffle elements in a list? Answer:
Collections.shuffle(list);
13. What is the Properties
class used for?
Answer:
Stores key-value pairs as Strings. Used for configuration files:
Properties prop = new Properties();
prop.setProperty("user", "admin");
14. What is a Hashtable
in Java?
Answer:
An older thread-safe Map implementation. Does not allow null
key/value. Replaced by ConcurrentHashMap
.
15. How do you create an immutable list? Answer:
List<String> list = Collections.unmodifiableList(myList);
16. What is EnumSet
?
Answer:
A high-performance Set implementation for use with enum types only. All elements must come from a single enum type.
17. What is the purpose of Optional
in Java 8+?
Answer:
A container object to avoid NullPointerException
. Represents a value that may or may not be present.
18. How can you convert an array to a list? Answer:
String[] arr = {"A", "B"};
List<String> list = Arrays.asList(arr);
19. How do you find the frequency of an element in a list? Answer:
Collections.frequency(list, "apple");
20. What is Queue
in Java?
Answer:
A Queue
is a collection for holding elements prior to processing. Implemented by classes like LinkedList
and PriorityQueue
.
21. What is Deque
in Java?
Answer:
A double-ended queue that supports element insertion and removal from both ends. Example: ArrayDeque
.
22. What is the PriorityQueue
class?
Answer:
Implements a min-heap queue where elements are ordered according to their natural ordering or comparator.
23. How do you synchronize a list in Java? Answer:
List<String> syncList = Collections.synchronizedList(new ArrayList<>());
24. What is the BitSet
class?
Answer:
Efficient representation of bits using array of bits (0 or 1). Used in situations like flag handling or compact storage.
25. What is the Stack
class in java.util
?
Answer:
A subclass of Vector
that implements a LIFO (Last In First Out) stack. It has methods like push()
, pop()
, peek()
.
✅ [Java Collections Framework] – 50 Real Questions & Answers
1. What is the Java Collections Framework (JCF)?
Answer:
JCF is a unified architecture for storing and manipulating collections. It includes interfaces (List
, Set
, Map
, Queue
) and their implementations (ArrayList
, HashSet
, HashMap
, etc.).
2. What is the root interface of the Java Collections Framework?
Answer:
java.util.Collection
is the root interface for most collections, except Map
.
3. What is the difference between Collection
and Collections
?
Answer:
-
Collection
: Interface for collection types. -
Collections
: Utility class with static methods (e.g.,sort()
,reverse()
).
4. What are the main interfaces in JCF?
Answer:
Collection
, List
, Set
, SortedSet
, NavigableSet
, Queue
, Deque
, Map
, SortedMap
, NavigableMap
.
5. What is the difference between List
, Set
, and Map
?
Answer:
-
List
: Ordered, allows duplicates (e.g.,ArrayList
). -
Set
: Unordered, no duplicates (e.g.,HashSet
). -
Map
: Key-value pairs, keys are unique (e.g.,HashMap
).
6. What is the difference between ArrayList
and LinkedList
?
Answer:
-
ArrayList
: Fast random access, slower insert/delete. -
LinkedList
: Slow access, faster insert/delete at ends.
7. What is the default capacity of an ArrayList
?
Answer:
The default capacity is 10. It grows by 50% when resized.
8. What is a Vector
in Java?
Answer:
A legacy synchronized version of ArrayList
. Slower due to synchronization overhead.
9. What is the difference between HashSet
and TreeSet
?
Answer:
-
HashSet
: Unordered, faster, uses hashing. -
TreeSet
: Sorted, slower, uses red-black tree.
10. Can a Set
contain duplicate elements?
Answer:
No. Set
implementations automatically eliminate duplicates.
11. How does HashSet
work internally?
Answer:
Uses a HashMap
under the hood. Elements are stored as keys in the map with dummy values.
12. What is the load factor in a HashMap
?
Answer:
The default load factor is 0.75, which determines when to resize the internal array.
13. What is hashing?
Answer:
A technique to convert a key into an index using a hash function. It’s used in HashMap
, HashSet
.
14. What is the role of equals()
and hashCode()
in collections?
Answer:
-
equals()
checks logical equality. -
hashCode()
determines the bucket in hash-based collections. Both must be consistent for correct behavior.
15. What is TreeMap
in Java?
Answer:
A sorted map implementation using red-black tree. Keys are sorted in natural or custom comparator order.
16. What is the difference between HashMap
and TreeMap
?
Answer:
-
HashMap
: Unordered, faster. -
TreeMap
: Sorted, slower.
17. Can HashMap
have null keys and values?
Answer:
Yes, it allows onenull
key and multiple null
values.
18. What is LinkedHashMap
?
Answer:
Maintains insertion order using a doubly linked list. Slightly slower than HashMap
.
19. What is ConcurrentHashMap
?
Answer:
A thread-safe alternative to HashMap
. It uses bucket-level locking for better concurrency.
20. What is the difference between Hashtable
and HashMap
?
Answer:
-
Hashtable
: Synchronized, legacy. -
HashMap
: Not synchronized, modern replacement.
21. What is the use of Queue
interface?
Answer:
Represents a collection for holding elements before processing. Follows FIFO order.
22. What is the difference between Queue
and Deque
?
Answer:
-
Queue
: FIFO structure. -
Deque
: Double-ended queue, supports insert/delete at both ends.
23. What is PriorityQueue
?
Answer:
A queue where elements are ordered based on their priority (natural or comparator). Implements a binary heap.
24. What is the difference between poll()
and remove()
in Queue
?
Answer:
-
poll()
: Returnsnull
if queue is empty. -
remove()
: ThrowsNoSuchElementException
.
25. What are fail-fast and fail-safe iterators? Answer:
-
Fail-fast: Throw
ConcurrentModificationException
if modified during iteration (e.g.,ArrayList
). -
Fail-safe: Don’t throw exception (e.g.,
CopyOnWriteArrayList
).
26. What is Iterator
in Java?
Answer:
Used to iterate over collections. Provides hasNext()
, next()
, and remove()
.
27. What is the difference between Iterator
and ListIterator
?
Answer:
ListIterator
supports bidirectional iteration and allows modification during iteration.
28. How do you sort a list of objects in Java?
Answer:
Using Collections.sort(list)
or list.sort(Comparator)
.
29. What is the difference between Comparable
and Comparator
?
Answer:
-
Comparable
: Natural ordering, implemented in the class. -
Comparator
: External ordering, implemented separately.
30. What is EnumMap
in Java?
Answer:
A Map
optimized for enum keys. Fast and memory-efficient.
31. What is the IdentityHashMap
?
Answer:
A hash map that uses ==
instead of equals()
to compare keys.
32. What is WeakHashMap
?
Answer:
A HashMap
where keys are weak references, allowing garbage collection if no strong reference exists.
33. What is NavigableMap
?
Answer:
An extension of SortedMap
with navigation methods like lowerKey()
, floorKey()
, ceilingKey()
.
34. What is TreeSet
backed by?
Answer:
Internally backed by a TreeMap
.
35. How to synchronize a collection?
Answer:
Using Collections.synchronizedXXX()
:
List list = Collections.synchronizedList(new ArrayList<>());
36. How do you convert a List
to a Set
?
Answer:
List<String> list = ...;
Set<String> set = new HashSet<>(list);
37. What is a singleton collection? Answer: A collection containing only one element:
Collections.singletonList("one");
38. What is the difference between deep copy and shallow copy in collections? Answer:
- Shallow copy: Copies object references.
- Deep copy: Duplicates the objects themselves.
39. How do you iterate over a Map
?
Answer:
for (Map.Entry<K, V> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
40. What is the difference between Set
and SortedSet
?
Answer:
-
Set
: Unordered, unique elements. -
SortedSet
: Maintains sorted order.
41. What is a CopyOnWriteArrayList
?
Answer:
A thread-safe list where all mutative operations create a new copy, ideal for read-heavy applications.
42. How do you make a list immutable in Java 9+? Answer:
List<String> list = List.of("a", "b", "c");
43. Can a List
contain null
elements?
Answer:
Yes, unless it’s a special implementation like CopyOnWriteArrayList
which may restrict it.
44. What is the purpose of Spliterator
?
Answer:
Supports parallel processing and functional-style traversal of collections.
45. What is a BlockingQueue
?
Answer:
Used in multithreading to safely enqueue/dequeue items with blocking support. Example: ArrayBlockingQueue
.
46. What is a Deque
?
Answer:
A double-ended queue. Implemented by ArrayDeque
, LinkedList
.
47. What is the internal data structure of HashMap
?
Answer:
Array of buckets using a combination of linked lists and balanced trees (Java 8+).
48. What happens on HashMap
collision?
Answer:
Entries are stored in a linked list or tree if hash codes match.
49. How does TreeSet
ensure ordering?
Answer:
Uses a Comparator
or Comparable
to maintain a red-black tree structure.
50. Can a Map
have duplicate values?
Answer:
Yes. Keys must be unique, but values can be duplicated.
✅ [Java 8 Features] – 50 Real Questions & Elaborate Answers (Set 1 of 2)
1. What are the main features introduced in Java 8? Answer: Java 8 was a revolutionary release that introduced several features aimed at supporting functional programming and improving developer productivity. Key features include:
- Lambda Expressions: Enables writing anonymous functions in a concise way.
- Functional Interfaces: Interfaces with a single abstract method, used with lambdas.
- Stream API: Enables processing sequences of elements with operations like filter, map, reduce.
- Default and Static Methods in Interfaces: Allows methods with body in interfaces to support backward compatibility.
- Optional Class: Avoids null pointer exceptions by wrapping a value that may or may not be present.
- New Date/Time API (java.time): Modern, immutable, and thread-safe date/time handling.
- Nashorn JavaScript Engine: A lightweight runtime to execute JavaScript code inside the JVM.
- Method References & Constructor References: Shorter syntax for invoking methods/functions.
2. What is a Lambda Expression in Java 8? Give an example. Answer: A lambda expression is a concise way to represent an anonymous function. It allows you to pass behavior as a parameter. The syntax is:
(parameters) -> expression_or_block
Example:
List<String> names = Arrays.asList("John", "Jane", "Adam");
names.forEach(name -> System.out.println(name));
This simplifies the need for verbose anonymous classes and makes code more readable.
3. What is a Functional Interface? Answer: A functional interface is an interface that contains only one abstract method. These interfaces can have any number of default or static methods. They are meant to be used with lambda expressions. Example:
@FunctionalInterface
interface MyFunctional {
void doSomething();
}
Java 8 includes several built-in functional interfaces in the java.util.function
package like Predicate
, Function
, Consumer
, and Supplier
.
4. What is the Stream API in Java 8? Answer: The Stream API enables functional-style operations on sequences of data. It supports operations like map, filter, reduce, collect, and more. It simplifies processing collections using a declarative approach instead of loops. Example:
List<String> list = Arrays.asList("apple", "banana", "orange");
list.stream()
.filter(s -> s.startsWith("a"))
.forEach(System.out::println); // prints "apple"
Streams can be sequential or parallel, and they do not store data; they only process it.
5. What is the difference between map()
and flatMap()
in Streams?
Answer:
-
map()
transforms each element and wraps the result in a stream (one-to-one mapping). -
flatMap()
flattens nested streams into a single stream (one-to-many mapping). Example:
List<List<String>> listOfLists = Arrays.asList(Arrays.asList("a", "b"), Arrays.asList("c", "d"));
List<String> flatList = listOfLists.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
This flattens the list of lists into a single list: ["a", "b", "c", "d"]
.
6. What is a Default Method in an Interface? Answer: Java 8 allows interfaces to have default methods (methods with a body). This enables the addition of new methods to interfaces without breaking existing implementations. Example:
interface Vehicle {
default void start() {
System.out.println("Starting...");
}
}
Classes implementing Vehicle
don’t have to override start()
unless they want to change the behavior.
7. What is a Static Method in an Interface? Answer: Java 8 also allows static methods in interfaces. These methods can only be called on the interface itself, not on an instance. Example:
interface Utility {
static int add(int a, int b) {
return a + b;
}
}
int result = Utility.add(5, 3);
This helps in grouping helper methods logically.
8. What is the Optional class in Java 8 and how does it help?
Answer:
The Optional
class is a container object used to avoid NullPointerException
. It represents a value that may or may not be present.
Example:
Optional<String> name = Optional.ofNullable(getName());
name.ifPresent(System.out::println);
Methods like isPresent()
, ifPresent()
, orElse()
, orElseGet()
, and orElseThrow()
provide safe and expressive null-handling.
9. What are Method References in Java 8?
Answer:
Method references provide a shorthand for calling methods via lambdas.
Syntax: ClassName::methodName
Types:
-
Static method →
ClassName::staticMethod
-
Instance method of a particular object →
object::instanceMethod
-
Instance method of an arbitrary object →
ClassName::instanceMethod
Example:
List<String> list = Arrays.asList("a", "b");
list.forEach(System.out::println); // same as s -> System.out.println(s)
10. What is a Predicate in Java 8?
Answer:
Predicate<T>
is a functional interface that represents a boolean-valued function of one argument. It is used for filtering.
Example:
Predicate<String> isLong = s -> s.length() > 5;
System.out.println(isLong.test("HelloWorld")); // true
It contains default methods like and()
, or()
, and negate()
for composing complex conditions.
✅ [Java 8 Features] – 40 Real Questions & Elaborate Answers (Set 2 of 2)
11. What is a Consumer in Java 8?
Answer:
Consumer<T>
is a functional interface that represents an operation that accepts a single input argument and returns no result. It is typically used to perform an action on an object.
Example:
Consumer<String> printer = s -> System.out.println(s.toUpperCase());
printer.accept("java"); // prints JAVA
12. What is a Supplier in Java 8?
Answer:
Supplier<T>
represents a function that provides a result without taking any input. It is often used for lazy initialization.
Example:
Supplier<Double> randomValue = () -> Math.random();
System.out.println(randomValue.get());
13. What is the Function interface in Java 8?
Answer:
Function<T, R>
represents a function that takes one input of type T and returns a result of type R.
Example:
Function<String, Integer> lengthFunction = s -> s.length();
System.out.println(lengthFunction.apply("Java")); // prints 4
14. What is a BiFunction in Java 8?
Answer:
BiFunction<T, U, R>
takes two input arguments and returns a result. It’s useful for operations combining two values.
Example:
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
System.out.println(add.apply(3, 4)); // 7
15. What is a UnaryOperator in Java 8?
Answer:
UnaryOperator<T>
is a specialization of Function<T, T>
which accepts and returns the same type.
Example:
UnaryOperator<String> toUpper = String::toUpperCase;
System.out.println(toUpper.apply("java")); // JAVA
16. What is a BinaryOperator in Java 8?
Answer:
BinaryOperator<T>
is a specialization of BiFunction<T, T, T>
for same-type operands and return values.
Example:
BinaryOperator<Integer> multiply = (a, b) -> a * b;
System.out.println(multiply.apply(2, 3)); // 6
17. What are intermediate and terminal operations in streams? Answer:
-
Intermediate operations: Return a new stream (e.g.,
map()
,filter()
,sorted()
), lazy and don’t process elements until a terminal operation is invoked. -
Terminal operations: Trigger the actual stream processing (e.g.,
collect()
,forEach()
,reduce()
).
18. What is the reduce()
operation in Java Streams?
Answer:
reduce()
combines stream elements into a single result. It takes a binary operator:
int sum = Stream.of(1, 2, 3).reduce(0, Integer::sum); // returns 6
19. How do you convert a stream to a list or set?
Answer:
Use Collectors
:
List<String> list = stream.collect(Collectors.toList());
Set<String> set = stream.collect(Collectors.toSet());
20. What is Collectors.groupingBy()
?
Answer:
Groups stream elements by a classifier function:
Map<Integer, List<String>> groupedByLength =
list.stream().collect(Collectors.groupingBy(String::length));
21. What is Collectors.joining()
?
Answer:
Concatenates elements into a single String
:
String result = Stream.of("A", "B", "C").collect(Collectors.joining(","));
22. What is Collectors.partitioningBy()
?
Answer:
Partitions data into two groups based on a predicate:
Map<Boolean, List<Integer>> partitioned =
Stream.of(1, 2, 3, 4, 5).collect(Collectors.partitioningBy(n -> n % 2 == 0));
23. How can you use filter()
with streams?
Answer:
filter()
is used to retain only elements that match a predicate:
Stream.of("apple", "banana", "cherry")
.filter(s -> s.startsWith("a"))
.forEach(System.out::println); // apple
24. What is short-circuiting in Streams?
Answer:
Operations like anyMatch()
, allMatch()
, limit()
can terminate stream processing early, improving performance.
25. What is lazy evaluation in Java Streams? Answer: Stream operations are not executed until a terminal operation is invoked. This allows chaining without immediate computation.
26. What are parallel streams in Java 8? Answer: Parallel streams split the source into multiple parts and process them concurrently, using ForkJoinPool.
list.parallelStream().forEach(System.out::println);
27. How do you sort a stream? Answer:
list.stream().sorted().forEach(System.out::println);
Or with a custom comparator:
list.stream().sorted(Comparator.reverseOrder())
28. What is peek()
used for in streams?
Answer:
peek()
is used for debugging or logging during intermediate operations:
list.stream().peek(System.out::println).collect(Collectors.toList());
29. Can streams be reused? Answer: No. Once a terminal operation is called, the stream is consumed and cannot be reused. You must recreate it.
30. How does flatMap()
differ from map()
in structure?
Answer:
-
map()
creates a stream of streams. -
flatMap()
flattens nested streams into a single stream.
31. What is findFirst()
in Java Streams?
Answer:
Returns an Optional
with the first element of the stream, if present:
Optional<String> result = list.stream().findFirst();
32. What is findAny()
in Java Streams?
Answer:
Returns any element from the stream (useful for parallel streams):
Optional<String> result = list.stream().findAny();
33. How do you handle null values in streams?
Answer:
Use filter(Objects::nonNull)
to eliminate nulls:
stream.filter(Objects::nonNull)
34. What is the benefit of the new java.time
API in Java 8?
Answer:
The java.time
API (JSR 310) is:
- Immutable
- Thread-safe
- ISO-compliant
- Easier to use than
Date
andCalendar
Classes include LocalDate
, LocalTime
, LocalDateTime
, Period
, Duration
, etc.
35. How do you create a LocalDate in Java 8? Answer:
LocalDate date = LocalDate.of(2023, Month.MARCH, 5);
LocalDate today = LocalDate.now();
36. What is the Period
class in Java 8?
Answer:
Represents a time-based amount in terms of years, months, and days.
Period period = Period.between(LocalDate.of(2020, 1, 1), LocalDate.now());
37. What is the Duration
class in Java 8?
Answer:
Represents a time-based amount in seconds and nanoseconds. Suitable for measuring time intervals.
Duration duration = Duration.ofMinutes(5);
38. What is the Instant
class in Java 8?
Answer:
Represents a moment on the timeline (timestamp), useful for machine time:
Instant now = Instant.now();
39. What is DateTimeFormatter
?
Answer:
Used for parsing and formatting date-time objects:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String date = LocalDate.now().format(formatter);
40. What is the Stream.generate()
method used for?
Answer:
Used to create infinite streams using a Supplier
:
Stream<String> stream = Stream.generate(() -> "Hello").limit(3);
stream.forEach(System.out::println); // prints Hello 3 times
✅ [Java Lang Package] – 50 Real Questions & Detailed Answers
1. What is the java.lang
package? Why is it important?
Answer:
The java.lang
package is a fundamental package that is automatically imported in every Java program. It contains essential classes that are frequently used such as:
-
Object
,String
,Math
,System
,Thread
,Runnable
,Exception
,Throwable
,Enum
, etc. Because of its foundational role, it enables core language constructs like class inheritance, exception handling, and thread management.
2. What is the Object
class in Java?
Answer:
The Object
class is the root class of the Java class hierarchy. Every class implicitly extends Object
, and it provides several fundamental methods like:
-
equals()
: Logical comparison -
hashCode()
: Used in hashing data structures -
toString()
: String representation -
clone()
: Creates a copy of the object -
getClass()
: Returns the class metadata -
finalize()
: Cleanup before GC (deprecated)
3. How does equals()
differ from ==
in Java?
Answer:
-
==
checks reference equality (memory address). -
equals()
checks logical/content equality. For example:
String s1 = new String("Java");
String s2 = new String("Java");
s1 == s2 // false (different objects)
s1.equals(s2) // true (same content)
4. What is the hashCode()
method and why is it important?
Answer:
hashCode()
returns an integer hash value for an object. It is used by hash-based collections like HashMap
, HashSet
.
Contract: If two objects are equal (equals()
), they must have the same hash code. Violating this can lead to incorrect behavior in collections.
5. Can you override equals()
and hashCode()
? Why would you do that?
Answer:
Yes. You override these when you want two objects with the same data to be treated as equal. This is important when you use objects in collections like HashSet
or as keys in HashMap
.
6. What is the toString()
method used for?
Answer:
toString()
returns a string representation of an object. It’s automatically called when an object is printed:
System.out.println(obj); // calls obj.toString()
You should override it for meaningful output.
7. What is the Class
class in Java?
Answer:
Class
represents metadata about classes and interfaces. It is used in reflection, allowing dynamic inspection:
Class<?> clazz = MyClass.class;
Method[] methods = clazz.getDeclaredMethods();
8. What is the System
class in Java?
Answer:
A utility class that provides access to system-related functionality. Common uses:
-
System.out.println()
-
System.currentTimeMillis()
-
System.gc()
-
System.exit()
9. What is the Runtime
class in Java?
Answer:
Runtime
allows the Java application to interact with the JVM runtime environment. It can:
- Get memory details
- Run system commands
- Trigger garbage collection
Example:
Runtime.getRuntime().exec("notepad.exe");
10. What is the difference between Runtime.gc()
and System.gc()
?
Answer:
Both suggest the JVM to perform garbage collection. System.gc()
is a static wrapper that internally calls Runtime.getRuntime().gc()
.
11. What is the Throwable
class?
Answer:
Throwable
is the superclass of all errors and exceptions. Its subclasses are:
-
Error
(e.g.,OutOfMemoryError
) -
Exception
(e.g.,IOException
)
12. What is the difference between Exception
and Error
?
Answer:
-
Exception
: Recoverable problems (e.g., file not found). -
Error
: Serious, non-recoverable problems (e.g., JVM crash).
13. What is the String
class in Java?
Answer:
String
represents a sequence of characters and is immutable. It is the most commonly used class in Java.
14. What is String immutability and why is it important?
Answer:
Once a String
is created, its value cannot be changed. New strings are created for modifications.
It ensures thread-safety and allows string pooling for performance optimization.
15. What is the String Pool? Answer: It is a special memory region where unique string literals are stored. If two strings have the same content and are declared as literals, they refer to the same object.
16. What are some useful methods in the String
class?
Answer:
-
charAt()
-
length()
-
substring()
-
indexOf()
-
equals()
,equalsIgnoreCase()
-
split()
-
replace()
-
toLowerCase()
,toUpperCase()
17. How is String concatenation handled in Java?
Answer:
Using +
or concat()
. Internally, Java uses StringBuilder
for performance:
String result = "Hello" + "World"; // optimized as StringBuilder
18. What is the StringBuilder
class?
Answer:
A mutable alternative to String
. Used to create and manipulate strings without creating new objects on each modification. It is not thread-safe but faster.
19. What is the StringBuffer
class?
Answer:
Like StringBuilder
but thread-safe. Use it when multiple threads need to modify the same string.
20. What is the Math
class used for?
Answer:
Provides mathematical operations like:
-
abs()
,sqrt()
,pow()
,max()
,min()
,random()
,floor()
,ceil()
21. What is autoboxing and unboxing in Java? Answer:
- Autoboxing: Converts primitive to wrapper.
Integer i = 10; // int → Integer
- Unboxing: Wrapper to primitive.
int j = i; // Integer → int
22. What is the Number
class in Java?
Answer:
An abstract class that is a superclass of wrapper classes like Integer
, Double
, Float
. Provides methods like intValue()
, doubleValue()
.
23. What is the Enum
class?
Answer:
Used to define a collection of constant values:
enum Day { MON, TUE, WED }
Enums are type-safe, can have fields, methods, and constructors.
24. What is the Character
class?
Answer:
A wrapper class for char
primitive. Provides methods like isDigit()
, isLetter()
, toUpperCase()
.
25. What is the Boolean
class?
Answer:
A wrapper class for boolean
. Provides parsing and string conversion.
26. What is the Byte
class in Java?
Answer:
Byte
is a wrapper class for the primitive type byte
. It provides utility methods for converting byte values to other primitive types or strings, and vice versa. It is often used in collections when objects (not primitives) are required.
27. What is the Short
class in Java?
Answer:
Short
is the wrapper class for short
. Like Byte
and Integer
, it provides type conversion methods and is used where objects are needed instead of primitives, such as in generics.
28. What is the difference between parseInt()
and valueOf()
in Integer
class?
Answer:
-
Integer.parseInt(String)
returns a primitiveint
. -
Integer.valueOf(String)
returns anInteger
object, enabling autoboxing.
int num = Integer.parseInt("100");
Integer numObj = Integer.valueOf("100");
29. What is the Thread
class in java.lang
?
Answer:
The Thread
class allows you to create and manage threads in Java. You can:
- Create threads by extending
Thread
or implementingRunnable
. - Control them using methods like
start()
,sleep()
,join()
,interrupt()
.
30. What is the Runnable
interface?
Answer:
A functional interface representing a task that can be run in a thread. It defines the run()
method. Used to pass logic into a Thread
object.
Runnable task = () -> System.out.println("Running!");
new Thread(task).start();
31. What is the Throwable
hierarchy?
Answer:
At the top:
-
Throwable
-
Error
(e.g.,OutOfMemoryError
) -
Exception
-
RuntimeException
(unchecked) - Other exceptions like
IOException
,SQLException
(checked)
-
-
32. What is the difference between checked and unchecked exceptions? Answer:
-
Checked exceptions: Must be declared or handled (
IOException
,SQLException
). -
Unchecked exceptions: Subclasses of
RuntimeException
. Compiler does not force handling (NullPointerException
,ArithmeticException
).
33. What is the finalize()
method?
Answer:
A method called by the garbage collector before an object is removed. It’s deprecated in Java 9+ due to its unpredictability and performance issues.
34. What is the Cloneable
interface?
Answer:
Marker interface that allows an object to be cloned via Object.clone()
. If a class doesn’t implement it and clone()
is called, CloneNotSupportedException
is thrown.
35. How do you create a clone of an object?
Answer:
Implement Cloneable
and override clone()
:
public class MyObject implements Cloneable {
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
36. What is the System.exit()
method?
Answer:
Terminates the currently running JVM:
System.exit(0); // normal exit
System.exit(1); // abnormal exit
It’s commonly used in CLI apps or on critical failure.
37. What is the SecurityManager
class?
Answer:
Used to implement a security policy for Java applications, particularly in sandboxed environments like applets. It’s deprecated for removal in modern Java versions.
38. What does getClass()
method do?
Answer:
Returns the runtime class of the object:
MyClass obj = new MyClass();
Class<?> c = obj.getClass();
System.out.println(c.getName()); // prints "MyClass"
39. What is reflection in Java? Answer: Reflection is the ability to inspect and manipulate classes, methods, fields, and constructors at runtime. Used in frameworks, testing tools, and libraries like Spring.
40. What are marker interfaces? Give examples. Answer: Interfaces with no methods, used to mark classes for special treatment by the compiler or runtime. Examples:
-
Serializable
-
Cloneable
-
Remote
41. What is the StrictMath
class?
Answer:
Similar to Math
, but guarantees consistent results across platforms using strict IEEE 754 floating-point calculations. It’s slower but predictable.
42. What is the difference between String.equals()
and String.equalsIgnoreCase()
?
Answer:
-
equals()
is case-sensitive. -
equalsIgnoreCase()
compares strings ignoring case differences.
"Java".equals("java") // false
"Java".equalsIgnoreCase("java") // true
43. What is the difference between String.length()
and StringBuilder.length()
?
Answer:
Both return the number of characters, but:
-
String.length()
returns the length of an immutable string. -
StringBuilder.length()
returns the current length of the mutable buffer.
44. What is the Package
class?
Answer:
Represents a Java package. You can get package information at runtime:
Package p = MyClass.class.getPackage();
System.out.println(p.getName());
45. How do you get the current time in milliseconds? Answer: Using:
long millis = System.currentTimeMillis();
Often used for performance measurement.
46. What is the Comparable
interface?
Answer:
Defines the natural ordering of objects using compareTo()
method. Used by sorting methods like Collections.sort()
.
47. What is the difference between compareTo()
and Comparator
?
Answer:
-
compareTo()
is fromComparable
and defined inside the class. -
Comparator
is external, and allows multiple sort orders.
48. What does System.arraycopy()
do?
Answer:
Efficiently copies data from one array to another:
System.arraycopy(src, 0, dest, 0, length);
Faster than manually looping through arrays.
49. What is the Void
class in Java?
Answer:
A placeholder class representing the void
return type. It is rarely used, typically in reflection APIs.
50. What are the key differences between String
, StringBuilder
, and StringBuffer
?
Answer:
Class | Mutability | Thread-Safety | Performance |
---|---|---|---|
String
|
Immutable | Yes (inherent) | Low (creates new) |
StringBuilder
|
Mutable | No | High (single-thread) |
StringBuffer
|
Mutable | Yes | Lower (due to sync) |
✅ [Java JDBC] – 25 Real Questions & Elaborative Answers
1. What is JDBC and why is it used? Answer: JDBC stands for Java Database Connectivity. It is an API provided by Java to connect and interact with relational databases (like MySQL, Oracle, PostgreSQL). It allows Java applications to execute SQL statements, retrieve results, and manage database connections in a database-agnostic way using drivers. JDBC serves as a bridge between Java code and SQL queries.
2. What are the key components of the JDBC API? Answer: The core components include:
-
DriverManager
: Manages JDBC drivers. -
Connection
: Interface for establishing a connection to the DB. -
Statement
: Used to send SQL queries. -
PreparedStatement
: Precompiled SQL statement for efficient execution. -
ResultSet
: Represents data returned by a query. -
CallableStatement
: Used to call stored procedures.
3. What is the role of DriverManager
in JDBC?
Answer:
DriverManager
acts as a factory for database connections. It loads JDBC drivers and provides the getConnection()
method to initiate DB communication.
Example:
Connection con = DriverManager.getConnection(url, user, password);
It auto-selects the right driver based on the URL prefix (e.g., jdbc:mysql:
).
4. How do you establish a JDBC connection? Answer:
Class.forName("com.mysql.cj.jdbc.Driver"); // Load driver
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "root", "password");
From JDBC 4.0+, loading via Class.forName()
is optional if the driver is in the classpath.
5. What is a Statement
in JDBC?
Answer:
Statement
is used to execute static SQL queries.
Example:
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
However, it is not safe from SQL injection. For dynamic or user-based inputs, PreparedStatement
is recommended.
6. What is a PreparedStatement
? Why is it preferred over Statement
?
Answer:
PreparedStatement
is a precompiled SQL statement used for executing queries with input parameters.
Benefits:
- Prevents SQL injection
- Faster for repeated execution
- Cleaner syntax Example:
PreparedStatement ps = con.prepareStatement("SELECT * FROM users WHERE id = ?");
ps.setInt(1, 5);
ResultSet rs = ps.executeQuery();
7. What is the CallableStatement
used for?
Answer:
Used to execute stored procedures in a database.
Example:
CallableStatement cs = con.prepareCall("{call getUser(?)}");
cs.setInt(1, 5);
ResultSet rs = cs.executeQuery();
It allows interaction with database-side logic encapsulated in procedures and functions.
8. What is a ResultSet
in JDBC?
Answer:
A ResultSet
is a cursor-like object that holds the result of an SQL query.
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
System.out.println(rs.getString("name"));
}
It supports methods like next()
, getInt()
, getString()
to navigate and retrieve data row by row.
9. What are the types of ResultSet
in JDBC?
Answer:
Based on scrolling and updatability:
- Type_FORWARD_ONLY (default)
- Type_SCROLL_INSENSITIVE (scrollable but not sensitive to DB changes)
- Type_SCROLL_SENSITIVE (reflects DB changes) And:
- CONCUR_READ_ONLY
- CONCUR_UPDATABLE
10. What is JDBC Driver? What are its types? Answer: JDBC Driver is a software component that enables Java applications to interact with a database. Types:
- Type 1 – JDBC-ODBC Bridge (obsolete)
- Type 2 – Native API driver (requires native libs)
- Type 3 – Network Protocol driver (uses middleware)
- Type 4 – Thin driver (pure Java, communicates directly with DB) → Most widely used today.
11. What is the difference between execute(), executeQuery(), and executeUpdate()? Answer:
-
execute()
: For any SQL statement; returns boolean (true if ResultSet). -
executeQuery()
: For SELECT statements; returns ResultSet. -
executeUpdate()
: For INSERT, UPDATE, DELETE; returns update count (int).
12. How do you prevent SQL injection in JDBC?
Answer:
Use PreparedStatement
instead of string concatenation in Statement
. This automatically escapes input and avoids injection.
13. How do you handle transactions in JDBC? Answer: By default, JDBC uses auto-commit (each SQL is committed immediately). To control transactions:
con.setAutoCommit(false);
stmt.executeUpdate(...);
con.commit(); // or con.rollback();
This ensures atomicity across multiple statements.
14. How do you close JDBC resources properly?
Answer:
Always close ResultSet
, Statement
, and Connection
in a finally
block or use try-with-resources (Java 7+):
try (Connection con = ...;
Statement stmt = ...;
ResultSet rs = ...) {
// operations
}
15. What happens if you don’t close a JDBC connection? Answer: Unclosed connections can:
- Exhaust connection pool
- Leak memory
- Cause resource exhaustion on the DB server
Always close connections explicitly or use connection pools with auto-closing.
16. What is connection pooling in JDBC? Answer: Connection pooling reuses existing DB connections instead of creating a new one for every request. This improves performance and scalability. Popular libraries: HikariCP, Apache DBCP, C3P0.
17. What is the role of JDBC in ORM frameworks like Hibernate? Answer: ORM frameworks internally use JDBC to interact with the DB. JDBC is the underlying layer for executing SQL even when using object-oriented abstraction in Hibernate or JPA.
18. What is batch processing in JDBC? Answer: Used to execute multiple queries in a batch for performance.
PreparedStatement ps = con.prepareStatement("INSERT INTO emp VALUES (?, ?)");
ps.setInt(1, 1);
ps.setString(2, "Alice");
ps.addBatch();
ps.setInt(1, 2);
ps.setString(2, "Bob");
ps.addBatch();
ps.executeBatch();
19. Can you update data using a ResultSet
?
Answer:
Yes, if the ResultSet
is updatable (CONCUR_UPDATABLE
):
ResultSet rs = stmt.executeQuery("SELECT * FROM users",
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs.next();
rs.updateString("name", "UpdatedName");
rs.updateRow();
20. What is metadata in JDBC? Answer: Metadata is data about the database structure.
-
DatabaseMetaData
: Info about DB itself -
ResultSetMetaData
: Info about columns in a result set
21. How do you get column names from a ResultSet
?
Answer:
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.println(rsmd.getColumnName(i));
}
22. How do you call stored procedures with IN and OUT parameters? Answer:
CallableStatement cs = con.prepareCall("{call getUser(?, ?)}");
cs.setInt(1, 1); // IN param
cs.registerOutParameter(2, Types.VARCHAR); // OUT param
cs.execute();
String name = cs.getString(2);
23. How does JDBC handle exceptions?
Answer:
All JDBC methods throw SQLException
, which must be handled with try-catch blocks. It provides error code, SQL state, and detailed messages.
24. What is the difference between JDBC and ODBC? Answer:
- JDBC is Java-based and platform-independent.
- ODBC is C-based and platform-dependent. JDBC is tailored for Java, while ODBC is more general and older.
25. What is the best practice for writing JDBC code? Answer:
- Use try-with-resources for auto-closing
- Prefer
PreparedStatement
for safety and speed - Use connection pooling
- Log and handle exceptions gracefully
- Avoid hardcoded credentials; use configuration files
- Use ORM for large applications, fall back to JDBC for fine control
✅ [Java Threads and Concurrency] – 50 Real Questions & Elaborate Answers
1. What is a thread in Java? Answer: A thread is a lightweight subprocess, the smallest unit of CPU execution. Java supports multithreading, allowing concurrent execution of two or more threads to perform tasks in parallel, improving performance and responsiveness in applications like GUIs or servers.
2. What is the difference between a process and a thread? Answer:
- A process is an independent program with its own memory space.
- A thread is a smaller unit within a process that shares memory with other threads but has its own execution stack. Threads are more efficient than processes for multitasking.
3. How do you create a thread in Java? Answer: Two primary ways:
-
Extending
Thread
class
class MyThread extends Thread {
public void run() {
System.out.println("Running...");
}
}
new MyThread().start();
-
Implementing
Runnable
interface
class MyRunnable implements Runnable {
public void run() {
System.out.println("Running...");
}
}
new Thread(new MyRunnable()).start();
4. What is the difference between start()
and run()
methods?
Answer:
-
start()
creates a new thread and callsrun()
on that thread. - Calling
run()
directly executes it on the current thread, not as a separate thread.
5. What is the life cycle of a thread in Java? Answer:
- New – Thread is created.
-
Runnable – After
start()
, ready to run. - Running – Thread scheduler picks it to run.
- Blocked/Waiting – Waiting for monitor lock or other threads.
- Terminated – Thread completes or is interrupted.
6. What is thread priority? Answer: Each thread has a priority (1 to 10). Threads with higher priority are more likely to be chosen by the scheduler:
-
MIN_PRIORITY = 1
-
NORM_PRIORITY = 5
(default) -
MAX_PRIORITY = 10
thread.setPriority(Thread.MAX_PRIORITY);
7. What is the Thread.sleep()
method?
Answer:
Temporarily pauses the thread for a specified duration:
Thread.sleep(1000); // sleeps for 1 second
Throws InterruptedException
. It does not release locks.
8. What is the difference between sleep()
and wait()
?
Answer:
-
sleep()
is static and pauses the thread for a duration. It doesn’t release the monitor lock. -
wait()
is used in synchronization, pauses until notified, and releases the lock.
9. What is synchronization in Java?
Answer:
Prevents multiple threads from accessing critical sections simultaneously. Achieved using synchronized
keyword on methods or blocks to ensure only one thread executes that section at a time.
10. How do you synchronize a method or block? Answer:
synchronized void update() { ... }
synchronized(obj) {
// critical section
}
Lock is associated with the object (this
or explicit).
11. What is a deadlock? Answer: Occurs when two or more threads are blocked forever, each waiting on the other to release a resource. It usually happens when locks are acquired in different orders.
12. How can you prevent deadlocks? Answer:
- Always acquire locks in a consistent order
- Use tryLock() with timeouts
- Avoid nested locks if possible
- Use higher-level concurrency APIs
13. What is the join()
method in threads?
Answer:
Used to wait for a thread to finish:
thread.join();
The current thread pauses until the target thread completes.
14. What is yield()
in Java threads?
Answer:
Hints the scheduler to pause the current thread and let others of the same priority run. It’s not guaranteed to switch threads.
15. What is thread starvation? Answer: Occurs when lower-priority threads never get CPU time due to continuous execution of higher-priority threads.
16. What is livelock? Answer: Similar to deadlock, but threads keep changing state (e.g., retrying) without progressing. They’re “alive” but not moving forward.
17. What is the volatile
keyword?
Answer:
Ensures visibility of changes to variables across threads. A volatile
variable is read directly from memory, preventing caching issues.
18. What is the synchronized
keyword used for?
Answer:
Used to mark a block or method as critical section to ensure atomic access and mutual exclusion for shared resources.
19. Can a constructor be synchronized
?
Answer:
No. Constructors cannot be synchronized because an object’s monitor doesn’t exist until after the constructor completes.
20. What is the difference between ReentrantLock
and synchronized
?
Answer:
-
synchronized
: Simpler, uses implicit locks. -
ReentrantLock
: More flexible, supports tryLock(), timed waits, interruptibility, and fair ordering.
21. What is a daemon thread? Answer: A background thread that does not prevent the JVM from exiting. Use it for services like garbage collection or monitoring.
thread.setDaemon(true);
22. How do you create a daemon thread?
Answer:
Before calling start()
:
Thread t = new Thread(...);
t.setDaemon(true);
t.start();
23. What is an atomic operation in concurrency?
Answer:
An operation that is indivisible, i.e., no thread can observe it in a partially complete state. Java provides atomic classes like AtomicInteger
.
24. What are AtomicInteger
and friends used for?
Answer:
They offer lock-free thread-safe operations on single variables using low-level CPU instructions.
AtomicInteger count = new AtomicInteger(0);
count.incrementAndGet();
25. What is the ExecutorService
in Java?
Answer:
A framework for managing and controlling thread pools. Provides methods like submit()
, shutdown()
, invokeAll()
for better thread management.
26. What is a thread pool and why is it important? Answer: A thread pool reuses a fixed number of threads to execute tasks, reducing the overhead of thread creation. It improves performance and prevents out-of-memory issues from too many threads.
27. How do you create a fixed thread pool in Java? Answer:
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> System.out.println("Task running"));
28. What is Callable
and Future
in Java?
Answer:
-
Callable
is likeRunnable
but returns a result and can throw exceptions. -
Future
represents the result of an async computation.
Callable<Integer> task = () -> 42;
Future<Integer> future = executor.submit(task);
System.out.println(future.get()); // blocks until result is ready
29. What is the Fork/Join framework? Answer: Introduced in Java 7, it’s designed for divide-and-conquer tasks. It splits tasks into subtasks and combines results using work-stealing algorithms.
30. What is the difference between Runnable
and Callable
?
Answer:
Feature | Runnable | Callable |
---|---|---|
Return Type | void | V (generic) |
Exception | Cannot throw checked | Can throw checked |
Result | Not available | via Future |
Use Case | Simple tasks | Result-based async tasks |
31. What is a CyclicBarrier
?
Answer:
Allows a group of threads to wait for each other to reach a common barrier point. Once all reach, they proceed together.
32. What is a CountDownLatch
?
Answer:
Allows one or more threads to wait until a set of operations complete in other threads.
CountDownLatch latch = new CountDownLatch(3);
latch.await(); // waits
latch.countDown(); // from worker threads
33. What is a semaphore in Java? Answer: Controls access to a resource with a fixed number of permits. Useful for limiting concurrent access (e.g., database connections).
34. What is a ReadWriteLock
?
Answer:
Allows multiple threads to read simultaneously, but only one to write exclusively. Prevents read-write conflicts.
35. What is optimistic vs. pessimistic locking? Answer:
- Pessimistic: Assume conflict will happen → lock aggressively.
- Optimistic: Assume conflict is rare → check for conflict during commit.
36. What is the ThreadLocal
class?
Answer:
Provides a variable that is accessible only by the thread that created it. Useful for per-thread state.
37. What is false sharing in multithreading? Answer: Performance degradation that occurs when threads on different processors modify variables that reside on the same cache line.
38. What is the ReentrantReadWriteLock
?
Answer:
A lock that allows concurrent reads but exclusive writes. Improves throughput for mostly-read scenarios.
39. What is the difference between busy-waiting and blocking? Answer:
- Busy-wait: Continuously checking a condition in a loop. Wastes CPU.
- Blocking: Thread waits and yields CPU until condition is met.
40. What is an interrupt in threading?
Answer:
Interrupts signal a thread to stop. It’s not forceful. The thread must check isInterrupted()
or handle InterruptedException
.
41. How do you interrupt a thread? Answer:
thread.interrupt();
The thread must check for Thread.interrupted()
or catch InterruptedException
.
42. What is the ThreadGroup
class?
Answer:
Used to manage a group of threads as a single unit. Rarely used now due to better control via ExecutorService
.
43. What is the ScheduledExecutorService
?
Answer:
Used to schedule tasks after a delay or periodically:
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS);
44. What is thread contention? Answer: Occurs when multiple threads try to access the same resource simultaneously, leading to blocking and performance bottlenecks.
45. What is a memory consistency error? Answer: Occurs when different threads see inconsistent views of shared data due to lack of synchronization or volatile.
46. What is Thread.UncaughtExceptionHandler
?
Answer:
A handler interface for catching uncaught exceptions in threads.
thread.setUncaughtExceptionHandler((t, e) -> {
System.out.println("Exception in " + t + ": " + e);
});
47. What is Executors.newCachedThreadPool()
?
Answer:
Creates a pool with dynamically growing threads. Ideal for short-lived async tasks.
48. What is starvation and how do you detect it? Answer: Occurs when a thread never gets CPU time. Detection requires monitoring and thread profiling tools like VisualVM or Java Mission Control.
49. What are lock-free data structures?
Answer:
Data structures that use atomic variables and CAS (Compare-And-Swap) to ensure thread safety without blocking, e.g., ConcurrentLinkedQueue
.
50. What is the Phaser
class?
Answer:
A flexible synchronization barrier, like CyclicBarrier
, but supports dynamic registration and multiple phases of execution.
✅ [Java OOAD – Object-Oriented Analysis & Design] – 50 Real Questions & Elaborative Answers
1. What is Object-Oriented Analysis and Design (OOAD)? Answer: OOAD is the process of analyzing and designing a system using object-oriented concepts. It involves:
- Object-Oriented Analysis (OOA): Understanding the problem domain by identifying entities and relationships (what the system must do).
- Object-Oriented Design (OOD): Defining how the system will be implemented using classes, interfaces, and interactions.
OOAD focuses on modeling real-world entities as objects that encapsulate state and behavior.
2. What are the four major principles of OOP used in OOAD? Answer:
- Encapsulation – Hiding internal state using private variables and exposing behavior via methods.
- Abstraction – Simplifying complex systems by modeling relevant behavior.
- Inheritance – Reusing common logic via hierarchical relationships.
- Polymorphism – Same interface, different implementations (method overriding or overloading).
These principles help build reusable, maintainable, and scalable systems.
3. What is abstraction and how is it applied in Java? Answer: Abstraction is the process of hiding implementation details and exposing only relevant features. In Java, it’s implemented using:
- Abstract classes: Define a template with some implemented methods.
- Interfaces: Define contracts without implementation (until Java 8 default methods).
Example:
interface Payment {
void pay(double amount);
}
4. What is encapsulation in Java OOAD? Answer: Encapsulation restricts direct access to class fields. It protects internal object state and enables better control through getters/setters:
public class Account {
private double balance;
public void deposit(double amount) { balance += amount; }
public double getBalance() { return balance; }
}
This promotes modularity and maintainability.
5. Explain the difference between composition and inheritance. Answer:
- Inheritance (IS-A): A class extends another to reuse its behavior.
- Composition (HAS-A): A class contains another class to delegate responsibilities.
Composition is preferred for flexibility and avoiding tight coupling.
6. What is UML and how is it used in OOAD? Answer: UML (Unified Modeling Language) is a standard for visualizing system design. It helps stakeholders understand class structures, interactions, workflows, and behaviors. Common diagrams:
- Class Diagram
- Sequence Diagram
- Use Case Diagram
- Activity Diagram
- State Diagram
7. What is a use case in OOAD? Answer: A use case describes a specific user interaction with the system. It outlines the behavior of the system from the end user’s perspective. Example:
- Actor: Customer
- Use Case: Place Order It’s a foundation for understanding requirements.
8. What is a class diagram? Answer: A class diagram shows the static structure of a system:
- Classes, their attributes and methods
- Relationships: association, generalization, dependency, aggregation, and composition
9. What is aggregation vs composition in OOAD? Answer:
- Aggregation: Weak relationship (whole-part), where the part can exist independently.
- Composition: Strong relationship; part cannot exist without the whole.
Example:
- Aggregation: Department has professors
- Composition: House has rooms
10. What is a sequence diagram? Answer: Depicts the interaction between objects in a time sequence. Shows method calls and the order in which they occur. Useful for modeling business logic and behavior flows.
11. What is generalization in OOAD? Answer: Generalization represents an inheritance relationship between a superclass and subclasses. It models the “IS-A” relationship, enabling reuse of behavior.
12. What is association in OOAD? Answer: Association represents a structural relationship between classes. It shows that objects of one class are connected to objects of another.
13. What is dependency in OOAD? Answer: A weaker relationship indicating one class uses another. For example, a method taking another class as a parameter shows a dependency.
14. What are design patterns in OOAD? Answer: Design patterns are proven solutions to common design problems. They improve software flexibility, reusability, and maintainability. They are classified into:
- Creational (e.g., Singleton, Factory)
- Structural (e.g., Adapter, Composite)
- Behavioral (e.g., Observer, Strategy)
15. What is cohesion and coupling in OOAD? Answer:
- Cohesion: Degree to which elements of a class belong together. Higher is better.
- Coupling: Degree of dependency between modules. Lower is better. Goal: High cohesion, low coupling.
16. What is polymorphism and how is it used in Java OOAD? Answer: Polymorphism allows the same interface to be used for different underlying data types:
- Overriding: Subclass modifies superclass method
- Overloading: Multiple methods with same name but different parameters
It promotes extensibility and flexibility in OOAD design.
17. What is an interface and when should it be used in OOAD? Answer: An interface defines a contract. Use it when:
- Multiple classes need to implement common behavior
- You want to decouple implementation from usage This supports dependency inversion and clean architecture.
18. What is the SOLID principle in OOAD? Answer: Five design principles for OO systems:
- S: Single Responsibility Principle
- O: Open/Closed Principle
- L: Liskov Substitution Principle
- I: Interface Segregation Principle
- D: Dependency Inversion Principle They guide better software architecture.
19. What is the Open/Closed Principle? Answer: A class should be open for extension but closed for modification. You can add behavior via inheritance or composition without changing existing code.
20. What is the Liskov Substitution Principle?
Answer:
Subclasses should be substitutable for their base classes without altering correctness.
If S
is a subtype of T
, then objects of type T
can be replaced with S
.
21. What is the Single Responsibility Principle? Answer: A class should have only one reason to change, meaning it should have just one job. This keeps classes focused and maintainable.
22. What is the Interface Segregation Principle? Answer: Avoid forcing classes to implement interfaces they don’t use. Favor smaller, role-specific interfaces over large ones.
23. What is the Dependency Inversion Principle? Answer: High-level modules should not depend on low-level modules. Both should depend on abstractions, not concrete implementations.
24. What is a domain model in OOAD? Answer: A conceptual model that represents real-world entities and their relationships. It helps in translating requirements into object-oriented structures.
25. What is GRASP in OOAD? Answer: General Responsibility Assignment Software Patterns — a set of principles for assigning responsibilities:
- Controller
- Creator
- Expert
- Low Coupling
- High Cohesion
- Polymorphism
- Indirection
- Protected Variations
26. What is the Law of Demeter? Answer: “Talk only to your immediate friends.” A method should only call methods of:
- Itself
- Its fields
- Its method parameters This reduces coupling.
27. What is an anti-pattern? Answer: A recurring poor solution to a problem. It may seem useful initially but has long-term negative consequences. Example: God object, Spaghetti code.
28. What is refactoring in OOAD? Answer: Changing the structure of code without changing its external behavior to improve readability, reduce complexity, and enhance maintainability.
29. How does OOAD differ from procedural design? Answer: OOAD models the real world using objects and interactions, focusing on what entities do. Procedural design uses functions and routines, focusing on how tasks are done. OOAD is better suited for complex and large-scale systems.
30. What is a package diagram in UML? Answer: Shows the organization of a system into packages (modules/namespaces) and their dependencies.
31. What is CRC (Class-Responsibility-Collaborator) modeling? Answer: A lightweight design technique:
- Class: Who?
- Responsibility: What?
- Collaborator: With whom? It’s used in early OOAD to brainstorm design roles.
32. What are design smells? Answer: Code/design patterns that indicate deeper problems:
- God class
- Feature envy
- Long method
- Switch statements They point to violations of OOAD principles.
33. How is testing supported in OOAD? Answer: OOAD supports unit testing due to clear boundaries and encapsulation. Design for testability includes:
- Dependency injection
- Use of interfaces/mocks
- High cohesion/low coupling
34. How is exception handling modeled in OOAD? Answer: Exception flows are shown in sequence diagrams. Design decisions include:
- Where to catch exceptions
- How to encapsulate fault-tolerance logic This improves reliability.
35. What is behavioral modeling in OOAD? Answer: Focuses on how objects behave and interact. Includes:
- Sequence diagrams
- Activity diagrams
- State machines
36. What are artifacts in OOAD? Answer: Tangible outputs produced during the development lifecycle:
- Use cases
- Class diagrams
- Code
- Test plans They help track progress and ensure quality.
37. What is anti-corruption layer (ACL)? Answer: A layer that isolates the domain model from external systems or legacy logic. Prevents external “corruption” of clean design.
38. How do use cases influence class design? Answer: They define required interactions and responsibilities, which guide:
- Class identification
- Method design
- Collaboration planning
39. What is an entity in OOAD? Answer: An object with a persistent identity, representing real-world domain elements like Customer, Invoice, Product.
40. What is a boundary class? Answer: Handles interaction between system and external actors. Example: UI controllers, REST endpoints.
41. What is a control class? Answer: Encapsulates complex business logic and coordinates between boundary and entity classes.
42. What is a persistent class? Answer: An entity whose state is stored in permanent storage (like DB). Modeled with attributes that map to fields/tables.
43. How do you ensure scalability in OOAD? Answer: Through:
- Composition over inheritance
- Interface-driven design
- Applying SOLID principles
- Using design patterns for extensibility
44. How does OOAD support maintainability? Answer: Clear modular structure, separation of concerns, and high cohesion make systems easier to understand, test, and change.
45. What is refactoring to patterns? Answer: The act of identifying areas of improvement in OO design and applying design patterns to improve flexibility and readability.
46. How do you represent polymorphism in UML? Answer: Using generalization arrows pointing from subclass to superclass. Multiple subclasses can override the same operation.
47. What is dynamic binding in OOAD? Answer: Method calls are resolved at runtime based on the object’s actual type, not reference type. Enables polymorphic behavior.
48. What is a message in OOAD? Answer: A communication between objects, typically a method call. It forms the basis of object collaboration.
49. What are responsibilities in CRC? Answer: Things a class knows and does. Responsibilities define the behavior and knowledge each class is expected to encapsulate.
50. How does OOAD relate to Agile development? Answer: OOAD supports iterative, incremental design—aligning with Agile principles. Use cases, class diagrams, and refactoring support adaptive and evolving systems.
✅ [Java Design Patterns] – 50 Real Questions & Elaborative Answers
🏗 Creational Patterns
1. What are creational design patterns? Answer: Creational patterns deal with object creation mechanisms, trying to create objects in a manner that is suitable to the situation. They help make systems independent of how their objects are created, composed, and represented.
Common examples include:
- Singleton
- Factory Method
- Abstract Factory
- Builder
- Prototype
2. What is the Singleton Pattern? Answer: Ensures a class has only one instance and provides a global point of access to it.
Use Case: Logger, Configuration, Caches Example:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
3. How do you make a Singleton thread-safe? Answer: Using synchronized blocks or the Bill Pugh approach:
public class Singleton {
private Singleton() {}
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}
This is thread-safe and efficient.
4. What is the Factory Method Pattern? Answer: Defines an interface for creating objects but lets subclasses decide which class to instantiate.
Use Case: When you need a class to defer the instantiation of objects to its subclasses.
5. What is the Abstract Factory Pattern? Answer: Provides an interface for creating families of related or dependent objects without specifying their concrete classes.
Use Case: UI themes, platform-specific factories (e.g., WindowsFactory vs MacFactory)
6. What is the Builder Pattern? Answer: Separates object construction from its representation. Useful when creating complex objects step by step.
Example:
new PizzaBuilder().addCheese().addToppings().build();
7. When would you use the Prototype Pattern?
Answer:
When object creation is costly, and you need to clone pre-built objects. Requires clone()
and Cloneable
implementation.
🧱 Structural Patterns
8. What are structural patterns? Answer: Structural patterns focus on how classes and objects are composed to form larger structures.
Examples:
- Adapter
- Bridge
- Composite
- Decorator
- Facade
- Flyweight
- Proxy
9. What is the Adapter Pattern? Answer: Allows two incompatible interfaces to work together. Acts as a wrapper.
Example:
SocketAdapter adapter = new SocketAdapterImpl();
adapter.get5Volt(); // adapts 240V to 5V
10. What is the Bridge Pattern? Answer: Separates abstraction from implementation so the two can vary independently.
Use Case: Shape abstraction with rendering backends like SVGRenderer
or CanvasRenderer
.
11. What is the Composite Pattern? Answer: Used to treat individual objects and compositions of objects uniformly.
Example: Tree structures like folders/files.
12. What is the Decorator Pattern? Answer: Adds new behavior to objects dynamically without altering their structure. Used for flexible code enhancements.
Example:
Coffee c = new MilkDecorator(new SugarDecorator(new BasicCoffee()));
13. What is the Facade Pattern? Answer: Provides a simplified interface to a complex subsystem. Ideal for hiding complexity.
Example: A HomeTheaterFacade
that combines multiple device operations.
14. What is the Flyweight Pattern? Answer: Minimizes memory usage by sharing common state among many objects. Often used in rendering or text editors.
15. What is the Proxy Pattern? Answer: Provides a surrogate or placeholder for another object to control access, enhance behavior, or delay instantiation.
Types:
- Virtual Proxy
- Protection Proxy
- Remote Proxy
🔁 Behavioral Patterns
16. What are behavioral design patterns? Answer: They define how objects interact and communicate. They help improve flexibility in carrying out communication between objects.
Examples:
- Strategy
- Observer
- Command
- Chain of Responsibility
- Template Method
- Mediator
- State
- Visitor
- Memento
17. What is the Strategy Pattern? Answer: Enables selecting an algorithm’s behavior at runtime. Uses composition to switch behaviors.
Example:
new Context(new QuickSort()).sort(data);
18. What is the Observer Pattern? Answer: Defines a one-to-many dependency so that when one object changes, all dependents are notified automatically.
Example: Event listeners, model-view synchronization.
19. What is the Command Pattern? Answer: Encapsulates a request as an object, allowing for undo, redo, or queue operations.
Example:
Command cmd = new LightOnCommand(light);
remote.setCommand(cmd);
remote.pressButton();
20. What is the Chain of Responsibility Pattern? Answer: Passes a request along a chain of handlers. Each handler decides whether to handle the request or pass it on.
Example: Logging framework or servlet filters.
21. What is the Template Method Pattern? Answer: Defines the skeleton of an algorithm in a method, deferring some steps to subclasses.
Used when multiple classes follow the same process but differ in some steps.
22. What is the Mediator Pattern? Answer: Centralizes complex communications between objects. Instead of objects referring to each other directly, they interact via a mediator.
23. What is the State Pattern? Answer: Allows an object to alter its behavior when its internal state changes.
Used in FSMs (Finite State Machines), e.g., ATMMachine
being in NoCard
, HasCard
, Authorized
states.
24. What is the Visitor Pattern? Answer: Allows you to define a new operation on a group of objects without changing the classes themselves.
25. What is the Memento Pattern? Answer: Captures and externalizes an object’s internal state so that it can be restored later.
Used for undo/redo implementations.
📐 General Design Pattern Concepts
26. Why use design patterns? Answer: They offer reusable, testable, and extensible solutions to common software problems. Patterns improve team communication and system robustness.
27. Are design patterns language-specific? Answer: No. While examples vary by language, design patterns are language-agnostic and follow OOP principles. Java just offers good syntax and features for them.
28. What are anti-patterns? Answer: Solutions that seem effective but are actually counterproductive or flawed. Examples:
- God Object
- Spaghetti Code
- Copy-paste Inheritance
29. What is the difference between a pattern and a framework? Answer:
- Pattern: Conceptual, flexible, and reusable solution
- Framework: Concrete implementation, often with defined structure and behavior
30. How does the Factory pattern promote loose coupling? Answer: By hiding object creation and relying on an interface rather than implementation. This decouples the client code from specific classes.
31. What is the benefit of using the Builder over telescoping constructors? Answer: Builder avoids constructor explosion by enabling step-by-step object construction with better readability and optional parameters.
32. How do design patterns follow the SOLID principles? Answer:
- Singleton: SRP (only one instance)
- Strategy: OCP (easy to extend behavior)
- Decorator: OCP + SRP
- Factory: DIP (depend on abstraction)
- Observer: ISP + OCP
33. What is dependency injection, and is it a design pattern? Answer: Yes. DI is a pattern where objects receive dependencies from an external source. It promotes testability and loose coupling.
34. What is a context class in the Strategy pattern? Answer: The context holds a reference to the strategy and delegates behavior to it:
context.setStrategy(new CreditCardPayment());
context.execute();
35. What is the key benefit of the Proxy pattern? Answer: It enables lazy loading, access control, and monitoring without changing the actual object.
36. When would you use Composite over Decorator? Answer: Use Composite to treat group of objects uniformly. Use Decorator to add responsibilities dynamically to a single object.
37. Can patterns be misused? Answer: Yes. Overusing or misapplying patterns leads to overengineering. Patterns should be used only when there’s a real need.
38. What is an example of using the Template Method in Java SDK?
Answer:
InputStream
and AbstractList
use Template Methods, allowing subclasses to override specific steps.
39. What’s the main drawback of Singleton pattern? Answer: It hides dependencies, makes unit testing harder, and can become a global state which is generally discouraged in clean architectures.
40. Can Singleton be broken via reflection or serialization? Answer: Yes. You can prevent this by:
- Throwing exceptions in constructor on multiple instantiations
- Overriding
readResolve()
for serialization
41. Is Enum-based Singleton recommended in Java? Answer: Yes. Enums provide serialization safety, reflection protection, and simplicity:
public enum Singleton {
INSTANCE;
}
42. What pattern does java.util.Observer
implement?
Answer:
The Observer Pattern. Subjects maintain a list of observers and notify them of changes.
43. What is the difference between Adapter and Facade? Answer:
- Adapter: Converts one interface to another.
- Facade: Simplifies an entire subsystem.
44. Can Factory and Strategy patterns work together? Answer: Yes. You can use a Factory to create Strategy objects dynamically based on context or configuration.
45. What’s the main benefit of the Command pattern? Answer: It decouples the object that invokes the operation from the one that performs it, enabling undo/redo and logging.
46. How is State pattern different from Strategy? Answer: State changes the behavior based on internal state, while Strategy is externally set and interchangeable.
47. What is the difference between Abstract Factory and Builder? Answer:
- Abstract Factory: Creates families of related objects.
- Builder: Creates a complex object step-by-step.
48. What is the benefit of the Visitor pattern? Answer: It allows adding operations to a class hierarchy without modifying the classes themselves.
49. When would you use the Memento pattern? Answer: To implement undo/redo in editors or recover state after failure.
50. Why should developers study design patterns? Answer: Because patterns:
- Improve design vocabulary
- Reduce time to solve common problems
- Make code more flexible and reusable
- Improve team communication and consistency
✅ Java Collections Deep Dive – Part 1 of 5
Topics: Maps, Sets, and Hashing
1. What is the Java Collections Framework (JCF) and why is it important? Answer: The Java Collections Framework is a set of interfaces, classes, and algorithms that enable developers to manage groups of objects (collections) efficiently. It provides:
- Standard data structures like
List
,Set
,Map
,Queue
- Utility classes like
Collections
andArrays
- Consistent APIs for traversal, searching, sorting, and manipulation
- Performance-optimized and interoperable implementations
This standardization makes development faster, more robust, and easier to maintain.
2. What is the difference between HashMap
and TreeMap
in Java?
Answer:
Feature | HashMap | TreeMap |
---|---|---|
Ordering | No order | Sorted by keys (natural or comparator) |
Performance | O(1) average time complexity | O(log n) due to tree structure |
Implementation | Uses hashing and buckets | Uses red-black tree |
Null keys/values | One null key, multiple null values | No null key allowed |
Use HashMap
for fast lookups and TreeMap
when key order is important.
3. How does HashMap
work internally in Java?
Answer:
- Uses an array of buckets internally.
- Each entry has a key, value, hashcode, and a pointer to next node (linked list or tree).
- Hashing is done using
hashCode()
and bucket index is calculated as(n - 1) & hash
. - From Java 8, buckets with many entries convert to balanced trees (red-black tree) for faster lookups (O(log n)).
Collisions are handled via chaining (linked list or tree depending on size).
4. What are collisions in HashMap
and how are they handled?
Answer:
A collision occurs when two different keys generate the same bucket index. HashMap
handles this using:
- Chaining: A linked list or tree at each bucket
- If the list size exceeds 8 and the array size is ≥ 64, it converts to a red-black tree This ensures better performance in worst-case scenarios.
5. What is the significance of overriding equals()
and hashCode()
in keys used in HashMap
or HashSet
?
Answer:
-
hashCode()
determines the bucket index. -
equals()
checks logical equality within the bucket. If both are not correctly overridden, it may lead to: - Duplicate keys not being recognized
- Incorrect retrieval or loss of entries
Always follow the contract: equal objects must have equal hash codes.
6. What is LinkedHashMap
and how does it differ from HashMap
?
Answer:
LinkedHashMap
maintains insertion order using a doubly linked list of entries.
- Time complexity is same as
HashMap
- Useful when order of insertion is important (e.g., caches)
- Supports access-order mode (for LRU cache)
Map<String, Integer> map = new LinkedHashMap<>();
7. What is HashSet
and how is it implemented internally?
Answer:
HashSet
is a collection of unique elements. Internally:
- It uses a backing
HashMap
. - The elements are stored as keys with a dummy value (
PRESENT
object).
public class HashSet<E> {
private transient HashMap<E,Object> map;
}
8. What is the difference between Set
, HashSet
, and TreeSet
?
Answer:
Feature | HashSet | TreeSet |
---|---|---|
Ordering | No order | Sorted by natural order or comparator |
Null elements | Allows one null | Does not allow null |
Performance | O(1) average | O(log n) |
Backed by | HashMap | TreeMap |
Use TreeSet
for sorted unique collections and HashSet
for fast, unordered unique elements.
9. What is EnumSet
and why is it more efficient than HashSet
?
Answer:
EnumSet
is a high-performance Set implementation for use with enum types only.
- Backed by a bit vector, making operations like
add()
,contains()
extremely fast. - Compact in memory.
enum Day { MON, TUE, WED }
EnumSet<Day> days = EnumSet.of(Day.MON, Day.TUE);
10. What is the load factor in HashMap
?
Answer:
The load factor is the measure of how full the map can get before resizing.
- Default: 0.75
- When
size ≥ capacity × loadFactor
, the map resizes (doubles capacity) - Lower load factor → more space, fewer collisions
- Higher load factor → better memory use, more collisions
✅ Java Collections Deep Dive – Part 2 of 5
Topics: Concurrency, Thread-Safety, Concurrent Collections
11. What are concurrent collections in Java and why are they needed?
Answer:
Concurrent collections are specialized classes designed for safe and efficient use in multithreaded environments. Unlike synchronized wrappers (e.g., Collections.synchronizedList()
), concurrent collections are:
- Non-blocking or lock-optimized
- More scalable and performant under heavy contention
Examples:
-
ConcurrentHashMap
-
CopyOnWriteArrayList
-
ConcurrentLinkedQueue
-
BlockingQueue
implementations
They reduce the risk of race conditions and improve throughput in multi-threaded systems like web servers or caches.
12. How does ConcurrentHashMap
work internally?
Answer:
ConcurrentHashMap
allows concurrent read and write without locking the entire map.
Java 8+ implementation:
- Uses bucket-level locking via a technique called lock striping
- For read operations: mostly lock-free
- For write/update operations: minimal locking at the bin level
- When buckets become large, they convert to balanced trees
This design ensures high concurrency and better performance than synchronizing the entire HashMap
.
13. How is ConcurrentHashMap
different from Collections.synchronizedMap()
?
Answer:
Feature | ConcurrentHashMap | synchronizedMap |
---|---|---|
Concurrency Level | Fine-grained (bucket-level) | Whole map lock |
Null keys/values allowed? | No | Yes |
Performance under load | High | Low (locks entire map) |
Iteration safety | Weakly consistent | Fail-fast (may throw exception) |
ConcurrentHashMap
is preferred in high-concurrency applications.
14. What is CopyOnWriteArrayList
and when should you use it?
Answer:
A thread-safe variant of ArrayList
in which every modification (add, remove, set) results in a new copy of the underlying array.
Advantages:
- Safe iteration without locking
- Useful in read-heavy environments like caching, observers, subscriptions
Disadvantages:
- Expensive writes (copying entire array)
15. What is BlockingQueue
and where is it used?
Answer:
A BlockingQueue
supports thread-safe producer-consumer operations.
-
put()
waits if the queue is full -
take()
waits if the queue is empty Used in thread pools, messaging systems, and concurrent pipelines. Implementations: -
ArrayBlockingQueue
-
LinkedBlockingQueue
-
PriorityBlockingQueue
-
DelayQueue
16. What is ConcurrentLinkedQueue
and how does it work?
Answer:
A non-blocking, thread-safe queue based on lock-free algorithms using Compare-And-Swap (CAS) operations.
- Good for high-throughput systems
- Iterator is weakly consistent (does not throw
ConcurrentModificationException
) - FIFO (first-in-first-out) ordering
17. How do you make a List
thread-safe in Java?
Answer:
Options include:
-
Collections.synchronizedList(new ArrayList<>())
-
CopyOnWriteArrayList
(for read-heavy scenarios) - Using
List
inside synchronized blocks
Example:
List<String> list = Collections.synchronizedList(new ArrayList<>());
18. What is the difference between ConcurrentSkipListMap
and TreeMap
?
Answer:
Feature | TreeMap | ConcurrentSkipListMap |
---|---|---|
Thread-safe | No | Yes |
Sorting | Natural or custom order | Same |
Performance | Single-thread optimized | High concurrency for reads/writes |
ConcurrentSkipListMap
uses a skip list and provides O(log n) performance with safe concurrent access.
19. What is a ConcurrentSkipListSet
?
Answer:
A thread-safe and sorted version of TreeSet
. Internally uses a ConcurrentSkipListMap
.
- Maintains natural ordering
- Safe for concurrent access
- Provides non-blocking reads and log-time performance
20. What are fail-fast and fail-safe iterators in Java? Answer:
Feature | Fail-Fast | Fail-Safe |
---|---|---|
Behavior | Throws ConcurrentModificationException if modified during iteration |
Does not throw, reflects snapshot or updated data |
Examples |
ArrayList , HashMap |
ConcurrentHashMap , CopyOnWriteArrayList |
Thread-safety | Not thread-safe by default | Thread-safe or snapshot-based |
Fail-fast iterators help detect bugs, while fail-safe iterators are safer in concurrent environments.
✅ Java Collections Deep Dive – Part 3 of 5
Topics: Map/Set Variants, Hashing, and Design Considerations
21. What is WeakHashMap
in Java and how does it differ from HashMap
?
Answer:
A WeakHashMap
is a special type of Map
where the keys are held using weak references.
- If a key is no longer referenced outside the map, it becomes eligible for garbage collection.
- Once GC occurs, such entries are automatically removed from the map.
Use Case: Caching where you don’t want to prevent objects from being GC’d.
Key differences from HashMap
:
- Automatic cleanup via GC
- Keys are not strongly referenced
22. What is the purpose of IdentityHashMap
?
Answer:
Unlike HashMap
, which uses equals()
for comparison, IdentityHashMap
uses the ==
operator (reference equality).
This means keys are considered equal only if they refer to the exact same object.
Use Case: Reference tracking, serialization, or when you need strict object identity semantics.
23. What is EnumMap
in Java?
Answer:
EnumMap
is a Map
implementation optimized for use with enum keys.
- Internally uses an array, making it faster and memory-efficient
- Maintains the natural order of enums
- Does not allow
null
keys
Example:
EnumMap<Day, String> map = new EnumMap<>(Day.class);
24. How does TreeMap
maintain sorted order?
Answer:
Internally, TreeMap
is backed by a red-black tree, a self-balancing binary search tree.
- Elements are sorted based on natural ordering (
Comparable
) or a providedComparator
. - Insertions, deletions, and lookups have O(log n) complexity.
25. How does HashSet
ensure uniqueness of elements?
Answer:
- Backed by a
HashMap
, where elements are stored as keys and values are a constant dummy object. - Uses hashCode() and equals() to check for duplicates.
- If
equals()
returns true for a new object and an existing key, the new element is not added.
26. What is load factor tuning in Hash-based collections?
Answer:
Load factor determines when a HashMap
or HashSet
should resize.
Default: 0.75 (good balance of memory and performance).
Trade-offs:
- Lower load factor: Less collision, more memory
- Higher load factor: Saves memory, more collisions (worse performance)
You can tune it in the constructor:
new HashMap<>(initialCapacity, loadFactor);
27. What is the initial capacity of HashMap
, and why does it matter?
Answer:
Initial capacity is the number of buckets at the time of map creation.
- Default: 16
- It affects rehashing and performance.
Choose an appropriate capacity if:
- You know how many elements will be stored
- You want to avoid resizing overhead
28. Can we store null
values in Java Maps and Sets?
Answer:
-
HashMap
: Onenull
key, multiplenull
values -
TreeMap
: Nonull
keys (throwsNullPointerException
) -
HashSet
: Onenull
value -
LinkedHashMap
: Supports null key/value -
ConcurrentHashMap
: No null keys or values
This is a crucial consideration when using collections in production systems.
29. What are the implications of poor hashCode()
implementation?
Answer:
If hashCode()
does not distribute keys uniformly:
- Many entries will go into the same bucket
- Increases lookup time from O(1) to O(n) (or O(log n) in case of tree bins)
- Leads to poor performance and collision clusters
Always override hashCode()
with a good distribution algorithm that matches equals()
behavior.
30. What is the difference between HashMap
and Hashtable
?
Answer:
Feature | HashMap | Hashtable |
---|---|---|
Thread-safety | Not thread-safe | Thread-safe (synchronized) |
Null key/value | Allows one/null | Does not allow |
Performance | Better (no locking) | Worse (synchronization) |
Modern usage | Preferred | Legacy (discouraged) |
Use ConcurrentHashMap
instead of Hashtable
for thread-safe operations in modern Java.
Great! Here’s the fourth batch of 10 elaborative questions, focusing on best practices, performance tuning, and concurrency-related design patterns involving Java Collections, Sets, and Maps.
✅ Java Collections Deep Dive – Part 4 of 5
Topics: Best Practices, Performance, Tuning, and Design Insights
31. When should you use ArrayList
over LinkedList
, and vice versa?
Answer:
Use Case | ArrayList | LinkedList |
---|---|---|
Random Access (get/set) | Fast (O(1)) | Slow (O(n)) |
Frequent Insertion/Deletion | Slow (shifting required) | Fast (O(1) at head/tail) |
Memory Overhead | Less (single array) | More (node objects with pointers) |
Iteration | Faster due to array locality | Slower |
ArrayList is better for read-heavy workloads, while LinkedList is better for write-heavy (especially at ends).
32. When should you use a Map
instead of a List
or Set
?
Answer:
Use a Map
when you want to store key-value pairs where:
- Keys are unique
- Fast lookup based on a unique key is required
- You want to associate metadata or properties with each entry
Use cases: caching, lookup tables, indexes.
33. How can you make a collection immutable in Java? Answer:
- Using Java 8 and earlier:
List<String> list = Collections.unmodifiableList(new ArrayList<>(original));
- Java 9+ factory methods:
List<String> list = List.of("A", "B");
Map<String, String> map = Map.of("key", "value");
Immutable collections are useful for concurrency and safe API design.
34. What is the best way to iterate over a Map
in Java?
Answer:
for (Map.Entry<K, V> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
This is more efficient than separately calling keySet()
and then get()
.
35. What is the difference between TreeSet
and TreeMap
?
Answer:
-
TreeSet
: Stores unique elements in sorted order. Backed by aTreeMap
. -
TreeMap
: Stores key-value pairs with keys in sorted order.
Use TreeSet
for sorted unique values, and TreeMap
for sorted key-value mappings.
36. Why are Set
and Map
interfaces not directly iterable using enhanced for-each
for values only?
Answer:
-
Set
is iterable as it extendsCollection
. -
Map
is not a subtype ofCollection
, so you must iterate overentrySet()
,keySet()
, orvalues()
individually.
This design ensures clear semantics between key-value and value-only iteration.
37. What are memory leaks in collections and how do you prevent them? Answer: Memory leaks occur when objects are referenced unintentionally, preventing GC. Common causes:
- Growing collections (
List
,Map
) that are never cleared - Improperly scoped static collections
- Caches not using weak references
Solutions:
- Use
WeakHashMap
,SoftReference
, or size-limited caches (e.g., LRU) - Remove unused entries manually or with TTL policies
38. When would you choose TreeSet
or ConcurrentSkipListSet
over HashSet
?
Answer:
- Use
TreeSet
for natural sorting - Use
ConcurrentSkipListSet
for sorted, thread-safe sets - Use
HashSet
when no order and fast operations are needed
39. What is boxing/unboxing overhead in collections, and how does it impact performance? Answer:
- Collections cannot store primitives; they store object wrappers (
int
→Integer
) - Boxing/unboxing creates temporary objects, increasing GC pressure
- Can significantly degrade performance in tight loops or large datasets
Solution: Use primitive collections from libraries like Trove, Eclipse Collections, or fastutil when performance is critical.
40. How do you design a concurrent cache using Java Collections?
Answer:
Use ConcurrentHashMap
combined with:
- Size limitation (manually or via eviction policy)
-
LinkedHashMap
with access-order for LRU cache - Libraries like Caffeine for advanced features
Example of simple LRU cache:
Map<String, String> lruCache = new LinkedHashMap<>(16, 0.75f, true) {
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > 100;
}
};
✅ Java Collections Deep Dive – Part 5 of 5
Topics: Interview Edge Cases, Optimization Patterns, Advanced Usage
41. How would you implement a Least Recently Used (LRU) cache in Java?
Answer:
Use a LinkedHashMap
with access-order and override removeEldestEntry()
:
class LRUCache<K, V> extends LinkedHashMap<K, V> {
private final int capacity;
public LRUCache(int capacity) {
super(capacity, 0.75f, true); // accessOrder = true
this.capacity = capacity;
}
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
}
This ensures that the least recently accessed entry is evicted once the size exceeds capacity.
42. How can you remove duplicates from a list using Set
?
Answer:
List<String> list = Arrays.asList("A", "B", "A", "C");
Set<String> set = new HashSet<>(list);
This removes duplicates but loses order. To preserve insertion order, use:
Set<String> set = new LinkedHashSet<>(list);
43. How do you sort a map by its values? Answer:
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 3); map.put("Banana", 2);
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
list.sort(Map.Entry.comparingByValue());
Result: Entries are sorted by values, though the map itself remains unordered unless reconstructed (e.g., with LinkedHashMap
).
44. What are common interview mistakes made when working with HashMap
in Java?
Answer:
- Forgetting to override
equals()
andhashCode()
in custom key classes - Using
null
keys/values inConcurrentHashMap
- Modifying the map during iteration (causing
ConcurrentModificationException
) - Using
HashMap
in concurrent contexts without proper synchronization
45. How can you iterate and modify a Map
safely?
Answer:
Use iterator-based traversal with entrySet()
:
Iterator<Map.Entry<K, V>> itr = map.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry<K, V> entry = itr.next();
if (shouldRemove(entry)) {
itr.remove(); // safe
}
}
Avoid modifying the map directly inside a for-each loop.
46. How do you detect if two Maps
are equal?
Answer:
map1.equals(map2);
This compares keys and values. Both maps must have the same key-value mappings, regardless of order (e.g., HashMap
vs LinkedHashMap
).
47. How do you compare two sets for equality? Answer:
set1.equals(set2);
Set
equality is based on element content only, not order or internal structure.
48. What are the performance characteristics of HashSet
vs TreeSet
?
Answer:
Feature | HashSet | TreeSet |
---|---|---|
Lookup Time | O(1) average | O(log n) |
Ordering | No | Sorted (natural/custom) |
Nulls | One null allowed | No nulls allowed |
Use case | Fast uniqueness check | Sorted, unique values |
Use HashSet
for fast access, TreeSet
for sorted data.
49. What is an efficient way to count word frequencies in Java? Answer:
Map<String, Integer> freq = new HashMap<>();
for (String word : words) {
freq.put(word, freq.getOrDefault(word, 0) + 1);
}
Or using merge()
:
freq.merge(word, 1, Integer::sum);
This avoids explicit condition checking for presence.
50. How would you ensure thread-safe iteration over a large map without locking the entire structure?
Answer:
Use ConcurrentHashMap
and its weakly consistent iterators:
for (Map.Entry<K, V> entry : concurrentMap.entrySet()) {
process(entry);
}
Alternatively, snapshot the keys if strong consistency is required:
List<K> keys = new ArrayList<>(concurrentMap.keySet());
for (K key : keys) {
process(concurrentMap.get(key));
}