Core Java Flashcards

(45 cards)

1
Q

What are the core OOP principles in Java?

4 core principles

A

Encapsulation: Bundling data (fields) and methods in a class; restrict access using access modifiers.

Inheritance: A class can inherit fields and methods from another class (using extends).

Polymorphism: Objects can take many forms; methods can be overridden or overloaded.

Abstraction: Hiding complex implementation details; expose only necessary parts (using abstract classes/interfaces).

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

What is the difference between method overriding and overloading?

A

Overriding
* Subclass redefines a method from its superclass with the same signature.
* Used for runtime polymorphism.

Overloading
* Multiple methods in the same class with the same name but different parameters (type/number/order).
* Used for compile-time polymorphism.

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

What is the difference between List and Set in Java?

A

List
* Ordered collection (elements have a defined sequence).
* Allows duplicate elements.
* Examples: ArrayList, LinkedList.

Set
* Unordered collection (no guaranteed order).
* Does not allow duplicates.
* Examples: HashSet, TreeSet.

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

What is the difference between HashMap and TreeMap?

A

HashMap
* No guaranteed order of keys.
* Allows one null key and multiple null values.
* Faster (constant-time operations on average).

TreeMap
* Keys are sorted in natural order or by a custom comparator.
* Does not allow null keys (but allows null values).
* Slower (logarithmic-time operations).

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

What is the difference between an abstract class and an interface, and when would you use each?

A

Abstract Class
* Can have method implementations and state (fields).
* Supports constructors.
* Use when classes share common code/behavior.

Interface
* Only method signatures (Java 8+ allows default/static methods).
* No constructors or state (except static/final fields).
* Use for defining a contract or when multiple inheritance is needed.

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

How does the==operator differ from the.equals()method?

A

== operator
* Compares object references (memory addresses), not content.
* For primitives, compares actual values.

.equals() method
* Compares object contents (can be overridden for custom comparison).
* Used for logical equality.

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

What is the order of initialization in a Java class?

A
  1. Static variables and static blocks (in order of appearance, top-down, only once when class loads)
  2. Instance variables and instance initializer blocks (in order of appearance, each time an object is created)
  3. Constructor (runs after all initializers)

This order applies from superclass to subclass.

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

What are access modifiers in Java?

A

public: Accessible from anywhere.

protected: Accessible within the same package and subclasses.

default (no modifier): Accessible within the same package.

private: Accessible only within the same class.

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

What is the difference between checked and unchecked exceptions?

A

Checked exceptions:
* Must be declared or handled with try-catch.
* Subclasses of Exception (except RuntimeException).
* Example: IOException.

Unchecked exceptions:
* Do not need to be declared or handled.
* Subclasses of RuntimeException.
* Example: NullPointerException.

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

What is the difference between a stack and a queue?

A

Stack:
* Follows LIFO (Last-In, First-Out) order.
* Example operations: push, pop.

Queue:
* Follows FIFO (First-In, First-Out) order.
* Example operations: offer/add, poll/remove.

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

What is the difference between Optional.of and Optional.ofNullable?

A

Optional.of
* Throws NullPointerException if the value is null.
* Use when you are sure the value is not null.

Optional.ofNullable
* Returns an empty Optional if the value is null.
* Use when the value might be null.

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

What is the difference between shallow copy and deep copy?

A

Shallow copy
* Copies object references, not the actual nested objects.
* Changes to nested objects affect both copies.

Deep copy
* Copies the object and all nested objects (full duplication).
* Changes to nested objects do not affect the other copy.

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

What are marker interfaces?

A
  • Interfaces with no methods or fields.
  • Used to “mark” a class for special behavior by the JVM or frameworks.
  • Examples: Serializable, Cloneable.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the purpose of the @FunctionalInterface annotation?

A
  • Indicates the interface is intended to have only one abstract method.
  • Helps the compiler enforce the single-method rule.
  • Used for lambda expressions and method references.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are the inheritance rules in Java?

A
  • A class can extend only one class (single inheritance).
  • A class can implement multiple interfaces.
  • All classes implicitly extend Object if no superclass is specified.
  • Constructors are not inherited.
  • Private members are not inherited, but protected and public members are accessible in subclasses.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the difference between HashMap and HashTable?

A

HashMap
* Not synchronized (not thread-safe).
* Allows one null key and multiple null values.
* Generally faster.

Hashtable
* Synchronized (thread-safe).
* Does not allow any null keys or values.
* Considered legacy; rarely used in new code.

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

What is the difference between object-level and class-level locks?

A

Object-level lock
* Acquired on an instance (using synchronized on instance methods or blocks).
* Only one thread can access synchronized code for that specific object at a time.

Class-level lock
* Acquired on the Class object (using static synchronized methods or synchronized(ClassName.class) blocks).
* Only one thread can access synchronized static code for the entire class at a time.

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

What is the difference between Runnable and Callable?

A

Runnable
* Has a run() method.
* Cannot return a result or throw checked exceptions.

Callable
* Has a call() method.
* Can return a result and throw checked exceptions.

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

What is the difference between Stream.of() and Arrays.stream()?

A

Stream.of()
* Creates a stream from a variable number of arguments or an array (as a single element if not varargs).
* Example: Stream.of(1, 2, 3) or Stream.of(array).

Arrays.stream()
* Creates a stream from the elements of an array (not as a single element).
* Example: Arrays.stream(array).

20
Q

What is the difference between map and flatMap in streams?

A

map
* Transforms each element using a function; returns a stream of the same structure (e.g., Stream<T> to Stream<R>).</R></T>

flatMap
* Transforms each element into a stream and flattens the result into a single stream (e.g., Stream<Stream<R>> to Stream<R>).</R></R>

21
Q

What is a method reference in Java?

A
  • A shorthand for calling a method using :: (double colon) syntax.
  • Used with functional interfaces and streams for cleaner, more readable code.
  • Types: reference to a static method, instance method, or constructor.
  • Example: String::toLowerCase, System.out::println, ArrayList::new.
22
Q

What are streams in Java and what types of operators do they have?

A

Streams
* Abstractions for processing sequences of elements (from collections, arrays, etc.) in a functional style.
* Support operations like filtering, mapping, and reducing data.

Operators
* Intermediate operators: Return a new stream (e.g., filter, map, flatMap, sorted, distinct).
* Terminal operators: Produce a result or side effect (e.g., collect, forEach, reduce, count, anyMatch).

23
Q

What enhancements were made to HashMap in Java 8?

A
  • Improved performance for large maps by using balanced trees (red-black trees) instead of linked lists for buckets with many collisions.
  • Added new methods from the Map interface, such as forEach, computeIfAbsent, computeIfPresent, merge, and getOrDefault.
  • Enhanced support for parallelism with methods like forEach and replaceAll.
24
Q

What is the difference between fail-fast and fail-safe collections?

A

Fail-fast
* Throw ConcurrentModificationException if the collection is modified while iterating.
* Examples: ArrayList, HashMap.

Fail-safe
* Do not throw exceptions on modification during iteration; work on a copy of the collection.
* Examples: CopyOnWriteArrayList, ConcurrentHashMap.

25
What is the difference between ordered and sorted collections?
**Ordered collections** * Maintain the order in which elements are inserted. * Example: LinkedHashSet, ArrayList. **Sorted collections** * Arrange elements according to a specific sort order (natural or custom comparator). * Example: TreeSet, TreeMap.
26
What is the difference between static class and singleton class?
**Static class:** * Java does not have top-level static classes, but you can have static nested classes. * All members are static; cannot be instantiated on its own. **Singleton class:** * Ensures only one instance exists in the application. * Provides a global access point (usually via a static method).
27
What is the difference between a Java singleton and a Spring singleton?
**Java singleton:** * Ensures only one instance of a class exists per JVM using design patterns (e.g., private constructor, static instance). **Spring singleton:** * Only one instance of a bean is created per Spring IoC container (not per JVM). * Multiple containers can have their own singleton instances.
28
What is the difference between Comparator and Comparable?
**Comparable:** * Interface for natural ordering; implement compareTo() in the class itself. * Used when objects have a default sort order. **Comparator:** * Interface for custom ordering; implement compare() in a separate class or as a lambda. * Used to define multiple or alternative sort orders.
29
What is the difference between final, finally, and finalize in Java?
**final:** * Keyword to mark variables as constants, prevent method overriding, or prevent class inheritance. **finally:** * Block used after try-catch to execute code regardless of exceptions. **finalize():** * Method called by the garbage collector before object destruction (deprecated in recent Java versions).
30
What is the difference between abstraction and encapsulation? Can you provide examples?
**Abstraction:** * Hides complex implementation details and shows only essential features. * Achieved using abstract classes and interfaces. * Example: An interface Vehicle with methods like start() and stop(), hiding how they work. **Encapsulation:** * Bundles data (fields) and methods together; restricts direct access to data. * Achieved using private fields and public getters/setters. * Example: A class Person with private age field and public getAge()/setAge() methods.
31
How would you implement encapsulation in a Java class? What are its benefits?
**Implementation:** * Make fields private. * Provide public getters and setters to access or modify fields. * Example: ``` public class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } ``` **Benefits:** * Protects data from unauthorized access/modification. * Improves code maintainability and flexibility. * Allows validation or logic in setters.
32
Can you explain inheritance in Java and provide a practical example?
**Inheritance:** * Mechanism where one class (subclass) acquires fields and methods from another class (superclass). * Promotes code reuse and establishes an "is-a" relationship. * Example: ``` class Animal { void eat() { System.out.println("Eating"); } } class Dog extends Animal { void bark() { System.out.println("Barking"); } } // Usage: Dog d = new Dog(); d.eat(); // Inherited from Animal d.bark(); // Defined in Dog ```
33
What does it mean to "favor composition over inheritance"?
* Prefer building classes by combining (composing) other classes/objects, rather than extending them. * Composition allows more flexibility and easier code changes, as behavior can be changed at runtime. * Inheritance creates tight coupling and can make code harder to maintain. Example: Instead of class Car extends Engine, use class Car { private Engine engine; }.
34
What are the advantages and disadvantages of using immutable objects in a multithreaded Java application?
**Advantages:** * Thread-safe by default (no synchronization needed). * Simpler code, fewer bugs from shared state. * Easy to cache and reuse. **Disadvantages:** * Can lead to more object creation (higher memory usage). * May require complex patterns for updates (since objects can’t be changed).
35
How would you implement immutability in Java? Why is it useful?
**Implementation:** * Make the class final (cannot be subclassed). * Make all fields private and final. * Do not provide setters; initialize fields via constructor. * Return copies of mutable fields in getters. * Example: ``` public final class Person { private final String name; public Person(String name) { this.name = name; } public String getName() { return name; } } ``` **Usefulness:** * Thread-safe by default. * Easier to reason about and debug. * Prevents accidental changes to data.
36
What are the different reference types in Java?
**Strong reference:** * Default type; prevents object from being garbage collected. **Soft reference:** * Cleared only when memory is low; useful for caches. **Weak reference:** * Cleared at next garbage collection; used in WeakHashMap. **Phantom reference:** * Used to track object finalization; enqueued after object is finalized, before memory is reclaimed.
37
When are inner, static inner, local, and anonymous classes used?
**Inner class:** * Defined inside another class; used for logically grouping classes that need access to outer class members. **Static inner class:** * Static member of outer class; used when inner class doesn’t need access to outer class instance. **Local class:** * Defined within a method; used for short-lived, method-specific tasks. **Anonymous class:** * No name; used for quick, one-off implementations (often for interfaces or abstract classes).
38
What is the Law of Demeter?
* A design principle that says: "Only talk to your immediate friends." * An object should only call methods of: * Itself * Its fields * Its method parameters * Objects it creates * Reduces coupling and increases code maintainability.
39
What is variance in Java? What types of variance exist?
**Variance:** * Describes how subtyping between more complex types relates to subtyping between their components (e.g., generics). **Types of variance:** * Covariance: Allows a generic type to accept subtypes (? extends Type). Example: List. * Contravariance: Allows a generic type to accept supertypes (? super Type). Example: List. * Invariance: No subtyping; types must match exactly. Example: List is not a subtype of List.
40
Why use Java generics?
**Why use generics?** * Enable type-safe code (catch errors at compile time). * Eliminate need for casting. * Allow code reuse for different types (e.g., List).
41
What is Type Erasure?
**Type erasure:** * Java compiler removes generic type information at runtime. * All generic types are replaced with their bounds or Object. * Prevents use of generic type info at runtime (e.g., can’t create new T()).
42
What are sealed classes in Java?
* Special classes that restrict which other classes or interfaces can extend or implement them. * Use the sealed, non-sealed, and permits keywords. * Improve control over class hierarchies and enhance code safety.
43
What are the default functional interfaces in Java? Give examples and use cases.
Functional interfaces have a single abstract method; used with lambdas and method references. Common examples: * Predicate: Takes T, returns boolean. Use case: Filtering (stream.filter(x -> x > 0)). * Function: Takes T, returns R. Use case: Mapping (stream.map(String::length)). * Consumer: Takes T, returns nothing. Use case: Performing actions (stream.forEach(System.out::println)). * Supplier: Takes nothing, returns T. Use case: Lazy value generation (Supplier now = Date::new). * UnaryOperator: Takes T, returns T. Use case: Transforming values (list.replaceAll(String::toUpperCase)). * BinaryOperator: Takes two Ts, returns T. Use case: Reducing (stream.reduce(Integer::sum)).
44
What is the significance of the final keyword for classes, methods, variables, and parameters?
* Class: Cannot be subclassed (no inheritance). Example: public final class Utility {} * Method: Cannot be overridden by subclasses. Example: public final void print() {} * Variable: Value cannot be changed after initialization (constant). Example: final int MAX = 10; * Parameter: Value cannot be changed within the method. Example: void setName(final String name) { ... }
45
What are the potential issues with using final fields in multithreaded environments?
**Advantages:** * final fields are guaranteed to be visible to other threads after the constructor finishes (safe publication). **Potential issues:** * If the object reference (this) escapes during construction (e.g., published to another thread before the constructor completes), other threads may see a partially constructed object, even with final fields. * Mutable objects referenced by final fields can still be changed, leading to thread-safety issues.