Prepare for technical interviews with questions by technology, clear explanations, step-by-step solutions and code you can run.
The JVM runs compiled bytecode. The JRE is the JVM plus the standard libraries. The JDK is the JRE plus developer tools like the compiler (javac). Java compiles to bytecode instead of machine code, so the same .class file runs on any operating system that has a JVM.
Encapsulation keeps data private and exposes it through methods. Inheritance lets a class reuse another with extends. Polymorphism lets one method call behave differently depending on the object. Abstraction shows what something does while hiding how.
For objects, == checks whether both references point to the same object in memory. .equals() checks whether the contents are considered equal, if the class overrides it, as String does. Two separate new String("hi") objects are equals but not ==.
Once created, a String can't change, which makes it safe to share across threads and to use as a HashMap key. Literals are stored in a special pool inside the heap, so identical literals reuse one object and save memory.
String is immutable. StringBuilder is mutable and fast but not thread-safe. StringBuffer is mutable and thread-safe, but slower because its methods are synchronized. For building text in a loop, StringBuilder is the usual choice.
An abstract class can hold state, constructors and a mix of implemented and unimplemented methods, but a class can extend only one. An interface defines a contract that many unrelated classes can implement, and since Java 8 it can also carry default methods. Use an abstract class for shared base behavior and an interface for a capability.
Overloading means the same method name with different parameters in one class, resolved at compile time. Overriding means a subclass redefines a parent's method with the same signature, resolved at runtime.
final blocks reassignment, overriding or inheritance. finally is a block that runs after try/catch no matter what. finalize() was a hook called before garbage collection. It's deprecated, so don't rely on it.
A static member belongs to the class, not to any object. All instances share it, and you can use it without creating an object, like Math.max(). Static methods can't directly use instance fields.
The stack holds method calls, local variables and references, and it's cleaned up automatically as methods return. The heap holds the actual objects and is shared across the program, with the garbage collector managing it.
The JVM finds objects that no live reference can reach and reclaims their memory. Modern collectors like G1 split the heap into regions and focus on the ones with the most garbage. You can suggest System.gc(), but the JVM doesn't have to obey.
Checked exceptions (like IOException) must be caught or declared with throws, and the compiler enforces that. Unchecked exceptions (subclasses of RuntimeException, like NullPointerException) usually signal programming mistakes and need no declaration.
A try statement that opens resources in parentheses and closes them automatically at the end, even if an exception occurs. The resource must implement AutoCloseable. It removes the need for messy finally blocks.
Almost always. ArrayList is backed by an array, so reading by index is instant and it's memory-friendly. LinkedList only wins when you constantly insert or remove at the ends and never index into the middle.
It computes the key's hash to pick a bucket in an array. Keys that land in the same bucket are chained together, and since Java 8 long chains convert to balanced trees. Lookups are near O(1) on average, and the table resizes as it fills.
If two objects are equal, they must return the same hash code. If you override one method, override the other, or HashMap and HashSet will misbehave and fail to find your keys.
HashMap isn't thread-safe and allows one null key. Hashtable is old, fully synchronized and slow. ConcurrentHashMap is thread-safe with fine-grained locking, so many threads can work on it at the same time, and it doesn't allow null keys.
Comparable gives a class one natural ordering through compareTo, defined inside the class itself. Comparator is a separate object that defines any ordering you like, so you can sort the same class in many ways.
They give type safety at compile time, so List<String> can only hold strings and you don't need casts. Type information is erased at runtime, which is called type erasure.
Java automatically converts between primitives and wrapper classes, for example int to Integer. Watch out for null when unboxing, because it throws a NullPointerException.
Extending Thread uses up your single inheritance slot. Implementing Runnable separates the task from the thread that runs it, and it works nicely with executors, so it's generally preferred.
synchronized gives mutual exclusion, so only one thread runs the block at a time, and it also makes changes visible. volatile only guarantees visibility of a variable's latest value across threads. It doesn't make compound actions like count++ atomic.
An interface with exactly one abstract method, such as Runnable or Comparator. It can be implemented with a lambda expression, and @FunctionalInterface makes the compiler check the rule.
A way to process collections as a pipeline of steps like filter, map and collect, written declaratively. Streams are lazy, meaning nothing runs until a terminal operation is called, and they don't modify the source collection.
It represents "a value might be missing" in the return type, so callers are forced to handle the empty case instead of getting a surprise null. Use it for return values, not for fields or method parameters.
Iterate through character array swapping characters from start and end pointers.
public static String reverse(String s) {
char[] c = s.toCharArray();
for (int i = 0, j = c.length - 1; i < j; i++, j--) {
char tmp = c[i];
c[i] = c[j];
c[j] = tmp;
}
return new String(c);
}
// reverse("java") -> "avaj"
Reverse integer using modulo 10 arithmetic and compare with original value.
public static boolean isPalindrome(int n) {
int original = n, rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n /= 10;
}
return original == rev;
}
// isPalindrome(1221) -> true
Compute sum of digits raised to power of total digit count.
public static boolean isArmstrong(int n) {
int digits = String.valueOf(n).length();
int sum = 0, temp = n;
while (temp > 0) {
sum += Math.pow(temp % 10, digits);
temp /= 10;
}
return sum == n;
}
// isArmstrong(153) -> true
Iteratively calculate Fibonacci sequence up to n terms.
public static void fib(int n) {
long a = 0, b = 1;
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
long next = a + b;
a = b;
b = next;
}
}
// fib(8) -> 0 1 1 2 3 5 8 13
Check divisibility up to square root of n.
public static boolean isPrime(int n) {
if (n < 2) return false;
for (int i = 2; (long) i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}
Use TreeMap and Map.merge with Integer::sum.
import java.util.*;
Map<Character, Integer> freq = new TreeMap<>();
for (char c : "banana".toCharArray()) {
freq.merge(c, 1, Integer::sum);
}
System.out.println(freq); // {a=3, b=1, n=2}
Pass List into LinkedHashSet to preserve insertion order while removing duplicates.
import java.util.*;
List<Integer> nums = List.of(4, 2, 4, 7, 2, 9);
List<Integer> unique = new ArrayList<>(new LinkedHashSet<>(nums));
System.out.println(unique); // [4, 2, 7, 9]
Track highest and second highest values in a single loop.
public static int secondLargest(int[] arr) {
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int n : arr) {
if (n > first) {
second = first;
first = n;
} else if (n > second && n != first) {
second = n;
}
}
return second;
}
// secondLargest(new int[]{10, 45, 32, 45, 8}) -> 32
Convert strings to lower-case char arrays, sort both, and compare equality.
import java.util.Arrays;
public static boolean isAnagram(String a, String b) {
char[] x = a.toLowerCase().toCharArray();
char[] y = b.toLowerCase().toCharArray();
Arrays.sort(x);
Arrays.sort(y);
return Arrays.equals(x, y);
}
// isAnagram("listen", "silent") -> true
Declare class final, private final fields, initialized in constructor, with no setters.
public final class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
public Point moveBy(int dx, int dy) {
return new Point(x + dx, y + dy); // returns a new object
}
}
Use static inner Holder class (Initialization-on-demand holder idiom).
public class AppConfig {
private AppConfig() {}
private static class Holder {
private static final AppConfig INSTANCE = new AppConfig();
}
public static AppConfig getInstance() {
return Holder.INSTANCE;
}
}
// The instance is created lazily and safely the first time Holder is loaded, so no explicit locking is needed.
Extend Exception class and throw when condition fails.
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
class Wallet {
private double balance = 100;
void pay(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Short by " + (amount - balance));
}
balance -= amount;
}
}
Add synchronized modifier to method ensuring thread-safe atomic increments.
class Counter {
private int count = 0;
public synchronized void increment() { count++; }
public int get() { return count; }
}
public static void main(String[] args) throws InterruptedException {
Counter c = new Counter();
Runnable task = () -> { for (int i = 0; i < 1000; i++) c.increment(); };
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println(c.get()); // always 2000
}
Use Comparator.comparingInt().reversed().thenComparing().
import java.util.*;
record Student(String name, int marks) {}
List<Student> list = new ArrayList<>(List.of(
new Student("Riya", 80), new Student("Amit", 92), new Student("Zoya", 80)));
list.sort(Comparator.comparingInt(Student::marks).reversed()
.thenComparing(Student::name));
list.forEach(s -> System.out.println(s.name() + " " + s.marks()));
// Amit 92, Riya 80, Zoya 80
Use Stream.collect(Collectors.groupingBy(String::length)).
import java.util.*;
import java.util.stream.*;
List<String> words = List.of("pear", "fig", "apple", "kiwi");
Map<Integer, List<String>> byLength =
words.stream().collect(Collectors.groupingBy(String::length));
System.out.println(byLength); // {3=[fig], 4=[pear, kiwi], 5=[apple]}
Use two pointers low and high, computing mid point iteratively.
public static int binarySearch(int[] arr, int target) {
int low = 0, high = arr.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
// binarySearch(new int[]{1, 3, 5, 7, 9}, 7) -> 3
Use Files.newBufferedReader inside try-with-resources and call br.lines().count().
import java.io.*;
import java.nio.file.*;
public static long countLines(String file) throws IOException {
try (BufferedReader br = Files.newBufferedReader(Path.of(file))) {
return br.lines().count();
}
}
Use two pointers to compare elements from both arrays into output array.
public static int[] merge(int[] a, int[] b) {
int[] out = new int[a.length + b.length];
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length) {
out[k++] = (a[i] <= b[j]) ? a[i++] : b[j++];
}
while (i < a.length) out[k++] = a[i++];
while (j < b.length) out[k++] = b[j++];
return out;
}
// merge({1,4,9}, {2,3,10}) -> [1, 2, 3, 4, 9, 10]
Create abstract class Shape with abstract area() method extended by Circle and Rect.
abstract class Shape {
abstract double area();
}
class Circle extends Shape {
private final double r;
Circle(double r) { this.r = r; }
double area() { return Math.PI * r * r; }
}
class Rect extends Shape {
private final double w, h;
Rect(double w, double h) { this.w = w; this.h = h; }
double area() { return w * h; }
}
// Shape[] shapes = { new Circle(2), new Rect(3, 4) };
// for (Shape s : shapes) System.out.printf("%.2f%n", s.area());
// 12.57
// 12.00
Use HashMap to store complement target - num[i] for O(N) lookup.
import java.util.*;
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
Integer j = seen.get(target - nums[i]);
if (j != null) return new int[]{j, i};
seen.put(nums[i], i);
}
return new int[]{};
}
// twoSum(new int[]{2, 7, 11, 15}, 9) -> [0, 1]
Use Deque stack to push open brackets and verify matching pop on closing brackets.
import java.util.*;
public static boolean balanced(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if ("([{".indexOf(c) >= 0) {
stack.push(c);
} else if (")]}".indexOf(c) >= 0) {
if (stack.isEmpty()) return false;
char open = stack.pop();
if ("([{".indexOf(open) != ")]}".indexOf(c)) return false;
}
}
return stack.isEmpty();
}
// balanced("{[()]}") -> true, balanced("(]") -> false
Convert string to lowercase IntStream, filter matching vowels and count.
String s = "Programming Language";
long vowels = s.toLowerCase().chars()
.filter(c -> "aeiou".indexOf(c) != -1)
.count();
System.out.println(vowels); // 7
Swap rows and columns into new matrix t[j][i] = m[i][j].
public static int[][] transpose(int[][] m) {
int[][] t = new int[m[0].length][m.length];
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m[0].length; j++)
t[j][i] = m[i][j];
return t;
}
// {{1,2,3},{4,5,6}} -> {{1,4},{2,5},{3,6}}
Use Stream.findFirst() returning Optional, map to upper case and provide orElse fallback.
import java.util.*;
List<String> names = List.of("asha", "dev", "isha");
Optional<String> match = names.stream()
.filter(n -> n.startsWith("d"))
.findFirst();
System.out.println(match.map(String::toUpperCase).orElse("none")); // DEV
Define enum constant values with custom constructor and helper boolean methods.
enum Priority {
LOW(1), MEDIUM(5), HIGH(10);
private final int weight;
Priority(int weight) { this.weight = weight; }
public boolean isUrgent() { return weight >= 10; }
}
// Priority.HIGH.isUrgent() -> true
// Priority.LOW.isUrgent() -> false
Try searching for keywords like "JWT", "Express", "useEffect", "PDO", "GIL", or "schema".
Connect with DigitalXNode expert interviewers for technical mock interviews, domain assessment, and enterprise job placement.