Interview Preparation
Practice real interview questions with detailed answers
232 Questions
Easy
62 questions
JAVA
#1.1
Q1:
What is Java?
Ans:
Java is a general-purpose, class-based, object-oriented programming language designed to have as few implementation dependencies as possible, following the 'write once, run anywhere' principle via the JVM.
JAVA
#1.2
Q2:
What is the difference between JDK, JRE, and JVM?
Ans:
JVM (Java Virtual Machine) executes Java bytecode; JRE (Java Runtime Environment) includes the JVM plus standard libraries needed to run applications; JDK (Java Development Kit) includes the JRE plus development tools like the compiler (javac) needed to build applications.
JAVA
#1.3
Q3:
What is bytecode in Java?
Ans:
Bytecode is the intermediate, platform-independent code produced by the Java compiler (javac) from source code, which the JVM interprets or compiles just-in-time into native machine code.
JAVA
#1.4
Q4:
Why is Java considered platform independent?
Ans:
Java source code is compiled into bytecode, which can run on any device with a compatible JVM, so the same compiled code runs on different operating systems without recompilation.
JAVA
#1.5
Q5:
What is the entry point of a Java application?
Ans:
The main method, public static void main(String[] args), is the entry point where the JVM begins executing a standalone Java application.
Code Example
public class App {
public static void main(String[] args) {
System.out.println("Hello");
}
}
JAVA
#1.6
Q6:
What are the basic data types in Java?
Ans:
Java has eight primitive types: byte, short, int, long, float, double, char, and boolean.
JAVA
#1.7
Q7:
What is the difference between primitive types and reference types?
Ans:
Primitive types store actual values directly in memory (like int, boolean), while reference types (objects, arrays) store a reference/address pointing to the object's data on the heap.
JAVA
#1.8
Q8:
What are wrapper classes in Java?
Ans:
Wrapper classes (Integer, Double, Boolean, Character, etc.) encapsulate primitive types as objects, enabling their use in collections and providing utility methods.
JAVA
#1.9
Q9:
What is the default value of an int and a boolean instance variable?
Ans:
An uninitialized int instance variable defaults to 0, and an uninitialized boolean defaults to false; local variables, however, have no default and must be explicitly initialized before use.
JAVA
#1.10
Q10:
What is the difference between == and .equals() in Java?
Ans:
== compares object references (memory addresses) for objects or actual values for primitives, while .equals() compares the logical content of objects, and can be overridden to define custom equality.
Code Example
String a = new String("hi");
String b = new String("hi");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
JAVA
#1.11
Q11:
What are the access modifiers in Java?
Ans:
Java has four access levels: private (class only), default/package-private (same package), protected (same package plus subclasses), and public (accessible everywhere).
JAVA
#1.12
Q12:
What is a package in Java?
Ans:
A package is a namespace that organizes related classes and interfaces together, helping avoid naming conflicts and controlling access with package-private visibility.
Code Example
package com.example.app;
JAVA
#1.13
Q13:
How do you import a class from another package?
Ans:
You use the import statement at the top of the file, specifying the fully qualified class name or a wildcard to import all classes from a package.
Code Example
import java.util.List;
import java.util.*;
JAVA
#1.14
Q14:
What is the difference between an object and a class?
Ans:
A class is a blueprint or template defining properties and behaviors, while an object is a concrete instance of a class created at runtime using the new keyword.
JAVA
#1.15
Q15:
What is the 'this' keyword used for?
Ans:
'this' refers to the current instance of the class, commonly used to distinguish instance variables from parameters with the same name or to invoke another constructor.
Code Example
class Point {
int x;
Point(int x) { this.x = x; }
}
JAVA
#1.16
Q16:
What is the 'super' keyword used for?
Ans:
'super' refers to the immediate parent class, used to access parent class methods, fields, or invoke the parent's constructor.
Code Example
class Dog extends Animal {
Dog() { super(); }
void sound() { super.sound(); System.out.println("Bark"); }
}
JAVA
#1.17
Q17:
What are command-line arguments in Java?
Ans:
Command-line arguments are values passed to the main method's String[] args parameter when running a Java program from the terminal.
Code Example
public static void main(String[] args) {
System.out.println(args[0]);
}
JAVA
#1.18
Q18:
What is the difference between a local variable and an instance variable?
Ans:
A local variable is declared within a method and only exists during that method's execution, while an instance variable belongs to an object and persists for the object's lifetime.
JAVA
#1.19
Q19:
What is a static variable in Java?
Ans:
A static variable belongs to the class rather than any instance, is shared among all objects of that class, and is initialized only once when the class is loaded.
Code Example
class Counter {
static int count = 0;
Counter() { count++; }
}
JAVA
#1.20
Q20:
What is the difference between static and instance methods?
Ans:
Static methods belong to the class and can be called without creating an instance, while instance methods operate on a specific object and require an instance to be invoked.
JAVA
#1.21
Q21:
What is a constant in Java and how do you declare one?
Ans:
A constant is declared using the final keyword (often combined with static), indicating its value cannot be reassigned after initialization.
Code Example
static final double PI = 3.14159;
JAVA
#1.22
Q22:
What is the instanceof operator used for?
Ans:
instanceof checks whether an object is an instance of a specified class or interface, returning a boolean, and can be used for safe downcasting.
Code Example
if (obj instanceof String) { String s = (String) obj; }
JAVA
#1.23
Q23:
What are the different categories of operators in Java?
Ans:
Java has arithmetic, relational, logical, bitwise, assignment, unary, ternary, and the instanceof operator.
JAVA
#1.24
Q24:
What is the difference between ++i and i++?
Ans:
++i (pre-increment) increments the value before it is used in the expression, while i++ (post-increment) uses the current value in the expression first and then increments it.
Code Example
int i = 5;
int a = ++i; // a=6, i=6
int b = i++; // b=6, i=7
JAVA
#1.25
Q25:
What is the ternary operator in Java?
Ans:
The ternary operator (condition ? valueIfTrue : valueIfFalse) is a shorthand conditional expression that evaluates to one of two values.
Code Example
int max = (a > b) ? a : b;
JAVA
#1.26
Q26:
What are Java's control flow statements?
Ans:
Java supports if-else, switch, for, while, do-while loops, along with break, continue, and return statements to control execution flow.
JAVA
#1.27
Q27:
What is the enhanced for loop (for-each) in Java?
Ans:
The for-each loop iterates over elements of an array or a Collection without needing an explicit index or iterator.
Code Example
for (int num : numbers) {
System.out.println(num);
}
JAVA
#1.28
Q28:
How does a traditional switch statement work in Java?
Ans:
switch evaluates an expression and executes the matching case block; without a break statement, execution falls through to subsequent cases.
Code Example
switch (day) {
case 1: System.out.println("Mon"); break;
default: System.out.println("Other");
}
JAVA
#1.29
Q29:
What is the difference between break and continue?
Ans:
break exits the loop or switch entirely, while continue skips the rest of the current iteration and proceeds to the next one.
JAVA
#1.30
Q30:
What is the difference between while and do-while loops?
Ans:
A while loop checks its condition before executing the loop body, potentially not running at all, while a do-while loop executes the body at least once before checking the condition.
JAVA
#1.31
Q31:
What are the four pillars of OOP?
Ans:
The four pillars are encapsulation (bundling data and methods), inheritance (reusing behavior from parent classes), polymorphism (many forms via overriding/overloading), and abstraction (hiding implementation details behind interfaces).
JAVA
#1.32
Q32:
What is encapsulation in Java?
Ans:
Encapsulation is the practice of keeping fields private and exposing controlled access through public getter and setter methods, protecting an object's internal state from unintended modification.
Code Example
public class Account {
private double balance;
public double getBalance() { return balance; }
public void deposit(double amt) { balance += amt; }
}
JAVA
#1.33
Q33:
What is inheritance in Java?
Ans:
Inheritance allows a class (subclass) to acquire the fields and methods of another class (superclass) using the extends keyword, promoting code reuse.
Code Example
class Animal { void eat() {} }
class Dog extends Animal {}
JAVA
#1.34
Q34:
What is method overloading?
Ans:
Method overloading occurs when multiple methods in the same class share a name but differ in parameter type, number, or order, resolved at compile time (static polymorphism).
Code Example
void print(int a) {}
void print(String s) {}
void print(int a, int b) {}
JAVA
#1.35
Q35:
What is method overriding?
Ans:
Method overriding occurs when a subclass provides its own implementation of a method already defined in its superclass, with the same signature, resolved at runtime (dynamic polymorphism).
Code Example
class Animal { void sound() { System.out.println("..."); } }
class Cat extends Animal { @Override void sound() { System.out.println("Meow"); } }
JAVA
#1.36
Q36:
What is constructor overloading?
Ans:
Constructor overloading is defining multiple constructors in a class with different parameter lists, allowing objects to be created in different ways.
Code Example
class Box {
Box() {}
Box(int size) {}
}
JAVA
#1.37
Q37:
What is a default constructor?
Ans:
If no constructor is explicitly defined, Java automatically provides a no-argument default constructor that initializes fields to their default values.
JAVA
#1.38
Q38:
What is the toString() method used for?
Ans:
toString() returns a string representation of an object, automatically called when the object is used in string concatenation or printed with System.out.println(), and is commonly overridden for meaningful output.
Code Example
@Override
public String toString() { return "Point(" + x + ", " + y + ")"; }
JAVA
#1.39
Q39:
What is an exception in Java?
Ans:
An exception is an event that disrupts normal program flow, represented as an object of a class extending Throwable, which can be thrown and caught to handle errors gracefully.
JAVA
#1.40
Q40:
How do you handle exceptions in Java?
Ans:
You use a try block for risky code, one or more catch blocks to handle specific exception types, and an optional finally block for cleanup code that always runs.
Code Example
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} finally {
System.out.println("Done");
}
JAVA
#1.41
Q41:
What is a stack trace?
Ans:
A stack trace is a report of the call stack at the point an exception was thrown, showing the sequence of method calls that led to the error, useful for debugging.
JAVA
#1.42
Q42:
What is the Java Collections Framework?
Ans:
The Collections Framework is a unified architecture of interfaces (List, Set, Map, Queue) and classes (ArrayList, HashMap, HashSet, etc.) for storing and manipulating groups of objects.
JAVA
#1.43
Q43:
What is the difference between List, Set, and Map?
Ans:
A List is an ordered collection that allows duplicate elements, a Set is a collection that disallows duplicates, and a Map stores key-value pairs where each key is unique.
JAVA
#1.44
Q44:
What is the difference between Array and ArrayList in Java?
Ans:
An array has a fixed size determined at creation and can hold primitives or objects, while an ArrayList is a resizable collection that can only hold objects (using autoboxing for primitives) and provides many convenience methods.
JAVA
#1.45
Q45:
How do you sort a List in Java?
Ans:
You can use Collections.sort() for natural ordering (requires Comparable) or pass a Comparator, or call the list's own sort() method introduced in Java 8.
Code Example
Collections.sort(names);
names.sort(Comparator.reverseOrder());
JAVA
#1.46
Q46:
How do you compare two strings for equality in Java?
Ans:
You should use the .equals() method to compare the content of two strings, since == compares references and may return false even for strings with identical content.
Code Example
String a = "hi";
String b = new String("hi");
System.out.println(a.equals(b)); // true
JAVA
#1.47
Q47:
What is the difference between equals() and equalsIgnoreCase()?
Ans:
equals() performs a case-sensitive comparison of string content, while equalsIgnoreCase() ignores letter case when comparing.
JAVA
#1.48
Q48:
How do you convert a String to an int and vice versa?
Ans:
Integer.parseInt() converts a String to a primitive int, and String.valueOf() or Integer.toString() converts an int to a String.
Code Example
int n = Integer.parseInt("42");
String s = String.valueOf(42);
JAVA
#1.49
Q49:
How do you split a String in Java?
Ans:
The split() method divides a string into an array of substrings based on a given regular expression delimiter.
Code Example
String[] parts = "a,b,c".split(",");
JAVA
#1.50
Q50:
How do you check if a string is null or empty in Java?
Ans:
You can check (str == null || str.isEmpty()), or use isBlank() (Java 11+) to also treat whitespace-only strings as empty.
JAVA
#1.51
Q51:
What is the difference between length() and length in Java?
Ans:
length() is a method used on String objects to get the number of characters, while length is a field (not a method) used on arrays to get the number of elements.
Code Example
String s = "hello"; s.length(); // 5
int[] arr = new int[5]; arr.length; // 5
JAVA
#1.52
Q52:
How do you create a multidimensional array in Java?
Ans:
You declare it with multiple sets of square brackets, and can initialize it with nested array literals or by specifying dimensions with new.
Code Example
int[][] matrix = new int[3][3];
int[][] grid = {{1,2},{3,4}};
JAVA
#1.53
Q53:
How do you sort an array in Java?
Ans:
Arrays.sort() sorts a primitive or object array in place, using natural ordering by default or a supplied Comparator for object arrays.
Code Example
int[] nums = {5,3,1,4};
Arrays.sort(nums);
JAVA
#1.54
Q54:
How do you reverse a String in Java?
Ans:
You can convert it to a StringBuilder and call reverse(), since String itself has no reverse method.
Code Example
String reversed = new StringBuilder("hello").reverse().toString();
JAVA
#1.55
Q55:
What is a thread in Java?
Ans:
A thread is a lightweight sub-process, the smallest unit of execution, allowing a program to perform multiple operations concurrently.
JAVA
#1.56
Q56:
What are the two ways to create a thread in Java?
Ans:
You can extend the Thread class and override its run() method, or implement the Runnable interface and pass an instance to a Thread object.
Code Example
class MyThread extends Thread {
public void run() { System.out.println("Running"); }
}
class MyTask implements Runnable {
public void run() { System.out.println("Running"); }
}
new Thread(new MyTask()).start();
JAVA
#1.57
Q57:
What is garbage collection in Java?
Ans:
Garbage collection is the automatic process by which the JVM reclaims memory occupied by objects that are no longer reachable from any live references, freeing developers from manual memory deallocation.
JAVA
#1.58
Q58:
What is the difference between an interface and a class regarding instantiation?
Ans:
An interface cannot be instantiated directly (though Java 8+ allows default/static methods), while a class can be instantiated using the new keyword unless it's declared abstract.
JAVA
#1.59
Q59:
What is the purpose of the @Override annotation?
Ans:
@Override signals to the compiler that a method is intended to override a superclass or interface method, causing a compile-time error if no matching method actually exists to override, helping catch typos or signature mismatches.
JAVA
#1.60
Q60:
What is JDBC?
Ans:
JDBC (Java Database Connectivity) is a Java API that provides a standard way to connect to and interact with relational databases using SQL, regardless of the specific database vendor.
JAVA
#1.61
Q61:
How do you convert a List to an array and vice versa?
Ans:
You use list.toArray() to convert a List to an array, and Arrays.asList() or List.of() to create a List view or immutable list from an array.
Code Example
String[] arr = list.toArray(new String[0]);
List<String> list2 = Arrays.asList(arr);
JAVA
#1.62
Q62:
What happens when you don't override toString() for a custom object?
Ans:
The default Object.toString() implementation is used, which returns the class name followed by an '@' and the object's hash code in hexadecimal, which is rarely useful for debugging.
Medium
127 questions
JAVA
#2.1
Q1:
Why must the main method be static?
Ans:
It must be static so the JVM can invoke it directly using the class name without first creating an instance of the class.
JAVA
#2.2
Q2:
What is autoboxing and unboxing in Java?
Ans:
Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class (e.g., int to Integer), and unboxing is the reverse conversion, both handled automatically by the compiler.
Code Example
Integer boxed = 10; // autoboxing
int unboxed = boxed; // unboxing
JAVA
#2.3
Q3:
What is type casting in Java and what are its two kinds?
Ans:
Type casting converts a value from one type to another; widening (implicit) casting converts a smaller type to a larger one automatically, while narrowing (explicit) casting requires an explicit cast and may lose data.
Code Example
int i = 100;
long l = i; // widening
int j = (int) 3.99; // narrowing, j = 3
JAVA
#2.4
Q4:
What is the String pool in Java?
Ans:
The String pool (or intern pool) is a special memory area in the heap where the JVM stores unique String literals, allowing multiple references to the same literal to share one object and save memory.
JAVA
#2.5
Q5:
Why are Strings immutable in Java?
Ans:
Strings are immutable for security, thread-safety, and to support the String pool's caching mechanism; once created, a String object's content cannot change, and operations like concatenation return new String objects.
JAVA
#2.6
Q6:
What is the difference between String, StringBuilder, and StringBuffer?
Ans:
String is immutable, StringBuilder is mutable and not synchronized (faster in single-threaded contexts), and StringBuffer is mutable and synchronized, making it thread-safe but slightly slower.
Code Example
StringBuilder sb = new StringBuilder();
sb.append("Hello").append(" World");
JAVA
#2.7
Q7:
What is the difference between var and explicit type declaration in Java 10+?
Ans:
var lets the compiler infer the variable's type from the assigned value at compile time, reducing verbosity, while the actual type remains static and fixed just as if explicitly declared.
Code Example
var list = new ArrayList<String>(); // inferred as ArrayList<String>
JAVA
#2.8
Q8:
Can a static method access instance variables directly?
Ans:
No, a static method cannot directly access instance variables or instance methods because it has no reference to any specific object (no 'this').
JAVA
#2.9
Q9:
What is the difference between & and && in Java?
Ans:
& is a bitwise/logical AND that always evaluates both operands, while && is a short-circuit logical AND that skips evaluating the right operand if the left is already false.
JAVA
#2.10
Q10:
What are switch expressions introduced in Java 14?
Ans:
Switch expressions allow switch to be used as an expression that returns a value, support the arrow (->) syntax without fall-through, and can use yield to return a value from a block.
Code Example
int numLetters = switch (day) {
case MONDAY, FRIDAY -> 6;
case TUESDAY -> 7;
default -> 0;
};
JAVA
#2.11
Q11:
Can you use a labeled break in Java?
Ans:
Yes, a labeled break allows breaking out of an outer loop from within a nested loop by specifying the label of the loop to exit.
Code Example
outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) break outer;
}
}
JAVA
#2.12
Q12:
Why doesn't Java support multiple inheritance of classes?
Ans:
Java disallows multiple class inheritance to avoid the 'diamond problem', where ambiguity arises if two parent classes define the same method; instead, Java allows implementing multiple interfaces to achieve similar flexibility.
JAVA
#2.13
Q13:
What is the difference between method overloading and overriding?
Ans:
Overloading involves multiple methods with the same name but different parameters within the same class (compile-time), while overriding involves a subclass redefining a parent method with an identical signature (runtime polymorphism).
JAVA
#2.14
Q14:
What is polymorphism in Java?
Ans:
Polymorphism allows objects of different classes to be treated as instances of a common superclass or interface, enabling the same method call to behave differently depending on the actual object type.
Code Example
Animal a = new Dog();
a.sound(); // calls Dog's overridden method
JAVA
#2.15
Q15:
What is an abstract class in Java?
Ans:
An abstract class cannot be instantiated and may contain both abstract methods (without a body) and concrete methods, serving as a partial blueprint for subclasses.
Code Example
abstract class Shape {
abstract double area();
void describe() { System.out.println("A shape"); }
}
JAVA
#2.16
Q16:
What is an interface in Java?
Ans:
An interface defines a contract of abstract methods (and optionally default/static methods) that implementing classes must fulfill, without providing state, traditionally supporting multiple inheritance of type.
Code Example
interface Drawable {
void draw();
}
class Circle implements Drawable {
public void draw() { System.out.println("Drawing circle"); }
}
JAVA
#2.17
Q17:
What is the difference between an abstract class and an interface?
Ans:
An abstract class can have constructors, instance fields, and a mix of abstract and concrete methods, and a class can extend only one; an interface traditionally only declares method signatures (plus default/static methods since Java 8) and a class can implement multiple interfaces.
JAVA
#2.18
Q18:
Can an interface have method implementations?
Ans:
Since Java 8, interfaces can include default methods (with a body, using the default keyword) and static methods, though they still cannot have instance state.
Code Example
interface Vehicle {
default void honk() { System.out.println("Beep"); }
}
JAVA
#2.19
Q19:
What is a functional interface in Java?
Ans:
A functional interface is an interface with exactly one abstract method, optionally annotated with @FunctionalInterface, intended to be implemented using a lambda expression or method reference.
Code Example
@FunctionalInterface
interface Calculator {
int operate(int a, int b);
}
JAVA
#2.20
Q20:
Can constructors be inherited in Java?
Ans:
No, constructors are not inherited by subclasses, but a subclass constructor can invoke a superclass constructor explicitly using super().
JAVA
#2.21
Q21:
What is the purpose of the final keyword in Java?
Ans:
final can be applied to variables (making them constants), methods (preventing overriding), and classes (preventing extension/inheritance).
Code Example
final class Utility {}
class Base { final void init() {} }
final int MAX = 100;
JAVA
#2.22
Q22:
What is a marker interface?
Ans:
A marker interface has no methods or fields and is used to signal metadata about a class to the JVM or a framework, such as Serializable or Cloneable.
JAVA
#2.23
Q23:
What is the Object class in Java?
Ans:
Object is the root superclass of all Java classes; every class implicitly extends Object and inherits its methods like equals(), hashCode(), toString(), and getClass().
JAVA
#2.24
Q24:
Why should you override equals() and hashCode() together?
Ans:
The general contract requires that equal objects must have equal hash codes; overriding only equals() without hashCode() can break the behavior of hash-based collections like HashMap and HashSet.
JAVA
#2.25
Q25:
What is composition in OOP and how does it differ from inheritance?
Ans:
Composition involves building a class using instances of other classes as fields (a 'has-a' relationship) rather than extending them (an 'is-a' relationship), often preferred for flexibility and avoiding tight coupling.
Code Example
class Engine {}
class Car {
private Engine engine = new Engine(); // composition
}
JAVA
#2.26
Q26:
What is a nested class in Java?
Ans:
A nested class is a class defined within another class; it can be static (not tied to an instance of the outer class) or non-static/inner (tied to and holding an implicit reference to an outer instance).
Code Example
class Outer {
static class StaticNested {}
class Inner {}
}
JAVA
#2.27
Q27:
What is an anonymous inner class?
Ans:
An anonymous inner class is a class without a name, defined and instantiated in a single expression, typically used to provide a one-off implementation of an interface or abstract class.
Code Example
Runnable r = new Runnable() {
public void run() { System.out.println("Running"); }
};
JAVA
#2.28
Q28:
Can an abstract class have a constructor?
Ans:
Yes, an abstract class can have a constructor, which is called when a subclass instance is created via super(), even though the abstract class itself cannot be instantiated directly.
JAVA
#2.29
Q29:
What is the difference between checked and unchecked exceptions?
Ans:
Checked exceptions (like IOException) must be declared or handled at compile time, while unchecked exceptions (RuntimeException and its subclasses like NullPointerException) are not required to be declared or caught.
JAVA
#2.30
Q30:
What is the difference between Error and Exception in Java?
Ans:
Error represents serious problems that applications typically should not try to catch (like OutOfMemoryError), while Exception represents conditions an application might want to catch and handle.
JAVA
#2.31
Q31:
What is the purpose of the finally block?
Ans:
The finally block contains code that always executes after try/catch, regardless of whether an exception occurred, typically used to release resources like closing files or connections.
JAVA
#2.32
Q32:
What is try-with-resources in Java?
Ans:
Introduced in Java 7, try-with-resources automatically closes resources (implementing AutoCloseable) declared in the try statement's parentheses at the end of the block, eliminating the need for manual finally cleanup.
Code Example
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
System.out.println(br.readLine());
}
JAVA
#2.33
Q33:
How do you create a custom exception in Java?
Ans:
You create a class extending Exception (for checked) or RuntimeException (for unchecked), typically with constructors that pass a message to the superclass.
Code Example
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) { super(message); }
}
JAVA
#2.34
Q34:
What is the difference between throw and throws?
Ans:
throw is used to explicitly raise an exception instance within a method body, while throws is used in a method signature to declare that the method might propagate a checked exception to its caller.
Code Example
void withdraw(double amt) throws InsufficientFundsException {
if (amt > balance) throw new InsufficientFundsException("Not enough");
}
JAVA
#2.35
Q35:
Can you have multiple catch blocks for a single try?
Ans:
Yes, you can have multiple catch blocks to handle different exception types, and Java also supports multi-catch syntax to handle several exception types in a single block using a pipe (|).
Code Example
try {
// risky code
} catch (IOException | SQLException e) {
e.printStackTrace();
}
JAVA
#2.36
Q36:
What happens if an exception is not caught?
Ans:
If an exception propagates up through all method calls without being caught, it reaches the JVM's default handler, which prints a stack trace and terminates the thread (or the program if it's the main thread).
JAVA
#2.37
Q37:
Is it a good practice to catch generic Exception or Throwable?
Ans:
Generally no; catching overly broad exception types can mask specific errors and make debugging harder, so it's better to catch the most specific exception types applicable to the situation.
JAVA
#2.38
Q38:
What is the difference between NullPointerException and ClassCastException?
Ans:
NullPointerException occurs when trying to use a reference variable that points to null, while ClassCastException occurs when attempting an invalid cast between incompatible object types.
JAVA
#2.39
Q39:
What is the difference between ArrayList and LinkedList?
Ans:
ArrayList is backed by a dynamic array offering fast random access (O(1)) but slower insertions/deletions in the middle (O(n)), while LinkedList is backed by a doubly linked list offering fast insertions/deletions but slower random access.
JAVA
#2.40
Q40:
What is the difference between ArrayList and Vector?
Ans:
ArrayList is not synchronized and generally faster, while Vector is synchronized (thread-safe) but has more overhead; Vector is considered a legacy class largely superseded by ArrayList with external synchronization when needed.
JAVA
#2.41
Q41:
What is the difference between HashMap and TreeMap?
Ans:
HashMap stores key-value pairs with no guaranteed order and offers average O(1) access, while TreeMap stores entries sorted by key (natural ordering or a Comparator) and offers O(log n) access via a red-black tree.
JAVA
#2.42
Q42:
What is the difference between HashMap and LinkedHashMap?
Ans:
HashMap does not guarantee any order of iteration, while LinkedHashMap maintains insertion order (or optionally access order) by using a linked list alongside the hash table.
JAVA
#2.43
Q43:
What is the difference between HashMap and Hashtable?
Ans:
HashMap is not synchronized and allows one null key and multiple null values, while Hashtable is synchronized (thread-safe legacy class) and does not allow null keys or values.
JAVA
#2.44
Q44:
What is the difference between HashSet and TreeSet?
Ans:
HashSet stores unique elements with no guaranteed order backed by a HashMap, while TreeSet stores unique elements in sorted order backed by a TreeMap (red-black tree).
JAVA
#2.45
Q45:
What is the difference between Comparable and Comparator?
Ans:
Comparable is implemented by a class itself to define its natural ordering via compareTo(), while Comparator is a separate class defining custom ordering logic via compare(), allowing multiple different sort orders for the same type.
Code Example
class Person implements Comparable<Person> {
public int compareTo(Person p) { return this.age - p.age; }
}
Comparator<Person> byName = (p1, p2) -> p1.name.compareTo(p2.name);
JAVA
#2.46
Q46:
What is an Iterator in Java?
Ans:
An Iterator is an object that allows traversing a collection sequentially, providing hasNext(), next(), and remove() methods, and is the standard way to safely remove elements while iterating.
Code Example
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
if (s.isEmpty()) it.remove();
}
JAVA
#2.47
Q47:
What is the difference between Iterator and ListIterator?
Ans:
Iterator allows forward-only traversal and element removal, while ListIterator (available only for List implementations) additionally supports backward traversal, element replacement, and insertion.
JAVA
#2.48
Q48:
What is the Queue interface used for?
Ans:
Queue represents a collection designed for holding elements prior to processing, typically in FIFO order, with implementations like LinkedList and PriorityQueue.
JAVA
#2.49
Q49:
What is a Deque in Java?
Ans:
Deque (double-ended queue) supports insertion and removal of elements from both ends, and can be used to implement both stacks and queues; ArrayDeque is a common implementation.
JAVA
#2.50
Q50:
What is the difference between poll() and remove() in a Queue?
Ans:
Both remove and return the head of the queue, but poll() returns null if the queue is empty, while remove() throws a NoSuchElementException.
JAVA
#2.51
Q51:
What is the difference between Collection and Collections in Java?
Ans:
Collection is a root interface representing a group of objects, while Collections is a utility class providing static methods to operate on collections, like sorting, searching, and creating immutable collections.
JAVA
#2.52
Q52:
How do you make a collection immutable in Java?
Ans:
You can use Collections.unmodifiableList()/Map()/Set() to wrap an existing collection, or since Java 9, use List.of(), Set.of(), and Map.of() to create truly immutable collections directly.
Code Example
List<String> immutable = List.of("a", "b", "c");
JAVA
#2.53
Q53:
What is the PriorityQueue used for?
Ans:
PriorityQueue is a queue implementation where elements are ordered according to their natural ordering or a provided Comparator, always retrieving the smallest (or highest priority) element first.
JAVA
#2.54
Q54:
What are generics in Java?
Ans:
Generics allow classes, interfaces, and methods to operate on typed parameters, providing compile-time type safety and eliminating the need for explicit casting.
Code Example
List<String> names = new ArrayList<>();
names.add("Alice"); // compile-time type checked
JAVA
#2.55
Q55:
What is a bounded type parameter in generics?
Ans:
A bounded type parameter restricts the types that can be used as a type argument using the extends keyword, such as , allowing calls to methods defined on that bound.
Code Example
public static <T extends Comparable<T>> T max(T a, T b) {
return a.compareTo(b) > 0 ? a : b;
}
JAVA
#2.56
Q56:
What is a generic method in Java?
Ans:
A generic method declares its own type parameter(s), independent of the class's generics, placed before the return type in the method signature.
Code Example
public static <T> void printArray(T[] array) {
for (T item : array) System.out.println(item);
}
JAVA
#2.57
Q57:
How do you concatenate strings efficiently in a loop?
Ans:
You should use StringBuilder inside loops instead of the + operator, since repeated String concatenation creates many intermediate immutable String objects, hurting performance.
Code Example
StringBuilder sb = new StringBuilder();
for (String s : items) sb.append(s);
JAVA
#2.58
Q58:
How do you copy an array in Java?
Ans:
You can use Arrays.copyOf(), System.arraycopy(), or clone(), each copying elements to a new array (shallow copy for object arrays).
Code Example
int[] copy = Arrays.copyOf(original, original.length);
JAVA
#2.59
Q59:
What is the difference between a shallow copy and a deep copy?
Ans:
A shallow copy duplicates the top-level structure but copies references to nested objects (so both copies share the same nested objects), while a deep copy recursively duplicates nested objects as well, creating fully independent copies.
JAVA
#2.60
Q60:
How do you search for an element in a sorted array?
Ans:
Arrays.binarySearch() performs a binary search on a sorted array and returns the index of the found element, or a negative value if not found.
JAVA
#2.61
Q61:
What is the String.format() method used for?
Ans:
String.format() creates a formatted string using a format string and arguments, similar to printf, useful for constructing strings with specific number or text formatting.
Code Example
String s = String.format("%s is %d years old", "Tom", 25);
JAVA
#2.62
Q62:
What is the difference between extending Thread and implementing Runnable?
Ans:
Implementing Runnable is generally preferred since Java doesn't support multiple inheritance of classes, so a class implementing Runnable can still extend another class, whereas extending Thread uses up the single inheritance slot.
JAVA
#2.63
Q63:
What is the difference between start() and run() on a Thread?
Ans:
Calling start() creates a new call stack and executes run() in a separate thread of execution, while calling run() directly executes the code synchronously in the current thread without creating a new one.
JAVA
#2.64
Q64:
What is synchronization in Java?
Ans:
Synchronization controls access to shared resources by multiple threads using the synchronized keyword, ensuring only one thread can execute a synchronized block or method on a given object at a time, preventing race conditions.
Code Example
public synchronized void increment() { count++; }
JAVA
#2.65
Q65:
What is a race condition?
Ans:
A race condition occurs when multiple threads access and modify shared data concurrently without proper synchronization, causing the outcome to depend unpredictably on the timing of thread execution.
JAVA
#2.66
Q66:
What is a deadlock?
Ans:
A deadlock occurs when two or more threads are blocked forever, each waiting for a resource held by another thread in the group, forming a circular dependency.
JAVA
#2.67
Q67:
What is the Executor framework in Java?
Ans:
The Executor framework (java.util.concurrent) provides a higher-level API for managing thread pools and asynchronous task execution, decoupling task submission from the details of thread creation and scheduling.
Code Example
ExecutorService executor = Executors.newFixedThreadPool(4);
executor.submit(() -> System.out.println("Task running"));
executor.shutdown();
JAVA
#2.68
Q68:
What is a thread pool and why is it useful?
Ans:
A thread pool maintains a set of reusable worker threads to execute submitted tasks, avoiding the overhead of creating and destroying threads repeatedly and controlling the level of concurrency.
JAVA
#2.69
Q69:
What is the difference between Callable and Runnable?
Ans:
Runnable's run() method returns no value and cannot throw checked exceptions, while Callable's call() method returns a value (via Future) and can throw checked exceptions.
Code Example
Callable<Integer> task = () -> 42;
Future<Integer> future = executor.submit(task);
JAVA
#2.70
Q70:
What is a Future in Java concurrency?
Ans:
A Future represents the result of an asynchronous computation, providing methods like get() to retrieve the result (blocking until available), and isDone() to check completion status.
JAVA
#2.71
Q71:
What is the difference between InputStream/OutputStream and Reader/Writer?
Ans:
InputStream and OutputStream handle raw binary data (bytes), while Reader and Writer are designed for handling character/text data with proper encoding support.
JAVA
#2.72
Q72:
How do you read a text file in Java?
Ans:
You can use classes like BufferedReader with FileReader, or the modern Files.readAllLines() / Files.lines() from java.nio.file for simpler file reading.
Code Example
List<String> lines = Files.readAllLines(Paths.get("data.txt"));
JAVA
#2.73
Q73:
How do you write to a file in Java?
Ans:
You can use FileWriter/BufferedWriter, or Files.write() from java.nio.file to write strings or byte data to a file.
Code Example
Files.write(Paths.get("out.txt"), "Hello".getBytes());
JAVA
#2.74
Q74:
What is serialization in Java?
Ans:
Serialization is the process of converting an object into a byte stream for storage or transmission, and deserialization reverses this process to reconstruct the object; classes must implement the Serializable marker interface.
Code Example
class User implements Serializable {
private String name;
}
JAVA
#2.75
Q75:
What is the transient keyword used for?
Ans:
transient marks a field to be excluded from the default serialization process, so its value is not saved when the object is serialized.
Code Example
private transient String password;
JAVA
#2.76
Q76:
What is try-with-resources and how does it relate to file handling?
Ans:
try-with-resources automatically closes resources like file streams that implement AutoCloseable at the end of the block, preventing resource leaks without needing explicit finally blocks.
Code Example
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("log.txt"))) {
writer.write("Log entry");
}
JAVA
#2.77
Q77:
What is a lambda expression in Java?
Ans:
A lambda expression is a concise way to represent an anonymous function, implementing a functional interface's single abstract method, introduced in Java 8.
Code Example
Runnable r = () -> System.out.println("Hello");
Comparator<Integer> cmp = (a, b) -> a - b;
JAVA
#2.78
Q78:
What is the Stream API in Java?
Ans:
The Stream API, introduced in Java 8, provides a functional-style approach to process sequences of elements (from collections, arrays, etc.) using operations like filter, map, and reduce, often in a pipeline.
Code Example
List<Integer> result = numbers.stream()
.filter(n -> n % 2 == 0)
.map(n -> n * n)
.collect(Collectors.toList());
JAVA
#2.79
Q79:
What is the difference between intermediate and terminal operations in streams?
Ans:
Intermediate operations (like filter, map) are lazy and return a new stream, allowing chaining, while terminal operations (like collect, forEach, reduce) trigger the actual processing and produce a result or side-effect, ending the stream pipeline.
JAVA
#2.80
Q80:
What is the Optional class used for?
Ans:
Optional is a container object that may or may not hold a non-null value, used to explicitly represent the potential absence of a value and reduce NullPointerException risks.
Code Example
Optional<String> name = Optional.ofNullable(getName());
name.ifPresent(System.out::println);
JAVA
#2.81
Q81:
What is a method reference in Java?
Ans:
A method reference (using ::) is shorthand syntax for a lambda expression that simply calls an existing method, improving readability when the lambda body does nothing more than invoke a method.
Code Example
list.forEach(System.out::println);
list.sort(String::compareTo);
JAVA
#2.82
Q82:
What is the Collectors class used for in the Stream API?
Ans:
Collectors provides implementations for common reduction operations like collecting stream elements into a List, Set, Map, or joining strings, typically used with the collect() terminal operation.
Code Example
String joined = names.stream().collect(Collectors.joining(", "));
JAVA
#2.83
Q83:
What is the default method feature in interfaces used for?
Ans:
Default methods allow interfaces to provide a method implementation, enabling new methods to be added to interfaces without breaking existing implementing classes.
JAVA
#2.84
Q84:
What is a Supplier, Consumer, Function, and Predicate in java.util.function?
Ans:
Supplier takes no input and returns a value, Consumer takes an input and returns nothing, Function takes an input and returns a transformed result, and Predicate takes an input and returns a boolean.
Code Example
Supplier<String> sup = () -> "Hello";
Consumer<String> con = System.out::println;
Function<Integer,Integer> square = n -> n * n;
Predicate<Integer> isEven = n -> n % 2 == 0;
JAVA
#2.85
Q85:
What are records in Java 16?
Ans:
Records are a concise way to declare immutable data-carrying classes, automatically generating a constructor, accessors, equals(), hashCode(), and toString() based on the declared components.
Code Example
public record Point(int x, int y) {}
JAVA
#2.86
Q86:
What is pattern matching for instanceof in Java 16?
Ans:
It allows combining an instanceof check and a cast into a single expression, automatically binding the cast result to a new variable if the check succeeds.
Code Example
if (obj instanceof String s) {
System.out.println(s.length());
}
JAVA
#2.87
Q87:
What are text blocks in Java 15?
Ans:
Text blocks, delimited by triple double-quotes ("""), allow multi-line string literals without needing explicit escape sequences for newlines or most quotes.
Code Example
String html = """
<html>
<body>Hello</body>
</html>
""";
JAVA
#2.88
Q88:
What is the difference between stack and heap memory in Java?
Ans:
The stack stores method call frames, local variables, and references, following LIFO order and being thread-specific, while the heap stores all objects and is shared across threads, managed by the garbage collector.
JAVA
#2.89
Q89:
Can you force garbage collection in Java?
Ans:
You can call System.gc() to suggest that the JVM run garbage collection, but this is only a hint, not a guarantee, and the JVM may choose to ignore or delay it.
JAVA
#2.90
Q90:
What is the difference between StackOverflowError and OutOfMemoryError?
Ans:
StackOverflowError occurs when a thread's call stack exceeds its allocated size, typically due to excessive or infinite recursion, while OutOfMemoryError occurs when the JVM cannot allocate more objects because the heap is exhausted.
JAVA
#2.91
Q91:
What is the Singleton design pattern and how do you implement it in Java?
Ans:
Singleton ensures a class has only one instance and provides a global access point to it, commonly implemented with a private constructor, a static instance field, and a public static method to retrieve or lazily create that instance.
Code Example
public class Config {
private static Config instance;
private Config() {}
public static synchronized Config getInstance() {
if (instance == null) instance = new Config();
return instance;
}
}
JAVA
#2.92
Q92:
What is dependency injection?
Ans:
Dependency injection is a design pattern where an object's dependencies are supplied externally (via constructor, setter, or field) rather than created internally, promoting loose coupling and easier testing.
JAVA
#2.93
Q93:
What is the difference between composition and inheritance in terms of design?
Ans:
Composition ('has-a') favors flexibility by delegating behavior to contained objects and is generally preferred, while inheritance ('is-a') creates tighter coupling between parent and child classes and can lead to fragile hierarchies if overused.
JAVA
#2.94
Q94:
What is the Builder design pattern?
Ans:
The Builder pattern constructs complex objects step-by-step using a fluent interface, separating the construction process from the final representation, often useful for objects with many optional parameters.
Code Example
Pizza pizza = new Pizza.Builder().size(12).addTopping("cheese").build();
JAVA
#2.95
Q95:
What are annotations in Java?
Ans:
Annotations provide metadata about code (classes, methods, fields) that can be processed by the compiler or at runtime via reflection, commonly used for configuration, validation, and framework behavior like @Override or @Deprecated.
Code Example
@Override
public String toString() { return "Custom"; }
JAVA
#2.96
Q96:
What is the @FunctionalInterface annotation used for?
Ans:
@FunctionalInterface documents and enforces at compile time that an interface has exactly one abstract method, making it eligible for lambda expressions.
JAVA
#2.97
Q97:
What is the difference between an interface's static and default methods?
Ans:
Static methods belong to the interface itself and are called using the interface name, not inherited by implementing classes, while default methods provide inheritable behavior that implementing classes can use as-is or override.
JAVA
#2.98
Q98:
What is the purpose of the enum type in Java?
Ans:
enum defines a fixed set of named constants, is type-safe, can have fields, constructors, and methods, and implicitly extends java.lang.Enum.
Code Example
enum Day { MONDAY, TUESDAY, WEDNESDAY }
Day today = Day.MONDAY;
JAVA
#2.99
Q99:
Can an enum implement an interface in Java?
Ans:
Yes, an enum can implement one or more interfaces, and each enum constant can even provide its own implementation of an interface method.
JAVA
#2.100
Q100:
What is the difference between an abstract method and a default method in an interface?
Ans:
An abstract method has no body and must be implemented by any concrete implementing class, while a default method provides a concrete implementation that implementing classes can inherit as-is or choose to override.
JAVA
#2.101
Q101:
What is a varargs parameter in Java?
Ans:
Varargs (denoted by ...) allows a method to accept a variable number of arguments of a specified type, which are treated as an array within the method.
Code Example
public static int sum(int... numbers) {
int total = 0;
for (int n : numbers) total += n;
return total;
}
JAVA
#2.102
Q102:
What is the difference between a checked exception and RuntimeException in terms of method signatures?
Ans:
Methods that may throw a checked exception must declare it in a throws clause or handle it in a try-catch, while RuntimeException (and its subclasses) do not need to be declared, since they represent programming errors rather than recoverable conditions.
JAVA
#2.103
Q103:
What is the difference between shallow cloning and deep cloning?
Ans:
Shallow cloning copies an object's primitive fields and references to other objects (so nested objects are shared), while deep cloning recursively duplicates nested objects as well, producing a fully independent copy.
JAVA
#2.104
Q104:
What is the purpose of the java.util.Objects class?
Ans:
Objects provides static utility methods like equals(), hashCode(), requireNonNull(), and isNull() that safely handle null values, simplifying common null-checking and object comparison logic.
Code Example
Objects.requireNonNull(name, "Name must not be null");
JAVA
#2.105
Q105:
What is JavaBeans convention?
Ans:
The JavaBeans convention specifies that classes should have a no-argument constructor, private fields with public getter/setter methods following a naming pattern (getX/setX), and implement Serializable, enabling frameworks to introspect and manipulate objects generically.
JAVA
#2.106
Q106:
What are the main steps to connect to a database using JDBC?
Ans:
The typical steps are: load the driver (often automatic since JDBC 4.0), establish a connection using DriverManager.getConnection(), create a Statement or PreparedStatement, execute the query, process the ResultSet, and close the resources.
Code Example
try (Connection conn = DriverManager.getConnection(url, user, pass);
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?")) {
stmt.setInt(1, 5);
ResultSet rs = stmt.executeQuery();
}
JAVA
#2.107
Q107:
What is the difference between Statement and PreparedStatement?
Ans:
Statement executes static SQL without parameters and is more vulnerable to SQL injection, while PreparedStatement precompiles SQL with placeholders for parameters, improving performance for repeated execution and preventing SQL injection.
JAVA
#2.108
Q108:
How do you prevent SQL injection in JDBC?
Ans:
You should use PreparedStatement with parameterized queries instead of concatenating user input directly into SQL strings, ensuring input is always treated as data, not executable SQL.
Code Example
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE email = ?");
stmt.setString(1, email);
JAVA
#2.109
Q109:
What is a ResultSet in JDBC?
Ans:
A ResultSet represents the table of data returned by executing a SQL query, providing methods to navigate rows (like next()) and retrieve column values by index or name.
JAVA
#2.110
Q110:
How do you handle transactions in JDBC?
Ans:
You disable auto-commit mode with setAutoCommit(false), execute multiple statements, then call commit() if successful or rollback() if an error occurs, ensuring atomicity across multiple operations.
Code Example
conn.setAutoCommit(false);
try {
// multiple statements
conn.commit();
} catch (SQLException e) {
conn.rollback();
}
JAVA
#2.111
Q111:
What is connection pooling and why is it used?
Ans:
Connection pooling maintains a cache of reusable database connections rather than creating a new connection for every request, reducing the overhead of connection setup/teardown and improving application performance and scalability.
JAVA
#2.112
Q112:
What is an ORM framework and name a popular one used with Java?
Ans:
An ORM (Object-Relational Mapping) framework maps database tables to Java classes and rows to objects, abstracting raw SQL; Hibernate and JPA (Java Persistence API) implementations are widely used in the Java ecosystem.
JAVA
#2.113
Q113:
What is the difference between Collections.sort() and Stream.sorted()?
Ans:
Collections.sort() sorts a List in place and returns void, while Stream.sorted() is a lazy intermediate operation returning a new sorted stream without modifying the original source collection.
JAVA
#2.114
Q114:
What is the difference between Collection.stream() and Collection.parallelStream()?
Ans:
stream() processes elements sequentially in a single thread, while parallelStream() splits the workload across multiple threads using the common ForkJoinPool for potentially faster processing of large datasets.
JAVA
#2.115
Q115:
How do you remove duplicate elements from a List?
Ans:
You can convert the List to a Set (like a LinkedHashSet to preserve order) and back to a List, or use stream().distinct().collect(Collectors.toList()).
Code Example
List<Integer> unique = list.stream().distinct().collect(Collectors.toList());
JAVA
#2.116
Q116:
What is the difference between Comparator.comparing() and a custom compare() implementation?
Ans:
Comparator.comparing() is a static factory method providing a concise, readable way to build a Comparator from a key extractor function, while a custom compare() implementation requires manually writing the full comparison logic.
Code Example
list.sort(Comparator.comparing(Person::getAge).thenComparing(Person::getName));
JAVA
#2.117
Q117:
What are the SOLID principles?
Ans:
SOLID stands for Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion — five object-oriented design principles intended to make software more maintainable and extensible.
JAVA
#2.118
Q118:
What is immutability and why is it useful in Java?
Ans:
An immutable object's state cannot change after construction; immutability simplifies reasoning about code, makes objects inherently thread-safe, and is used extensively in classes like String and the java.time API.
JAVA
#2.119
Q119:
How do you create an immutable class in Java?
Ans:
Declare the class final, make all fields private and final, provide no setters, initialize all fields via the constructor, and ensure mutable fields (like arrays or collections) are defensively copied on input/output.
Code Example
public final class Point {
private final int x, y;
public Point(int x, int y) { this.x = x; this.y = y; }
public int getX() { return x; }
}
JAVA
#2.120
Q120:
What is the difference between String.equals() and Objects.equals()?
Ans:
String.equals() throws a NullPointerException if called on a null reference, while Objects.equals() safely handles null by checking both arguments for null before delegating to equals(), returning true if both are null.
JAVA
#2.121
Q121:
What is the difference between Integer.parseInt() and Integer.valueOf()?
Ans:
Integer.parseInt() returns a primitive int, while Integer.valueOf() returns an Integer object, potentially using the internal cache for small values between -128 and 127.
JAVA
#2.122
Q122:
What is a static nested class used for and how do you instantiate one?
Ans:
A static nested class behaves like a regular top-level class but is namespaced within the outer class, and does not require an instance of the outer class to be instantiated.
Code Example
class Outer {
static class Nested {}
}
Outer.Nested obj = new Outer.Nested();
JAVA
#2.123
Q123:
What is the difference between this() and super() constructor calls?
Ans:
this() calls another constructor within the same class (constructor chaining), while super() calls a constructor of the immediate parent class; both must be the first statement in a constructor and cannot be used together.
JAVA
#2.124
Q124:
What is the difference between an interface reference and a concrete class reference?
Ans:
An interface reference variable can point to any object implementing that interface, enabling polymorphism and decoupling code from specific implementations, whereas a concrete class reference is tied to that specific class and its subclasses.
JAVA
#2.125
Q125:
What is the difference between throw new Exception() and throw new RuntimeException()?
Ans:
Throwing a plain Exception (checked) requires callers to handle or declare it, while throwing a RuntimeException (unchecked) does not require explicit handling, representing a programming error rather than an expected recoverable condition.
JAVA
#2.126
Q126:
What is the difference between a HashMap's keySet(), values(), and entrySet() methods?
Ans:
keySet() returns a view of all the keys, values() returns a view of all the values, and entrySet() returns a view of key-value pairs as Map.Entry objects, useful for iterating over both keys and values together.
Code Example
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
JAVA
#2.127
Q127:
What is the difference between compile-time polymorphism and runtime polymorphism?
Ans:
Compile-time (static) polymorphism is achieved through method overloading, resolved by the compiler based on method signatures, while runtime (dynamic) polymorphism is achieved through method overriding, resolved by the JVM based on the actual object type at runtime.
Hard
43 questions
JAVA
#3.1
Q1:
What happens if a class implements two interfaces with the same default method?
Ans:
The implementing class must explicitly override the method to resolve the ambiguity, otherwise a compile-time error occurs.
JAVA
#3.2
Q2:
What is the diamond problem and how does Java handle it with interfaces?
Ans:
The diamond problem occurs when a class inherits conflicting implementations from two sources; Java avoids it for classes by disallowing multiple inheritance, and for interfaces with conflicting default methods, it forces the implementing class to explicitly override the method.
JAVA
#3.3
Q3:
What is a local inner class?
Ans:
A local inner class is defined within a method body and is only visible and usable within that method's scope.
JAVA
#3.4
Q4:
What is method hiding in Java?
Ans:
Method hiding occurs when a subclass defines a static method with the same signature as a static method in the superclass; unlike overriding, the method called is determined by the reference type at compile time, not the actual object type.
JAVA
#3.5
Q5:
What is exception chaining?
Ans:
Exception chaining wraps a lower-level exception inside a new, higher-level exception (using the cause constructor parameter), preserving the original exception's information while providing more context.
Code Example
try {
// code
} catch (SQLException e) {
throw new RuntimeException("Query failed", e);
}
JAVA
#3.6
Q6:
How does a HashMap work internally?
Ans:
A HashMap stores entries in an array of buckets, computing a bucket index from the key's hashCode(); when multiple keys hash to the same bucket (collision), Java 8+ uses a linked list (or a balanced tree for large buckets) to store them.
JAVA
#3.7
Q7:
What is a ConcurrentModificationException?
Ans:
This runtime exception is thrown when a collection is structurally modified (e.g., adding/removing elements) while being iterated using a fail-fast iterator, other than through the iterator's own remove method.
JAVA
#3.8
Q8:
What is the difference between fail-fast and fail-safe iterators?
Ans:
Fail-fast iterators throw a ConcurrentModificationException if the underlying collection is modified during iteration (e.g., ArrayList), while fail-safe iterators operate on a cloned or separate copy of the collection, allowing modifications without exceptions (e.g., CopyOnWriteArrayList).
JAVA
#3.9
Q9:
What is the initial capacity and load factor of a HashMap?
Ans:
The default initial capacity is 16 buckets and the default load factor is 0.75, meaning the HashMap resizes (doubles capacity) once it is 75% full to maintain efficient performance.
JAVA
#3.10
Q10:
Why must objects used as HashMap keys override equals() and hashCode()?
Ans:
The HashMap relies on hashCode() to locate the correct bucket and equals() to confirm key equality within that bucket; without proper overrides, lookups and duplicate detection would not work correctly for custom objects.
JAVA
#3.11
Q11:
What is type erasure in Java generics?
Ans:
Type erasure is the process by which the compiler removes generic type information after compile-time checks, replacing type parameters with their bounds or Object, so generic type info is not available at runtime.
JAVA
#3.12
Q12:
What is a wildcard in Java generics?
Ans:
A wildcard (?) represents an unknown type in generics; ? extends T restricts to T or its subtypes (producer, read-only), and ? super T restricts to T or its supertypes (consumer, write-only).
Code Example
void printList(List<? extends Number> list) {
for (Number n : list) System.out.println(n);
}
JAVA
#3.13
Q13:
What is the PECS principle in Java generics?
Ans:
PECS stands for 'Producer Extends, Consumer Super' — use ? extends T when you only read (produce) items from a structure, and ? super T when you only write (consume) items into it.
JAVA
#3.14
Q14:
Can you create a generic array in Java?
Ans:
No, Java does not allow creating generic arrays directly (like new T[10]) due to type erasure and array covariance issues; workarounds include using Object arrays with casting or collections instead.
JAVA
#3.15
Q15:
What is the difference between String.intern() and creating a new String?
Ans:
intern() returns a canonical reference from the string pool for a given string's content, ensuring that equal string values share the same reference, unlike 'new String()' which always creates a distinct object on the heap.
JAVA
#3.16
Q16:
How can you prevent deadlocks in Java?
Ans:
Common strategies include acquiring locks in a consistent global order, using timeouts when attempting to acquire locks, minimizing lock scope, and avoiding nested locks where possible.
JAVA
#3.17
Q17:
What is the volatile keyword used for?
Ans:
volatile ensures that a variable's value is always read from and written directly to main memory, guaranteeing visibility of changes across threads, though it does not provide atomicity for compound operations.
Code Example
private volatile boolean running = true;
JAVA
#3.18
Q18:
What is the difference between synchronized and volatile?
Ans:
synchronized provides both mutual exclusion (atomicity) and visibility for a block of code, while volatile only guarantees visibility of a single variable's latest value across threads, without locking or atomicity for compound actions.
JAVA
#3.19
Q19:
What is the wait(), notify(), and notifyAll() used for?
Ans:
These Object class methods enable inter-thread communication: wait() makes a thread release its lock and pause until notified, notify() wakes one waiting thread, and notifyAll() wakes all threads waiting on that object's monitor.
JAVA
#3.20
Q20:
What is CompletableFuture used for?
Ans:
CompletableFuture, introduced in Java 8, represents a future result that can be composed, chained, and combined with other asynchronous operations without blocking, using methods like thenApply() and thenCombine().
Code Example
CompletableFuture.supplyAsync(() -> compute())
.thenApply(result -> result * 2)
.thenAccept(System.out::println);
JAVA
#3.21
Q21:
What are atomic classes in Java concurrency?
Ans:
Classes like AtomicInteger and AtomicLong provide lock-free, thread-safe operations on single variables using low-level compare-and-swap (CAS) instructions, useful for simple counters without full synchronization overhead.
Code Example
AtomicInteger counter = new AtomicInteger(0);
counter.incrementAndGet();
JAVA
#3.22
Q22:
What is the difference between a thread's user thread and daemon thread?
Ans:
User threads keep the JVM running until they complete, while daemon threads run in the background and are automatically terminated when all user threads finish, typically used for tasks like garbage collection.
JAVA
#3.23
Q23:
What is the difference between java.io and java.nio?
Ans:
java.io provides a stream-based, blocking I/O API, while java.nio (New I/O) introduced buffer-based, potentially non-blocking I/O with channels, offering better performance for certain use cases like handling many connections.
JAVA
#3.24
Q24:
What is the difference between map() and flatMap() in streams?
Ans:
map() transforms each element into another single element, while flatMap() transforms each element into a stream and flattens all resulting streams into a single stream.
Code Example
List<List<Integer>> nested = List.of(List.of(1,2), List.of(3,4));
List<Integer> flat = nested.stream().flatMap(List::stream).collect(Collectors.toList());
JAVA
#3.25
Q25:
What are the different types of method references?
Ans:
Java supports references to static methods (ClassName::staticMethod), instance methods of a particular object (instance::method), instance methods of an arbitrary object of a type (ClassName::instanceMethod), and constructors (ClassName::new).
JAVA
#3.26
Q26:
What is the difference between findFirst() and findAny() in streams?
Ans:
findFirst() returns the first element encountered in encounter order, while findAny() returns any element and may be more efficient in parallel streams since it doesn't need to respect ordering.
JAVA
#3.27
Q27:
What is a parallel stream in Java?
Ans:
A parallel stream splits the source data into multiple chunks processed concurrently across multiple threads (using the common ForkJoinPool), potentially improving performance for large datasets and CPU-intensive operations.
Code Example
list.parallelStream().forEach(System.out::println);
JAVA
#3.28
Q28:
What is a sealed class in Java 17?
Ans:
Sealed classes restrict which other classes or interfaces may extend or implement them, explicitly listing permitted subtypes, improving control over class hierarchies for pattern matching and exhaustiveness.
Code Example
public sealed interface Shape permits Circle, Square {}
JAVA
#3.29
Q29:
What are the different memory areas managed by the JVM?
Ans:
The JVM manages the heap (objects), the stack (method frames per thread), the method area/metaspace (class metadata), the program counter register, and native method stacks.
JAVA
#3.30
Q30:
What is the difference between the young generation and old generation in heap memory?
Ans:
The young generation holds newly created, typically short-lived objects and is collected frequently (minor GC), while the old (tenured) generation holds long-lived objects that have survived multiple garbage collection cycles, collected less frequently (major GC).
JAVA
#3.31
Q31:
What causes a memory leak in Java despite automatic garbage collection?
Ans:
Memory leaks can still occur when objects remain reachable through unintended references (like static collections that keep growing, unclosed resources, or listeners not deregistered), preventing the garbage collector from reclaiming them.
JAVA
#3.32
Q32:
What is class loading in Java?
Ans:
Class loading is the process by which the JVM's class loader dynamically loads compiled .class files into memory, following a hierarchy (bootstrap, extension/platform, and application class loaders) as classes are needed.
JAVA
#3.33
Q33:
What is reflection in Java?
Ans:
Reflection is an API (java.lang.reflect) that allows a program to inspect and manipulate classes, methods, fields, and constructors at runtime, even those not known at compile time.
Code Example
Class<?> clazz = Class.forName("com.example.User");
Method[] methods = clazz.getDeclaredMethods();
JAVA
#3.34
Q34:
What is the difference between == and equals() for wrapper classes like Integer?
Ans:
For small cached Integer values (-128 to 127), == may return true due to integer caching, but for values outside that range or explicitly created objects, == compares references while equals() correctly compares values.
Code Example
Integer a = 100, b = 100;
System.out.println(a == b); // true (cached)
Integer c = 200, d = 200;
System.out.println(c == d); // false
JAVA
#3.35
Q35:
What is object cloning in Java?
Ans:
Cloning creates a copy of an object using the clone() method from the Cloneable interface; by default, Object's clone() performs a shallow copy, so classes needing deep copies must override clone() accordingly.
Code Example
class Point implements Cloneable {
public Point clone() throws CloneNotSupportedException {
return (Point) super.clone();
}
}
JAVA
#3.36
Q36:
What is the difference between a top-level class and an inner class regarding access to private members?
Ans:
An inner (non-static nested) class has implicit access to the enclosing instance's private members, while a top-level class must access another class's members through normal visibility rules (public/protected/package-private).
JAVA
#3.37
Q37:
What does the Collectors.groupingBy() do?
Ans:
groupingBy() collects stream elements into a Map grouped by a classifier function, similar to a SQL GROUP BY, optionally combined with a downstream collector for further aggregation.
Code Example
Map<String, List<Person>> byCity = people.stream()
.collect(Collectors.groupingBy(Person::getCity));
JAVA
#3.38
Q38:
What is the difference between reduce() and collect() in the Stream API?
Ans:
reduce() combines stream elements into a single immutable result using an associative accumulator function, while collect() performs a mutable reduction, accumulating elements into a mutable container like a List or Map.
JAVA
#3.39
Q39:
What is the difference between Arrays.asList() and a regular ArrayList?
Ans:
Arrays.asList() returns a fixed-size list backed directly by the array, so you cannot add or remove elements (though you can set existing ones), while a regular ArrayList is fully resizable and independent of any array.
JAVA
#3.40
Q40:
What is the difference between peek() and forEach() in streams?
Ans:
peek() is an intermediate operation used mainly for debugging that returns the same stream unchanged for further processing, while forEach() is a terminal operation that consumes the stream and returns nothing.
JAVA
#3.41
Q41:
What is the Liskov Substitution Principle?
Ans:
It states that objects of a superclass should be replaceable with objects of a subclass without altering the correctness of the program, meaning subclasses must honor the behavioral contract of their parent type.
JAVA
#3.42
Q42:
What is the purpose of the Comparable interface's compareTo() method contract?
Ans:
compareTo() should return a negative number, zero, or a positive number if the current object is less than, equal to, or greater than the specified object, and should be consistent with equals() for well-behaved sorted collections.
JAVA
#3.43
Q43:
What is the purpose of the assert keyword in Java?
Ans:
assert evaluates a boolean expression and throws an AssertionError if it's false, primarily used for internal self-checks during development and testing; assertions are disabled by default at runtime unless explicitly enabled with the -ea flag.
Code Example
assert age >= 0 : "Age cannot be negative";