π Interview Prep Questions
What is Java, and what are its key features?
Java is a high-level, object-oriented programming language known for its platform independence, achieved through the JVM. Key features include platform independence, object-oriented nature, robustness, security, multithreading, and a rich API.
What is the difference between JDK, JRE, and JVM?
JDK (Java Development Kit) is a software development kit with tools like javac for developing Java applications. JRE (Java Runtime Environment) provides libraries and JVM to run Java applications. JVM (Java Virtual Machine) executes Java bytecode, enabling platform independence.
What is the purpose of the `main` method in Java?
The `main` method is the entry point of a Java program, where execution begins. It has the signature `public static void main(String[] args)` and is called by the JVM.
What are the different data types in Java?
Java has two categories of data types: primitive (byte, short, int, long, float, double, char, boolean) and non-primitive (classes, interfaces, arrays, String).
What is the difference between primitive and non-primitive data types?
Primitive data types are predefined (e.g., int, char) with fixed sizes, stored directly in memory. Non-primitive data types (e.g., String, arrays) are objects, reference-based, and can be null.
What is a variable in Java, and how do you declare it?
int number = 10; // Declares an integer variable named 'number' with value 10
What is type casting in Java? Explain implicit and explicit casting.
Type casting converts one data type to another. Implicit casting (widening) happens automatically (e.g., int to double). Explicit casting (narrowing) requires manual casting (e.g., double to int).
int i = 10;
double d = i; // Implicit
double d2 = 10.5;
int i2 = (int) d2; // Explicit
What are the access modifiers in Java?
Java access modifiers are public, protected, default (package-private), and private, controlling the visibility of classes, methods, and fields.
What is the difference between `public`, `private`, `protected`, and `default` access modifiers?
`public`: Accessible everywhere. `private`: Accessible only within the class. `protected`: Accessible within the package and subclasses. `default` (no modifier): Accessible within the package.
What is the significance of the `static` keyword in Java?
The `static` keyword indicates that a member belongs to the class, not instances. Static variables and methods can be accessed without creating an object.
static int count = 0; // Static variable
static void print() { System.out.println("Static method"); }
What is the difference between `final`, `finally`, and `finalize`?
`final`: Restricts modification (class, method, variable). `finally`: Executes code after try-catch, regardless of exceptions. `finalize`: Called by the garbage collector before object cleanup (deprecated in Java 9).
What is the purpose of the `this` keyword in Java?
The `this` keyword refers to the current object, used to distinguish instance variables from parameters or invoke current class methods/constructors.
class MyClass {
int x;
void setX(int x) {
this.x = x; // Differentiates instance variable from parameter
}
}
What is the `super` keyword used for in Java?
The `super` keyword refers to the parent class, used to call parent class methods, constructors, or access parent class fields.
class Child extends Parent {
Child() {
super(); // Calls parent constructor
}
}
What is a constructor in Java?
A constructor is a special method used to initialize objects, with the same name as the class and no return type.
class MyClass {
MyClass() {
System.out.println("Constructor called");
}
}
What is the difference between default and parameterized constructors?
A default constructor has no parameters and initializes fields to default values. A parameterized constructor accepts parameters to initialize fields with specific values.
class MyClass {
int x;
MyClass() {} // Default
MyClass(int x) { this.x = x; } // Parameterized
}
Can a constructor be private in Java?
Yes, a private constructor prevents instantiation from outside the class, often used in singleton patterns or utility classes.
class Singleton {
private Singleton() {}
}
What is constructor overloading?
Constructor overloading allows multiple constructors with different parameter lists in the same class.
class MyClass {
MyClass() {}
MyClass(int x) {}
}
What is the difference between a local variable and an instance variable?
Local variables are declared in methods and have no default value, scoped to the method. Instance variables are declared in a class, belong to objects, and have default values.
class MyClass {
int instanceVar; // Instance variable
void method() {
int localVar = 0; // Local variable
}
}
What is a static variable, and when is it used?
A static variable belongs to the class, shared across all instances, used for common data like counters or constants.
class MyClass {
static int count = 0; // Static variable
}
What is the role of the `System.out.println` method?
`System.out.println` prints text to the console with a newline, where `System.out` is a `PrintStream` object.
System.out.println("Hello, World!");
What is the difference between `==` and `equals()` in Java?
`==` compares object references or primitive values. `equals()` compares object content, defined in the `Object` class and overridden in classes like `String`.
String s1 = new String("test");
String s2 = new String("test");
System.out.println(s1 == s2); // false
System.out.println(s1.equals(s2)); // true
What is the `toString()` method in Java?
The `toString()` method returns a string representation of an object, defined in `Object` class and often overridden for meaningful output.
class MyClass {
@Override
public String toString() {
return "MyClass object";
}
}
What is the purpose of the `hashCode()` method?
The `hashCode()` method returns an integer hash code for an object, used in hash-based collections like `HashMap` for efficient storage and retrieval.
class MyClass {
@Override
public int hashCode() {
return 42;
}
}
What is the difference between `String`, `StringBuilder`, and `StringBuffer`?
`String` is immutable. `StringBuilder` is mutable, non-thread-safe, and faster. `StringBuffer` is mutable, thread-safe, and slower.
Why is `String` immutable in Java?
`String` is immutable for security, thread-safety, and memory efficiency (string pool). It prevents unintended modifications in critical contexts.
What is a wrapper class in Java?
A wrapper class (e.g., `Integer`, `Double`) wraps a primitive type into an object, enabling use in collections and providing utility methods.
Integer i = new Integer(10); // Wraps int
What is autoboxing and unboxing in Java?
Autoboxing converts primitives to wrapper objects (e.g., `int` to `Integer`). Unboxing converts wrapper objects to primitives.
List list = new ArrayList<>();
list.add(5); // Autoboxing
int value = list.get(0); // Unboxing
What is the difference between `int` and `Integer` in Java?
`int` is a primitive type with a fixed size. `Integer` is a wrapper class that can be null and provides methods like `parseInt()`.
What is the purpose of the `var` keyword introduced in Java 10?
The `var` keyword enables local variable type inference, simplifying code by omitting explicit type declarations while maintaining type safety.
var list = new ArrayList(); // Inferred as ArrayList
What is the difference between a class and an object in Java?
A class is a blueprint defining properties and behavior. An object is an instance of a class, created at runtime.
class MyClass {}
MyClass obj = new MyClass(); // Object
What are the four pillars of OOP in Java?
The four pillars are encapsulation (data hiding), inheritance (code reuse), polymorphism (flexible behavior), and abstraction (simplifying complexity).
What is encapsulation, and how is it achieved in Java?
Encapsulation hides data and exposes methods, achieved using private fields and public getters/setters.
class MyClass {
private int x;
public int getX() { return x; }
public void setX(int x) { this.x = x; }
}
What is inheritance, and how does Java support it?
Inheritance allows a class to inherit properties and methods from another, supported via the `extends` keyword.
class Parent {}
class Child extends Parent {}
What is the difference between single and multiple inheritance in Java?
Single inheritance allows a class to extend one parent. Multiple inheritance (not supported for classes in Java) would allow multiple parents, but Java supports it via interfaces.
Why doesn’t Java support multiple inheritance for classes?
Java avoids multiple inheritance for classes to prevent the diamond problem and complexity, using interfaces for similar functionality.
What is polymorphism in Java?
Polymorphism allows objects to be treated as instances of their parent class, enabling method overriding (runtime) and overloading (compile-time).
class Animal {
void sound() {}
}
class Dog extends Animal {
void sound() { System.out.println("Bark"); }
}
What is the difference between method overloading and method overriding?
Overloading uses different parameter lists in the same class (compile-time). Overriding redefines a parent class method in a subclass (runtime).
class MyClass {
void method(int x) {} // Overloading
void method(String x) {}
}
class Child extends MyClass {
void method(int x) {} // Overriding
}
What is an abstract class in Java?
An abstract class cannot be instantiated and may contain abstract methods, used as a base for subclasses.
abstract class MyClass {
abstract void method();
}
Can an abstract class have a constructor?
Yes, an abstract class can have a constructor, used to initialize fields when subclasses are instantiated.
abstract class MyClass {
MyClass() {}
}
What is an interface in Java?
An interface defines a contract of methods to be implemented by classes, supporting multiple inheritance.
interface MyInterface {
void method();
}
What is the difference between an abstract class and an interface?
Abstract classes can have state and partial implementation; interfaces (pre-Java 8) only declare methods. Classes can implement multiple interfaces but extend one abstract class.
Can an interface have instance variables?
No, interfaces cannot have instance variables; fields are implicitly `public static final` (constants).
interface MyInterface {
int CONSTANT = 10; // Constant
}
What are default methods in Java interfaces (introduced in Java 8)?
Default methods provide a default implementation in interfaces, allowing backward compatibility.
interface MyInterface {
default void method() {
System.out.println("Default");
}
}
What is a marker interface in Java?
A marker interface has no methods or fields, used to tag classes (e.g., `Serializable`, `Cloneable`).
What is the `implements` keyword used for?
The `implements` keyword is used by a class to implement an interface, promising to provide implementations for its methods.
class MyClass implements MyInterface {
public void method() {}
}
What is the `extends` keyword used for?
The `extends` keyword is used to inherit a class or interface, enabling code reuse or interface extension.
class Child extends Parent {}
What is method hiding in Java?
Method hiding occurs when a static method in a subclass redefines a static method in the parent class, not overridden.
class Parent {
static void method() {}
}
class Child extends Parent {
static void method() {} // Hides Parent.method()
}
What is the diamond problem in Java?
The diamond problem occurs in multiple inheritance when a class inherits conflicting methods from two parents. Java avoids it by disallowing multiple class inheritance.
Can a class implement multiple interfaces in Java?
Yes, a class can implement multiple interfaces, providing implementations for all their methods.
class MyClass implements Interface1, Interface2 {}
What is the purpose of the `super()` call in a constructor?
The `super()` call invokes the parent class constructor, ensuring proper initialization of inherited fields.
class Child extends Parent {
Child() {
super();
}
}
What is a package in Java?
A package is a namespace that organizes related classes and interfaces, preventing naming conflicts and enabling access control.
package com.example;
What is the purpose of the `import` statement in Java?
The `import` statement allows access to classes or static members from other packages without fully qualifying their names.
import java.util.ArrayList;
What is the difference between `import` and `import static`?
`import` brings in classes or interfaces. `import static` imports static members, allowing their use without class qualification.
import static java.lang.System.out;
out.println("Hello"); // No need for System.out
What is the `Object` class in Java?
The `Object` class is the root of the Java class hierarchy, providing methods like `toString()`, `equals()`, and `hashCode()` inherited by all classes.
What is the `Class` class in Java?
The `Class` class represents the metadata of a class at runtime, used in reflection to inspect or instantiate classes.
Class cls = String.class;
What is reflection in Java?
Reflection allows inspection and modification of classes, methods, and fields at runtime.
Class cls = Class.forName("java.lang.String");
What is the `instanceof` operator in Java?
The `instanceof` operator checks if an object is an instance of a specific class or interface.
if (obj instanceof String) {
String s = (String) obj;
}
What is a static block in Java?
A static block initializes static variables when a class is loaded, executed before the `main` method.
static {
System.out.println("Static block executed");
}
What is an instance initializer block?
An instance initializer block runs during object creation, before the constructor, for common initialization logic.
class MyClass {
{
System.out.println("Instance initializer");
}
}
What is the `transient` keyword in Java?
The `transient` keyword prevents a field from being serialized.
transient int sensitiveData;
What is the Java Collections Framework?
The Java Collections Framework provides interfaces (e.g., List, Set, Map) and classes (e.g., ArrayList, HashMap) for managing groups of objects.
What is the difference between `List`, `Set`, and `Map`?
`List` allows ordered, duplicate elements. `Set` ensures unique elements, unordered or ordered. `Map` stores key-value pairs, with unique keys.
What is an `ArrayList` in Java?
`ArrayList` is a resizable array implementation of the `List` interface, allowing dynamic size and random access.
ArrayList list = new ArrayList<>();
list.add("Item");
What is a `LinkedList` in Java?
`LinkedList` is a doubly-linked list implementation of `List` and `Deque`, efficient for insertions and deletions.
LinkedList list = new LinkedList<>();
list.add("Item");
What is the difference between `ArrayList` and `LinkedList`?
`ArrayList` uses a dynamic array, faster for random access. `LinkedList` uses nodes, better for frequent insertions/deletions.
What is a `HashSet` in Java?
`HashSet` is an unordered collection of unique elements, backed by a hash table.
HashSet set = new HashSet<>();
set.add("Item");
What is a `TreeSet` in Java?
`TreeSet` is a sorted, unique collection backed by a red-black tree.
TreeSet set = new TreeSet<>();
set.add("Item");
What is a `HashMap` in Java?
`HashMap` stores key-value pairs with unique keys, using a hash table for fast lookup.
HashMap map = new HashMap<>();
map.put("Key", 1);
What is a `TreeMap` in Java?
`TreeMap` is a sorted map based on a red-black tree, ordering keys naturally or via a comparator.
TreeMap map = new TreeMap<>();
map.put("Key", 1);
What is the difference between `HashMap` and `TreeMap`?
`HashMap` is unordered, faster for lookups. `TreeMap` is sorted by keys, slower but maintains order.
What is the `Iterator` interface in Java?
The `Iterator` interface allows traversal and removal of elements from a collection.
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
iterator.next();
}
What is the `ListIterator` interface in Java?
`ListIterator` extends `Iterator`, allowing bidirectional traversal and modification of lists.
ListIterator iterator = list.listIterator();
while (iterator.hasPrevious()) {
iterator.previous();
}
What is a fail-fast iterator in Java?
Fail-fast iterators throw `ConcurrentModificationException` if a collection is modified during iteration.
What is a fail-safe iterator in Java?
Fail-safe iterators (e.g., in `CopyOnWriteArrayList`) operate on a snapshot, allowing modifications without exceptions.
What is the `Comparable` interface in Java?
The `Comparable` interface defines natural ordering via the `compareTo` method.
class MyClass implements Comparable {
public int compareTo(MyClass other) {
return 0;
}
}
What is the `Comparator` interface in Java?
The `Comparator` interface defines custom ordering via the `compare` method.
Comparator comp = (a, b) -> a.compareTo(b);
What is the difference between `Comparable` and `Comparator`?
`Comparable` defines natural ordering within a class. `Comparator` defines external, flexible ordering.
What is an exception in Java?
An exception is an error event that disrupts normal program flow, handled using try-catch blocks.
What is the difference between checked and unchecked exceptions?
Checked exceptions (e.g., `IOException`) must be declared or handled. Unchecked exceptions (e.g., `NullPointerException`) do not require explicit handling.
What is the `try-catch` block in Java?
The `try-catch` block handles exceptions, executing code in `try` and catching errors in `catch`.
try {
int x = 1 / 0;
} catch (ArithmeticException e) {
System.out.println("Error");
}
What is the `finally` block in Java?
The `finally` block executes code after `try-catch`, regardless of exceptions, often for cleanup.
try {
// Code
} catch (Exception e) {
} finally {
System.out.println("Cleanup");
}
What is the `throw` keyword in Java?
The `throw` keyword explicitly throws an exception.
throw new RuntimeException("Error");
What is the `throws` keyword in Java?
The `throws` keyword declares exceptions that a method may throw.
void method() throws IOException {}
Common algorithms include binary search (O(log n)), bubble sort (O(n²)), merge sort (O(n log n)), and quicksort (O(n log n) average).
int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
How do you implement a binary search in Java?
Binary search finds an element in a sorted array by dividing the search interval in half.
int binarySearch(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) return mid;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}
What is the time complexity of common Java collection operations?
`ArrayList` get/add: O(1), remove: O(n). `HashSet` add/contains: O(1). `TreeSet` add/contains: O(log n). `HashMap` get/put: O(1).
What is the `Arrays` class in Java?
The `Arrays` class provides utility methods for array manipulation, like sorting and searching.
int[] arr = {3, 1, 2};
Arrays.sort(arr);
What is the `Collections` class in Java?
The `Collections` class provides utility methods for collections, like sorting, shuffling, and synchronization.
Collections.sort(list);
How do you synchronize a collection in Java?
Use `Collections.synchronizedList` or similar methods to make a collection thread-safe.
List list = Collections.synchronizedList(new ArrayList<>());
What is the `ConcurrentModificationException` in Java?
`ConcurrentModificationException` occurs when a collection is modified during iteration by a fail-fast iterator.
List list = new ArrayList<>();
list.add("Item");
for (String s : list) {
list.remove(s); // Throws exception
}
What is a checked exception in Java?
Checked exceptions are subclasses of `Exception` (not `RuntimeException`), requiring explicit handling or declaration.
void method() throws IOException {}
What is an unchecked exception in Java?
Unchecked exceptions are subclasses of `RuntimeException`, not requiring explicit handling.
throw new NullPointerException();
What is the `try-with-resources` statement in Java?
`try-with-resources` automatically closes resources implementing `AutoCloseable`.
try (FileReader fr = new FileReader("file.txt")) {
// Use resource
}
What is a custom exception in Java?
A custom exception is a user-defined exception extending `Exception` or `RuntimeException`.
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
How do you create a custom exception in Java?
Extend `Exception` for checked or `RuntimeException` for unchecked exceptions.
class MyException extends RuntimeException {
public MyException(String message) {
super(message);
}
}
What is the `Exception` class hierarchy in Java?
`Throwable` is the root, with `Error` (e.g., `OutOfMemoryError`) and `Exception` (checked like `IOException`, unchecked like `RuntimeException`) as subclasses.
What is the `Error` class in Java?
`Error` represents serious problems (e.g., `StackOverflowError`) that applications typically should not catch.
What is the difference between `throw` and `throws` in Java?
`throw` triggers an exception. `throws` declares exceptions a method may throw.
void method() throws IOException {
throw new IOException("Error");
}
What happens if an exception is not caught?
An uncaught exception propagates up the call stack, potentially terminating the program with a stack trace.
How do you handle multiple exceptions in a single `catch` block?
Use a multi-catch block (Java 7+) with `|` to catch multiple exception types.
try {
// Code
} catch (IOException | SQLException e) {
e.printStackTrace();
}