JAVA CORE Flashcards

(27 cards)

1
Q

What is Object-Oriented Programming in Java?

A

Object-Oriented Programming (OOP) is a way of designing software by organizing code around objects that combine state (data) and behavior (methods).

In Java, OOP helps control complexity by:

Encapsulating state

Protecting invariants

Reducing coupling

Improving maintainability and testability

OOP is not about syntax or keywords, but about designing systems that are easier to evolve safely.

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

What is Encapsulation?

A

Encapsulation means hiding internal state and exposing behavior through well-defined methods.

Its main goal is to:

Prevent invalid states

Centralize business rules

Reduce unintended side effects

Example:

public void withdraw(BigDecimal amount) {
    if (amount.signum() <= 0) throw new IllegalArgumentException();
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Why is Encapsulation important?

A

Encapsulation is important because it:

Protects invariants

Makes code easier to reason about

Reduces ripple effects when changes occur

Improves reliability and safety

Without encapsulation, rules are scattered and bugs appear easily.

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

Inheritance vs Composition

A

Inheritance models an is-a relationship and shares behavior via a parent class.

Composition models a has-a relationship by delegating behavior to another object.

Composition is preferred because it:

Reduces coupling

Avoids fragile base class problems

Is easier to test and refactor

Inheritance should be used carefully and only when the relationship is stable.

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

What is Polymorphism?

A

Polymorphism allows different implementations to be treated as the same abstraction.

In Java, this is typically achieved through interfaces.

Example:

PaymentProcessor processor;

The concrete implementation can change without affecting the caller.

Polymorphism enables flexibility and extensibility.

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

What are Java Generics?

A

Java Generics provide compile-time type safety and eliminate the need for casts.

They:

Prevent runtime ClassCastException

Improve code readability

Make APIs self-documenting

Example:

List<String> names = new ArrayList<>();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Why are Java generics invariant?

A

In Java, List<String> is NOT a subtype of List<object>.</object></String>

This prevents unsafe operations such as:

objects.add(10);

Invariance protects type safety at compile time.

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

What is ? extends T?

A

? extends T means an unknown subtype of T.

Use it when:

The collection is a producer

You only need to read from it

Example:

List<? extends Number>

You can read safely, but you cannot add elements.

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

What is ? super T?

A

? super T means an unknown supertype of T.

Use it when:

The collection is a consumer

You need to write into it

Example:

List<? super Integer>

You can add Integer values safely.

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

What is PECS?

A

PECS is a mnemonic:

Producer → Extends

Consumer → Super

It helps decide when to use ? extends or ? super in generics.

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

Difference between == and .equals()

A

== compares references (memory identity).

.equals() compares logical equality, if implemented.

Example:

Integer a = 1000;
Integer b = 1000;

a == b      // false
a.equals(b) // true

Always use .equals() for value comparison.

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

equals() and hashCode() contract

A

If two objects are equal according to equals(), they must have the same hashCode().

Breaking this contract causes bugs in:

HashMap

HashSet

Caches

This can lead to silent, hard-to-diagnose production issues.

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

Why mutable keys break HashMap

A

If an object used as a key in a HashMap is mutable and changes after insertion:

Its hashCode changes

The entry becomes unreachable

Solution:

Make keys immutable

Or avoid mutable fields in equality

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

ArrayList vs LinkedList

A

ArrayList:

  • Fast random access O(1)
  • Compact memory usage
  • Usually best choice

LinkedList:

  • Slow random access O(n)
  • High memory overhead
  • Rarely optimal in practice

LinkedList is almost never faster in real systems.

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

HashMap vs TreeMap vs LinkedHashMap

A

HashMap:

  • O(1) average lookup
  • No order guarantee

TreeMap:

  • Sorted keys
  • O(log n)
  • Requires Comparable or Comparator

LinkedHashMap:

  • Predictable iteration order
  • Useful for LRU caches
17
Q

What is immutability?

A

An immutable object cannot change after creation.

Benefits:

  • Thread safety
  • Safe sharing
  • Easier reasoning
  • Better caching

Immutability reduces bugs and complexity.

18
Q

How to create an immutable class

A

Rules:

  • Class is final
  • Fields are private and final
  • No setters
  • Defensive copies for mutable fields
this.roles = List.copyOf(roles);
19
Q

Checked vs Unchecked Exceptions

A

Checked exceptions:

  • Must be handled
  • Useful at system boundaries (I/O, infra)

Unchecked exceptions:

  • Represent programming errors or invalid state
  • Do not force handling

Both have valid use cases.

20
Q

Best practices for exception handling

A

Validate early

  • Throw meaningful exceptions
  • Wrap low-level exceptions with context
  • Avoid swallowing exceptions
  • Avoid duplicate logging
  • Exceptions should communicate intent clearly.
21
Q

What is a race condition?

A

A race condition occurs when multiple threads access shared mutable state and the result depends on timing.

Example:

count++;

This operation is not atomic.

22
Q

What does synchronized do?

A

synchronized:

  • Ensures mutual exclusion
  • Guarantees visibility
  • Protects compound operations

It prevents race conditions but can reduce performance if overused.

23
Q

What does volatile do?

A

volatile guarantees visibility, not atomicity.

It ensures that changes made by one thread are visible to others.

It does NOT make compound operations thread-safe.

24
Q

What are Atomic classes?

A

Atomic classes (e.g. AtomicInteger) provide thread-safe operations using CAS (Compare-And-Swap).

They avoid explicit locks and scale better in many cases.

25
When to use Streams in Java
Streams are useful for: * Transformations * Filtering * Aggregations They should be avoided when: * Side effects are required * Debugging becomes unclear * Simple loops are more readable Clarity > cleverness.
26
What is map vs flatMap?
`map` transforms elements one-to-one. `flatMap` flattens nested structures. Example: ``` List> → List ```
27
What is a memory leak in Java?
A memory leak occurs when objects are still reachable but no longer useful. Common causes: * Static collections * Unbounded caches * Listeners not removed Garbage Collector cannot clean reachable objects.