Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools
Core Java

Top 50 Core Java Interview Questions

Curated questions covering OOP, collections, multithreading, exception handling, Java 8+ features, streams, JVM internals, and design patterns.

01

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

  • JVM (Java Virtual Machine) - executes Java bytecode. Platform-specific but provides platform independence for Java code.
  • JRE (Java Runtime Environment) - includes JVM plus standard libraries needed to run Java programs.
  • JDK (Java Development Kit) - includes JRE plus compiler (javac), debugger, and development tools. Required to write and compile Java.
02

What are the four pillars of OOP in Java?

  • Encapsulation - bundling data and methods together; hiding internal state via access modifiers.
  • Inheritance - a class acquires properties of another class using extends.
  • Polymorphism - one interface, multiple implementations (method overloading and overriding).
  • Abstraction - hiding implementation details; exposing only essential features via abstract classes and interfaces.
03

What is the difference between abstract class and interface in Java?

  • Abstract class - can have abstract and concrete methods, constructors, instance variables, and access modifiers. A class can extend only one abstract class.
  • Interface - all methods are public and abstract by default (Java 8+ allows default and static methods). A class can implement multiple interfaces.
  • Use abstract class for shared base implementation; use interface for defining contracts.
Example
abstract class Shape { abstract double area(); void print() { System.out.println(area()); } }\ninterface Drawable { void draw(); default void show() { System.out.println("Showing"); } }
04

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

== compares object references (memory addresses) for objects, and values for primitives. .equals() compares the content/value of objects. Always use .equals() for String and object comparison.

Example
String a = new String("hello");\nString b = new String("hello");\nSystem.out.println(a == b);       // false (different references)\nSystem.out.println(a.equals(b));  // true (same content)
05

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

  • String - immutable. Every modification creates a new object. Thread-safe but inefficient for frequent modifications.
  • StringBuilder - mutable, not thread-safe. Fastest for single-threaded string manipulation.
  • StringBuffer - mutable, thread-safe (synchronized methods). Slower than StringBuilder.
  • Use StringBuilder for most cases; StringBuffer only when thread safety is needed.
06

What is the Java Collections Framework?

The Collections Framework provides interfaces and implementations for storing and manipulating groups of objects.

  • List (ArrayList, LinkedList) - ordered, allows duplicates.
  • Set (HashSet, LinkedHashSet, TreeSet) - no duplicates.
  • Map (HashMap, LinkedHashMap, TreeMap) - key-value pairs.
  • Queue (PriorityQueue, ArrayDeque) - FIFO ordering.
Example
List<String> list = new ArrayList<>();\nMap<String, Integer> map = new HashMap<>();\nSet<Integer> set = new HashSet<>();
07

What is the difference between ArrayList and LinkedList?

  • ArrayList - backed by a dynamic array. O(1) random access. O(n) insertion/deletion in middle. Better for frequent reads.
  • LinkedList - doubly linked list. O(n) random access. O(1) insertion/deletion at head/tail. Better for frequent insertions/deletions.
  • ArrayList is preferred in most cases due to better cache performance.
08

What is the difference between HashMap and Hashtable?

  • HashMap - not synchronized (not thread-safe). Allows one null key and multiple null values. Faster.
  • Hashtable - synchronized (thread-safe). Does not allow null keys or values. Slower.
  • Use ConcurrentHashMap instead of Hashtable for thread-safe operations.
09

What is the difference between HashMap and TreeMap?

  • HashMap - no ordering guarantee. O(1) average for get/put. Uses hashCode() and equals().
  • TreeMap - sorted by natural order or custom Comparator. O(log n) for get/put. Uses compareTo().
  • Use TreeMap when you need sorted keys; HashMap for general-purpose key-value storage.
10

What is the difference between Comparable and Comparator?

  • Comparable - defines natural ordering within the class itself via compareTo(). The class must implement it.
  • Comparator - defines external ordering. Can be passed to sort methods. Allows multiple sort strategies without modifying the class.
Example
// Comparable\nclass Student implements Comparable<Student> {\n  public int compareTo(Student s) { return this.name.compareTo(s.name); }\n}\n\n// Comparator\nstudents.sort(Comparator.comparing(Student::getAge).thenComparing(Student::getName));
11

What is the difference between checked and unchecked exceptions?

  • Checked exceptions - must be declared with throws or caught with try/catch. Checked at compile time. Examples: IOException, SQLException.
  • Unchecked exceptions - extend RuntimeException. Not required to be caught or declared. Examples: NullPointerException, ArrayIndexOutOfBoundsException.
  • Use checked exceptions for recoverable conditions; unchecked for programming errors.
12

What is the difference between throw and throws in Java?

  • throw - used to explicitly throw an exception instance inside a method.
  • throws - used in method signature to declare that the method may throw checked exceptions.
Example
public void readFile(String path) throws IOException {\n  if (path == null) throw new IllegalArgumentException("Path cannot be null");\n  // ...\n}
13

What is the finally block and when does it not execute?

The finally block always executes after try/catch, whether or not an exception occurred. It is used for cleanup (closing resources). It does NOT execute if: System.exit() is called, the JVM crashes, or the thread is killed.

Example
try {\n  // risky code\n} catch (Exception e) {\n  // handle\n} finally {\n  connection.close(); // always runs\n}
14

What is try-with-resources in Java?

Try-with-resources automatically closes resources that implement AutoCloseable when the try block exits. Eliminates the need for finally blocks for resource cleanup.

Example
try (Connection conn = getConnection();\n     PreparedStatement ps = conn.prepareStatement(sql)) {\n  ps.executeQuery();\n} // conn and ps are automatically closed
15

What is the difference between method overloading and overriding?

  • Overloading - same method name, different parameters (compile-time polymorphism). Resolved at compile time.
  • Overriding - subclass provides a specific implementation of a superclass method (runtime polymorphism). Resolved at runtime. Method signature must match.
Example
// Overloading\nvoid print(int x) {}\nvoid print(String s) {}\n\n// Overriding\n@Override\npublic String toString() { return "MyClass"; }
16

What is the difference between static and instance methods?

  • Static methods - belong to the class, not instances. Called via ClassName.method(). Cannot access instance variables or this.
  • Instance methods - belong to an object. Can access both static and instance variables.
17

What are Java 8 lambda expressions?

Lambda expressions provide a concise way to implement functional interfaces (interfaces with a single abstract method). They enable functional programming style in Java.

Example
// Before Java 8\nRunnable r = new Runnable() { public void run() { System.out.println("Hello"); } };\n\n// Lambda\nRunnable r = () -> System.out.println("Hello");\n\n// With parameters\nComparator<String> c = (a, b) -> a.compareTo(b);
18

What is the Java Stream API?

Streams provide a functional approach to processing collections. They support lazy evaluation, parallel processing, and a rich set of operations.

Example
List<String> names = employees.stream()\n  .filter(e -> e.getSalary() > 50000)\n  .map(Employee::getName)\n  .sorted()\n  .collect(Collectors.toList());\n\n// Parallel stream\nlong count = list.parallelStream().filter(x -> x > 0).count();
19

What is the difference between map() and flatMap() in Java Streams?

  • map() - transforms each element to another element. Returns Stream> for nested collections.
  • flatMap() - transforms each element to a stream and flattens all streams into one. Returns Stream.
Example
// map: Stream<List<String>>\nlist.stream().map(s -> s.split(","));\n\n// flatMap: Stream<String>\nlist.stream().flatMap(s -> Arrays.stream(s.split(",")));
20

What is Optional in Java 8?

Optional is a tl-container that may or may not contain a non-null value. It avoids NullPointerException and makes null handling explicit.

Example
Optional<String> name = Optional.ofNullable(getName());\n\nString result = name\n  .filter(n -> n.length() > 2)\n  .map(String::toUpperCase)\n  .orElse("DEFAULT");
21

What is the difference between interface default methods and abstract class methods?

Java 8 default methods allow interfaces to have method implementations. Difference: abstract classes can have state (instance variables) and constructors; interfaces cannot. A class can implement multiple interfaces with default methods but extend only one abstract class.

Example
interface Greeter {\n  default String greet(String name) { return "Hello, " + name; }\n  void farewell(String name); // still abstract\n}
22

What is multithreading in Java?

Multithreading allows concurrent execution of two or more threads. Create threads by extending Thread or implementing Runnable. Use ExecutorService for thread pool management.

Example
// Runnable (preferred)\nExecutorService executor = Executors.newFixedThreadPool(4);\nexecutor.submit(() -> processTask());\nexecutor.shutdown();\n\n// Thread\nnew Thread(() -> System.out.println("Running")).start();
23

What is the difference between synchronized method and synchronized block?

  • Synchronized method - locks the entire method on the object (or class for static). Coarser granularity.
  • Synchronized block - locks only a specific section of code on a specified object. Finer granularity, better performance.
Example
// Synchronized method\npublic synchronized void increment() { count++; }\n\n// Synchronized block (preferred - finer control)\npublic void increment() {\n  synchronized(this) { count++; }\n}
24

What is the volatile keyword in Java?

volatile ensures that a variable is read from and written to main memory, not a thread-local cache. It guarantees visibility of changes across threads but does NOT guarantee atomicity.

Example
private volatile boolean running = true;\n\n// Thread 1\npublic void stop() { running = false; }\n\n// Thread 2\nwhile (running) { doWork(); } // sees updated value
25

What is the difference between wait(), notify(), and notifyAll()?

  • wait() - releases the lock and puts the thread in waiting state until notified. Must be called in synchronized context.
  • notify() - wakes up one waiting thread (arbitrary choice).
  • notifyAll() - wakes up all waiting threads. Prefer notifyAll() to avoid missed signals.
26

What is the Java Memory Model and what are heap and stack?

  • Stack - stores method frames, local variables, and references. Each thread has its own stack. LIFO. Fast allocation.
  • Heap - stores all objects and class instances. Shared across threads. Managed by garbage collector.
  • Method Area (Metaspace) - stores class metadata, static variables, and constant pool.
27

What is garbage collection in Java?

Garbage collection automatically reclaims memory occupied by objects that are no longer reachable. The JVM uses generational GC: Young Generation (Eden + Survivor spaces) for short-lived objects, Old Generation for long-lived objects. GC algorithms: Serial, Parallel, G1 (default), ZGC.

28

What is the difference between final, finally, and finalize?

  • final - keyword: final variable cannot be reassigned; final method cannot be overridden; final class cannot be extended.
  • finally - block that always executes after try/catch for cleanup.
  • finalize() - deprecated method called by GC before object is collected. Unreliable, avoid using it.
29

What is the difference between String pool and heap allocation for Strings?

String literals are stored in the String pool (part of heap). When you create a String literal, Java checks the pool first and reuses existing instances. new String() always creates a new object on the heap outside the pool.

Example
String a = "hello";          // pool\nString b = "hello";          // same pool reference\nString c = new String("hello"); // new heap object\nSystem.out.println(a == b);  // true\nSystem.out.println(a == c);  // false\nSystem.out.println(a.equals(c)); // true
30

What is the difference between Iterator and ListIterator?

  • Iterator - traverses any Collection in forward direction only. Supports remove().
  • ListIterator - extends Iterator for Lists. Supports bidirectional traversal, add(), set(), and index access.
31

What are Java generics and what is type erasure?

Generics enable type-safe collections and methods. Type erasure removes generic type information at compile time, replacing it with Object or bounds. This means generic type info is not available at runtime.

Example
// Generic method\npublic <T extends Comparable<T>> T max(T a, T b) {\n  return a.compareTo(b) > 0 ? a : b;\n}\n\n// Bounded wildcard\npublic double sum(List<? extends Number> list) {\n  return list.stream().mapToDouble(Number::doubleValue).sum();\n}
32

What is the difference between Runnable and Callable?

  • Runnable - run() method returns void. Cannot throw checked exceptions.
  • Callable - call() method returns a value (Future). Can throw checked exceptions.
  • Use Callable when you need a return value from a thread.
Example
Callable<Integer> task = () -> {\n  return computeResult(); // can return value and throw\n};\nFuture<Integer> future = executor.submit(task);\nint result = future.get(); // blocks until done
33

What is the difference between HashMap and ConcurrentHashMap?

  • HashMap - not thread-safe. Can cause data corruption with concurrent modifications.
  • ConcurrentHashMap - thread-safe without locking the entire map. Uses segment-level locking (Java 7) or CAS operations (Java 8+). Better performance than Hashtable.
Example
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();\nmap.put("key", 1);\nmap.computeIfAbsent("key2", k -> expensiveCompute(k));
34

What is the difference between Stack and Deque in Java?

Stack is a legacy class extending Vector (synchronized, slow). Deque (ArrayDeque) is the modern replacement - faster, not synchronized, supports both stack (push/pop) and queue (offer/poll) operations.

Example
Deque<Integer> stack = new ArrayDeque<>();\nstack.push(1); stack.push(2);\nstack.pop(); // 2\n\nDeque<Integer> queue = new ArrayDeque<>();\nqueue.offer(1); queue.offer(2);\nqueue.poll(); // 1
35

What are Java records?

Records (Java 16+) are immutable data classes that automatically generate constructor, getters, equals(), hashCode(), and toString(). Ideal for DTOs and value objects.

Example
record Point(int x, int y) {}\n\nPoint p = new Point(3, 4);\nSystem.out.println(p.x());    // 3\nSystem.out.println(p);        // Point[x=3, y=4]
36

What are sealed classes in Java?

Sealed classes (Java 17+) restrict which classes can extend or implement them. Used with permits keyword. Enables exhaustive pattern matching.

Example
sealed interface Shape permits Circle, Rectangle, Triangle {}\nrecord Circle(double radius) implements Shape {}\nrecord Rectangle(double w, double h) implements Shape {}
37

What is the difference between Iterable and Iterator?

  • Iterable - interface with iterator() method. Implemented by collections to support for-each loops.
  • Iterator - interface with hasNext(), next(), and remove() methods. Returned by Iterable.iterator().
38

What is the difference between deep copy and shallow copy in Java?

  • Shallow copy - copies the object but not the objects it references. References point to the same objects.
  • Deep copy - copies the object and all objects it references recursively. Completely independent copy.
  • Implement Cloneable and override clone() for shallow copy; use serialization or copy constructors for deep copy.
39

What is the difference between static initializer and instance initializer?

  • Static initializer block - runs once when the class is loaded. Used to initialize static variables.
  • Instance initializer block - runs every time an object is created, before the constructor.
Example
class MyClass {\n  static { System.out.println("Static init"); } // once\n  { System.out.println("Instance init"); }       // every new\n  MyClass() { System.out.println("Constructor"); }\n}
40

What is the difference between String.format() and String.valueOf()?

  • String.valueOf(obj) - converts any type to its String representation. Null-safe (returns "null" for null).
  • String.format(template, args) - creates a formatted string using format specifiers (%s, %d, %f).
Example
String.valueOf(42);           // "42"\nString.valueOf(null);         // "null"\nString.format("Hi %s, you are %d", "Alice", 30); // "Hi Alice, you are 30"
41

What is the difference between Enum and constants in Java?

Enums are type-safe, can have methods and fields, support switch statements, and are singletons. Constants (static final) are just values with no type safety or behavior.

Example
enum Status {\n  ACTIVE("Active"), INACTIVE("Inactive");\n  private final String label;\n  Status(String label) { this.label = label; }\n  public String getLabel() { return label; }\n}
42

What is the difference between @Override, @Deprecated, and @SuppressWarnings?

  • @Override - tells compiler the method overrides a superclass method. Compile error if it does not.
  • @Deprecated - marks a method/class as outdated. Compiler warns when it is used.
  • @SuppressWarnings - suppresses specific compiler warnings.
43

What is the difference between composition and inheritance in Java?

  • Inheritance (is-a) - subclass extends superclass. Tight coupling. Cannot change at runtime.
  • Composition (has-a) - class contains instances of other classes. Loose coupling. More flexible. Prefer composition over inheritance.
Example
// Composition (preferred)\nclass Car {\n  private Engine engine; // has-a\n  Car(Engine e) { this.engine = e; }\n}
44

What is the difference between List.of() and Arrays.asList()?

  • Arrays.asList() - returns a fixed-size list backed by the array. Cannot add/remove but can set elements.
  • List.of() (Java 9+) - returns a truly immutable list. Cannot add, remove, or set elements. Does not allow null values.
Example
List<String> a = Arrays.asList("a", "b"); // can set, cannot add/remove\nList<String> b = List.of("a", "b");       // fully immutable
45

What is the difference between Map.of() and new HashMap()?

  • Map.of() (Java 9+) - creates an immutable map. Cannot add, remove, or update entries. Limited to 10 entries (use Map.ofEntries() for more).
  • new HashMap() - mutable map. Can add, remove, and update entries freely.
46

What is the difference between var (local variable type inference) and explicit types?

var (Java 10+) lets the compiler infer the type of local variables. It is not dynamic typing - the type is still fixed at compile time. Cannot be used for fields, method parameters, or return types.

Example
var list = new ArrayList<String>(); // inferred as ArrayList<String>\nvar map = new HashMap<String, Integer>();\nfor (var entry : map.entrySet()) { ... }
47

What is the difference between text blocks and regular strings in Java?

Text blocks (Java 15+) are multi-line string literals that preserve formatting and reduce escape sequences. Ideal for JSON, SQL, and HTML strings.

Example
// Regular string\nString json = "{\n  \"name\": \"Alice\"\n}";\n\n// Text block\nString json = """\n    {\n      "name": "Alice"\n    }\n    """;
48

What is the difference between pattern matching instanceof and traditional instanceof?

Pattern matching instanceof (Java 16+) combines the type check and cast into one expression, eliminating the explicit cast.

Example
// Traditional\nif (obj instanceof String) {\n  String s = (String) obj;\n  System.out.println(s.length());\n}\n\n// Pattern matching\nif (obj instanceof String s) {\n  System.out.println(s.length()); // s is already cast\n}
49

What is the difference between CompletableFuture and Future?

  • Future - basic async result. Can only get() (blocking) or cancel(). No chaining.
  • CompletableFuture - supports chaining (thenApply, thenCompose, thenCombine), exception handling (exceptionally), and combining multiple futures. Non-blocking.
Example
CompletableFuture.supplyAsync(() -> fetchUser(id))\n  .thenApply(user -> enrichUser(user))\n  .thenAccept(user -> saveUser(user))\n  .exceptionally(ex -> { log(ex); return null; });
50

What is the difference between Predicate, Function, Consumer, and Supplier in Java 8?

  • Predicate - takes T, returns boolean. Used for filtering.
  • Function - takes T, returns R. Used for mapping/transformation.
  • Consumer - takes T, returns void. Used for side effects.
  • Supplier - takes nothing, returns T. Used for lazy value creation.
Example
Predicate<String> notEmpty = s -> !s.isEmpty();\nFunction<String, Integer> length = String::length;\nConsumer<String> print = System.out::println;\nSupplier<List<String>> newList = ArrayList::new;

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.