Java Interview Flashcards

Prepare for Java interviews (54 cards)

1
Q

What method is used to find if a key exists in a Map?

A

map.containsKey(key)

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

What method is used to get a section of a String by index?

A

str.substring(start, end)

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

In the method substring(start, end), is the end index included or excluded?

A

excluded

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

How do I get the number of keys in a Map?

A

map.size()

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

What does map.getKeys() do in Java?

A

This method doesn’t exist. The actual method is map.keySet() which returns Set<K> containing all keys in the map.</K>

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

How to get all the values from a Map?

A

map.values()

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

What is the difference between JDK, JRE, and JVM?

A

JDK (Java Development Kit): - Contains tools for developing Java applications (compiler, debugger, etc.).

  • The JRE
  • The JVM
  • Development tools:
  • javac (compiler)
  • java (launcher)

JRE (Java Runtime Environment):
- Provides libraries and JVM to run Java programs.

  • The JVM
  • Core libraries (e.g., java.lang, java.util)
  • Supporting files for runtime execution

JVM (Java Virtual Machine): - Executes compiled Java bytecode. Loads .class files.

  • Verifies and interprets bytecode.
  • Manages memory (heap, stack, garbage collection).
  • Provides platform independence — “Write once, run anywhere.”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

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

A

== Compares references (memory addresses) when used with objects.
For primitives, it compares values directly.

.equals() compares values (object content), unless overridden.

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

What are primitive data types in Java?

A

8 primitives: byte, short, int, long, float, double, char, boolean.

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

What is autoboxing and unboxing?

A

Autoboxing: automatic conversion of primitive → wrapper (e.g., int → Integer).

Unboxing (automatic): wrapper → primitive (e.g., Integer → int).

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

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

A

String → immutable. Any modification (e.g., concatenation) creates a new String object in memory. Safe to use in multithreaded environments. Inefficient for frequent modifications (like loops or concatenations).

StringBuilder → mutable, not thread-safe (faster). Not synchronized, so faster than StringBuffer. Best for Single-threaded operations.

StringBuffer → mutable, thread-safe (slower). Synchronized, meaning thread-safe, but slower due to locking overhead. Best for Multi-threaded environments where multiple threads modify the same string.

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

What are the four pillars of OOP?

A

Encapsulation

Inheritance

Polymorphism

Abstraction

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

What is method overloading vs method overriding?

A

Method overloading happens when multiple methods in the same class have the same name but different parameters (different number, type, or order of parameters). It is resolved at compile time — hence called compile-time polymorphism.

Method overriding happens when a subclass provides its own implementation of a method that already exists in its parent class with the same name, parameters, and return type. It is resolved at runtime — hence called runtime polymorphism.

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

Can you override a static method in Java?

A

No — static methods are class-level and not polymorphic. You can hide them, not override them. Static methods belong to the class, not to instances (objects).

Overriding is a runtime concept — it depends on the actual object type.

Static methods are resolved at compile time, based on the reference type, not the object type.

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

What is the difference between an abstract class and an interface?

A

Abstract Class:
- Can contain both abstract and concrete methods.

  • Can declare fields to hold state.
  • Can define constructors for initialization.
  • Supports any access modifier (public, protected, package-private, private).
  • A class can extend only one abstract class (single inheritance).
  • Useful when multiple classes share common code or state.

Interface:
- Methods are implicitly abstract and public by default.

  • Since Java 8, interfaces can include default and static methods.
  • Since Java 9, they can also include private methods for internal reuse.
  • Can only declare public static final constants (no instance fields).
  • A class can implement multiple interfaces (multiple inheritance of type).
  • Useful to define a contract or capability independent of implementation.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the difference between ArrayList and LinkedList?

A

ArrayList:
- Backed by a dynamic array.

  • Fast random access (O(1)).
  • Slow insertion/deletion in the middle (O(n)) due to element shifting.
  • Better cache locality and lower memory overhead.

LinkedList:
- Implemented as a doubly linked list.

  • Fast insertion/deletion at known positions (O(1)) if node reference is known.
  • Slow random access (O(n)) since traversal is required.
  • Higher memory usage due to node objects and pointers.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the difference between HashMap, LinkedHashMap, and TreeMap?

A

HashMap → Unordered; entries are stored based on hash codes of keys.

LinkedHashMap → Maintains insertion order (or access order if configured).

TreeMap → Maintains sorted order of keys according to their natural ordering or a custom Comparator.

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

What happens if you put a duplicate key in a HashMap?

A

The new value replaces the old value for that key.

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

What is the difference between HashSet and TreeSet?

A

HashSet → Unordered; based on a HashMap; offers constant-time operations (O(1) average).

TreeSet → Elements are sorted by their natural order or a custom Comparator; based on a TreeMap; operations are O(log n).

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

What is the difference between checked and unchecked exceptions?

A

Checked exceptions → Represent recoverable conditions; must be declared in the method signature or handled with try-catch.

Examples: IOException, SQLException, FileNotFoundException.

Unchecked exceptions → Represent programming errors; subclasses of RuntimeException; not required to be declared or handled.

Examples: NullPointerException, IndexOutOfBoundsException, ArithmeticException.

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

What does finally do in a try-catch-finally block?

A

The finally block executes always, even if an exception occurs — typically used to close resources.

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

What is garbage collection in Java?

A

Automatic memory management — the JVM removes objects that are no longer reachable from any references.

23
Q

How is ArrayList implemented internally in Java?

A

ArrayList uses a dynamic array internally (Object[] elementData).

It automatically resizes when capacity is exceeded.

Random access (get, set) is O(1), but insertion/removal (except at the end) is O(n) due to shifting.

24
Q

How is LinkedList implemented internally in Java?

A

LinkedList is a doubly-linked list of nodes.

Each node stores: data, next, and prev references.

No random access — traversal is O(n).

Insertions/removals at ends are O(1).

25
How is LinkedHashMap implemented internally in Java?
LinkedHashMap extends HashMap and adds a doubly-linked list connecting entries in insertion order (or access order if enabled). This preserves predictable iteration order. Slightly more memory than HashMap.
26
How is TreeMap implemented internally in Java?
TreeMap uses a Red-Black Tree (a self-balancing binary search tree). Keys are sorted either by natural order or a custom Comparator. Operations like get, put, remove are O(log n).
27
What is the SOLID principle in software design?
Single Responsibility — one reason to change. Open/Closed — open for extension, closed for modification. Liskov Substitution — derived classes should substitute base classes. Interface Segregation — many small interfaces > one large. Dependency Inversion — depend on abstractions, not concretions.
28
What is “KISS” in software development?
Keep It Simple, Stupid.
29
What is the YAGNI principle?
You Aren’t Gonna Need It.
30
What are HTTP status codes?
1xx — Informational 2xx — Success 3xx — Redirection 4xx — Client error 5xx — Server error
31
What is REST?
REST (Representational State Transfer) is an architectural style for APIs. Principles: Uses standard HTTP methods (GET, POST, PUT, DELETE). Stateless communication. Resources identified by URLs. Often uses JSON for data exchange.
32
What is JSON and why is it used in APIs?
JSON (JavaScript Object Notation) is a lightweight data format for representing structured data. It’s easy to read, language-independent, and widely used in REST APIs.
33
What is the difference between PUT, POST and PATCH in REST?
POST → creates a new resource (server assigns ID). PUT → replaces an existing resource entirely (or creates it if missing). PATCH → updates part of a resource (partial change). POST = create PUT = replace PATCH = modify
34
In Java, when a variable (primitive or object reference) is passed to a method, is it passed by reference or by value? And what happens if you reassign the parameter inside the method?
For primitives, the actual value is copied — changing it inside the method does not affect the original variable. For objects, a copy of the reference is passed — you can modify the object’s fields (affects the original), but reassigning the parameter to a new object affects only the local copy of the reference, not the caller’s variable.
35
In Java, what happens when you pass a wrapper type (like Integer, Double, Boolean) to a method and try to modify or reassign it inside the method?
Wrapper types in Java (like Integer, Double, Boolean) are immutable objects. When passed to a method, the reference to the wrapper is passed by value (just like any object). However, since wrappers are immutable, you cannot change their internal value — any operation that looks like a modification actually creates a new object. Reassigning the parameter inside the method does not affect the original variable outside the method.
36
What is a Trie?
A Trie (pronounced “try”) — also called a prefix tree — is a tree-based data structure used to store and search strings efficiently by their prefixes. Each node represents a character, and paths from the root represent words.
37
What can be used as a key in a map?
Any object can be used as a key — but it must satisfy certain requirements for correct behavior: 1. equals() and hashCode() contract For maps like HashMap, LinkedHashMap, or HashSet (which rely on hashing): The key must implement equals() and hashCode() consistently. Two keys that are equal according to equals() must produce the same hash code. The key’s fields used in equals()/hashCode() should be immutable while the key is in the map.
38
How to get the size of a list?
list.size()
39
How to print an array as a string?
System.out.println(Arrays.toString(arr));
40
How to get this size of an array?
array.length
41
How to implement insertion sort?
Start from the second element (index 1), treating the first element as a sorted subarray. For each element, compare it with the elements to its left in the sorted part. Shift all larger elements one position to the right to make space. Insert the current element in its correct position. Repeat until the entire array is sorted.
42
If I modify an element in an array passed as parameter, will the original array be modified, why?
Yes. Arrays in Java are reference types. When passed to a method, a copy of the reference is passed, not a copy of the array. Both variables point to the same array object in memory, so modifying an element affects the original array.
43
Is an array an object in Java?
Yes. In Java, arrays are objects that live on the heap. They have a runtime type (e.g. int[], String[]) and contain fields like .length. You can check this with array.getClass() or instanceof Object, both of which return true.
44
What makes method overriding runtime polymorphism?
The overriding method is chosen at runtime based on the parameters.
45
What is Encapsulation in OOP?
Encapsulation is the bundling of data (attributes) and methods (functions) that operate on that data into a single unit (class). It restricts direct access to some components and protects the internal state of an object by using access modifiers (private, protected, public). This promotes data hiding and allows controlled access through getters and setters.
46
What is Abstraction in OOP?
Abstraction is the concept of hiding complex implementation details and showing only the essential features of an object. It focuses on what an object does rather than how it does it. This is achieved through abstract classes and interfaces, allowing developers to work with simplified models of complex systems and reduce code complexity.
47
What is Polymorphism in OOP?
Polymorphism means 'many forms' and allows objects of different classes to be treated as objects of a common parent class. It enables a single interface to represent different underlying forms (data types). There are two types: compile-time polymorphism (method overloading) and runtime polymorphism (method overriding), allowing flexibility and code reusability.
48
What is Inheritance in OOP?
Inheritance is a mechanism where a new class (child/derived class) derives properties and behaviors from an existing class (parent/base class). It promotes code reusability and establishes a hierarchical relationship between classes. The child class inherits all accessible members of the parent class and can add new features or override existing ones.
49
What is the Singleton Design Pattern?
The Singleton pattern ensures that a class has only one instance throughout the application and provides a global point of access to it. It's implemented by making the constructor private and providing a static method to get the instance. Common uses include database connections, logging, and configuration managers.
50
What is the Observer Design Pattern?
The Observer pattern defines a one-to-many dependency between objects where when one object (subject) changes state, all its dependents (observers) are notified automatically. The subject maintains a list of observers and notifies them of state changes. This pattern is widely used in event handling system.
51
What is the Strategy Design Pattern?
The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. It allows the algorithm to vary independently from clients that use it. In Java, this is typically implemented using interfaces where different classes implement different strategies. Common use cases include sorting algorithms, payment methods, compression algorithms, and validation rules. It promotes the Open/Closed Principle by allowing new strategies without modifying existing code.
52
What is the Decorator Design Pattern?
The Decorator pattern allows behavior to be added to individual objects dynamically without affecting other objects of the same class. It wraps an object with decorator classes that add new functionality while maintaining the same interface. Java's I/O streams are a classic example (BufferedReader wrapping FileReader). This pattern provides a flexible alternative to subclassing for extending functionality and follows the Single Responsibility Principle.
53
What is the Builder Design Pattern?
The Builder pattern separates the construction of a complex object from its representation, allowing step-by-step object creation. It's especially useful for objects with many optional parameters, avoiding telescoping constructors and improving code readability. In Java, it typically uses method chaining with a static inner Builder class that has methods for each parameter and a build() method that returns the final object. Common examples include StringBuilder and building complex objects like HTTP requests or database queries.
54
What is the Factory Design Pattern?
The Factory pattern provides an interface for creating objects without specifying their exact classes. It encapsulates object creation logic in a separate factory class or method, promoting loose coupling. Instead of using 'new' directly, clients request objects from the factory. This makes code more flexible and easier to maintain when adding new types. Common in Java for creating different types of database connections, UI components, or document types.