Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Interview Questions»100 Java Interview Questions and Answers (Freshers to Experienced)
    Interview Questions

    100 Java Interview Questions and Answers (Freshers to Experienced)

    Anirudh KhuranaBy Anirudh Khurana30 November 2026No Comments92 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    100 Java interview questions by Code and Debug, showing a String == vs equals example
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Java is still the language behind most bank, telecom and enterprise back ends in India, and it is the main language for Android and for Spring Boot microservices. That is why Java interview questions come up in campus drives at TCS, Infosys and Wipro just as often as in product company rounds. Freshers get “JDK vs JRE vs JVM” and “== vs equals”. Experienced candidates get HashMap internals, concurrency, garbage collection and Java 21 features.

    This page has the 100 Java interview questions asked most often, with clear answers, grouped for freshers, intermediate and experienced candidates. 36 answers include a Java example that was compiled and run on Java 21, so the output you see is real. Four interactive tools let you watch the stack, heap and String pool change line by line, test yourself on tricky “what does this print?” snippets, pick the right collection, and take a quick quiz. Prefer to study offline? Download all 100 questions as a free PDF.

    Free PDF
    All 100 Java interview questions with answers
    54 pages, with every code example and its output. No sign-up needed.
    Download PDF

    What you will find on this page

    • 100 questions with answers in three levels: 40 for freshers, 35 intermediate, 25 for experienced candidates.
    • Core Java and Java 8: basics, OOP, strings, exceptions, collections, generics, multithreading, the JVM and memory, streams and lambdas, plus records, sealed classes and virtual threads from Java 17 and 21.
    • Four interactive tools: a stack, heap and String pool visualiser, a “guess the output” game, a collection chooser and a quiz.
    • 36 Java examples with real output.
    • Study tools: filters by level and topic, search, and a “Done” button on every question that remembers your progress.
    • A free 54-page PDF of everything.

    Also useful (each opens our own guide):

    OOPs interview questionsThe concepts behind a quarter of these questions. DSA interview cheat sheetFor the coding round that usually follows. SQL interview questionsMost Java back-end roles test SQL too.
    Study tools

    Study these 100 questions your way

    Filter the Java interview questions by level or topic, or search them. Press “Mark as done” under each question you have finished; your progress is saved in this browser.

    Showing
    100 / 100
    Done
    0 / 100
    Download PDF (54 pages)

    No questions match these filters. Try another topic or clear the search.

    How to prepare for a Java interview

    • Know the classic comparisons cold: JDK vs JRE vs JVM, == vs equals(), String vs StringBuilder, abstract class vs interface, ArrayList vs LinkedList, HashMap vs ConcurrentHashMap, checked vs unchecked exceptions, Comparable vs Comparator.
    • Be ready to explain internals: how HashMap works, why String is immutable, what happens in memory when you create an object, and how garbage collection decides what to free.
    • Write Java 8 stream code by hand: group employees by department, find the second highest salary, count word frequencies. Many companies ask for these on a shared editor or on paper.
    • For 3+ years of experience, revise concurrency (synchronized, volatile, ExecutorService, CompletableFuture), JVM tuning, and what your project used from Java 17 and 21.
    • Expect a coding round as well. Practise arrays, strings, hashing and two pointers in Java; our DSA cheat sheet lists the patterns.

    Learn the tricky parts by doing

    Three topics trip up more Java candidates than any others: what happens in memory, small snippets with surprising output, and choosing the right collection. These tools let you practise each one before you read the questions.

    Stack, heap and String pool visualiser

    Step through two short programs and watch where every variable and object lives. The first shows the String pool and why == can be false for equal strings. The second shows why Java is pass by value, even for objects.

    Visualiser

    Java memory, one line at a time

    Code
    Stack
    Heap
    String pool

    Guess the output: 14 tricky Java snippets

    Interviewers love short snippets with a surprising result. Every snippet below was run on Java 21, so the answers are what the JVM really prints.

    Game

    What does this code print?

    14 snippets, about five minutes.

    Which collection should I use?

    “Which collection would you use for this?” is one of the most common follow-up questions. Answer three questions and see the class to use, its cost, and one line of code.

    Try it

    Collection chooser

    What do you need to store?
    What will you mostly do?
    What order do you need when you loop through it?
    In what order should items come out?
    Will several threads change it at the same time?

    Java interview questions for freshers

    These 40 core Java interview questions cover what campus placements and first interviews ask: how Java runs, data types, OOP, strings, exceptions, the basic collections, threads, memory and the main Java 8 features.

    Q1FreshersBasics

    1. What is Java and what are its main features?

    Java is a general-purpose, object-oriented programming language released by Sun Microsystems in 1995 and now owned by Oracle. Java code is compiled into bytecode that runs on the Java Virtual Machine (JVM), which is why the same program runs on Windows, Linux and macOS without changes.

    • Platform independent: “write once, run anywhere”, thanks to bytecode and the JVM.
    • Object-oriented: code is organised into classes and objects, with encapsulation, inheritance, polymorphism and abstraction.
    • Robust and secure: strong typing, no pointer arithmetic, automatic garbage collection and checked exceptions.
    • Multithreaded: threads and concurrency utilities are built into the language and the standard library.
    • Fast enough for most work: the JIT compiler turns hot bytecode into native machine code at run time.
    • Huge ecosystem: Spring Boot, Android, Hadoop, Kafka and most bank and enterprise back ends run on Java.
    Q2FreshersBasics

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

    What it isContainsWho needs it
    JVMThe virtual machine that runs bytecodeClass loader, memory areas, interpreter, JIT compiler, garbage collectorEvery Java program, at run time
    JREJava Runtime EnvironmentJVM + core class libraries (java.lang, java.util and so on)Users who only run Java programs
    JDKJava Development KitJRE + development tools: javac, java, jar, javadoc, jdb, jshellDevelopers who write and compile Java

    In short: JDK = JRE + tools, and JRE = JVM + libraries. Since Java 11, Oracle no longer ships a separate JRE download; you install a JDK and can build a small custom runtime with jlink if you need one.

    Q3FreshersBasics

    3. Why is Java platform independent? Is the JVM platform independent?

    The javac compiler does not produce machine code for one processor. It produces bytecode (.class files), an instruction set for the JVM. Each operating system has its own JVM that understands the same bytecode, so one .class file runs everywhere.

    So Java the language and its bytecode are platform independent, but the JVM itself is platform dependent: there is a different JVM build for Windows, Linux and macOS, and for x64 and ARM. That is the trade: the JVM vendors handle each platform so your code does not have to.

    Q4FreshersBasics

    4. Explain public static void main(String[] args).

    • public: the JVM must be able to call it from outside the class.
    • static: the JVM calls it without creating an object of the class.
    • void: it returns nothing to the JVM. Use System.exit(code) to return an exit status.
    • main: the name the JVM looks for as the entry point.
    • String[] args: command-line arguments, for example java Main hello 42 gives args[0] = “hello”.

    Follow-up questions: you can overload main, but the JVM only calls the version with String[]. String... args also works. Since Java 21 (as a preview, and final in Java 25), simpler instance main methods like void main() are allowed for small programs.

    Q5FreshersBasics

    5. What are the primitive data types in Java?

    TypeSizeDefaultRange or example
    byte1 byte0-128 to 127
    short2 bytes0-32,768 to 32,767
    int4 bytes0about ±2.1 billion
    long8 bytes0Labout ±9.2 × 10¹⁸
    float4 bytes0.0fabout 7 decimal digits
    double8 bytes0.0dabout 15 decimal digits
    char2 bytes‘\u0000’one UTF-16 code unit
    booleanJVM dependentfalsetrue or false

    Defaults apply to fields only; local variables must be assigned before use. Everything else, including String and arrays, is a reference type. Never use float or double for money; use BigDecimal, because 0.1 + 0.2 is not exactly 0.3 in binary floating point.

    Q6FreshersBasics

    6. What are wrapper classes and autoboxing? Why does Integer 127 == 127 give true but 128 == 128 give false?

    Each primitive has a wrapper class: Integer, Long, Double, Character, Boolean and so on. Collections and generics only work with objects, so you need wrappers for List<Integer>. Autoboxing converts a primitive to its wrapper automatically, and unboxing does the reverse.

    public class Main {
        public static void main(String[] args) {
            Integer a = 127, b = 127;
            Integer c = 128, d = 128;
            System.out.println(a == b);      // same cached object
            System.out.println(c == d);      // two different objects
            System.out.println(c.equals(d)); // compares values
    
            int total = a + c;               // unboxing happens here
            System.out.println(total);
        }
    }

    Output:

    true
    false
    true
    255

    Integer.valueOf(), which autoboxing uses, caches the objects from -128 to 127. Inside that range both variables point to the same cached object, so == is true; outside it you get two objects. The lesson: always compare wrapper objects with equals(). Also, unboxing a null wrapper throws a NullPointerException.

    Q7FreshersBasics

    7. Is Java pass by value or pass by reference?

    Java is always pass by value. For primitives the value is the number itself. For objects, the value that gets copied is the reference (the address of the object). The method can use that copy to change the object, but re-pointing the copy does not affect the caller’s variable.

    import java.util.*;
    
    public class Main {
        static void change(int x, List<String> list) {
            x = 100;                 // changes only the local copy
            list.add("Java");        // changes the object the copy points to
            list = new ArrayList<>(); // re-points only the local copy
            list.add("Python");
        }
    
        public static void main(String[] args) {
            int num = 5;
            List<String> langs = new ArrayList<>();
            change(num, langs);
            System.out.println(num);
            System.out.println(langs);
        }
    }

    Output:

    5
    [Java]

    num stays 5. The list shows “Java” because both references pointed to the same object at that moment, but not “Python”, because by then the method had re-pointed only its own copy. This is why a classic swap(a, b) method cannot swap two objects in Java.

    Q8FreshersBasics

    8. What does the static keyword mean?

    static members belong to the class, not to any one object. A static variable has one copy shared by all objects; a static method can be called with the class name and has no this.

    public class Main {
        static class Student {
            static int count = 0;   // one copy, shared by all objects
            String name;            // one copy per object
    
            Student(String name) {
                this.name = name;
                count++;
            }
    
            static void showCount() {
                System.out.println("Students created: " + count);
            }
        }
    
        public static void main(String[] args) {
            new Student("Riya");
            new Student("Arjun");
            new Student("Meera");
            Student.showCount();
        }
    }

    Output:

    Students created: 3
    • Static variable: shared data such as a counter or a constant.
    • Static method: utility code like Math.max(). It cannot use instance variables directly.
    • Static block: runs once when the class is loaded, used to set up static data.
    • Static nested class: a nested class that does not need an outer object.
    Q9FreshersBasics

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

    KeywordUsed forMeaning
    finalVariable, method, classA final variable cannot be reassigned, a final method cannot be overridden, a final class cannot be extended (for example String)
    finallyBlock after try/catchRuns whether or not an exception happened, used to release resources
    finalize()Method of ObjectWas called by the garbage collector before removing an object. Deprecated since Java 9 and marked for removal; use try-with-resources or Cleaner instead
    import java.util.*;
    
    public class Main {
        static final double GST = 0.18;          // constant
    
        static class Base {
            final void rule() { System.out.println("cannot be overridden"); }
        }
    
        public static void main(String[] args) {
            final List<String> list = new ArrayList<>();
            list.add("Java");                    // allowed: the object can change
            // list = new ArrayList<>();         // compile error: reference is final
            System.out.println(list);
    
            try {
                System.out.println("in try");
            } finally {
                System.out.println("finally always runs");
            }
            new Base().rule();
            System.out.println(1000 * (1 + GST));
        }
    }

    Output:

    [Java]
    in try
    finally always runs
    cannot be overridden
    1180.0

    A final reference cannot point to a new object, but the object itself can still change, which is why the list above accepts “Java”.

    Q10FreshersBasics

    10. What is the difference between this and super?

    • this refers to the current object. Use it to tell a field from a parameter with the same name (this.name = name), to pass the current object to another method, or to call another constructor of the same class with this(...).
    • super refers to the parent class part of the object. Use it to call the parent’s constructor with super(...) or a method you have overridden with super.method().

    A call to this(...) or super(...) must be the first statement in a constructor, so a constructor can use only one of them. If you write neither, the compiler inserts super() automatically. Neither keyword can be used in a static method.

    Q11FreshersBasics

    11. What is a constructor? Can a constructor be private, static or final?

    A constructor is a special block that runs when you create an object with new. It has the same name as the class and no return type. If you write no constructor, the compiler adds a default no-argument one; if you write any constructor, it does not.

    • Private: yes. Used in singletons and utility classes so that outside code cannot create objects.
    • Static: no. A constructor initialises an object, so it cannot belong to the class.
    • Final or abstract: no. Constructors are not inherited, so they can never be overridden anyway.
    • Overloaded: yes, with different parameter lists, and one can call another with this(...) (constructor chaining).
    Q12FreshersOOP

    12. What are the four pillars of object-oriented programming in Java?

    • Encapsulation: keep fields private and expose them through methods, so an object controls its own state. Example: a BankAccount that only changes its balance through deposit() and withdraw().
    • Inheritance: a class reuses and extends another with extends. Example: Car extends Vehicle.
    • Polymorphism: one interface, many forms. Overloading is compile-time polymorphism; overriding is runtime polymorphism.
    • Abstraction: show what an object does and hide how, using abstract classes and interfaces. Example: you call list.add() without caring whether it is an ArrayList or a LinkedList.

    Our OOPs interview questions post goes deeper into each pillar with examples in several languages.

    Q13FreshersOOP

    13. Why does Java not support multiple inheritance of classes?

    If class C could extend both A and B, and both had a method show(), C would not know which one to inherit. This is the diamond problem. Java avoids it by allowing a class to extend only one class.

    A class can implement many interfaces, though. Before Java 8 that was always safe because interfaces had no method bodies. Since Java 8, interfaces can have default methods, so the diamond problem can appear again, and Java makes you resolve it yourself (see question 69). Java supports single, multilevel and hierarchical inheritance with classes.

    Q14FreshersOOP

    14. What is the difference between method overloading and method overriding?

    PointOverloadingOverriding
    WhereSame class (or subclass)Subclass redefines a parent method
    SignatureSame name, different parametersSame name and same parameters
    Return typeCan be anythingSame or a subtype (covariant)
    Decided atCompile time (static binding)Run time (dynamic binding)
    AccessAnyCannot be more restrictive than the parent
    static / privateCan be overloadedCannot be overridden
    public class Main {
        static class Shape {
            double area() { return 0; }
            String describe() { return "Shape with area " + area(); }
        }
        static class Circle extends Shape {
            double r;
            Circle(double r) { this.r = r; }
            @Override
            double area() { return Math.round(Math.PI * r * r * 100) / 100.0; }
        }
    
        // overloading: same name, different parameters
        static int add(int a, int b) { return a + b; }
        static double add(double a, double b) { return a + b; }
        static int add(int a, int b, int c) { return a + b + c; }
    
        public static void main(String[] args) {
            System.out.println(add(2, 3));
            System.out.println(add(2.5, 3.5));
            System.out.println(add(1, 2, 3));
    
            Shape s = new Circle(2);        // reference type Shape, object Circle
            System.out.println(s.describe()); // Circle's area() runs: overriding
        }
    }

    Output:

    5
    6.0
    6
    Shape with area 12.57

    The last line is the key point: the variable type is Shape, but the object is a Circle, so the JVM calls Circle’s area() at run time. Changing only the return type is not overloading and does not compile.

    Q15FreshersOOP

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

    PointAbstract classInterface
    MethodsAbstract and concreteAbstract, plus default and static (Java 8) and private (Java 9)
    FieldsAny instance or static fieldsOnly public static final constants
    ConstructorYesNo
    InheritanceA class extends only oneA class implements many
    AccessAny access modifierMethods are public by default
    Use whenRelated classes share state and codeUnrelated classes share a capability (Comparable, Runnable)
    public class Main {
        interface Payment {
            double FEE = 0.02;                   // public static final
            void pay(double amount);             // abstract
            default String receipt(double amount) {  // default method (Java 8)
                return "Paid Rs " + amount + " + fee Rs " + amount * FEE;
            }
        }
    
        static abstract class Account {
            protected double balance;            // state is allowed
            Account(double balance) { this.balance = balance; }
            abstract String type();
            String summary() { return type() + " balance: " + balance; }
        }
    
        static class Savings extends Account implements Payment {
            Savings(double b) { super(b); }
            String type() { return "Savings"; }
            public void pay(double amount) { balance -= amount; }
        }
    
        public static void main(String[] args) {
            Savings s = new Savings(5000);
            s.pay(1200);
            System.out.println(s.summary());
            System.out.println(s.receipt(1200));
        }
    }

    Output:

    Savings balance: 3800.0
    Paid Rs 1200.0 + fee Rs 24.0

    Rule of thumb: start with an interface to define what something can do, and add an abstract class when several implementations share real code and fields.

    Q16FreshersOOP

    16. What are the access modifiers in Java?

    ModifierSame classSame packageSubclass (other package)Everywhere
    privateYesNoNoNo
    default (no keyword)YesYesNoNo
    protectedYesYesYesNo
    publicYesYesYesYes

    A top-level class can only be public or default. Good encapsulation means making fields private and opening up only what other code needs. When overriding, you can keep or widen access (protected to public) but never narrow it.

    Q17FreshersOOP

    17. What is polymorphism? Explain compile-time and runtime polymorphism.

    Compile-time (static) polymorphism is method overloading: the compiler picks the method from the argument types. Runtime (dynamic) polymorphism is method overriding: a parent reference can hold a child object, and the JVM calls the child’s version of the method through dynamic method dispatch.

    Example: List<String> list = new ArrayList<>(); Your code talks to List, and you can switch to LinkedList by changing one line. This “program to an interface” idea is why polymorphism matters in real projects, not just in theory.

    Q18FreshersOOP

    18. Can we override static or private methods?

    No. Private methods are not visible to subclasses, so a method with the same name in a child class is a brand-new method. Static methods belong to the class; if a child declares the same static method, it hides the parent’s method instead of overriding it. Which one runs depends on the reference type, not the object.

    Final methods also cannot be overridden. You can, however, overload static and private methods. Adding @Override to a method that does not actually override anything gives a compile error, which is why using that annotation is good practice.

    Q19FreshersStrings

    19. Why is String immutable in Java?

    • String pool: many variables share one pooled “java” object. That is only safe if no one can change it.
    • Security: file paths, URLs, class names and database credentials are passed as strings. If they could change after a security check, the check would be useless.
    • Thread safety: immutable objects can be shared between threads without locks.
    • Hash code caching: a String computes its hash once and reuses it, which makes it a fast and safe HashMap key.

    Methods like concat(), toUpperCase() and replace() never change the original; they return a new String. The String class is also final, so no subclass can break this guarantee.

    Q20FreshersStrings

    20. What is the String pool? What is the difference between == and equals() for strings?

    The String pool is a special area in the heap where Java keeps one copy of each string literal. == checks whether two references point to the same object; equals() checks whether the characters are the same.

    public class Main {
        public static void main(String[] args) {
            String a = "java";               // goes to the string pool
            String b = "java";               // reuses the same pooled object
            String c = new String("java");   // new object on the heap
            String d = c.intern();           // pooled version of c
    
            System.out.println(a == b);
            System.out.println(a == c);
            System.out.println(a.equals(c));
            System.out.println(a == d);
    
            String e = "ja" + "va";          // joined at compile time
            String part = "ja";
            String f = part + "va";          // joined at run time
            System.out.println(a == e);
            System.out.println(a == f);
        }
    }

    Output:

    true
    false
    true
    true
    true
    false

    new String("java") always creates a new object, so a == c is false. intern() returns the pooled copy. Literals joined at compile time (“ja” + “va”) are pooled; strings built at run time are not. In real code, always compare strings with equals() (or equalsIgnoreCase()).

    Q21FreshersStrings

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

    PointStringStringBuilderStringBuffer
    MutableNoYesYes
    Thread safeYes (immutable)NoYes (synchronized methods)
    Speed for many changesSlow, new object each timeFastestSlower than StringBuilder
    Use whenText that does not changeBuilding text in one thread (most cases)Legacy code shared across threads
    public class Main {
        public static void main(String[] args) {
            String s = "Code";
            s.concat(" and Debug");          // result thrown away
            System.out.println(s);           // s is unchanged
            s = s.concat(" and Debug");      // assign the new String
            System.out.println(s);
    
            StringBuilder sb = new StringBuilder("Code");
            sb.append(" and").append(" Debug");  // changes the same object
            sb.insert(0, "Learn at ");
            System.out.println(sb);
            System.out.println(sb.reverse());
        }
    }

    Output:

    Code
    Code and Debug
    Learn at Code and Debug
    gubeD dna edoC ta nraeL

    Joining strings with + inside a loop creates a new String each time, which is O(n²) work for n pieces. Use StringBuilder in loops. A single line like "Hi " + name is fine; the compiler optimises it.

    Q22FreshersStrings

    22. How many objects are created by String s = new String(“hello”)?

    One or two. If “hello” is not already in the String pool, the literal creates one pooled object when the class is loaded, and new creates a second object on the heap. If the literal is already in the pool, only the heap object is created.

    This is why new String("...") is almost never needed in real code; it only wastes memory. The answer interviewers want is “two, if the literal is not already in the pool”, along with the reason.

    Q23FreshersExceptions

    23. What is the exception hierarchy? What is the difference between checked and unchecked exceptions?

    Everything that can be thrown extends Throwable, which has two branches: Error (serious JVM problems such as OutOfMemoryError, which you normally do not catch) and Exception. Under Exception, RuntimeException and its subclasses are unchecked; everything else is checked.

    CheckedUnchecked
    Checked byCompiler: you must catch or declare with throwsNot checked at compile time
    Typical causeThings outside your controlBugs in the code
    ExamplesIOException, SQLException, ClassNotFoundExceptionNullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, IllegalArgumentException
    Q24FreshersExceptions

    24. What is the difference between throw and throws?

    throwthrows
    What it doesActually throws one exception objectDeclares which exceptions a method may throw
    WhereInside a method bodyIn the method signature
    Followed byAn instance: throw new IllegalArgumentException(“age”)Class names: throws IOException, SQLException
    How manyOne at a timeSeveral, comma separated

    You need throws for checked exceptions that you do not handle inside the method. For unchecked exceptions it is optional and mostly used for documentation.

    Q25FreshersExceptions

    25. How do try, catch and finally work? Does finally always run?

    public class Main {
        static int test() {
            try {
                System.out.println("try");
                int x = 10 / 0;
                return 1;
            } catch (ArithmeticException e) {
                System.out.println("catch: " + e.getMessage());
                return 2;
            } finally {
                System.out.println("finally runs before the method returns");
            }
        }
    
        public static void main(String[] args) {
            System.out.println("returned " + test());
        }
    }

    Output:

    try
    catch: / by zero
    finally runs before the method returns
    returned 2

    The exception jumps from the division straight to the matching catch block. The catch block prepares to return 2, but finally runs first, and only then does the method return. Finally runs whether the try block completes normally, throws, or returns.

    It does not run if the JVM stops: System.exit(), a JVM crash, or the thread being killed. Avoid return inside finally; it silently overrides the value from try or catch and swallows any exception.

    Q26FreshersExceptions

    26. How do you create a custom exception?

    Extend Exception for a checked exception or RuntimeException for an unchecked one, and pass the message (and optionally the cause) to the parent constructor.

    public class Main {
        static class InsufficientBalanceException extends Exception {
            InsufficientBalanceException(String msg) { super(msg); }
        }
    
        static double balance = 3000;
    
        static void withdraw(double amount) throws InsufficientBalanceException {
            if (amount > balance)
                throw new InsufficientBalanceException(
                    "Need Rs " + amount + " but balance is Rs " + balance);
            balance -= amount;
            System.out.println("Withdrawn Rs " + amount);
        }
    
        public static void main(String[] args) {
            try {
                withdraw(1000);
                withdraw(5000);
            } catch (InsufficientBalanceException e) {
                System.out.println("Error: " + e.getMessage());
            }
        }
    }

    Output:

    Withdrawn Rs 1000.0
    Error: Need Rs 5000.0 but balance is Rs 2000.0

    Custom exceptions make errors self-explaining. Name them after the problem, not the code location: InsufficientBalanceException says more than WithdrawException. Most modern code, Spring included, prefers unchecked custom exceptions.

    Q27FreshersCollections

    27. What is the Java Collections Framework?

    It is the set of interfaces and classes in java.util for storing and working with groups of objects. The main interfaces are Collection (with List, Set and Queue/Deque under it) and Map, which is separate because it stores key-value pairs.

    InterfaceMain classesKey property
    ListArrayList, LinkedListOrdered, allows duplicates, index access
    SetHashSet, LinkedHashSet, TreeSetNo duplicates
    Queue / DequeArrayDeque, PriorityQueue, LinkedListProcess in FIFO, LIFO or priority order
    MapHashMap, LinkedHashMap, TreeMapUnique keys mapped to values

    The Collections class (with an s) is a different thing: a utility class with static methods like sort(), reverse() and unmodifiableList().

    Q28FreshersCollections

    28. What is the difference between an array and an ArrayList?

    PointArrayArrayList
    SizeFixed when createdGrows automatically (by about 1.5 times when full)
    Element typesPrimitives and objectsObjects only (int is autoboxed to Integer)
    Lengtharr.length (field)list.size() (method)
    FeaturesBasic indexingadd, remove, contains, sort, iterators
    PerformanceSlightly faster, less memorySmall overhead from boxing and resizing

    Use arrays for fixed-size data and performance-critical code with primitives, such as DSA problems. Use ArrayList for most application code. Convert with Arrays.asList() or List.of() and list.toArray().

    Q29FreshersCollections

    29. What is the difference between ArrayList and LinkedList?

    OperationArrayListLinkedList
    Internal structureResizable arrayDoubly linked list
    get(index)O(1)O(n)
    Add at endO(1) amortisedO(1)
    Add or remove in the middleO(n), shifts elementsO(1) once you are at the node, but O(n) to get there
    MemoryCompactExtra two pointers per element
    Also implementsListList and Deque

    In practice ArrayList wins almost every time because arrays are cache friendly. For a queue or stack, use ArrayDeque rather than LinkedList. See our time complexity guide for what O(1) and O(n) mean.

    Q30FreshersCollections

    30. What is the difference between List, Set and Map? Compare HashSet, LinkedHashSet and TreeSet.

    A List keeps insertion order and allows duplicates. A Set rejects duplicates. A Map stores unique keys with a value each. The three Set classes differ in ordering:

    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            List<String> cities = List.of("Pune", "Delhi", "Surat", "Delhi", "Agra");
    
            System.out.println("HashSet:       " + new HashSet<>(cities));
            System.out.println("LinkedHashSet: " + new LinkedHashSet<>(cities));
            System.out.println("TreeSet:       " + new TreeSet<>(cities));
        }
    }

    Output:

    HashSet:       [Delhi, Pune, Agra, Surat]
    LinkedHashSet: [Pune, Delhi, Surat, Agra]
    TreeSet:       [Agra, Delhi, Pune, Surat]
    HashSetLinkedHashSetTreeSet
    OrderNo guaranteed orderInsertion orderSorted
    add / containsO(1)O(1)O(log n)
    Backed byHashMapLinkedHashMapTreeMap (red-black tree)
    nullOne null allowedOne null allowedNot allowed

    The same three choices exist for maps: HashMap, LinkedHashMap and TreeMap.

    Q31FreshersCollections

    31. What is the difference between Comparable and Comparator?

    ComparableComparator
    Packagejava.langjava.util
    MethodcompareTo(T other)compare(T a, T b)
    Where it livesInside the class itselfA separate object or lambda
    How many ordersOne natural orderAs many as you need
    Used byCollections.sort(list), TreeSetlist.sort(comparator), Comparator.comparing(…)
    import java.util.*;
    
    public class Main {
        record Student(String name, int marks, int age) implements Comparable<Student> {
            public int compareTo(Student o) {          // natural order: by name
                return name.compareTo(o.name);
            }
        }
    
        public static void main(String[] args) {
            List<Student> list = new ArrayList<>(List.of(
                new Student("Riya", 88, 21), new Student("Arjun", 92, 22),
                new Student("Meera", 88, 20), new Student("Kabir", 75, 21)));
    
            Collections.sort(list);                     // uses Comparable
            list.forEach(s -> System.out.print(s.name() + " "));
            System.out.println();
    
            // Comparator: marks high to low, then age low to high
            list.sort(Comparator.comparingInt(Student::marks).reversed()
                                .thenComparingInt(Student::age));
            list.forEach(s -> System.out.print(s.name() + " "));
            System.out.println();
        }
    }

    Output:

    Arjun Kabir Meera Riya 
    Arjun Meera Riya Kabir 

    Kabir is last in the second line because his marks are lowest; Meera comes before Riya because they tie on 88 marks and Meera is younger.

    Q32FreshersMultithreading

    32. What is a thread? How do you create one in Java?

    A thread is a separate path of execution inside a program. Threads share the same heap memory, which makes them cheaper than processes but also means they can interfere with each other. There are two classic ways to create one: extend Thread, or implement Runnable and pass it to a Thread.

    public class Main {
        public static void main(String[] args) throws InterruptedException {
            // 1. extend Thread
            Thread t1 = new Thread() {
                public void run() { System.out.println("Thread 1 running"); }
            };
            // 2. implement Runnable (preferred), here with a lambda
            Thread t2 = new Thread(() -> System.out.println("Thread 2 running"));
    
            t1.start();
            t1.join();      // wait for t1 to finish
            t2.start();
            t2.join();
            System.out.println("Both done, main thread ends");
        }
    }

    Output:

    Thread 1 running
    Thread 2 running
    Both done, main thread ends

    Implementing Runnable is preferred because your class can still extend another class, and the task is separated from the thread that runs it. Always call start(), not run(): run() just executes the code in the current thread. In real projects, you usually submit tasks to an ExecutorService instead of creating threads by hand (question 61).

    Q33FreshersMultithreading

    33. What is the difference between a process and a thread?

    ProcessThread
    What it isA running program with its own memoryA unit of execution inside a process
    MemorySeparate address spaceShares heap with other threads; has its own stack
    Cost to create and switchHighLow
    CommunicationNeeds IPC: pipes, sockets, filesThrough shared objects, so needs synchronisation
    If one crashesOthers are unaffectedCan bring down the whole process

    A JVM is one process; your main method runs on the “main” thread, and the JVM runs others in the background, such as garbage collector threads.

    Q34FreshersJVM and memory

    34. What is garbage collection in Java?

    Garbage collection (GC) automatically frees heap memory used by objects that are no longer reachable. An object is reachable if a chain of references leads to it from a GC root: local variables on thread stacks, static fields, and a few others. Anything unreachable is garbage.

    • You cannot force GC. System.gc() is only a request the JVM may ignore.
    • An object becomes eligible when you set its last reference to null, the reference goes out of scope, or it is only reachable from other garbage (cycles are fine for the GC).
    • The heap is split into a young generation (new objects, collected often and cheaply) and an old generation (long-lived objects), because most objects die young.
    • The default collector since Java 9 is G1. Question 79 covers the different collectors.
    Q35FreshersJVM and memory

    35. What is the difference between stack and heap memory?

    StackHeap
    StoresMethod calls (frames), local primitives, referencesAll objects and arrays, and their instance fields
    Owned byOne stack per threadShared by all threads
    LifetimeFreed automatically when the method returnsFreed by the garbage collector
    SizeSmall (set with -Xss)Large (set with -Xms and -Xmx)
    Error when fullStackOverflowError (often deep recursion)OutOfMemoryError: Java heap space

    In Student s = new Student(); inside a method, the reference s lives on the stack and the Student object lives on the heap.

    Q36FreshersBasics

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

    == compares primitive values, or for objects it checks whether two references point to the same object. equals() compares the content of two objects, as defined by the class. The version in Object is the same as ==, so classes like String, Integer and the collections override it.

    Practical rules: use == for primitives and enums; use equals() for strings, wrappers and your own objects; use Objects.equals(a, b) when either side might be null. If you override equals(), you must also override hashCode() (question 41).

    Q37FreshersBasics

    37. What are the differences between break, continue and return?

    • break exits the nearest loop or switch immediately.
    • continue skips the rest of the current iteration and moves to the next one.
    • return exits the whole method, optionally with a value.

    Java also has labelled break and continue for nested loops, for example outer: for (...) { for (...) { if (found) break outer; } }. They are handy in search problems but use them sparingly, because they make the flow harder to follow.

    Q38FreshersBasics

    38. What is a package? Why do we use import?

    A package is a namespace that groups related classes, such as java.util or com.codeanddebug.payments. Packages avoid name clashes (you can have two classes called Date in different packages), control access through the default and protected modifiers, and match the folder structure of your code.

    import lets you use a class by its short name instead of the full name. java.lang (String, Math, System) is imported automatically. import java.util.*; imports all classes in that package but not sub-packages, and has no run-time cost; it is only a compile-time shortcut.

    Q39FreshersBasics

    39. What is type casting? Explain widening and narrowing.

    Widening (implicit) converts a smaller type to a larger one with no data loss, so Java does it automatically: byte → short → int → long → float → double. Narrowing (explicit) goes the other way and needs a cast, because data can be lost: int x = (int) 9.99; gives 9, and (byte) 130 gives -126 because the value wraps around.

    For objects, upcasting (child to parent reference) is automatic and always safe. Downcasting (parent to child) needs a cast and throws ClassCastException at run time if the object is not really that type, so check with instanceof first, or use pattern matching: if (obj instanceof String s).

    Q40FreshersJava 8

    40. What are the main features introduced in Java 8?

    • Lambda expressions and functional interfaces (Predicate, Function, Supplier, Consumer).
    • Stream API for filter, map, reduce and collect on collections.
    • Default and static methods in interfaces.
    • Method references such as String::length.
    • Optional to represent a value that may be missing.
    • New date and time API (java.time: LocalDate, LocalDateTime, ZonedDateTime, Duration).
    • CompletableFuture for asynchronous programming.
    • Metaspace replaced PermGen, and ConcurrentHashMap was redesigned.

    Java 8 is still the most asked-about version in Indian interviews because many companies moved from it to Java 11, 17 or 21 only recently. Questions 63 to 72 cover these features with code.

    Intermediate Java interview questions

    These 35 questions are for candidates with one to three years of experience: HashMap internals, iterators, generics, immutability, serialization, multithreading, and the Java 8 stream and lambda questions that almost every company asks.

    Q41IntermediateCollections

    41. What is the contract between equals() and hashCode()? What happens if you override only equals()?

    • If two objects are equal according to equals(), they must have the same hashCode().
    • Two objects with the same hash code do not have to be equal (that is a collision).
    • Both methods must be consistent: calling them again without changing the object gives the same result.
    import java.util.*;
    
    public class Main {
        static class NoHash {
            String id;
            NoHash(String id) { this.id = id; }
            @Override public boolean equals(Object o) {
                return o instanceof NoHash n && id.equals(n.id);
            }
            // hashCode() NOT overridden
        }
    
        static class WithHash {
            String id;
            WithHash(String id) { this.id = id; }
            @Override public boolean equals(Object o) {
                return o instanceof WithHash w && id.equals(w.id);
            }
            @Override public int hashCode() { return Objects.hash(id); }
        }
    
        public static void main(String[] args) {
            Set<NoHash> a = new HashSet<>();
            a.add(new NoHash("E101"));
            a.add(new NoHash("E101"));
            System.out.println("Without hashCode: " + a.size());
    
            Set<WithHash> b = new HashSet<>();
            b.add(new WithHash("E101"));
            b.add(new WithHash("E101"));
            System.out.println("With hashCode:    " + b.size());
        }
    }

    Output:

    Without hashCode: 2
    With hashCode:    1

    HashSet and HashMap first use the hash code to pick a bucket, and only then call equals() inside it. Without hashCode(), the two “equal” objects get different default hash codes, land in different buckets, and both are stored. Generate both methods together, use Objects.hash(), or use a record, which does it for you.

    Q42IntermediateCollections

    42. How does HashMap work internally?

    A HashMap is an array of buckets (16 by default). To store a key, it calls key.hashCode(), mixes the high bits into the low bits, and uses hash & (n - 1) to pick a bucket. Each bucket holds a linked list of entries (key, value, hash, next).

    • put: find the bucket; if a key there is equals() to the new key, replace its value, otherwise add a new entry.
    • get: find the bucket, then walk it comparing hashes and keys with equals().
    • Collisions: different keys in one bucket. Since Java 8, a bucket with more than 8 entries (when the table has at least 64 buckets) turns into a red-black tree, so the worst case drops from O(n) to O(log n).
    • Resizing: when size exceeds capacity × load factor (0.75), the table doubles and entries are redistributed.
    • One null key is allowed (it goes to bucket 0), and any number of null values.

    Average put and get are O(1). This is why mutable keys are dangerous: if a key’s fields change after you insert it, its hash changes and you can no longer find the entry.

    Q43IntermediateCollections

    43. What is the difference between HashMap, Hashtable and ConcurrentHashMap?

    PointHashMapHashtableConcurrentHashMap
    Thread safeNoYes, every method is synchronizedYes, with fine-grained locking and CAS
    Performance with many threadsNot safe to shareSlow: one lock for the whole tableFast: reads mostly lock-free
    null keys or valuesOne null key, many null valuesNot allowedNot allowed
    IteratorFail-fastFail-fast (Enumeration is not)Weakly consistent, never throws ConcurrentModificationException
    StatusDefault choiceLegacy, avoidUse for shared maps

    Collections.synchronizedMap() is another option, but it also uses one lock for everything. Question 87 explains how ConcurrentHashMap achieves its speed.

    Q44IntermediateCollections

    44. What are fail-fast and fail-safe iterators?

    A fail-fast iterator (ArrayList, HashMap and most java.util collections) keeps a modification count. If the collection is changed structurally while you iterate, other than through the iterator itself, the next call throws ConcurrentModificationException. A fail-safe iterator (CopyOnWriteArrayList, ConcurrentHashMap) works on a snapshot or tolerates changes, so it never throws.

    import java.util.*;
    import java.util.concurrent.CopyOnWriteArrayList;
    
    public class Main {
        public static void main(String[] args) {
            List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
            try {
                for (Integer n : nums)
                    if (n % 2 == 0) nums.remove(n);   // modifying while looping
            } catch (ConcurrentModificationException e) {
                System.out.println("Fail-fast: " + e.getClass().getSimpleName());
            }
    
            nums = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
            nums.removeIf(n -> n % 2 == 0);            // the safe way
            System.out.println("removeIf: " + nums);
    
            List<Integer> safe = new CopyOnWriteArrayList<>(List.of(1, 2, 3));
            for (Integer n : safe) safe.add(n * 10);   // fail-safe: loops over a snapshot
            System.out.println("CopyOnWriteArrayList: " + safe);
        }
    }

    Output:

    Fail-fast: ConcurrentModificationException
    removeIf: [1, 3, 5]
    CopyOnWriteArrayList: [1, 2, 3, 10, 20, 30]

    To remove while looping, use iterator.remove() or removeIf(). Fail-fast is a best-effort bug detector, not a guarantee; do not rely on it for thread safety.

    Q45IntermediateCollections

    45. What is the difference between Iterator and ListIterator?

    IteratorListIterator
    Works onAny CollectionLists only
    DirectionForward onlyForward and backward (hasPrevious, previous)
    Modifyremove()remove(), set(), add()
    IndexNonextIndex(), previousIndex()

    The for-each loop uses an Iterator behind the scenes, which is why removing inside a for-each loop triggers the fail-fast check from the previous question.

    Q46IntermediateCollections

    46. When would you use a PriorityQueue, ArrayDeque or TreeMap?

    • PriorityQueue: a binary heap that always gives you the smallest element (or the largest with a reversed comparator) in O(log n). Use it for “top K”, scheduling and Dijkstra’s algorithm.
    • ArrayDeque: a resizable circular array that works as both a stack and a queue, faster than Stack and LinkedList. Use it for BFS, undo history and sliding window problems.
    • TreeMap: a red-black tree that keeps keys sorted and supports range queries like floorKey(), ceilingKey() and subMap() in O(log n). Use it for leaderboards, time-based lookups and booking slots.

    These three show up again and again in coding rounds. Our DSA interview cheat sheet lists which data structure fits each problem pattern.

    Q47IntermediateGenerics

    47. What are generics? What is type erasure, and what do ? extends and ? super mean?

    Generics let you write classes and methods that work with any type while keeping compile-time type safety: List<String> will not accept an Integer, and you never need a cast when reading from it.

    import java.util.*;
    
    public class Main {
        // generic method: works for any type that can be compared
        static <T extends Comparable<T>> T max(List<T> list) {
            T best = list.get(0);
            for (T x : list) if (x.compareTo(best) > 0) best = x;
            return best;
        }
    
        // upper-bounded wildcard: read numbers of any subtype
        static double sum(List<? extends Number> list) {
            double s = 0;
            for (Number n : list) s += n.doubleValue();
            return s;
        }
    
        public static void main(String[] args) {
            System.out.println(max(List.of(4, 19, 7)));
            System.out.println(max(List.of("pear", "apple", "mango")));
            System.out.println(sum(List.of(1, 2, 3)));
            System.out.println(sum(List.of(1.5, 2.5)));
    
            List<String> a = new ArrayList<>();
            List<Integer> b = new ArrayList<>();
            System.out.println(a.getClass() == b.getClass()); // type erasure
        }
    }

    Output:

    19
    pear
    6.0
    4.0
    true
    • Type erasure: generic types exist only at compile time. The compiler checks them, inserts casts and removes them, so at run time both lists are plain ArrayList. That is why you cannot write new T() or List<int>.
    • ? extends Number: accepts a list of Number or any subtype. You can read Numbers from it but not add to it.
    • ? super Integer: accepts a list of Integer or any supertype. You can add Integers but reads only give you Object.
    • Memory aid PECS: Producer Extends, Consumer Super.
    Q48IntermediateOOP

    48. How do you create an immutable class in Java?

    1. Make the class final so no subclass can add mutable behaviour.
    2. Make all fields private final.
    3. Set every field in the constructor and provide no setters.
    4. For mutable fields such as lists or dates, store a defensive copy in the constructor and return a copy or an unmodifiable view from getters.
    import java.util.*;
    
    public class Main {
        static final class Employee {               // 1. final class
            private final String name;              // 2. private final fields
            private final List<String> skills;
    
            Employee(String name, List<String> skills) {
                this.name = name;
                this.skills = List.copyOf(skills);  // 3. defensive copy in
            }
            String getName() { return name; }       // 4. no setters
            List<String> getSkills() { return skills; } // already unmodifiable
        }
    
        public static void main(String[] args) {
            List<String> s = new ArrayList<>(List.of("Java", "SQL"));
            Employee e = new Employee("Riya", s);
            s.add("Python");                        // caller changes its own list
            System.out.println(e.getSkills());      // object is unaffected
            try {
                e.getSkills().add("Go");
            } catch (UnsupportedOperationException ex) {
                System.out.println("Cannot modify skills");
            }
        }
    }

    Output:

    [Java, SQL]
    Cannot modify skills

    Immutable objects are thread safe, can be cached and shared freely, and make good HashMap keys. Since Java 16, a record gives you most of this in one line, though you still need the defensive copy for mutable fields.

    Q49IntermediateOOP

    49. What is the difference between a shallow copy and a deep copy?

    A shallow copy copies the fields of an object, so any referenced objects (like a list) are shared between the original and the copy. A deep copy also copies the referenced objects, so the two are fully independent.

    import java.util.*;
    
    public class Main {
        static class Team implements Cloneable {
            String name;
            List<String> members;
            Team(String name, List<String> members) { this.name = name; this.members = members; }
    
            Team shallowCopy() throws CloneNotSupportedException {
                return (Team) super.clone();           // copies the reference to the list
            }
            Team deepCopy() {
                return new Team(name, new ArrayList<>(members)); // new list
            }
        }
    
        public static void main(String[] args) throws Exception {
            Team original = new Team("Backend", new ArrayList<>(List.of("Riya")));
            Team shallow = original.shallowCopy();
            Team deep = original.deepCopy();
    
            original.members.add("Arjun");
            System.out.println("Shallow copy sees: " + shallow.members);
            System.out.println("Deep copy sees:    " + deep.members);
        }
    }

    Output:

    Shallow copy sees: [Riya, Arjun]
    Deep copy sees:    [Riya]

    Object.clone() makes a shallow copy and needs the Cloneable marker interface. Many developers avoid clone() because it is awkward and easy to get wrong, and use a copy constructor or a static factory method instead, as deepCopy() does here.

    Q50IntermediateOOP

    50. What is serialization? What does the transient keyword do?

    Serialization converts an object into a stream of bytes so it can be saved to a file or sent over the network; deserialization rebuilds it. A class opts in by implementing the Serializable marker interface, and you write and read objects with ObjectOutputStream and ObjectInputStream.

    • transient fields are skipped. Use it for passwords, caches and fields that cannot be serialized, such as a database connection. They come back as default values (null, 0, false).
    • Static fields are not serialized because they belong to the class.
    • serialVersionUID is a version number. If the class changes and the UIDs do not match, deserialization fails with InvalidClassException. Declare it explicitly.
    • Java’s built-in serialization has a long history of security problems. Modern systems usually send JSON (Jackson, Gson) or Protocol Buffers instead.
    Q51IntermediateOOP

    51. What are the types of nested classes in Java?

    TypeDeclaredNeeds an outer object?Typical use
    Static nested classInside a class, with staticNoHelpers like Map.Entry, the Builder pattern
    Inner classInside a class, without staticYes, and it can use the outer object’s fieldsAn iterator that reads its list’s data
    Local classInside a methodYesRare, a helper used in one method
    Anonymous classInline, with no nameDepends on whereOne-off implementations; mostly replaced by lambdas

    An inner class holds a hidden reference to its outer object. If the inner object lives longer, for example a listener that is never removed, it keeps the outer object in memory. Prefer static nested classes unless you need that reference.

    Q52IntermediateOOP

    52. What is a marker interface? Give examples.

    A marker interface has no methods. Implementing it only “tags” a class so that the JVM or a library treats it differently. Examples: Serializable (allows serialization), Cloneable (allows Object.clone()) and RandomAccess (tells algorithms that get(index) is fast, as in ArrayList).

    Since Java 5, annotations such as @FunctionalInterface or @Entity do the same job more flexibly, so new code rarely defines marker interfaces. One advantage of a marker interface is that it is a type, so the compiler can check it.

    Q53IntermediateExceptions

    53. What is try-with-resources?

    Introduced in Java 7, it closes resources automatically. Any object that implements AutoCloseable (files, streams, JDBC connections, sockets) can be declared in the brackets after try, and its close() method runs when the block ends, even if an exception is thrown.

    public class Main {
        static class Resource implements AutoCloseable {
            String name;
            Resource(String name) { this.name = name; System.out.println("open " + name); }
            public void close() { System.out.println("close " + name); }
        }
    
        public static void main(String[] args) {
            try (Resource db = new Resource("database");
                 Resource file = new Resource("file")) {
                System.out.println("working");
                throw new IllegalStateException("something failed");
            } catch (IllegalStateException e) {
                System.out.println("caught: " + e.getMessage());
            }
        }
    }

    Output:

    open database
    open file
    working
    close file
    close database
    caught: something failed

    Resources close in reverse order of opening. If close() itself throws while another exception is already in flight, the close exception is added to the main one as a suppressed exception (getSuppressed()) instead of replacing it. This removes the need for long, error-prone finally blocks.

    Q54IntermediateExceptions

    54. What is the difference between Error and Exception? When do you get StackOverflowError and OutOfMemoryError?

    An Exception is a condition your program can reasonably handle: a missing file, bad input, a network timeout. An Error is a serious problem in the JVM environment that an application usually cannot recover from, so you should not catch it.

    • StackOverflowError: the thread stack is full, almost always from recursion without a proper base case, or recursion that is simply too deep.
    • OutOfMemoryError: Java heap space: objects keep piling up, from a memory leak or a heap that is too small for the data.
    • OutOfMemoryError: Metaspace: too many classes loaded, often from class loader leaks in application servers.

    Debug OOM by running with -XX:+HeapDumpOnOutOfMemoryError and opening the dump in Eclipse MAT or VisualVM (question 80).

    Q55IntermediateExceptions

    55. What are multi-catch and exception chaining?

    Multi-catch (Java 7) handles several unrelated exception types in one block: catch (IOException | SQLException e). The types cannot be parent and child of each other, and e is implicitly final.

    Exception chaining wraps a low-level exception in a higher-level one without losing the original: throw new ServiceException("Could not load user", e); The original is available through getCause() and appears as “Caused by” in the stack trace. Always pass the cause; throwing a new exception without it hides the real error.

    Q56IntermediateMultithreading

    56. What are the states in a thread’s life cycle?

    StateMeaning
    NEWCreated but start() not yet called
    RUNNABLERunning or ready to run, waiting for the CPU
    BLOCKEDWaiting to get a monitor lock to enter a synchronized block
    WAITINGWaiting with no timeout: wait(), join(), LockSupport.park()
    TIMED_WAITINGWaiting with a timeout: sleep(ms), wait(ms), join(ms)
    TERMINATEDrun() has finished, normally or with an exception

    You can read the state with thread.getState(). A thread dump (question 98) shows every thread with its state, which is the first thing to look at when an application hangs.

    Q57IntermediateMultithreading

    57. What is synchronization? What is a race condition?

    A race condition happens when two threads read and update shared data at the same time and the result depends on timing. count++ looks like one step but is three: read, add, write. Two threads can both read 5 and both write 6, losing an update.

    import java.util.concurrent.atomic.AtomicInteger;
    
    public class Main {
        static int syncCount = 0;
        static AtomicInteger atomicCount = new AtomicInteger();
    
        static synchronized void increment() { syncCount++; }
    
        public static void main(String[] args) throws InterruptedException {
            Runnable task = () -> {
                for (int i = 0; i < 100_000; i++) {
                    increment();
                    atomicCount.incrementAndGet();
                }
            };
            Thread t1 = new Thread(task), t2 = new Thread(task);
            t1.start(); t2.start();
            t1.join(); t2.join();
            System.out.println("synchronized: " + syncCount);
            System.out.println("AtomicInteger: " + atomicCount.get());
        }
    }

    Output:

    synchronized: 200000
    AtomicInteger: 200000

    synchronized makes a method or block run in one thread at a time, using the object’s monitor lock (or the class’s, for static methods). It also guarantees that changes made inside are visible to the next thread that takes the lock. For a simple counter, AtomicInteger is faster because it uses a lock-free compare-and-swap. Without either, the count above would usually come out below 200,000.

    Q58IntermediateMultithreading

    58. What does the volatile keyword do? Is it enough for thread safety?

    Each CPU core may keep its own cached copy of a variable. volatile guarantees visibility: every write goes straight to main memory and every read sees the latest value. It also stops the compiler and CPU from reordering instructions around it.

    It does not make compound actions atomic. volatile int count; count++; is still a race. Use volatile for simple flags written by one thread and read by others, like volatile boolean running = false; to stop a worker, and in double-checked locking. Use synchronized or atomic classes for read-modify-write.

    Q59IntermediateMultithreading

    59. What is the difference between wait(), sleep() and join()?

    wait()sleep()join()
    Defined inObjectThread (static)Thread
    Releases the lock?YesNoNot applicable
    Must hold the lock?Yes, call inside synchronizedNoNo
    Wakes up whennotify() / notifyAll(), or timeoutTime passesThe other thread finishes
    Use forCoordination between threadsPausingWaiting for a thread to complete

    Always call wait() in a loop that rechecks the condition, because threads can wake up spuriously. In modern code, prefer higher-level tools like BlockingQueue, CountDownLatch or CompletableFuture over raw wait and notify.

    Q60IntermediateMultithreading

    60. What is a deadlock? How do you prevent it?

    A deadlock is when two or more threads wait for each other forever. Thread 1 holds lock A and wants lock B; thread 2 holds lock B and wants lock A. Neither can continue. Four conditions must all hold: mutual exclusion, hold and wait, no pre-emption, and circular wait.

    • Lock ordering: always take locks in the same global order (for example by account ID in a money transfer). This breaks the circular wait and is the most common fix.
    • Timeouts: use ReentrantLock.tryLock(timeout) and back off if you cannot get the second lock.
    • Hold locks briefly: never call unknown code or do I/O while holding a lock.
    • Detect: a thread dump (jstack) reports “Found one Java-level deadlock” with the threads involved.
    Q61IntermediateMultithreading

    61. What is ExecutorService? Why use a thread pool? What is the difference between Runnable and Callable?

    Creating a thread for every task is expensive and can exhaust memory under load. A thread pool keeps a fixed set of threads that pick up tasks from a queue. ExecutorService is the Java API for this.

    import java.util.*;
    import java.util.concurrent.*;
    
    public class Main {
        public static void main(String[] args) throws Exception {
            ExecutorService pool = Executors.newFixedThreadPool(3);
    
            List<Callable<Integer>> tasks = new ArrayList<>();
            for (int n = 1; n <= 5; n++) {
                final int x = n;
                tasks.add(() -> x * x);           // Callable returns a value
            }
    
            List<Future<Integer>> results = pool.invokeAll(tasks);
            int total = 0;
            for (Future<Integer> f : results) total += f.get(); // get() waits for the result
            System.out.println("Sum of squares: " + total);
    
            pool.shutdown();
            System.out.println("Terminated: " + pool.awaitTermination(1, TimeUnit.SECONDS));
        }
    }

    Output:

    Sum of squares: 55
    Terminated: true
    RunnableCallable
    Methodvoid run()V call() throws Exception
    Returns a valueNoYes, through a Future
    Checked exceptionsCannot throw themCan throw them

    Future.get() blocks until the result is ready. Always shut a pool down, or the JVM will not exit. In production, create a ThreadPoolExecutor with a bounded queue rather than newFixedThreadPool, whose queue is unbounded.

    Q62IntermediateMultithreading

    62. What are atomic classes? What is compare-and-swap (CAS)?

    java.util.concurrent.atomic has classes like AtomicInteger, AtomicLong, AtomicBoolean and AtomicReference. Their operations, such as incrementAndGet() and compareAndSet(), are atomic without using locks.

    They rely on compare-and-swap, a single CPU instruction: “if the value is still 5, set it to 6, otherwise fail”. On failure the code simply reads the new value and retries. With little contention, this is much faster than locking. With very heavy contention on one counter, LongAdder is faster still, because it spreads updates across several cells and adds them up when you read.

    Q63IntermediateJava 8

    63. What is a lambda expression? What is a functional interface?

    A functional interface has exactly one abstract method (it can still have default and static methods). A lambda is a short way to write an implementation of that one method: (params) -> expression or (params) -> { statements }.

    import java.util.*;
    import java.util.function.*;
    
    public class Main {
        @FunctionalInterface
        interface Discount { double apply(double price); }  // one abstract method
    
        public static void main(String[] args) {
            Discount festive = p -> p * 0.8;
            System.out.println(festive.apply(1000));
    
            Predicate<Integer> isEven = n -> n % 2 == 0;
            Function<String, Integer> length = String::length;
            Supplier<List<String>> newList = ArrayList::new;
            BiFunction<Integer, Integer, Integer> add = Integer::sum;
            Consumer<String> greet = name -> System.out.println("Hi " + name);
    
            System.out.println(isEven.test(10));
            System.out.println(length.apply("Code and Debug"));
            System.out.println(newList.get().size());
            System.out.println(add.apply(7, 8));
            greet.accept("Riya");
        }
    }

    Output:

    800.0
    true
    14
    0
    15
    Hi Riya
    Built-in interfaceMethodUse
    Predicate<T>boolean test(T)Conditions, filter()
    Function<T, R>R apply(T)Transformations, map()
    Consumer<T>void accept(T)Side effects, forEach()
    Supplier<T>T get()Lazy creation, orElseGet()
    BiFunction<T, U, R>R apply(T, U)Two inputs, one output

    A lambda can use local variables from its surrounding method only if they are effectively final (never reassigned).

    Q64IntermediateJava 8

    64. What is the Stream API? What are intermediate and terminal operations?

    A stream is a pipeline that processes data from a source (a collection, an array, a file) through a series of operations. It does not store data and does not change the source.

    • Intermediate operations such as filter, map, sorted, distinct and limit return a new stream and are lazy: nothing runs until a terminal operation is called.
    • Terminal operations such as collect, forEach, reduce, count and findFirst start the processing and produce a result.
    import java.util.*;
    import java.util.stream.*;
    
    public class Main {
        public static void main(String[] args) {
            List<Integer> nums = List.of(5, 12, 8, 3, 20, 7, 12);
    
            List<Integer> result = nums.stream()
                .filter(n -> {                       // intermediate (lazy)
                    System.out.println("checking " + n);
                    return n > 6;
                })
                .map(n -> n * 10)                    // intermediate (lazy)
                .limit(2)                            // stop after two results
                .collect(Collectors.toList());       // terminal: starts the work
            System.out.println(result);
    
            System.out.println(nums.stream().distinct().sorted().toList());
            System.out.println(nums.stream().mapToInt(Integer::intValue).sum());
        }
    }

    Output:

    checking 5
    checking 12
    checking 8
    [120, 80]
    [3, 5, 7, 8, 12, 20]
    67

    Look at the output: only 5, 12 and 8 were checked. Because of laziness and limit(2), the stream stopped as soon as it had two results. A stream can be used only once; calling a second terminal operation throws IllegalStateException.

    Q65IntermediateJava 8

    65. What is the difference between map() and flatMap()?

    map() turns each element into exactly one new element. flatMap() turns each element into a stream of elements and then flattens all those streams into one.

    import java.util.*;
    import java.util.stream.*;
    
    public class Main {
        public static void main(String[] args) {
            List<String> lines = List.of("java is fun", "streams are fun");
    
            List<String[]> mapped = lines.stream()
                .map(l -> l.split(" "))              // one array per line
                .toList();
            System.out.println("map gives " + mapped.size() + " arrays");
    
            List<String> words = lines.stream()
                .flatMap(l -> Arrays.stream(l.split(" ")))  // flatten into one stream
                .distinct()
                .toList();
            System.out.println("flatMap gives " + words);
        }
    }

    Output:

    map gives 2 arrays
    flatMap gives [java, is, fun, streams, are]

    Use flatMap whenever each item expands into several: the words in each line, the orders of each customer, the elements of a list of lists. The same idea exists in Optional: flatMap avoids ending up with Optional<Optional<T>>.

    Q66IntermediateJava 8

    66. How do you use Collectors.groupingBy, partitioningBy and joining?

    import java.util.*;
    import java.util.stream.*;
    
    public class Main {
        record Employee(String name, String dept, int salary) {}
    
        public static void main(String[] args) {
            List<Employee> emps = List.of(
                new Employee("Riya", "Tech", 90000), new Employee("Arjun", "Sales", 45000),
                new Employee("Meera", "Tech", 120000), new Employee("Kabir", "HR", 50000),
                new Employee("Isha", "Sales", 60000));
    
            Map<String, Long> countByDept = emps.stream()
                .collect(Collectors.groupingBy(Employee::dept, TreeMap::new, Collectors.counting()));
            System.out.println(countByDept);
    
            Map<String, Double> avgSalary = emps.stream()
                .collect(Collectors.groupingBy(Employee::dept, TreeMap::new,
                         Collectors.averagingInt(Employee::salary)));
            System.out.println(avgSalary);
    
            Map<Boolean, List<String>> highPaid = emps.stream()
                .collect(Collectors.partitioningBy(e -> e.salary() > 55000,
                         Collectors.mapping(Employee::name, Collectors.toList())));
            System.out.println(highPaid);
    
            String names = emps.stream().map(Employee::name).collect(Collectors.joining(", ", "[", "]"));
            System.out.println(names);
        }
    }

    Output:

    {HR=1, Sales=2, Tech=2}
    {HR=50000.0, Sales=52500.0, Tech=105000.0}
    {false=[Arjun, Kabir], true=[Riya, Meera, Isha]}
    [Riya, Arjun, Meera, Kabir, Isha]
    • groupingBy(classifier) builds a Map from key to a List of elements. Add a downstream collector such as counting(), averagingInt(), summingInt() or mapping() to summarise each group, and a map factory such as TreeMap::new for sorted keys.
    • partitioningBy(predicate) always gives a map with exactly two keys, false and true.
    • joining(", ") concatenates strings, with an optional prefix and suffix.

    This is the Java version of SQL’s GROUP BY, and “group employees by department and find the average salary” is one of the most common Java 8 coding questions. Compare it with our SQL GROUP BY examples.

    Q67IntermediateJava 8

    67. What is Optional and how should you use it?

    Optional<T> is a container that either holds a value or is empty. It makes “this might be missing” visible in a method’s return type, so callers handle it instead of getting a NullPointerException.

    import java.util.*;
    
    public class Main {
        static Map<Integer, String> users = Map.of(1, "Riya", 2, "Arjun");
    
        static Optional<String> findUser(int id) {
            return Optional.ofNullable(users.get(id));
        }
    
        public static void main(String[] args) {
            System.out.println(findUser(1).map(String::toUpperCase).orElse("Guest"));
            System.out.println(findUser(9).map(String::toUpperCase).orElse("Guest"));
            findUser(2).ifPresent(n -> System.out.println("Found " + n));
            System.out.println(findUser(9).isPresent());
            try {
                findUser(9).orElseThrow(() -> new NoSuchElementException("No user 9"));
            } catch (NoSuchElementException e) {
                System.out.println(e.getMessage());
            }
        }
    }

    Output:

    RIYA
    Guest
    Found Arjun
    false
    No user 9
    • Create with Optional.of(x) (x must not be null), Optional.ofNullable(x) or Optional.empty().
    • Use it as a return type. Do not use it for fields, method parameters or collections (return an empty list instead).
    • Avoid get() without checking; prefer orElse, orElseGet (lazy), orElseThrow, map and ifPresent.
    Q68IntermediateJava 8

    68. What are method references? What are the different kinds?

    A method reference is a shorter lambda when the lambda only calls an existing method. s -> s.length() becomes String::length.

    KindSyntaxLambda it replaces
    Static methodInteger::parseInts -> Integer.parseInt(s)
    Instance method of a particular objectSystem.out::printlnx -> System.out.println(x)
    Instance method of an arbitrary object of a typeString::toUpperCases -> s.toUpperCase()
    ConstructorArrayList::new() -> new ArrayList<>()
    Q69IntermediateJava 8

    69. Why were default methods added to interfaces? How is the diamond problem resolved?

    Default methods let library authors add new methods to existing interfaces without breaking every class that implements them. That is how Java 8 added forEach() to Iterable, stream() to Collection and sort() to List.

    If a class implements two interfaces with the same default method, it will not compile until the class overrides the method. Inside, it can call a specific version with InterfaceName.super.method(). A method from a superclass always wins over an interface default.

    public class Main {
        interface Camera { default String start() { return "Camera ready"; } }
        interface Phone  { default String start() { return "Phone ready"; } }
    
        static class SmartPhone implements Camera, Phone {
            @Override
            public String start() {            // must resolve the conflict
                return Camera.super.start() + " and " + Phone.super.start();
            }
        }
    
        public static void main(String[] args) {
            System.out.println(new SmartPhone().start());
        }
    }

    Output:

    Camera ready and Phone ready
    Q70IntermediateJava 8

    70. What is the Java 8 date and time API? Why was it needed?

    The old java.util.Date and Calendar were mutable, not thread safe, used months starting at 0, and mixed dates with times and time zones. SimpleDateFormat was not thread safe either. The java.time package fixed all of this with immutable, clear classes.

    import java.time.*;
    import java.time.format.DateTimeFormatter;
    import java.time.temporal.ChronoUnit;
    
    public class Main {
        public static void main(String[] args) {
            LocalDate joined = LocalDate.of(2024, 7, 15);
            LocalDate review = joined.plusMonths(6);
            System.out.println(review);
            System.out.println(review.getDayOfWeek());
    
            LocalDate today = LocalDate.of(2026, 11, 30);
            System.out.println(ChronoUnit.DAYS.between(joined, today) + " days");
            Period p = Period.between(joined, today);
            System.out.println(p.getYears() + " years " + p.getMonths() + " months");
    
            DateTimeFormatter f = DateTimeFormatter.ofPattern("dd MMM yyyy, hh:mm a");
            LocalDateTime meeting = LocalDateTime.of(2026, 12, 1, 15, 30);
            System.out.println(meeting.format(f));
            ZonedDateTime ist = meeting.atZone(ZoneId.of("Asia/Kolkata"));
            System.out.println(ist.withZoneSameInstant(ZoneId.of("America/New_York")).format(f));
        }
    }

    Output:

    2025-01-15
    WEDNESDAY
    868 days
    2 years 4 months
    01 Dec 2026, 03:30 PM
    01 Dec 2026, 05:00 AM
    • LocalDate, LocalTime, LocalDateTime: no time zone, for birthdays and schedules.
    • ZonedDateTime and Instant: an exact moment, for timestamps and converting between zones.
    • Period (years, months, days) and Duration (hours, minutes, seconds).
    • DateTimeFormatter: immutable and thread safe.
    Q71IntermediateJava 8

    71. What do reduce(), findFirst() and anyMatch() do?

    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            List<Integer> nums = List.of(4, 9, 2, 7);
    
            int sum = nums.stream().reduce(0, Integer::sum);
            int product = nums.stream().reduce(1, (a, b) -> a * b);
            Optional<Integer> max = nums.stream().reduce(Integer::max);
    
            System.out.println(sum + " " + product + " " + max.get());
            System.out.println(nums.stream().filter(n -> n > 3).findFirst().get());
            System.out.println(nums.stream().anyMatch(n -> n > 8));
            System.out.println(nums.stream().allMatch(n -> n > 1));
        }
    }

    Output:

    22 504 9
    4
    true
    true
    • reduce(identity, accumulator) combines all elements into one value; without an identity it returns an Optional, because the stream could be empty.
    • findFirst() returns the first element in encounter order. findAny() may return any element and can be faster on parallel streams.
    • anyMatch, allMatch and noneMatch are short-circuiting: they stop as soon as the answer is known.

    For sums and averages of numbers, mapToInt(...).sum() or summaryStatistics() avoid boxing and are clearer than reduce.

    Q72IntermediateJava 8

    72. What is the difference between a Collection and a Stream? When should you use parallel streams?

    CollectionStream
    PurposeStores dataComputes on data
    EvaluationEagerLazy
    ReusableYesNo, one terminal operation only
    IterationExternal (you write the loop)Internal (the library loops)
    SizeFiniteCan be infinite (Stream.iterate, generate)

    parallelStream() splits work across the common ForkJoinPool. It helps only for large data, CPU-heavy work and sources that split well (arrays, ArrayList). It hurts for small lists, I/O work, LinkedList sources, ordered operations like limit, and code with shared mutable state. Measure before using it, and never block inside one in a server application.

    Q73IntermediateOOP

    73. What can enums do in Java beyond simple constants?

    A Java enum is a full class: it can have fields, constructors (always private), methods and even abstract methods that each constant implements. Each constant is a single instance created when the enum class loads.

    public class Main {
        enum Plan {
            FREE(0), PRO(2499), TEAM(9999);
    
            private final int price;
            Plan(int price) { this.price = price; }       // constructor is private
            int price() { return price; }
            boolean isPaid() { return price > 0; }
        }
    
        public static void main(String[] args) {
            for (Plan p : Plan.values())
                System.out.println(p + " " + p.ordinal() + " Rs " + p.price() + " paid=" + p.isPaid());
    
            Plan chosen = Plan.valueOf("PRO");
            switch (chosen) {
                case FREE -> System.out.println("Start learning");
                case PRO, TEAM -> System.out.println("Unlock all courses");
            }
        }
    }

    Output:

    FREE 0 Rs 0 paid=false
    PRO 1 Rs 2499 paid=true
    TEAM 2 Rs 9999 paid=true
    Unlock all courses

    Enums can be used in switch statements, compared safely with ==, and stored efficiently in EnumSet and EnumMap. values() lists all constants and valueOf() converts a string (and throws IllegalArgumentException for an unknown name).

    Q74IntermediateDesign

    74. How do you write a thread-safe singleton?

    A singleton ensures only one object of a class exists. The naive lazy version (if (instance == null) instance = new X();) can create two objects when two threads arrive at once.

    public class Main {
        // Bill Pugh singleton: lazy and thread-safe without synchronized
        static class Config {
            private Config() { System.out.println("Config created"); }
            private static class Holder { static final Config INSTANCE = new Config(); }
            static Config getInstance() { return Holder.INSTANCE; }
        }
    
        // Enum singleton: also safe against reflection and serialization
        enum Logger {
            INSTANCE;
            void log(String m) { System.out.println("LOG: " + m); }
        }
    
        public static void main(String[] args) {
            System.out.println("Before first use");
            Config a = Config.getInstance();
            Config b = Config.getInstance();
            System.out.println(a == b);
            Logger.INSTANCE.log("app started");
        }
    }

    Output:

    Before first use
    Config created
    true
    LOG: app started
    • Bill Pugh (holder class): the inner class is loaded only on first use, and class loading is thread safe, so you get laziness with no synchronization cost.
    • Enum: the simplest and the safest. Joshua Bloch recommends it because it also resists reflection and serialization attacks.
    • Double-checked locking: works only if the field is volatile; interviewers like to ask why (without it, another thread may see a half-constructed object).

    In Spring applications you rarely write singletons by hand; beans are singletons by default.

    Q75IntermediateCollections

    75. What is the difference between Arrays.asList(), List.of() and Collections.unmodifiableList()?

    Arrays.asList(arr)List.of(…) (Java 9)Collections.unmodifiableList(list)
    add / removeUnsupportedOperationException (fixed size)UnsupportedOperationExceptionUnsupportedOperationException
    set(i, x)Allowed, and it changes the original arrayNot allowedNot allowed
    null elementsAllowedNullPointerExceptionAllowed
    Linked to the sourceYes, it is a view of the arrayNo, independent copyYes, a read-only view: changes to the original list show through

    A classic trap: Arrays.asList(1, 2, 3).add(4) compiles but throws at run time. For a list you can change, wrap it: new ArrayList<>(List.of(1, 2, 3)). For a truly immutable snapshot of an existing list, use List.copyOf(list).

    Java interview questions for experienced candidates

    These 25 questions are for senior developers: JVM internals, garbage collection, memory leaks, the Java Memory Model, advanced concurrency, ConcurrentHashMap, virtual threads, modern Java features and production debugging.

    Q76ExperiencedJVM and memory

    76. Explain the architecture of the JVM.

    • Class loader subsystem: loads .class files, then links them (verifies the bytecode, prepares static fields, resolves references) and initialises them (runs static blocks).
    • Runtime data areas: the heap and metaspace, shared by all threads; and per thread, a JVM stack, a program counter register and a native method stack.
    • Execution engine: an interpreter that runs bytecode right away, a JIT compiler (C1 and C2) that compiles hot methods to native code, and the garbage collector.
    • Native interface (JNI) and native libraries, for calling C and C++ code.

    A good answer walks through what happens on java Main: the class loader loads Main, the bytecode verifier checks it, main() is interpreted at first, and the hot paths are JIT-compiled as the program runs.

    Q77ExperiencedJVM and memory

    77. How does class loading work? What is the parent delegation model?

    Java has a hierarchy of class loaders: the Bootstrap loader (core classes from java.base, written in native code), the Platform loader (other JDK modules; it was called the Extension loader before Java 9), and the Application (system) loader (your classpath).

    Under parent delegation, a loader first asks its parent to load a class and only tries itself if the parent cannot. This stops anyone from replacing core classes like java.lang.String with their own version, and ensures each class is loaded once per loader. A class is identified by its name plus its loader, so the same class loaded by two loaders gives two different types; app servers and plugin systems use custom loaders for exactly this kind of isolation, and it is also the source of confusing ClassCastExceptions and Metaspace leaks.

    Q78ExperiencedJVM and memory

    78. What are the JVM memory areas? What replaced PermGen?

    AreaShared?HoldsError
    Heap: young generation (Eden + 2 survivor spaces)YesNew objectsOutOfMemoryError
    Heap: old generationYesObjects that survived several minor GCsOutOfMemoryError
    Metaspace (native memory)YesClass metadata, method bytecode, constant poolsOutOfMemoryError: Metaspace
    JVM stackPer threadFrames with local variables and partial resultsStackOverflowError
    PC register and native stackPer threadCurrent instruction, native calls

    Java 8 removed PermGen, a fixed-size part of the heap for class metadata that often caused “OutOfMemoryError: PermGen space”. Metaspace lives in native memory and grows automatically; cap it with -XX:MaxMetaspaceSize. The String pool moved from PermGen to the main heap in Java 7.

    Q79ExperiencedJVM and memory

    79. What garbage collectors does the JVM offer, and how do you choose?

    CollectorFlagBest for
    Serial-XX:+UseSerialGCSmall heaps, single-core containers, simple tools
    Parallel-XX:+UseParallelGCBatch jobs where total throughput matters more than pauses
    G1 (default since Java 9)-XX:+UseG1GCGeneral purpose; splits the heap into regions and aims for a pause target (-XX:MaxGCPauseMillis, 200 ms by default)
    ZGC-XX:+UseZGCLarge heaps and low-latency services; pauses under a millisecond, generational since Java 21
    Shenandoah-XX:+UseShenandoahGCLow latency, similar goals to ZGC

    Most GC work happens in two kinds of collections: frequent, cheap minor GCs in the young generation, and rarer major or full GCs of the old generation. Choose by your goal (throughput or latency), then tune heap size first; that fixes more problems than any flag. Measure with GC logs (-Xlog:gc*) rather than guessing.

    Q80ExperiencedJVM and memory

    80. Can Java have memory leaks? How do you find one?

    Yes. GC frees only unreachable objects, so a leak in Java is an object that is still referenced but no longer needed. Common causes:

    • Static collections and caches that only grow. Use a bounded cache (Caffeine) or eviction.
    • Listeners and callbacks that are registered and never removed.
    • ThreadLocal values in pooled threads that are never removed (question 88).
    • Inner classes and lambdas that capture a large outer object.
    • Unclosed resources such as streams, connections and result sets.
    • Keys whose hashCode changes after being added to a HashMap.

    To find one: watch the heap after each full GC in your monitoring; if the floor keeps rising, you have a leak. Take a heap dump (jcmd <pid> GC.heap_dump file.hprof, or automatically with -XX:+HeapDumpOnOutOfMemoryError), open it in Eclipse MAT, and follow the “dominator tree” and “path to GC roots” to see who is holding the memory.

    Q81ExperiencedJVM and memory

    81. What is the JIT compiler? How does it make Java fast?

    The JVM starts by interpreting bytecode, which is slow but starts instantly. It counts how often each method and loop runs. Once code is “hot”, the Just-In-Time compiler compiles it to native machine code. HotSpot uses tiered compilation: C1 compiles quickly with light optimisation, and C2 later recompiles the hottest code with aggressive optimisation based on real profiling data.

    Key optimisations: inlining small methods, escape analysis (an object that never leaves a method can live on the stack or be eliminated entirely), loop unrolling, removing bounds checks, and deoptimisation when an assumption turns out wrong. This is why benchmarks need a warm-up phase (use JMH), and why projects like GraalVM native image and CDS exist to cut start-up time.

    Q82ExperiencedJVM and memory

    82. What are strong, soft, weak and phantom references?

    ReferenceCollected whenUse
    Strong (normal)Never while reachableEveryday code
    SoftReferenceOnly when memory is running lowMemory-sensitive caches
    WeakReferenceAt the next GC once no strong reference remainsWeakHashMap, canonical maps, listener lists
    PhantomReferenceAfter finalization; get() always returns nullClean-up actions after an object is gone (Cleaner)

    A WeakHashMap entry disappears when nothing else references its key, which makes it useful for attaching metadata to objects without keeping them alive. For real caches, a library like Caffeine with size or time limits is usually more predictable than soft references.

    Q83ExperiencedMultithreading

    83. What is the Java Memory Model? What does happens-before mean?

    The Java Memory Model defines when a write by one thread is guaranteed to be visible to another. Without it, compilers and CPUs are free to cache values and reorder instructions, so another thread might see stale or half-written data.

    The key idea is the happens-before relation: if action A happens-before B, then B sees everything A did. Rules that create it:

    • Unlocking a monitor happens-before every later lock of the same monitor.
    • A write to a volatile field happens-before every later read of it.
    • Thread.start() happens-before any action in the started thread, and all actions in a thread happen-before another thread returns from join() on it.
    • Final fields set in a constructor are visible to any thread that sees the object, if this did not escape during construction.
    • Actions in one thread happen in program order, and the relation is transitive.
    Q84ExperiencedMultithreading

    84. What is the difference between synchronized and ReentrantLock?

    FeaturesynchronizedReentrantLock
    ReleaseAutomatic at the end of the blockManual: unlock() in finally
    Try without waitingNotryLock(), tryLock(timeout)
    Interruptible waitNolockInterruptibly()
    FairnessNoOptional fair mode
    ConditionsOne wait set (wait/notify)Many Condition objects
    Read/write splitNoReentrantReadWriteLock, StampedLock

    Both are reentrant: a thread that holds the lock can take it again. Use synchronized by default because it is simpler and cannot be forgotten. Reach for ReentrantLock when you need timeouts, interruptible waits, several conditions or a read-write lock. Before Java 24, synchronized could also “pin” virtual threads during blocking calls, which was another reason to prefer ReentrantLock in virtual-thread code.

    Q85ExperiencedMultithreading

    85. Explain CountDownLatch, CyclicBarrier and Semaphore.

    ClassWhat it doesReusable?Example
    CountDownLatchThreads wait until a count reaches zeroNoMain thread waits until 5 services have started
    CyclicBarrierA fixed number of threads wait for each other at a barrier pointYesParallel simulation steps that must finish together
    SemaphoreLimits how many threads can use a resource at onceYesAt most 10 concurrent calls to a payment API
    PhaserA flexible barrier where parties can register and leaveYesMulti-phase tasks with a changing number of workers

    All of these are in java.util.concurrent and are built on AbstractQueuedSynchronizer (AQS), the same framework behind ReentrantLock.

    Q86ExperiencedMultithreading

    86. What is CompletableFuture? How is it better than Future?

    A plain Future can only be checked or blocked on with get(). CompletableFuture (Java 8) lets you chain steps, combine several async results and handle errors without blocking, much like promises in JavaScript.

    import java.util.concurrent.*;
    
    public class Main {
        static int price(String item) { return item.equals("laptop") ? 55000 : 1200; }
    
        public static void main(String[] args) {
            CompletableFuture<Integer> laptop = CompletableFuture.supplyAsync(() -> price("laptop"));
            CompletableFuture<Integer> mouse  = CompletableFuture.supplyAsync(() -> price("mouse"));
    
            int total = laptop.thenCombine(mouse, Integer::sum)  // both run in parallel
                              .thenApply(t -> (int) (t * 1.18))   // add GST
                              .join();
            System.out.println("Total with GST: " + total);
    
            String r = CompletableFuture.supplyAsync(() -> 10 / 0)
                .thenApply(x -> "result " + x)
                .exceptionally(ex -> "failed: " + ex.getCause().getMessage())
                .join();
            System.out.println(r);
        }
    }

    Output:

    Total with GST: 66316
    failed: / by zero
    • supplyAsync and runAsync start work, by default on the common ForkJoinPool. Pass your own executor for I/O work.
    • thenApply transforms a result, thenCompose chains another async call, thenCombine joins two independent results, and allOf and anyOf wait for groups.
    • exceptionally and handle recover from errors; the original exception arrives wrapped in a CompletionException.
    Q87ExperiencedCollections

    87. How does ConcurrentHashMap work internally in Java 8 and later?

    Before Java 8, it split the table into 16 segments, each with its own lock. Java 8 dropped segments. Now it uses a single array of bins like HashMap, and:

    • Reads take no lock; nodes use volatile fields, so a reader always sees a consistent value.
    • Inserting into an empty bin uses a lock-free CAS.
    • Updating a non-empty bin synchronizes only on that bin’s first node, so writers to different bins never block each other.
    • Long bins turn into trees, as in HashMap.
    • Resizing is done cooperatively: threads that arrive during a resize help move bins.
    • size() is an estimate built from counter cells, similar to LongAdder.

    For atomic updates, use compute(), merge() or computeIfAbsent(). A “check then put” with containsKey followed by put is still a race, even on a ConcurrentHashMap.

    Q88ExperiencedMultithreading

    88. What is ThreadLocal? What is the risk of using it in a thread pool?

    ThreadLocal gives each thread its own copy of a variable. It is used for per-request data such as the logged-in user, a transaction or a database connection, and to make non-thread-safe objects (like the old SimpleDateFormat) safe by giving each thread one.

    The risk: in a thread pool, threads live for the life of the application. If you set a value and never call remove(), it stays attached to that thread. The next request on that thread may see the previous user’s data, and large values leak memory, especially in app servers where they also pin the class loader. Always clean up in a finally block. With virtual threads, prefer ScopedValue (final in Java 25) for passing context.

    Q89ExperiencedModern Java

    89. What are virtual threads (Java 21)? When should you use them?

    Platform threads map one to one to OS threads, which cost about 1 MB of stack each, so a server can only hold a few thousand. Virtual threads (Project Loom, final in Java 21) are managed by the JVM. When one blocks on I/O, the JVM parks it and frees the OS carrier thread for another. You can have millions.

    import java.util.concurrent.*;
    import java.util.stream.*;
    
    public class Main {
        public static void main(String[] args) throws Exception {
            long start = System.currentTimeMillis();
            try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
                IntStream.range(0, 10_000).forEach(i ->
                    ex.submit(() -> {
                        Thread.sleep(1000);     // blocking call, but cheap on a virtual thread
                        return i;
                    }));
            }                                   // close() waits for all tasks
            long secs = (System.currentTimeMillis() - start) / 1000;
            System.out.println("10,000 tasks that each sleep 1 second finished in about " + secs + " s");
            System.out.println(Thread.ofVirtual().unstarted(() -> {}).isVirtual());
        }
    }

    Output:

    10,000 tasks that each sleep 1 second finished in about 1 s
    true
    • Use them for many concurrent, I/O-bound tasks such as HTTP calls and database queries, keeping simple blocking code instead of reactive callbacks. Spring Boot 3.2+ enables them with one property.
    • They do not make CPU-bound work faster.
    • Do not pool them; create one per task.
    • Watch for pinning: before Java 24, blocking inside synchronized kept the carrier thread busy. Also be careful with large ThreadLocal values.
    Q90ExperiencedMultithreading

    90. What is the Fork/Join framework?

    Fork/Join (Java 7) runs divide-and-conquer tasks in parallel. A RecursiveTask (returns a value) or RecursiveAction (no value) splits its work in half with fork() until pieces are small enough to compute directly, then combines the results with join().

    Its ForkJoinPool uses work stealing: each worker has its own deque of tasks, and an idle worker steals from the tail of a busy one, which keeps all cores busy with little locking. Parallel streams and the default CompletableFuture executor both use the shared ForkJoinPool.commonPool(), which is why blocking calls inside them can starve the whole application.

    Q91ExperiencedModern Java

    91. What are records? When would you not use one?

    A record (final in Java 16) is a concise, immutable data carrier. From one line, the compiler generates private final fields, a constructor, accessors, equals(), hashCode() and toString().

    public class Main {
        record Point(int x, int y) {
            Point {                                   // compact constructor for validation
                if (x < 0 || y < 0) throw new IllegalArgumentException("negative");
            }
            double distance() { return Math.sqrt(x * x + y * y); }
        }
    
        public static void main(String[] args) {
            Point p = new Point(3, 4);
            Point q = new Point(3, 4);
            System.out.println(p);                    // toString generated
            System.out.println(p.x() + ", " + p.y()); // accessors, not getX()
            System.out.println(p.equals(q));          // equals and hashCode generated
            System.out.println(p.distance());
        }
    }

    Output:

    Point[x=3, y=4]
    3, 4
    true
    5.0
    • A compact constructor validates or normalises input.
    • Records can implement interfaces and have static fields and extra methods, but cannot extend a class or declare instance fields beyond the components.
    • Good for DTOs, API responses, map keys and multiple return values.
    • Not suitable for JPA entities (they need a no-argument constructor and mutable fields) or any class that needs to change after creation.
    Q92ExperiencedModern Java

    92. What are sealed classes and pattern matching for switch?

    A sealed class or interface (Java 17) lists exactly which classes may extend it with permits. Subclasses must be final, sealed or non-sealed. Pattern matching for switch (Java 21) lets a switch test types, deconstruct records and add when guards.

    public class Main {
        sealed interface Shape permits Circle, Square, Rectangle {}
        record Circle(double r) implements Shape {}
        record Square(double side) implements Shape {}
        record Rectangle(double w, double h) implements Shape {}
    
        static double area(Shape s) {
            return switch (s) {                       // no default needed: compiler knows all cases
                case Circle c -> Math.round(Math.PI * c.r() * c.r() * 100) / 100.0;
                case Square sq -> sq.side() * sq.side();
                case Rectangle(double w, double h) when w == h -> w * w;  // record pattern + guard
                case Rectangle(double w, double h) -> w * h;
            };
        }
    
        public static void main(String[] args) {
            System.out.println(area(new Circle(1)));
            System.out.println(area(new Square(3)));
            System.out.println(area(new Rectangle(2, 5)));
    
            Object o = "Code and Debug";
            if (o instanceof String str && str.length() > 5)   // pattern matching for instanceof
                System.out.println(str.toUpperCase());
        }
    }

    Output:

    3.14
    9.0
    10.0
    CODE AND DEBUG

    Together they give you algebraic data types: because the compiler knows every possible Shape, the switch needs no default branch, and if someone adds a new Shape, every switch that does not handle it fails to compile. That is safer than the classic Visitor pattern.

    Q93ExperiencedModern Java

    93. Explain var, switch expressions and text blocks.

    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            var marks = new HashMap<String, Integer>();   // var: type inferred
            marks.put("Riya", 91);
            marks.put("Arjun", 67);
    
            for (var e : marks.entrySet()) {
                String grade = switch (e.getValue() / 10) {   // switch expression
                    case 10, 9 -> "A";
                    case 8, 7 -> "B";
                    default -> {
                        String g = e.getValue() >= 40 ? "C" : "F";
                        yield g;
                    }
                };
                System.out.println(e.getKey() + ": " + grade);
            }
    
            String json = """
                {
                  "course": "Java",
                  "level": "beginner"
                }""";                                      // text block
            System.out.println(json);
        }
    }

    Output:

    Riya: A
    Arjun: C
    {
      "course": "Java",
      "level": "beginner"
    }
    • var (Java 10) infers the type of a local variable from its initialiser. It is still static typing; it cannot be used for fields, parameters or with null. Use it when the type is obvious from the right-hand side.
    • Switch expressions (Java 14) return a value, use arrows with no fall-through, allow several labels per case, and use yield to return from a block.
    • Text blocks (Java 15) are multi-line strings between triple quotes, handy for JSON, SQL and HTML. Common indentation is removed automatically.
    Q94ExperiencedAdvanced

    94. What is reflection? What are its uses and drawbacks?

    Reflection lets code inspect and use classes at run time: list fields and methods, read annotations, create objects and call methods by name, even private ones (with setAccessible(true)). The entry point is the Class object, from obj.getClass() or Class.forName("...").

    • Used by: Spring dependency injection, Hibernate and JPA, Jackson, JUnit, and IDE tools.
    • Drawbacks: slower than direct calls, no compile-time checking, breaks encapsulation, and since Java 16 the module system blocks reflective access to JDK internals unless you open them with flags.
    • Modern frameworks increasingly generate code at compile time (annotation processing) or use MethodHandle to avoid the cost.
    Q95ExperiencedAdvanced

    95. How do you create a custom annotation?

    Declare it with @interface and add meta-annotations: @Retention (SOURCE, CLASS or RUNTIME) decides how long it is kept, and @Target decides where it can be placed (TYPE, METHOD, FIELD and so on). Elements look like methods and can have defaults: @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Audit { String action() default "read"; }.

    An annotation does nothing on its own. Something has to read it: reflection at run time (method.getAnnotation(Audit.class)), an annotation processor at compile time (as Lombok and MapStruct do), or a framework such as Spring AOP that applies logic around annotated methods.

    Q96ExperiencedDesign

    96. Which design patterns are used inside the JDK?

    PatternExample in the JDK
    SingletonRuntime.getRuntime()
    Factory methodCalendar.getInstance(), List.of(), NumberFormat.getInstance()
    BuilderStringBuilder, HttpRequest.newBuilder(), Stream.builder()
    Decoratornew BufferedReader(new InputStreamReader(in)), Collections.synchronizedList()
    AdapterArrays.asList(), InputStreamReader (bytes to characters)
    IteratorIterator in every collection
    StrategyComparator passed to sort()
    ObserverEvent listeners in Swing, Flow.Subscriber
    Template methodAbstractList, InputStream.read(byte[])
    Proxyjava.lang.reflect.Proxy, used by Spring AOP
    Q97ExperiencedDesign

    97. Explain the SOLID principles with Java examples.

    • Single responsibility: a class has one reason to change. Split an InvoiceService that calculates, saves and emails into three classes.
    • Open/closed: open for extension, closed for modification. Add a new PaymentMethod class instead of another if-else in checkout().
    • Liskov substitution: a subclass must work wherever its parent does. A Square that breaks Rectangle’s setWidth/setHeight behaviour violates it.
    • Interface segregation: many small interfaces beat one large one. Do not force a Printer class to implement scan() and fax().
    • Dependency inversion: depend on abstractions. OrderService should take a PaymentGateway interface in its constructor, not create a RazorpayClient itself. This is what Spring’s dependency injection is built on.

    Interviewers usually follow up with “show me where you applied this in your project”, so prepare one real example. Our OOPs interview questions cover these principles in more depth.

    Q98ExperiencedAdvanced

    98. A Java service in production has high CPU usage or hangs. How do you investigate?

    1. Find the busy threads: top -H -p <pid> shows CPU per thread. Convert the busiest thread ID to hex.
    2. Take thread dumps: jstack <pid> or jcmd <pid> Thread.print, three or four of them a few seconds apart. Search for the hex ID (nid) to see exactly what that thread is running. Threads stuck in the same frame across dumps are your suspects.
    3. Check GC: jstat -gcutil <pid> 1000 or GC logs. High CPU with an old generation that is always full means the JVM is spending its time collecting garbage, which usually points to a leak or a heap that is too small.
    4. Look for deadlocks and lock contention: many threads BLOCKED on the same lock, or a deadlock report at the end of the dump.
    5. Profile: Java Flight Recorder (jcmd <pid> JFR.start) and JDK Mission Control, or async-profiler for flame graphs, with very low overhead in production.

    Common culprits: an infinite loop, catastrophic regex backtracking, a HashMap corrupted by concurrent writes (in old Java versions this caused infinite loops), GC thrashing, or a thread pool exhausted by slow downstream calls.

    Q99ExperiencedAdvanced

    99. What are some practical ways to improve Java performance?

    • Measure first with a profiler or JMH. Guessing is usually wrong.
    • Pick the right data structure and algorithm; an O(n²) loop over a list dwarfs every micro-optimisation. See our time complexity guide.
    • Avoid unnecessary objects: StringBuilder in loops, primitives instead of wrappers in hot code, primitive streams (IntStream).
    • Size collections up front when you know the size: new ArrayList<>(n), new HashMap<>(capacity).
    • Cache expensive results, and use connection pools (HikariCP) and thread pools.
    • Batch database writes and fetch only the columns you need; most “Java is slow” problems are really database or network problems.
    • Tune the heap and GC from data, and use virtual threads for I/O-bound concurrency.
    Q100ExperiencedModern Java

    100. What changed from Java 8 to Java 21? Which features should every developer know?

    VersionYearKey features
    Java 8 (LTS)2014Lambdas, streams, Optional, java.time, default methods, CompletableFuture
    Java 92017Module system (JPMS), JShell, List.of / Set.of / Map.of, private interface methods
    Java 102018var for local variables
    Java 11 (LTS)2018HttpClient, String methods (isBlank, strip, lines, repeat), run single-file programs with java File.java
    Java 14 to 162020 to 2021Switch expressions, text blocks, records, pattern matching for instanceof, helpful NullPointerException messages
    Java 17 (LTS)2021Sealed classes; Spring Boot 3 requires Java 17 or later
    Java 21 (LTS)2023Virtual threads, pattern matching for switch, record patterns, sequenced collections (getFirst, getLast, reversed), generational ZGC

    LTS (long-term support) versions are what companies actually run. Java 25 (September 2025) is the newest LTS, with features such as scoped values and compact source files. In an interview, say which version your project used and one feature from it that you relied on.

    Java quiz: test yourself

    Ten multiple-choice questions from across this page. Eight or more right means you are in good shape for a Java interview.

    Quiz

    10 Java MCQs

    About three minutes.

    Download all 100 Java interview questions as a PDF

    The PDF has the same 100 Java interview questions and answers, with every code example and its output, in a clean 54-page printable format with a clickable table of contents. Use it to revise offline, on your phone, or on paper before the interview. It is free, with no sign-up.

    Free PDF

    100 Java Interview Questions and Answers

    54 pages · Freshers, intermediate and experienced · 36 Java examples

    Download PDF

    Frequently asked questions

    What Java questions are asked in interviews for freshers?

    Freshers are most often asked about JDK, JRE and JVM, OOP concepts, == vs equals(), String immutability and the String pool, String vs StringBuilder, exception handling, ArrayList vs LinkedList, HashMap basics, static and final, and the main Java 8 features. Questions 1 to 40 on this page cover them.

    Which Java topics are most important for interviews?

    Collections (especially HashMap), OOP, String handling, exceptions, multithreading and Java 8 streams come up in almost every interview. For experienced roles, add JVM memory and garbage collection, concurrency utilities, ConcurrentHashMap internals and features from Java 17 and 21.

    Which Java version should I prepare for?

    Know Java 8 thoroughly, because most interview questions still use its features. Then learn what Java 11, 17 and 21 added, mainly records, sealed classes, switch expressions, pattern matching and virtual threads. Many companies now run Java 17 or 21, and Spring Boot 3 needs at least Java 17.

    How should I prepare for a Java interview with 3 to 5 years of experience?

    Expect deeper questions on HashMap and ConcurrentHashMap internals, thread safety, ExecutorService and CompletableFuture, JVM memory and GC tuning, design patterns and SOLID, plus questions about your own project. Practise explaining a production issue you debugged, and write stream code without an IDE.

    Are Spring Boot questions asked in a core Java interview?

    For back-end developer roles, usually yes, in a separate round. This page covers core Java and Java 8+; Spring Boot interview questions (dependency injection, beans, REST controllers, JPA, transactions) are a separate topic.

    Can I download these Java interview questions as a PDF?

    Yes. All 100 questions and answers, with every code example and its output, are in a free 54-page PDF. Use the Download PDF button at the top of this page; no sign-up is needed.

    Next steps

    Work through one level at a time and press “Mark as done” on each of the Java interview questions once you can answer it out loud without looking. Most Java interviews also include a coding round and questions on databases, so continue with our DSA interview cheat sheet, SQL interview questions, DBMS interview questions and OOPs interview questions. All the best for your interview!

    Java
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleSQL Queries with Examples: Run Online, 50 Practice Questions and Free PDF
    Next Article 100 Python Programs with Examples and Output (Run Online + PDF)
    Anirudh Khurana
    • Website

    Anirudh Khurana is the founder of Code and Debug, an Indian EdTech platform that helps students and working professionals crack coding interviews and move into data and AI roles. He teaches DSA, Python, SQL, data engineering and machine learning through live bootcamps and his YouTube channel, Code and Debug, which has over 50,000 subscribers. Every guide on this blog is written or reviewed by him and tested with real code.

    Related Posts

    Interview Questions

    100 React Interview Questions and Answers (2026) + Free PDF

    3 December 2026
    Interview Questions

    100 JavaScript Interview Questions and Answers (2026) + Free PDF

    2 December 2026
    Interview Questions

    100 Machine Learning Interview Questions and Answers (Freshers to Experienced)

    25 November 2026
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • AI & Machine Learning (8)
    • Data Structures & Algorithms (243)
      • Beginner (84)
      • Expert (52)
      • Intermediate (106)
    • Interview Questions (9)
    • Pandas (1)
    • Python (2)
    • Resume (1)
    • SQL (3)
    Recent Posts

    100 React Interview Questions and Answers (2026) + Free PDF

    3 December 2026

    100 JavaScript Interview Questions and Answers (2026) + Free PDF

    2 December 2026

    100 Python Programs with Examples and Output (Run Online + PDF)

    1 December 2026

    100 Java Interview Questions and Answers (Freshers to Experienced)

    30 November 2026

    SQL Queries with Examples: Run Online, 50 Practice Questions and Free PDF

    27 November 2026
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.