0% found this document useful (0 votes)
2 views31 pages

In Java

Uploaded by

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

In Java

Uploaded by

fantacy.market
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

In Java:

 == checks if two references point to the same object in memory.

 .equals() checks if two objects are considered equal by their value/content (as defined by the
class’s equals method).

Example with Integer:

 Java
 Integer a = 127;
 Integer b = 127;
 [Link](a == b); // true
 [Link]([Link](b)); // true

 Integer a = 128;
 Integer b = 128;
 [Link](a == b); // false
 [Link]([Link](b)); // true

This happens because Java caches Integer objects for values from -128 to 127. Integer variables within this range
refer to the same object when created using valueOf() (default for autoboxing), hence == returns true. Outside this
range, new Integer objects are created, so == returns false.

What is the difference between abstraction and encapsulation in Java? Explain with examples.

Abstraction:

 Definition: Abstraction is the concept of showing only essential details to the user and hiding the
implementation details.

 Example: Abstract classes and interfaces let you declare methods that must be implemented by subclasses,
while the specific implementation is hidden.

 Usage: Use abstract classes or interfaces when you want to define a contract or functionality without
specifying the details.


Java
 abstract class Animal {
 abstract void eat(); // abstraction: we don’t say HOW animals eat
 }

 class Dog extends Animal {
 void eat() { [Link]("Dog eats bones"); } // concrete
implementation
 }
Encapsulation:

 Definition: Encapsulation means wrapping data (fields) and code (methods) together in a class, and
controlling access to them.

 Example: Using private fields and public getter/setter methods so the internal state can’t be accessed directly.

 Usage: Protects the internal state and only allows it to be changed in a controlled manner (through methods).


Java
 class Person {
 private String name;
 public String getName() { return name; }
 public void setName(String name) { [Link] = name; }
 }
Access modifiers:

 private: visible only within the class

 default (no modifier): visible only within package

 protected: visible within package and subclasses (even outside package)

 public: visible everywhere

Why answer like this?

Interviewers want to see that:

 You understand abstraction hides implementation, lets you specify what (not how)

 You understand encapsulation means bundling data and restricting access—using access modifiers

What is Polymorphism in Java? Can you give two types and a real-life code example?

Polymorphism:

 Definition: Polymorphism allows objects to be treated as instances of their parent class, enabling a single
interface with multiple implementations.

 Types:

i. Compile-time polymorphism (Method Overloading):

 Multiple methods with the same name but different parameter lists (number, type, or both).

 Decided at compile time.

 Example:


Java
 class MathUtil {
 int add(int a, int b) { return a + b; }
 int add(int a, int b, int c) { return a + b + c; }
 }
i. Run-time polymorphism (Method Overriding):

 A subclass overrides a method of the parent class.

 Decided at runtime, allows dynamic method dispatch.

 Example:


Java
 class Animal {
 void speak() { [Link]("Animal speaks"); }
 }
 class Dog extends Animal {
 void speak() { [Link]("Dog barks"); }
 }
 Animal a = new Dog();
 [Link](); // prints "Dog barks"
What is the difference between ArrayList and LinkedList in Java? When would you use one over the other?
Provide reasoning and basic example code.

ArrayList:

 Indexed list backed by a dynamic array (contiguous memory).

 Fast access by index (O(1)).

 Insertion/removal at end is fast (O(1)), middle is slow (O(n)) due to shifting elements.

 Good for scenarios where you need to access elements frequently by index.

LinkedList:

 Doubly-linked structure, elements are not stored in contiguous memory.

 Access by index is slow (O(n)), as traversal is needed.

 Insertion/removal at head/tail is fast (O(1)), middle insertion is O(n) if position must be found by index.

 Good for scenarios with frequent insertions/removals from ends.

Example:


List<String> arrList = new ArrayList<>();
 [Link]("A"); // O(1)
 [Link](0); // O(1)

 List<String> linkList = new LinkedList<>();
 [Link]("A"); // O(1)
 [Link]("B"); // O(1)
 [Link](); // prints "Dog barks"

When to use:

 ArrayList: Frequent indexed access, infrequent inserts/removals except at end.

 LinkedList: Frequent insertions/removals at ends, less need for indexed access.

Explain the difference between synchronized methods and synchronized blocks in Java. Why would you
use one over the other? Provide an example.

Synchronized Method:

 When you declare a method as synchronized, only one thread can execute it at a time for a given
object (locks the object’s monitor).

 All code inside the method is synchronized.


Java
 public synchronized void increment() {
 counter++;
 }
 Equivalent to locking on this for instance methods.

Synchronized Block:

 You can synchronize only a portion of code, and explicitly specify the object to lock.


Java
 public void increment() {
 synchronized(this) {
 counter++;
 }
 }
or:


Java
 synchronized(someOtherObject) {
 // code
 }
 More flexible; can reduce time spent holding the lock, improving concurrency.

Why choose one over the other?

 Synchronized block: When you don’t need to lock the whole method, just some code; or to lock on
a different object.

 Synchronized method: Simpler, but less control.

Next Question (Advanced: Exceptions): What is the difference between checked and unchecked
exceptions in Java? Give examples of each, and explain why we use checked exceptions.

Checked Exceptions:

 Must be handled (caught or declared) in code.

 Checked by the compiler at compile time.

 Examples:

o IOException

o SQLException

o FileNotFoundException

 Purpose: Enforce error handling for operations that may fail in normal circumstances (file IO, database
access).

 Java

 try {
 FileReader f = new FileReader("[Link]"); // may throw
FileNotFoundException
 } catch (FileNotFoundException e) {
 [Link]();
 }
Unchecked Exceptions:

 Not checked at compile time.

 Usually indicate programming errors (logic mistakes).

 Examples:

o ArithmeticException (divide by zero)

o NullPointerException

o ArrayIndexOutOfBoundsException

 No compile-time requirement to handle them.

 int a = 10 / 0; // throws ArithmeticException at runtime

Why use checked exceptions?

 Enforces handling errors that are likely during normal program operations.

 Provides more robust/error-resilient programs.

What are generics in Java? Why are they used, and how do they improve type safety? Provide a short
code example.

Generics:

 Definition: Generics allow classes, interfaces, and methods to operate on a specified type (parameterized
types) without sacrificing type safety.

 Why use:

o Type safety: Ensures only objects of the specified type can be added.

o No need for casting: Reduces runtime errors, makes code easier to read.

 Code Example:


Java
 List<Integer> list = new ArrayList<>(); // only Integers allowed
 [Link](42);
 // [Link]("hello"); // compile-time error

 for (Integer i : list) {
 [Link](i); // no cast needed
 }
Without generics:


List list = new ArrayList();
 [Link](42); // OK
 [Link]("hello"); // OK

 // Run-time error when retrieving and casting



What are Java Streams? How do you use them for processing collections? Provide a short
example (with a lambda).

Java Streams, introduced in Java 8, provide a functional programming approach to


process collections of data. Streams support intermediate and terminal operations,
enabling efficient and declarative data processing.

Streams in Java:

 Streams provide a declarative, pipeline way to process collections (like filtering,


mapping, reducing), often using lambda expressions.

 Once a stream is consumed (terminal operation like forEach, collect), it cannot be


reused.

 Common stream operations: filter, map, reduce, collect.

Example:

Java
 List<Integer> numbers = [Link](1, 2, 3, 4, 5);
 // Get squares of even numbers
 List<Integer> squares = [Link]()
 .filter(n -> n % 2 == 0) // filter even numbers
 .map(n -> n * n) // map to squares
 .collect([Link]()); // collect as List

Why answer like this? Interviewers want evidence you know how Java Streams work, their advantages, and basic
code usage.

Explain the difference between heap and stack memory in Java. What is stored where, and how does
garbage collection relate to this?

Stack Memory:

 Used for method call frames, local variables, and primitive data.

 Every time a method is called, a stack frame is created with its local variables and arguments.

 Primitive data (like int, char) is stored directly in stack frames.

 Reference variables are stored in stack, actual objects on the heap.

 Stack memory is smaller and managed by the JVM; grows/shrinks with method calls/returns.

Heap Memory:

 Used for storing all objects (created via new) and arrays.
 Variables in stack that reference objects actually point to their location in the heap.

 Heap is larger and shared across all threads.

Garbage Collection:

 Automatic process in JVM that frees up heap memory by removing objects no longer referenced ("eligible for
GC").

 Stack memory is managed automatically with method calls/returns; heap is managed with GC.

Example:

Java

try {

FileReader f = new FileReader("[Link]"); // may throw FileNotFoundException

} catch (FileNotFoundException e) {

[Link]();

What is the Singleton pattern in Java? Why is it used, and how would you implement a thread-safe
Singleton? Give example code and reasoning.

What is Singleton Pattern?

 Ensures only one instance of a class exists in the JVM, and provides a global point of access to that instance.

Why Use It?

 Useful for resource management (e.g., database connection pools, logging), where only one instance should
manage the resource.

Thread-Safe Implementation:

Example (using synchronized for thread safety):


Java
 public class Singleton {
 private static Singleton instance;

 private Singleton() { } // private constructor

 public static synchronized Singleton getInstance() {
 if (instance == null) {
 instance = new Singleton();
 }
 return instance;
 }
 }
 }
}

Better Approach (using Double-Checked Locking):

Java
 public class Singleton {
 private static volatile Singleton instance;

 private Singleton() { }

 public static Singleton getInstance() {
 if (instance == null) {
 synchronized([Link]) {
 if (instance == null) {
 instance = new Singleton();
 }
 }
 }
 return instance;
 }
 }

Or (Eager Initialization):


public class Singleton {
 private static final Singleton instance = new Singleton();
 private Singleton() { }
 public static Singleton getInstance() { return instance; }
 }

Explain the concept of Functional Interfaces in Java. How do they relate to lambdas? Give an example of
defining and using a custom functional interface.

Functional Interface:

 An interface with exactly one abstract method (can have default/static methods).

 Allows lambda expressions to implement that method concisely.

 Marked with @FunctionalInterface (optional but recommended for clarity).

Example—Defining and Using Custom Functional Interface:


Java

 @FunctionalInterface
 interface MyFunc {
 int operate(int a, int b);
 }

 // Using lambda expression:
 MyFunc sum = (a, b) -> a + b;
 [Link]([Link](5, 3)); // output: 8

Relation to Lambdas:

 You can use a lambda expression anywhere a functional interface is expected, since Java knows which single
method to implement.

Common Examples:

 Runnable (single method: run())

 Comparator<T> (single method: compare(T t1, T t2))

What is Java Reflection? What are some use cases and limitations? Provide a code snippet that gets all
methods of a class at runtime.

Runnable:

 Represents a task to be run in a thread.

 Method:

Java
 void run();
 Does not return a value or throw checked exceptions.

Callable:

 Represents a task and returns a result (or throws exception).

 Method:

Java
 V call() throws Exception;
 Used with classes like ExecutorService, Future.

Example

 Java
 Callable<Integer> task = () -> {
 return 42;
 };

 ExecutorService service = [Link]();
 Future<Integer> future = [Link](task);
 Integer result = [Link](); // result = 42

What is Java Reflection? What are some use cases and limitations? Provide a code snippet that gets all
methods of a class at runtime.

Java Reflection:

 Allows programs to examine or modify the runtime properties (methods, fields, constructors, etc.) of classes.
 Enables dynamic code, such as creating objects, invoking methods, or modifying fields, without knowing their
names at compile time.

Common Use Cases:

 Frameworks (Spring, Hibernate) for dependency injection and serialization

 Testing tools for mocking/stubbing

 Building generic libraries (e.g., JSON serialization)

 Accessing private fields/methods in special cases

Limitations:

 Performance overhead (reflection is slower than direct calls)

 Security risks (can bypass access controls)

 Loss of compile-time type checks

Example—listing all methods of a class:

Example—listing all methods of a class:

 Java
 Class<?> clazz = [Link];
 Method[] methods = [Link]();
 for (Method m : methods) {
 [Link]([Link]());
 }

Explain what happens during Java class loading. What are the different class loaders, and why might you
use a custom class loader?

Java Class Loading Process:

1. Loading: The class file is located and brought into memory by a class loader.

2. Linking: Verifies bytecode, prepares static fields/methods, resolves references.

3. Initialization: Static initializers and static variables are executed.

Types of ClassLoaders:

 Bootstrap ClassLoader: Loads core Java classes ([Link]). Part of the JVM.

 Extension (Platform) ClassLoader: Loads JDK extensions present in the ext directory.

 System/Application ClassLoader: Loads application classes in the classpath.

 Custom ClassLoader: User-defined for specialized loading (e.g., loading encrypted classes, plugins, or
classes from networks/databases).

Why Use a Custom ClassLoader?

 Load classes in a special way (e.g., from encrypted files, over a network, or for class reloading in frameworks).

 Sandbox untrusted code.

Example:

 Java
 ClassLoader cl = [Link]();
 Class<?> clazz = [Link]("[Link]");

What are strong, weak, soft, and phantom references in Java? When would you use each?

Types of References ([Link]):

1. Strong Reference:

o The ordinary reference (e.g., Object obj = new Object();).

o GC does not reclaim unless reference is nullified.

o Usage: Normal objects in application code.

2. Soft Reference:

o SoftReference<Object> ref = new SoftReference<>(obj);

o Cleared only when JVM is low on memory.

o Usage: Caches that can be purged in memory shortage (e.g. image caches).

3. Weak Reference:

o WeakReference<Object> ref = new WeakReference<>(obj);

o Cleared as soon as the only references are weak (even if not low on memory).

o Usage: Canonicalized mappings, like keys in WeakHashMap, to avoid memory leaks.

4. Phantom Reference:

o PhantomReference<Object> ref = new PhantomReference<>(obj, queue);

o Used to know exactly when an object is removed from memory (object is already finalized, used for
resource cleanup, and always enqueued post-GC).

o Usage: Plug-ins for post-mortem cleanup, advanced resource management.

Example:

Example:

 Java
 Object obj = new Object();
 SoftReference<Object> softRef = new SoftReference<>(obj);
 WeakReference<Object> weakRef = new WeakReference<>(obj);
 ReferenceQueue<Object> queue = new ReferenceQueue<>();
 PhantomReference<Object> phantomRef = new PhantomReference<>(obj, queue);

What is a memory leak in Java if there is garbage collection? Can you describe a scenario that causes a
leak, and how would you detect and prevent it?

A memory leak in Java occurs when objects that are no longer needed by the application remain in
memory because the garbage collector cannot remove them.
Memory Leak in Java:

 Occurs when unused objects are still referenced, so they can't be garbage collected, causing memory usage to
grow.

Example Scenario:

 Static collections:

 Java
 static List<User> userList = new ArrayList<>();
If you add user objects and never remove them, even if they’re obsolete, the list keeps growing—objects are never
eligible for GC.

 Listener leaks: Registering event listeners but never deregistering them (e.g., GUI listeners).

 Caches with strong references: E.g., HashMap caching objects but never removing them.

Detection:

 Using tools like VisualVM, Eclipse MAT (Memory Analyzer Tool), YourKit, or JProfiler.

 Look for steady memory increase, many unreachable objects referenced from roots (like static variables).

Prevention:

 Remove references when objects are no longer needed.

 Use weak references in caches or listeners (WeakHashMap).

 Be careful with static fields and inner classes.

 Regularly profile memory in large applications.

What is the difference between composition and inheritance in Java? In which scenarios would you prefer
one over the other, and why? Give examples.

Inheritance:

 (“extends”) Expresses an IS-A relationship.

 Use when one class is a specialized version of another.

Example:

 Java
 class Animal { void speak() {} }
 class Dog extends Animal { void speak() { [Link]("Bark"); } }
Here, Dog IS-A Animal.

Composition:

 Expresses a HAS-A relationship.

 A class is composed of one or more objects from other classes; delegates behavior.

Example:

 Java
 class Engine { void start() {} }
 class Car {
 private Engine engine = new Engine(); // composition
 void startCar() { [Link](); }
 }
Here, Car HAS-A Engine.

Why prefer composition?

 More flexible—behavior can be changed at runtime or by swapping components.

 Leads to looser coupling and easier maintenance.

When to use inheritance?

 When subclassing gives clear code re-use, follows Liskov Substitution, and matches real domain (“Dog IS-A
Animal”).

When to use composition?

 By default—especially for sharing code/behavior, or when combining functionality from different classes.

Serialization in Java

 Definition: Serialization is the process of converting an object into a byte stream so it can be saved to a file,
sent over a network, etc.

 Deserialization: The reverse process — converting a byte stream back into an object.

 Requirement: The class must implement [Link].

transient Keyword in Java

 Definition: The transient keyword is used to exclude a field from serialization.

 Use Case: Prevents sensitive or unnecessary data from being stored (e.g., passwords, temporary values).

Deadlock

In Java multithreading, a deadlock is a situation where two or more threads are permanently blocked because
each thread is waiting for a resource (lock) that another thread holds, and none of them can proceed.

How Deadlock Happens

Deadlock typically occurs when:

1. Multiple threads need multiple shared resources.

2. Each thread acquires a lock on one resource and waits for another resource that is already locked by
another thread.

3. This creates a circular wait where no thread can continue.

Method References ( : : )
Method references in Java provide a way to refer to methods or constructors directly by their names, making the code
more concise and readable. They are particularly useful for replacing simple lambda expressions that call existing
methods.

30 BASIC Rerepeated Quest

1. JVM, JRE, and JDK

 JVM (Java Virtual Machine): Runs compiled Java bytecode; platform-independent; manages memory and
execution.

 JRE (Java Runtime Environment): JVM plus core libraries—enough to run Java applications.

 JDK (Java Development Kit): JRE plus compilers, tools (javac etc)—used to develop Java programs.

2. OOP Principles in Java

Inheritance: Acquires features from parent class;

 Java
 class Animal {}
 class Dog extends Animal {}

Polymorphism: One interface, many implementations;


Java
 Animal a = new Dog(); [Link](); // Calls Dog's version

Encapsulation: Data hidden with accessors;


Java
 private int age; public int getAge() { return age; }

Abstraction: Hides complexity with interfaces/abstract classes;


Java
 abstract class Shape { abstract void draw();

3. Garbage Collection in Java

 Works: JVM automatically frees unused objects.

 Minor GC: Collects young generation (short-lived).


 Major (Old/Full) GC: Collects old generation (long-lived).

 Full GC: Collects both young and old generations.

4. Checked vs Unchecked Exceptions

 Checked: Must be handled/declared. Example: IOException, SQLException

 Unchecked: Runtime errors; not declared. Example: NullPointerException, RuntimeException

5. String Pool

 The Java String Pool is a special memory area for Strings.

 It reduces memory usage by reusing identical String literals.

6. Reverse a String Without Built-in Methods

 Java
 String str = "hello";
 char[] arr = [Link]();
 for(int i = 0, j = [Link]-1; i < j; i++, j--) {
 char temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;
 }
 String reversed = new String(arr);

7. String vs StringBuilder vs StringBuffer

 String: Immutable, slow for heavy edits.

 StringBuilder: Mutable, fast, not thread-safe.

 StringBuffer: Mutable, thread-safe (synchronized), used when safety is needed.

8. Multithreading: Thread vs Runnable

 By extending Thread, you override the run() method; use if you need a new thread type.

 By implementing Runnable, you share resources more easily and use thread pooling.

 Prefer Runnable for greater flexibility and design elegance.

9. synchronized Keyword

 Ensures only one thread executes a method/block at a time, preventing race conditions and data inconsistency.

10. volatile Keyword


 Guarantees visibility of changes to a variable across threads, but doesn’t guarantee atomicity.

 Useful for simple flags; not as robust as synchronized for complex atomicity.

11. HashMap vs Hashtable

 HashMap: Fast, not thread-safe, allows nulls.

 Hashtable: Thread-safe, legacy, does not allow nulls.

 Use HashMap unless legacy or strict thread-safety is required.

12. ConcurrentHashMap

 Allows safe concurrent access with minimal locking by segmenting the map.

 Multiple threads can read/write efficiently without blocking each other.

13. ArrayList vs LinkedList

 ArrayList: Fast random access, slow insert/delete (especially in the middle).

 LinkedList: Fast insert/delete, slow random access.

 Use ArrayList for most cases, LinkedList for frequent inserts/deletes.

14. Comparator vs Comparable

 Comparable: Natural ordering (defines compareTo in the class).

 Comparator: Custom ordering (defines compare in a separate class or via lambda).

15. Memory Leaks & Detection

 Leaks can occur if references are accidentally kept to unused objects.

 Use tools like VisualVM, Eclipse MAT, or profilers to find leaks.

16. fail-fast vs fail-safe Iterators

 fail-fast: Throws exception if collection is modified while iterating (e.g. ArrayList).

 fail-safe: Works on a copy; no exception (e.g. CopyOnWriteArrayList).

17. Java Stream API: Intermediate vs Terminal Operations

 Intermediate: Transform stream (e.g. filter, map), lazy, don’t trigger processing.

 Terminal: Ends pipeline, triggers processing (e.g. collect, forEach).

18. Abstract Classes vs Interfaces


 Abstract Class: Can have implemented methods and fields.

 Interface: Only defines contracts; Java 8+ allows default/static methods.

 Use abstract class for shared code; interface for common contract.

19. Singleton (Thread-safe) Example

 Java
 class Singleton {
 private static volatile Singleton instance;
 private Singleton() {}
 public static Singleton getInstance() {
 if(instance == null) {
 synchronized([Link]) {
 if(instance == null) instance = new Singleton();
 }
 }
 return instance;
 }
 }

20. final vs finally vs finalize

 final: Prevents modification (variables, methods, classes).

 finally: Code block executed after try/catch.

 finalize: Method called before GC (deprecated/not recommended).

21. Deadlocks

 Deadlock: Two/more threads wait forever for each other’s locks.

 Avoid deadlocks: Lock resources in consistent order, use timeouts, or avoid shared locks.

22. HashSet vs TreeSet

 HashSet: Fast, unordered, uses hashCode.

 TreeSet: Sorted, slower, uses compareTo or Comparator.

23. Shallow Copy vs Deep Copy

 Shallow: Copies references.

 Deep: Copies entire object graph (new objects).

24. Immutability (why is String immutable?)

 Prevents accidental/unwanted changes.

 Makes Strings thread-safe and useful as map keys.


 Implemented by marking class/final fields and no setters.

25. Callable vs Runnable with Future

 Runnable: No return value, cannot throw checked exceptions.

 Callable: Returns value, can throw checked.

 Use Future to get result from Callable via ExecutorService.

26. Producer-Consumer with wait()/notify()

 Use synchronized blocks; producer calls notify(), consumer calls wait().

 Both operate on shared object/queue.

27. Static vs Dynamic Binding

 Static (compile-time): Overloading (method resolution via parameter types).

 Dynamic (run-time): Overriding (method resolution via object type).

28. Serialization; serialVersionUID

 Makes object persistable/transmittable.

 serialVersionUID ensures version compatibility.

 Define in class implementing Serializable.

29. Stack vs Queue

 Stack: Last-in-first-out; use Stack or Deque.

 Queue: First-in-first-out; use Queue or LinkedList.

30. Reflection

 Allows runtime inspection/modification of classes and members.

 Used in frameworks, DI, serialization.

 Limitations: Slower, can break security, harder to debug.

Exceptions Quest

What is an Exception? (Absolute Basics)

An Exception is an unexpected event that stops the normal flow of a program.

Examples:

 Divide by zero
 File not found

 Database connection failed

 Null reference

 Wrong input

Checked vs Unchecked Exceptions

Checked Exceptions (Compile-Time Exceptions)

These are the exceptions that the compiler checks at compile-time.


If you don’t handle them, your code won’t compile.

Because these are exceptions that can be predicted and should be handled.

📌 Examples

 IOException

 SQLException

 ClassNotFoundException

 FileNotFoundException

Unchecked Exceptions (Runtime Exceptions)

📌 Definition

Exceptions that occur during runtime, and the compiler does NOT force you to handle them.

📌 Examples

 ArithmeticException

 NullPointerException

 ArrayIndexOutOfBoundsException

 NumberFormatExceptioncompiles fine but fails while running.

Checked by
Type When occurs? Examples
compiler?

Checked
Yes Compile time IOException
Exception

Unchecked NullPointerExcepti
No Runtime
Exception on

Runtime
Error No OutOfMemoryError
(serious)

throw vs throws

throw

Used to manually throw exception.

throws
Used in method signature to declare exceptions.

Common Exceptions (Must Know)

Unchecked

 NullPointerException

 ArithmeticException

 ArrayIndexOutOfBoundsException

 IllegalArgumentException

Checked

 IOException

 FileNotFoundException

 SQLException

finally Block

📌 Purpose

A block that always executes,


even if:

 exception occurs

 no exception occurs

 return statement inside try/catch

throw Keyword

📌 Purpose

Used to manually throw an exception from your code.

📌 When used?

 When you want to create your own custom validation

 When you want to throw an exception deliberately

Program stops after throw


We create the exception object manually

throws Keyword

📌 Purpose

Used in method signature to declare that method may throw exceptions.


📌 Means:

“I am not handling the exception here, someone else should handle it.”

Feature throw throws

Explicitly throw Declare


Purpose
exception exceptions

Method
Used inside Method body
signature

Number of
Only one at a time Multiple allowed
exceptions

Exception type Throwable object Class names

When happens Runtime Compile time

Why Do We Need Custom Exceptions?

Custom exceptions are used when:

 You want to throw meaningful, business-related errors.

 Built-in exceptions don’t represent your scenario.

 You want clean, readable error handling.

✔ Example in real life

 "InvalidAgeException"

 "InsufficientBalanceException"

 "InvalidEmailFormatException"

These tell exactly what the problem is — unlike generic exceptions.

What is try-with-resources?

It is a special form of try block that automatically closes resources after use.

✔ A resource means:

Any object that must be closed after using it, like:

 FileReader

 BufferedReader

 FileInputStream

 Socket

 Connection

 PreparedStatement

All these implement AutoCloseable.


try-with-resources Syntax

Java

try (Resource res = new Resource()) {

// use resource

// resource auto-closed

✔ No need for finally

✔ No manual close()

✔ No resource leak

What is Exception Propagation?

Exception Propagation means:

If a method does not handle an exception, it is passed to the caller.


And if the caller also doesn’t handle → passed further → up the call stack.

Eventually, if no one handles it, Java Runtime (JVM) handles it → program stops.

Exception Chaining?

Exception Chaining means one exception causes another exception, and Java allows you to link them.

It helps you see the root cause of a failure.

📌 Why needed?

When a low-level method throws an exception, a higher-level method might want to throw a different, more
meaningful exception — without losing the original cause.

Consider:

 Database connection fails → SQLException

 Service layer catches it and throws new exception like:


"Unable to fetch user"

But we still want to keep original cause (SQLException).

This is done by chaining:

Java

throw new ServiceException("Unable to fetch user", causeException);

What is the difference between checked and unchecked exceptions?

Answer:
 Checked exceptions → Checked at compile-time (e.g., IOException).

 Unchecked exceptions → Occur at runtime (e.g., NullPointerException).


Compiler does not force handling unchecked exceptions.

✅ Q2. Can finally block be skipped?

Answer:
Yes, in rare cases:

1. [Link]()

2. JVM crash

3. Thread death

Otherwise, finally always executes.

✅ Q3. What is exception propagation?

Answer:
If a method does not handle an exception, it is thrown to its caller.
Unchecked exceptions propagate automatically.
Checked exceptions must be declared using throws.

✅ Q4. What is the difference between throw and throws?

throw → Used to manually throw exception inside method.


throws → Used in method signature to declare exceptions.

✅ Q5. Can we use multiple catch blocks?

Answer:
Yes.
From Java 7 onward, you can also use multi-catch:

Java

catch(IOException | SQLException e)

Show more lines

✅ Q6. What happens when both try and finally have return statements?

Answer:
Return in finally overrides return in try.

✅ Q7. What is exception chaining?

Answer:
Linking one exception as the cause of another:

Java

throw new RuntimeException("Error", cause);


Show more lines

Used to keep the root cause.

✅ Q8. What are suppressed exceptions?

Answer:
In try-with-resources, if both try block and close() throw exceptions,
Exception from close() becomes suppressed, not lost.

✅ Q9. Difference between masked & suppressed exceptions?

Masked → Happens in try-finally; original exception is lost.


Suppressed → Happens in try-with-resources; original exception is kept, cleanup exception stored as suppressed.

✅ Q10. Can a constructor throw exceptions?

Answer:
Yes.
Constructors can throw checked or unchecked exceptions.

✅ Q11. Can overriding method throw new exceptions?

Rules:
✔ Can throw narrower checked exceptions
✔ Can throw any unchecked exception
❌ Cannot throw broader or new checked exceptions

✅ Q12. What happens if an exception occurs in a static block?

Answer:
Unchecked exception → allowed, program fails at class loading.
Checked exception → NOT allowed (compile-time error).

✅ Q13. Why should we avoid catching Exception or Throwable?

Because:

 It hides specific errors

 It may catch Error (OutOfMemoryError)

 Makes debugging harder

Always catch specific exceptions.

✅ Q14. Why should we avoid empty catch blocks?

Because:

 The exception is swallowed


 No message

 No debugging information

 Application silently fails

✅ Q15. What is best practice for closing resources?

Use try-with-resources:

Java

try (BufferedReader br = new BufferedReader(new FileReader("[Link]"))) {

Show more lines

Automatic cleanup → no leaks → clean code.

Real Interview Questions Covered

 Difference between checked & unchecked exception

 throw vs throws

 Exception Propagation

 try-with-resources & suppressed exceptions

 Custom exceptions

 finally behavior

 Masked vs suppressed

 Why avoid catching Exception/Throwable?

 Multiple catch / multi-catch

 Exception chaining

 Why not use exceptions for flow?

 Overriding & exception rules

 What happens in static block?

 What if exception in constructor?

 What if exception before try block?

Collection Quest

What is ArrayList internally?


ArrayList internally uses a dynamic array.

Meaning:

 Starts small

 Expands automatically

 Stores elements continuously in memory

Default capacity after creation

When you create:

List<Integer> list = new ArrayList<>();

Size = 0, Capacity = 0 (YES — this is true in JDK 8+)

ArrayList does not allocate memory until you add the first element.

What happens on first add()?

Creates internal array of size 10 (Default capacity = 10)

So after first add:

 Size = 1

 Capacity = 10

4. What happens when array becomes full?

Let’s say capacity = 10 and you add the 11th element.

ArrayList grows automatically using this formula:

✔ New Capacity = Old Capacity + (Old Capacity / 2)

Which means 1.5 times expansion.

When ArrayList fills up:

A new bigger array is created


Old elements are copied to new array
Reference is shifted to new array
Old array is eligible for GC

👉 Resizing is expensive (O(n))

That’s why:

 Adding at end = usually O(1)

 But sometimes “amortized O(n)” when resize happens

How does ArrayList grow internally?

ArrayList grows by 1.5x its old capacity. It allocates a new array using
newCapacity = oldCapacity + oldCapacity / 2,
then copies old elements to the new array, and the old array is garbage collected.
This resizing is costly, so adding is amortized O(1).
What is LinkedList?

LinkedList is a doubly linked list implementation of:

 List interface

 Deque interface

So it supports:

 FIFO (Queue)

 LIFO (Stack)

 List operations

Each element is stored in a Node object:

class Node<E> {

E item;

Node<E> next;

Node<E> prev;

So each node has:

 item → value

 next → pointer to next node

 prev → pointer to previous node

This is how nodes look:

null ← [A] ↔ [B] ↔ [C] → null

When to use LinkedList?

Use LinkedList when:

 Frequent insertions/removals are required

 You work with Queue/Deque operations

 Accessing elements by index is NOT a priority

Do NOT use LinkedList when:

 You need fast access (get(i) / set(i))


Why LinkedList is slow for get(index)?

Because it must traverse from head or tail until it reaches the index.
No direct memory access.

Is LinkedList thread safe?

No (like ArrayList)

Why LinkedList consumes more memory?

Because each node stores:

 value

 next pointer

 previous pointer

We have “make & edit” dialog in our sismage app


and in this dilapge we have 2 panel
“Compute mismatches”in which we select the wellbore and have this “Compute Mismatch” button on click of which
we are able to see mismatchOutput value table and the of it
once we clicked on this “Compute Mismatch” button we are able to see some value in “with influence radius of” field
and this field is in
“Adjust” panel and one of the dialoge box also popup
of name "Created Mismatches for " + [Link](),
public MismatchesDisplayDialog(SismageJFrame parent, MismatchesProcessOutput output) {

super(parent, "Created Mismatches for " + [Link](), false,


SismageModule.SURFACE_POLYGON_GRAPH_TST_MAP);

[Link] = [Link]();

[Link] = [Link]();

mismatches = output;

initGUI();

}
any way we need to work on “Adjust” creation

so in this “Adjust” panel we have this “Shift and flex”


and “Create new version” radio button once we select both of them and click on “Adjust” button which is bellow
the new horizon is created
but we have noticed the new horizon which is created is below the old horizon or reference one and distance between
them is same as mismatchOutput value the distande between them is correct but we want this new _ adjusted horizon
which got created will created above not below the existing one
I just feel like we need to subtract this adjusted mismatchOutput value not added while creation or vice vesra

analyze the code and class and see what are the factor and thing responsible for this behavioure and see if it posibe to
create this new adjusted horizon above in please of down
give me code changes which are required to perform this task

How does the internal structure of HashMap change after Java 8, and why was this change made? What
problem does it solve?
Before Java 8, each HashMap bucket was a linked list of entries with the same hash code. If many keys collided (bad
hash distribution), these lists could become very long, making get/put operations O(n) for a bucket.

From Java 8 onward, HashMap changes:

 When a bucket becomes too large (default threshold: 8), it turns from a linked list into a balanced binary tree
(specifically, a red-black tree).

 In a tree, lookups and inserts are O(log n) instead of O(n).


Why was this change made?

 To fix performance issues caused by hash collisions and poor hashCode implementations.

 Tree structure ensures consistent performance even with many collisions, preventing denial-of-service attacks
and speeding up operations on large bucket chains.

Summary:
Java 8 improved HashMap's worst-case performance by switching from linked lists to balanced trees within buckets
when collisions are high.

What is CopyOnWriteArrayList? How does it achieve thread safety, and when would you
use it over other collection types?
CopyOnWriteArrayList is a thread-safe variant of ArrayList from [Link].
It achieves thread safety by copying the entire array whenever it's modified (add, set, remove), so readers always see
a consistent snapshot. Its iterators are fail-safe—they iterate over the snapshot, so they never
throw ConcurrentModificationException.

When to use:

 Ideal for situations where reads greatly outnumber writes (e.g., event listeners, configuration objects).

 Not efficient for frequent modifications, since every write copies the array.

 Use when you want thread-safe, lock-free reads with <i>rare</i> mutations.

Summary:
CopyOnWriteArrayList is best for read-heavy concurrency scenarios; it trades update performance for safe, fast reads
and fail-safe iteration.

Explain the difference between fail-fast and fail-safe iterators in Java. Give practical examples of each.

Fail-fast iterators detect structural modifications to the collection during iteration and immediately throw
a ConcurrentModificationException.
Example:

Java

List<String> list = new ArrayList<>();

for (String s : list) {

[Link]("new"); // Throws ConcurrentModificationException

To update safely during iteration, always use the iterator’s remove() method:

Java

Iterator<String> it = [Link]();

while ([Link]()) {

[Link]();

[Link](); // No exception

}
Fail-safe iterators allow concurrent modifications without exception because they iterate over a snapshot or copy of
the collection.
Examples include:

 CopyOnWriteArrayList (iterator over a snapshot)

 ConcurrentHashMap (iterator is weakly consistent)

Modifications during iteration are visible only to future iterators—current iterator never fails.

Summary:
Fail-fast: throws error if modified during iteration (e.g., ArrayList, HashMap).
Fail-safe: allows safe iteration and concurrent updates (e.g., CopyOnWriteArrayList, ConcurrentHashMap).

What is the purpose of IdentityHashMap? How does it differ from HashMap in terms of key equality, and
when is it useful?

IdentityHashMap is a special Map implementation in Java where keys are compared using reference equality (==)
rather than object equality as in HashMap (which uses .equals() for comparison).

 HashMap: Two keys are considered equal if their .equals() method returns true.

 IdentityHashMap: Keys are only considered equal if they are the exact same object in memory (same
reference).

When is it useful?
IdentityHashMap is useful for scenarios where you need to distinguish keys based on their identity, not their contents—
such as object caches, tracking proxy objects, serialization frameworks, or mapping metadata to specific object
instances.

Example:

Java

Map<String, String> hashMap = new HashMap<>();

[Link](new String("a"), "1");

[Link](new String("a"), "2"); // overrides previous entry

Map<String, String> identityMap = new IdentityHashMap<>();

[Link](new String("a"), "1");

[Link](new String("a"), "2"); // both entries remain, since keys are different objects

You might also like