JAVA DEEP Flashcards

(128 cards)

1
Q

What is the difference between a primitive type and a reference type in Java?

A

Primitive types store actual values (such as int, long, boolean). Reference types store a reference to an object (such as String, List, or a custom class). Primitives cannot be null; references can be null.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Name the 8 primitive types in Java.

A

byte, short, int, long, float, double, char, boolean.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the default value of an int field? What about a local variable?

A

An int field defaults to 0. A local variable has no default value and must be initialized before use.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the difference between == and .equals() for objects in Java?

A

== compares reference identity (whether two references point to the exact same object). .equals() compares logical/value equality as defined by the class (when overridden).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Why can == be misleading with Integer objects?

A

Because Integer uses caching for some small values (commonly -128 to 127). Two Integer objects in that range may refer to the same cached instance, so == may appear to work even though it is not reliable for value comparison.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Is Java pass-by-value or pass-by-reference?

A

Java is always pass-by-value. For objects, the value passed is the reference, which is why you can mutate the object but cannot reassign the caller’s variable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What happens when you pass an object to a method in Java?

A

A copy of the reference is passed by value. The method can modify the object through that reference, but reassigning the parameter does not affect the caller’s reference.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does the final keyword mean for a variable?

A

A final variable cannot be reassigned after initialization. If it is a reference, the reference cannot point to another object, but the object itself may still be mutable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What does final mean for a method?

A

A final method cannot be overridden by subclasses.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What does final mean for a class?

A

A final class cannot be extended. Example: String is final.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Does final make an object immutable?

A

No. final only prevents reassignment of the reference. The object can still change unless the object’s state itself is designed to be immutable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is autoboxing in Java?

A

Autoboxing is the automatic conversion between primitives and their wrapper types, for example int to Integer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is unboxing in Java?

A

Unboxing is the automatic conversion from a wrapper type to its primitive type, for example Integer to int.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Why can autounboxing cause NullPointerException?

A

If a wrapper object like Integer is null and Java tries to unbox it to a primitive int, it throws NullPointerException.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is String immutability and why is it useful?

A

A String cannot be changed after creation. Immutability improves safety, thread-friendliness, caching, and predictable behavior for hashing and reuse.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the difference between String, StringBuilder, and StringBuffer?

A

String is immutable. StringBuilder is mutable and not synchronized, so it is faster in single-threaded contexts. StringBuffer is mutable and synchronized, so it is thread-safe but usually slower.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Why is repeated string concatenation in a loop often inefficient?

A

Because each concatenation can create a new String object. StringBuilder is usually more efficient for repeated concatenation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is an enum in Java and when would you use it?

A

An enum is a special type for a fixed set of constants, such as statuses or roles. It improves type safety and readability over raw strings or ints.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is null in Java?

A

null means a reference points to no object. Accessing methods or fields on a null reference causes NullPointerException.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is the difference between stack and heap in Java?

A

The stack stores method frames and local variables. The heap stores objects and arrays. Stack memory is managed per thread; heap memory is managed by the garbage collector.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is encapsulation?

A

Encapsulation is bundling data and behavior together and hiding internal implementation details so that object invariants are protected.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Why is encapsulation important?

A

It prevents invalid states, reduces coupling, and makes code easier to change safely.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is inheritance?

A

Inheritance lets a class reuse and extend the behavior of another class using extends.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Why is composition often preferred over inheritance?

A

Composition is usually more flexible and less tightly coupled. Inheritance can create fragile class hierarchies and make changes in the parent class risky for subclasses.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What is polymorphism?
Polymorphism allows the same interface or parent type to represent different underlying implementations, enabling flexible and extensible code.
26
What does 'program to an interface, not an implementation' mean?
It means depend on abstractions so implementations can change more easily, code becomes easier to test, and coupling is reduced.
27
What is the Single Responsibility Principle (SRP)?
A class should have one reason to change. In practice, each class should focus on a single responsibility.
28
What is the Open/Closed Principle (OCP)?
Software entities should be open for extension but closed for modification. You should be able to add new behavior without changing existing, stable code too much.
29
What is the Liskov Substitution Principle (LSP)?
Subtypes must be substitutable for their base types without breaking expected behavior.
30
Give an example of an LSP violation.
If a subclass changes behavior in a way that breaks assumptions of the parent type, such as a ReadOnlyList subclass throwing UnsupportedOperationException for inherited mutating methods expected by callers, that can violate LSP.
31
What is the Interface Segregation Principle (ISP)?
Clients should not be forced to depend on methods they do not use. Smaller, focused interfaces are usually better than large 'god interfaces'.
32
What is the Dependency Inversion Principle (DIP)?
High-level modules should depend on abstractions, not concrete implementations. This supports loose coupling and testability.
33
What is a value object?
A value object is defined by its values rather than identity. It is usually immutable and compares using all meaningful fields.
34
What is an entity?
An entity is an object with identity that persists over time, even if some of its attributes change.
35
Why is immutability useful in Java design?
Immutability makes objects safer to share, easier to reason about, naturally thread-friendly, and less error-prone in collections and caching.
36
What is the difference between List, Set, and Map in Java?
List is ordered and allows duplicates. Set stores unique elements. Map stores key-value pairs.
37
When would you choose a List over a Set?
Use a List when order matters or duplicates are allowed. Use a Set when uniqueness matters.
38
What is an ArrayList and when is it a good choice?
ArrayList is a resizable array. It is a good choice for fast random access and append-heavy use cases where frequent middle insertions/removals are not the main operation.
39
What is a LinkedList and when is it useful?
LinkedList is a doubly linked list. It supports efficient insertions/removals at known positions like ends, but random access is slow. In practice, it is less useful than many people think.
40
Why is ArrayList often preferred over LinkedList in real applications?
ArrayList has better cache locality and fast random access. LinkedList has pointer overhead and poor locality, so it is often slower in practice even if some operations look better in Big-O terms.
41
What is the time complexity of ArrayList.get(i)?
O(1), because it accesses an array index directly.
42
What is the time complexity of LinkedList.get(i)?
O(n), because it must traverse nodes.
43
What is a HashSet?
HashSet stores unique elements and is backed internally by a HashMap. It typically offers average O(1) add, remove, and contains operations.
44
What is a TreeSet?
TreeSet stores unique elements in sorted order, usually backed by a TreeMap, with O(log n) operations.
45
What is a HashMap?
HashMap stores key-value pairs and uses hashCode and equals to support average O(1) lookup, insertion, and removal.
46
How does HashMap generally work internally?
It computes a bucket from the key’s hashCode, then uses equals to find the correct entry among possible collisions in that bucket.
47
What is a hash collision?
A hash collision happens when two different keys map to the same bucket. HashMap handles this by checking equals within the bucket structure.
48
What is a TreeMap?
TreeMap stores key-value pairs in sorted order using a tree structure and typically provides O(log n) operations.
49
What is a LinkedHashMap?
LinkedHashMap preserves insertion order, and it can also preserve access order, which makes it useful for LRU cache implementations.
50
What is ConcurrentHashMap?
ConcurrentHashMap is a thread-safe map designed for concurrent access without synchronizing the entire map on most operations.
51
Can HashMap be used safely from multiple threads without synchronization?
No. HashMap is not thread-safe and concurrent modifications can cause incorrect behavior.
52
What is the difference between Collections.unmodifiableList and List.copyOf?
Collections.unmodifiableList returns a read-only view of an existing list, so changes to the original list are still visible. List.copyOf creates an unmodifiable copy.
53
Why are mutable objects risky as HashMap keys?
If fields used in equals/hashCode change after insertion, the object may no longer be found in the correct bucket, causing failed lookups and inconsistent behavior.
54
When would you use a Queue or Deque?
Use a Queue for FIFO processing and a Deque when you need efficient insertion/removal from both ends, such as implementing stacks or sliding window algorithms.
55
What is the difference between ArrayDeque and Stack?
ArrayDeque is generally preferred for stack-like behavior because Stack is an older synchronized class. ArrayDeque is usually faster and more modern.
56
What is the contract of equals() in Java?
equals() should be reflexive, symmetric, transitive, consistent, and return false when compared with null.
57
What is the contract between equals() and hashCode()?
If two objects are equal according to equals(), they must return the same hashCode(). The reverse is not required.
58
Why must you override hashCode() if you override equals()?
Because hash-based collections rely on both methods. If equals changes without hashCode, collections like HashMap and HashSet may behave incorrectly.
59
Can two unequal objects have the same hashCode()?
Yes. That is allowed and is called a hash collision.
60
What should a good hashCode implementation aim for?
It should be consistent with equals and distribute values reasonably well to reduce collisions.
61
How should value objects usually implement equals()?
Value objects usually compare all meaningful fields because they are defined by their values.
62
Why is implementing equals/hashCode for JPA entities tricky?
Because database IDs may be assigned later, proxies may be involved, and mutable identity fields can cause inconsistent behavior in sets and maps.
63
What is the purpose of toString()?
toString() provides a human-readable representation of an object, useful for debugging and logging.
64
What should you avoid including in toString()?
Sensitive data such as passwords, tokens, personal information, or very large nested structures that make logs noisy or unsafe.
65
Why is String a good HashMap key?
String is immutable and has stable equals/hashCode behavior, which makes it safe and predictable as a key.
66
What is the difference between checked and unchecked exceptions?
Checked exceptions must be declared or handled at compile time. Unchecked exceptions extend RuntimeException and do not require explicit handling.
67
Give examples of checked and unchecked exceptions.
Checked: IOException, SQLException. Unchecked: NullPointerException, IllegalArgumentException, IllegalStateException.
68
When are checked exceptions useful?
They can be useful for recoverable conditions, especially at boundaries like file I/O or external system interaction, where the caller may realistically handle the failure.
69
When are unchecked exceptions useful?
They are useful for programming errors, invalid input, broken invariants, and situations where callers typically cannot recover meaningfully.
70
What is the difference between throw and throws?
throw is used to actually throw an exception. throws is used in a method signature to declare possible checked exceptions.
71
Why is swallowing exceptions a bad practice?
Because it hides failures, makes debugging harder, and can leave the system in an inconsistent state.
72
What does 'wrap an exception with context' mean?
It means catching a lower-level exception and throwing a higher-level one that adds meaningful business or technical context, often keeping the original exception as the cause.
73
Why should you avoid logging and rethrowing the same exception everywhere?
It creates duplicate noisy logs and makes debugging harder. Usually exceptions should be logged at the boundary where they are handled.
74
When would you create a custom exception?
When you want to represent a specific domain or application error clearly, such as InsufficientFundsException or CustomerNotFoundException.
75
What is try-with-resources?
It is a Java construct that automatically closes resources implementing AutoCloseable, such as streams or files, even if an exception occurs.
76
Why do generics exist in Java?
Generics provide compile-time type safety, reduce casting, and make APIs clearer and more reusable.
77
Why is List not a subtype of List?
Because Java generics are invariant. If it were allowed, you could add an Object that is not a String into a List through the List reference.
78
What does ? extends T mean?
? extends T means an unknown type that is T or a subtype of T. It is usually used when the structure produces values you want to read as T.
79
What does ? super T mean?
? super T means an unknown type that is T or a supertype of T. It is usually used when the structure consumes values of type T.
80
What does PECS stand for?
Producer Extends, Consumer Super.
81
Why can you read from List but usually not add to it?
Because the exact subtype is unknown. It could be List or List, so adding a Number may not be type-safe.
82
Why can you add Integer to List?
Because the list is guaranteed to accept Integer or one of its supertypes, so inserting an Integer is type-safe.
83
What is type erasure?
Type erasure means generic type information is mostly removed at runtime. The compiler enforces generic types, but runtime types are usually raw forms.
84
Why is instanceof List not allowed?
Because generic type arguments are erased at runtime, so the JVM cannot reliably distinguish List from List.
85
Why can't you create new T() directly in a generic class?
Because the actual type parameter is erased at runtime, so Java does not know which constructor or runtime type to instantiate without additional information.
86
What is a bounded type parameter?
A bounded type parameter restricts the allowed type arguments, for example means T must be Number or a subclass.
87
What is a raw type and why should it be avoided?
A raw type is a generic type used without its type parameter, such as List instead of List. It bypasses type safety and can lead to runtime ClassCastException.
88
What is a thread in Java?
A thread is a path of execution within a program. Multiple threads can run concurrently and share memory in the same process.
89
What is a race condition?
A race condition happens when multiple threads access shared mutable state and the result depends on timing or interleaving.
90
Why is count++ not thread-safe?
Because it is a compound operation: read, modify, write. Multiple threads can interleave these steps and lose updates.
91
What does synchronized do?
synchronized enforces mutual exclusion for a code block or method and also provides memory visibility guarantees between threads.
92
What does volatile do?
volatile guarantees visibility of writes across threads, but it does not make compound operations like increment atomic.
93
What is the difference between volatile and synchronized?
volatile provides visibility only. synchronized provides both visibility and mutual exclusion for critical sections.
94
What is an AtomicInteger and why is it useful?
AtomicInteger supports thread-safe atomic operations like incrementAndGet using low-level compare-and-swap techniques, often without full locking.
95
What is compare-and-swap (CAS)?
CAS is an atomic operation that updates a value only if it still matches an expected old value, which helps implement lock-free algorithms.
96
What is a deadlock?
A deadlock happens when two or more threads wait forever for locks held by each other.
97
How can you reduce the risk of deadlocks?
Acquire locks in a consistent order, keep lock scopes small, avoid nested locking when possible, and use timeouts or higher-level concurrency utilities when appropriate.
98
Why is immutability good for concurrency?
Immutable objects can be shared safely between threads because their state never changes after construction.
99
Why is HashMap not thread-safe?
Because it allows unsynchronized concurrent access to shared internal state, which can lead to incorrect reads, lost updates, or corruption under concurrent writes.
100
What is ExecutorService and why is it preferred over manually creating threads?
ExecutorService manages a pool of worker threads and task execution, which is more scalable and easier to control than creating raw threads directly.
101
What is the difference between submit() and execute() on an ExecutorService?
execute() runs a Runnable and returns no result. submit() returns a Future and can accept Runnable or Callable.
102
What is a Future?
A Future represents the result of an asynchronous computation and allows checking completion, waiting for the result, or cancellation.
103
What is the JVM?
The JVM is the Java Virtual Machine. It runs Java bytecode and provides services such as memory management, garbage collection, and just-in-time compilation.
104
What is bytecode?
Bytecode is the intermediate instruction set produced by the Java compiler and executed by the JVM.
105
What is garbage collection?
Garbage collection is the automatic process of reclaiming memory from objects that are no longer reachable.
106
Can Java have memory leaks even with garbage collection?
Yes. If references to unused objects are still reachable, the garbage collector cannot reclaim them. Examples include static caches, listener leaks, or collections that keep growing.
107
What is GC pressure?
GC pressure refers to the amount of work the garbage collector must do, often increased by creating many short-lived objects or retaining too much memory.
108
Why can too many temporary objects hurt performance?
They increase allocation rate and garbage collection work, which can raise CPU usage and latency.
109
What is the difference between stack memory and heap memory?
Stack memory stores method-local data and call frames. Heap memory stores objects and arrays shared across method calls.
110
How would you start investigating a Java performance issue?
Measure first. Look at CPU, memory, GC behavior, thread states, logs, and profiling data. Then isolate whether the issue is computation, allocation, blocking, I/O, or database related.
111
What is the purpose of the JIT compiler?
The Just-In-Time compiler optimizes frequently executed bytecode into native machine code at runtime for better performance.
112
Why is premature optimization discouraged?
Because it can make code more complex without solving the real bottleneck. It is better to measure first and optimize based on evidence.
113
What does var do in Java?
var enables local variable type inference. The compiler still knows the exact type; it only reduces verbosity in source code.
114
When is var useful and when can it hurt readability?
var is useful when the type is obvious from the right-hand side. It hurts readability when the type is unclear or the variable name does not give enough context.
115
What is a record in Java?
A record is a concise syntax for immutable data carriers that automatically provides components, constructor, equals, hashCode, and toString.
116
Are records always deeply immutable?
No. The record components are final, but if a component refers to a mutable object like a List, that object can still be mutated unless you defensively copy it.
117
What are sealed classes?
Sealed classes restrict which classes can extend or implement them, allowing more controlled hierarchies.
118
What is a switch expression?
A switch expression returns a value and supports a more concise arrow syntax, reducing boilerplate compared to the old switch statement.
119
What are text blocks?
Text blocks are multi-line string literals that improve readability for large strings such as JSON, SQL, or HTML snippets.
120
Why are modern Java features useful in interviews?
They show up-to-date language familiarity and often improve readability, safety, and expressiveness when used appropriately.
121
What is a unit test?
A unit test verifies a small unit of code in isolation, usually quickly and without external dependencies like real databases or network calls.
122
What is an integration test?
An integration test verifies that multiple components work together correctly, often involving frameworks, databases, or real configuration.
123
What makes a good unit test?
A good unit test is fast, deterministic, focused, readable, and checks meaningful behavior rather than implementation details.
124
What is mocking and when is it useful?
Mocking replaces real dependencies with test doubles so you can isolate the unit under test and verify behavior without external systems.
125
What is the Arrange-Act-Assert pattern?
Arrange sets up the test data and collaborators, Act executes the code under test, and Assert verifies the outcome.
126
Why are flaky tests harmful?
Flaky tests reduce trust in the test suite, slow teams down, and make real failures harder to spot.
127
How can you reduce flaky tests?
Avoid real time dependencies, shared mutable state, test order dependence, randomness without control, and external network calls. Keep tests isolated and deterministic.
128
What is the difference between testing behavior and testing implementation details?
Behavior-focused tests verify what the code should do. Implementation-focused tests verify how it does it, which often makes tests brittle during refactoring.