Java Basics and JVM Interview Questions

Output:

Hello Java

11. Why is the main method static, and what happens if it isn’t?

main is static so the JVM can call it before any object exists. On Java 21, if you remove static, the code still compiles but fails at launch:

Output (Java 21):

Error: Main method is not static in class NotStatic, please define the main method as:   public static void main(String[] args)

Java 25 update: JEP 512 made instance main methods final. On Java 25 and later, void main() (no public, no static, no args) is a valid entry point, and the launcher creates the object for you. In an interview, give the classic answer and then mention this change.

12. Can we overload the main method?

Yes. You can write several main methods with different parameter lists, but the JVM only calls main(String[] args) as the entry point. You have to call the other versions yourself.

Output:

main(String[]) called by JVMmain(int) called manually: 5

13. What is the difference between Java and C++?

  • Platform: Java compiles to bytecode for the JVM. C++ compiles to native code for one platform.
  • Pointers: Java has references with no pointer arithmetic. C++ has full pointers.
  • Memory: Java uses a garbage collector. C++ uses manual new/delete (or RAII).
  • Multiple inheritance: Java allows it only through interfaces. C++ allows it for classes.
  • Operator overloading: not supported in Java. Supported in C++.
  • Destructors: Java has none (use try-with-resources for cleanup). C++ has destructors.

14. What are packages in Java, and what are their advantages?

A package is a namespace that groups related classes and interfaces, for example java.util or com.examadda.payments.

Advantages:

  1. No name clashes: java.util.Date and java.sql.Date can coexist.
  2. Organisation: related classes stay together.
  3. Access control: default (package-private) members are hidden from other packages.
  4. Reuse: packages can be shared as JAR files.

There are two types: built-in (java.lang, java.util, java.io) and user-defined. java.lang is imported automatically.

15. What are access modifiers in Java?

Access modifiers control who can see a class member.

  • private: visible only inside the same class.
  • default (no keyword): visible in the same class and the same package.
  • protected: visible in the same package, plus subclasses in other packages.
  • public: visible everywhere.

A top-level class can only be public or default. Making fields private and exposing methods is the basis of encapsulation.

16. Is Java pass-by-value or pass-by-reference?

Java is always pass-by-value. For primitives, the value is copied. For objects, the reference is copied. So a method can change the object’s fields through the copied reference, but reassigning the parameter doesn’t affect the caller.

Output:

10100
100

Data Types and Variables Interview Questions

17. What is the difference between primitive and non-primitive data types?

Java has 8 primitive types: byte (1 byte), short (2), int (4), long (8), float (4), double (8), char (2, UTF-16), and boolean.

  • Primitive: stores the actual value, has a fixed size, can’t be null, has no methods. For example, int’s default is 0.
  • Non-primitive (reference): stores a reference to an object, can be null, has methods. Examples: String, arrays, classes, interfaces. Default is null.

String is not a primitive. It is a class.

Learn more: Primitive Data Types and Reference Types

18. What are instance, local, and static (class) variables?

  • Instance variable: declared in a class, outside methods. Each object gets its own copy, stored in the heap with the object. Gets a default value.
  • Local variable: declared inside a method or block. Exists only while that method runs, on the thread’s stack. No default value, so it must be initialised before use.
  • Static variable: declared with static. One copy is shared by all objects and belongs to the class. Gets a default value.

19. What are static variables? Give an example.

A static variable belongs to the class, not to any object. It is created once when the class is initialised and shared by every instance. Typical uses are counters, constants, and shared configuration.

Output:

objectCount = 3c.instanceCount = 1

20. What are the default values of variables in Java?

Instance and static fields get defaults: 0 for numeric types, 0.0 for float/double, '\u0000' for char, false for boolean, and null for references. Local variables get no default. Reading one before you assign it is a compile-time error.

Output:

00.0
false
null

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

Type casting converts a value from one type to another.

  • Widening (implicit): smaller to larger type, safe and automatic. Order: byte → short → int → long → float → double (and char → int).
  • Narrowing (explicit): larger to smaller type. It needs a cast and may lose data, either by truncating decimals or by overflowing.

Output:

85.010
-126

130 doesn’t fit in a byte (range −128 to 127), so it wraps around to -126.

Learn more: Type Casting in Java

22. What are wrapper classes, and why do we need them?

Wrapper classes are object versions of primitives: Byte, Short, Integer, Long, Float, Double, Character, Boolean. They are immutable. We need them because:

  1. Collections and generics only store objects (List<Integer>, not List<int>).
  2. They can hold null, which can mean “no value”.
  3. They provide utility methods such as Integer.parseInt("42"), Integer.MAX_VALUE, and Character.isDigit().

23. What are autoboxing and unboxing?

Autoboxing is the automatic conversion of a primitive into its wrapper (Integer a = 100;). Unboxing is the reverse (int b = a;). There are two traps interviewers love:

Output:

truefalse
true
NPE while unboxing null

Integer caches values from −128 to 127, so a == b points to the same cached object, while 128 creates two separate objects. Always compare wrappers with equals(). Unboxing a null wrapper throws NullPointerException. Heavy autoboxing inside loops also creates extra objects and slows code down.

24. What is the var keyword in Java?

Since Java 10, var lets the compiler infer the type of a local variable from its initializer: var names = new ArrayList<String>();. The variable is still statically typed. var can’t be used for fields, method parameters, or return types, and it needs an initializer (var x; doesn’t compile).

Operators and Control Flow Interview Questions

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

  • ==: for primitives, compares values. For objects, checks whether both references point to the same object.
  • equals(): compares content, as defined by the class. String, wrappers, and collections override it. The default version in Object behaves like ==.

Output:

falsetrue

26. What is the difference between >> and >>>?

>> is the signed right shift: it copies the sign bit, so negative numbers stay negative. >>> is the unsigned right shift: it fills with zeros, so a negative number becomes a large positive number. For positive numbers both give the same result.

Output:

-42147483644
4
4

27. What is the ternary operator?

The ternary operator condition ? valueIfTrue : valueIfFalse is a compact if-else that returns a value. Avoid nesting it, because it becomes hard to read.

Output:

20

Learn more: Operators in Java

28. What is the difference between break and continue?

break exits the loop (or switch) completely. continue skips the rest of the current iteration and moves to the next one.

Output:

1 2 1 2 4 5

Dry run (break loop):

  • i = 1: 1 == 3 is false, prints 1
  • i = 2: 2 == 3 is false, prints 2
  • i = 3: 3 == 3 is true, break exits the loop, nothing more is printed

29. What is the difference between while and do-while?

while checks the condition first, so it may run zero times. do-while runs the body first and checks afterwards, so it always runs at least once.

Output:

do-while: 10

30. What is an infinite loop?

A loop whose condition never becomes false, for example while (true) { } or for (;;) { }. Servers, game loops, and menu-driven programs use them on purpose, but always with an exit path (break, return, or a flag). An accidental infinite loop keeps a CPU core busy and hangs the program.

31. What is a switch statement, and what is a switch expression?

A switch picks one branch based on a value. It works with int-like types, char, String (Java 7+), and enums. Since Java 14, switch expressions use ->, have no fall-through, allow several labels per case, and return a value.

Output:

Weekend

In the old case X: style, forgetting break causes fall-through into the next case. It’s a classic bug.

Java OOPs Interview Questions for Freshers

32. What is OOP? Is Java a purely object-oriented language?

Object-Oriented Programming organises code into objects that bundle data (fields) and behaviour (methods). It makes code reusable, modular, and easier to maintain. Java is not purely object-oriented, because it has primitive types (int, char, and so on) that aren’t objects, and static members that belong to classes rather than objects.

33. What are the four pillars of OOP?

  1. Encapsulation: hide data and expose it through methods.
  2. Inheritance: reuse a parent class’s code in a child class (IS-A).
  3. Polymorphism: one interface, many forms (overloading and overriding).
  4. Abstraction: show what an object does and hide how.

34. What is the difference between a class and an object?

A class is a blueprint that defines fields and methods. An object is a real instance of it, created with new, with its own field values in heap memory. Example: Student is a class, and new Student() with name “Neha” is an object. A class still uses some memory before any object exists, because the JVM stores its metadata and static fields when the class is first loaded. Objects add instance memory on the heap.

35. What is encapsulation?

Encapsulation means keeping fields private and exposing controlled access through public methods (getters, setters, or business methods). The class can then validate input and change its internal design without breaking callers.

36. What is inheritance? Why doesn’t Java support multiple inheritance of classes?

Inheritance lets a child class reuse and extend a parent class with extends (an IS-A relationship: a Dog IS-A Animal). For classes, Java supports single, multilevel, and hierarchical inheritance. Multiple inheritance of classes isn’t allowed because it causes the diamond problem: if two parents had the same method, the child wouldn’t know which to inherit. A class can implement several interfaces. If two interfaces have the same default method, the class must override it and choose.

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

Polymorphism means one name with many behaviours.

  • Compile-time (static) polymorphism: method overloading. The compiler picks the method from the argument types.
  • Runtime (dynamic) polymorphism: method overriding. The JVM picks the method from the actual object type at runtime (dynamic method dispatch).

Output:

56.0
Dog barks

38. What is abstraction?

Abstraction exposes only essential behaviour and hides implementation details. You call list.add(x) without knowing how the array grows. In Java, you get abstraction through abstract classes and interfaces.

39. What is the difference between abstraction and encapsulation?

  • Abstraction: hides complexity by showing only what matters. A design-level idea, built with abstract classes and interfaces.
  • Encapsulation: hides data and protects it from direct access. An implementation-level idea, built with private fields and methods.

40. What is an interface in Java?

An interface is a contract: it declares methods that implementing classes must provide. Its fields are implicitly public static final. Since Java 8, interfaces can also have default and static methods with bodies, and since Java 9, private methods. A class can implement many interfaces.

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

  • Methods: an abstract class can have abstract and concrete methods. An interface has abstract methods plus default/static/private methods (Java 8/9+).
  • Fields: an abstract class can have any fields, including instance state. An interface only has public static final constants.
  • Constructors: an abstract class has them. An interface doesn’t.
  • Inheritance: a class can extend one abstract class but implement many interfaces.
  • Access: abstract class members can be private or protected. Interface abstract methods are public.
  • Use when: choose an abstract class when related classes share state and code. Choose an interface to define a capability that unrelated classes can have (Comparable, Runnable).

Output:

Paid Rs. 499.0 via UPIReceipt: Rs. 499.0
Bike has 2 wheels

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

  • Overloading: same method name, different parameter list, usually in the same class. Resolved at compile time. Return type alone can’t distinguish overloads.
  • Overriding: a subclass redefines a parent method with the same signature. Resolved at runtime. Rules: the return type must be the same or a subtype (covariant), access can’t be narrower, it can’t throw broader checked exceptions, and static, final, and private methods can’t be overridden. Use @Override so the compiler catches mistakes.

43. What is a constructor?

A constructor is a special block that initialises a new object. It has the same name as the class, no return type, and runs automatically when you call new.

Output:

 Constructor called for Neha

44. What are the types of constructors in Java?

  1. Default constructor: added by the compiler only if you write no constructor at all. It takes no arguments.
  2. No-argument constructor: written by you with no parameters.
  3. Parameterized constructor: takes arguments to set fields.

As soon as you write any constructor, the compiler stops adding the default one.

45. What is constructor overloading?

Having several constructors with different parameter lists in one class, so objects can be created in different ways (new Student(), new Student("Neha"), new Student("Neha", 21)). It is a form of compile-time polymorphism.

46. What is a copy constructor in Java?

Java has no built-in copy constructor like C++. You write one yourself: a constructor that takes an object of the same class and copies its fields, for example Student(Student other) { this.name = other.name; }. For mutable fields such as lists, copy the contents (a deep copy) so the two objects don’t share state.

47. What is the this keyword?

this refers to the current object. It is used to:

  1. Tell fields apart from parameters (this.id = id;).
  2. Call another constructor of the same class (this(...), which must be the first statement).
  3. Pass the current object to a method or return it.

this can’t be used inside a static method.

48. What is the super keyword, and in what order do constructors run?

super refers to the parent class. It is used to call a parent method (super.sound()), access a parent field, or call a parent constructor (super(...)). If you don’t write super(...), the compiler inserts a call to the parent’s no-arg constructor. The parent constructor always finishes before the child’s body runs.

Output:

1. Parent constructor2. Child(String) constructor: default
3. Child no-arg constructor

49. Can constructors be inherited, made private, or given a return type?

  • Inherited: no. A child calls the parent’s constructor through super(), but doesn’t inherit it.
  • Private: yes. It is used for singletons and utility classes so outsiders can’t create objects.
  • Return type: no. If you add one (even void), it becomes an ordinary method that happens to share the class name.

50. What are the methods of the Object class? What is the equals() and hashCode() contract?

Every class extends Object, which provides equals(), hashCode(), toString(), getClass(), clone(), wait(), notify(), notifyAll(), and the deprecated finalize(). The contract: if two objects are equal by equals(), they must return the same hashCode(). If you override equals() but not hashCode(), hash-based collections such as HashSet and HashMap treat equal objects as different.

Output:

Without equals/hashCode: 2With equals/hashCode: 1

51. What is a static block, and in what order do static blocks, instance blocks, and constructors run?

A static block (static { }) runs once, when the class is initialised. It is used to set up static data. An instance initializer block ({ }) runs every time an object is created, just before the constructor body.

Output:

1. Static block (runs once, when class is initialized)2. main starts
3. Instance block (runs for every object)
4. Constructor
3. Instance block (runs for every object)
4. Constructor

Strings Interview Questions

52. What is the String Pool?

The String Pool (string constant pool) is a special area in the heap where Java keeps one shared copy of each string literal. When you write "Java" twice, both variables point to the same pooled object, which saves memory. new String("Java") always creates a separate heap object. intern() returns the pooled copy.

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

  • String: immutable. Every “change” creates a new object. Thread-safe because it can’t change. Use it for values that don’t change.
  • StringBuilder: mutable (it edits its own resizable character array), not synchronized, fastest. Use it for building strings in a single thread, for example in loops.
  • StringBuffer: mutable, and its methods are synchronized, so it is thread-safe but slower. Use it only when several threads must edit the same buffer, which is rare.

Output:

JavaJava Rocks

54. Why are Strings immutable in Java?

  1. String Pool: many variables share one literal. If it could change, one change would affect them all.
  2. Security: file paths, URLs, class names, and credentials passed as Strings can’t be changed after they are validated.
  3. Thread safety: immutable objects can be shared safely without locks.
  4. Hash caching: a String’s hashCode() never changes, which makes it a reliable HashMap key.

55. What is the difference between a String literal and new String()?

Output:

truefalse
true
true

A literal reuses the pooled object. new String() always creates a new heap object (and puts the literal in the pool if it isn’t there already). Use literals unless you have a specific reason not to.

56. How do you reverse a String in Java?

The simplest way is new StringBuilder(s).reverse(). Interviewers often ask for a manual version too, such as a two-pointer swap on a char array:

Output (the third line is empty, because the empty string reverses to an empty string):

avaJaddAmaxE

Time is O(n) and extra space is O(n) for the char array.

57. Why is char[] preferred over String for passwords?

A String is immutable and may sit in memory (and in the pool) until garbage collection, so a heap dump could expose it. A char[] can be wiped right after use with Arrays.fill(password, '\0'). It also doesn’t print the secret by accident in logs (printing an array shows its type and hash, not the characters). Java’s own Console.readPassword() returns char[] for this reason.

Arrays Interview Questions

58. What is an array in Java?

An array is a fixed-size container of elements of one type, indexed from 0. In Java, an array is an object stored on the heap, and its size is available through length (a field, not a method).

Output:

104
3
Index 4 out of bounds for length 4

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

  • Size: an array is fixed at creation. An ArrayList grows automatically.
  • Element types: arrays can hold primitives and objects. ArrayList holds objects only (ArrayList<Integer>, with autoboxing).
  • Length: arr.length (field) vs list.size() (method).
  • Features: arrays have basic syntax. ArrayList offers add, remove, contains, iteration, and more.
  • Performance: arrays are slightly faster with no boxing. ArrayList is a little slower but far more flexible.

60. Why does array indexing start at 0?

The index is an offset from the start of the array. The address of element i is base + i × elementSize, so the first element is at offset 0. This convention comes from C and keeps the address arithmetic simple. Java follows it for consistency, even though Java code never sees raw memory addresses.

61. What are the types of arrays in Java? What is a jagged array?

  1. Single-dimensional: int[] a = new int[5];
  2. Multidimensional: int[][] grid = new int[3][4];. Java implements this as an array of arrays.
  3. Jagged array: a 2D array whose rows have different lengths.

Output:

Row 0 has 2 columnsRow 1 has 4 columns
Row 2 has 1 columns

62. What is the difference between int[] arr and int arr[]?

Both declare an int array and work the same way. int[] arr is the recommended Java style because the type (int[]) stays together. Watch out for int[] a, b; (both are arrays) versus int a[], b; (only a is an array).

63. What are the advantages and disadvantages of arrays?

  • Advantages: O(1) access by index, contiguous and cache-friendly storage, simple syntax, and they can hold primitives without boxing.
  • Disadvantages: fixed size, O(n) insertion and deletion in the middle (elements must shift), and few built-in methods (you need the Arrays helper class).

Exception Handling Interview Questions

64. What is exception handling in Java?

Exception handling lets a program deal with runtime problems (bad input, missing files, division by zero) without crashing, using try, catch, finally, throw, and throws.

Output:

Caught: / by zeroFinally block executed
Handled in main after propagation
Program continues

65. What is the difference between checked and unchecked exceptions?

  • Checked exceptions are subclasses of Exception other than RuntimeException. The compiler forces you to catch them or declare them with throws. Examples: IOException, SQLException, FileNotFoundException.
  • Unchecked exceptions are RuntimeException and its subclasses. The compiler doesn’t force handling, and they usually signal programming bugs. Examples: NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException.

Both happen at runtime. The difference is only whether the compiler checks that you handle them.

66. What is the difference between Error and Exception?

Both extend Throwable. An Exception is a condition the application can reasonably catch and recover from. An Error is a serious problem in the JVM or system, such as OutOfMemoryError or StackOverflowError, that applications normally shouldn’t try to catch.

Whiteboard
Loading diagram...

Everything throwable descends from Throwable. RuntimeException and its children are unchecked, and the other Exception subclasses are checked.

67. Explain try, catch, and finally.

  • try: wraps code that might throw.
  • catch: handles a specific exception type. You can have several, ordered from most specific to most general, and Java 7+ allows multi-catch (catch (IOException | SQLException e)).
  • finally: runs whether or not an exception occurred. It is used for cleanup.

A try needs at least one catch or a finally (or resources, see Q73).

68. Can the finally block be skipped?

Yes, in rare cases: when System.exit() is called inside try or catch, when the JVM crashes or is killed, or when the thread running it dies abruptly. A normal return inside try does not skip finally.

Output:

69. What is the difference between throw and throws?

  • throw: a statement inside a method body that raises one exception object: throw new IllegalArgumentException("Age must be positive");
  • throws: part of a method signature that declares which checked exceptions the method may pass to its caller: void readFile() throws IOException

70. What is exception propagation?

If a method doesn’t catch an exception, it passes up the call stack to the caller, then to that caller’s caller, until some method catches it. If nobody catches it, the thread terminates. Unchecked exceptions propagate automatically. Checked exceptions must be declared with throws at each level they pass through. Q64 shows an exception thrown in method2() passing through method1() and being handled in main.

71. What is a NullPointerException, and how do you avoid it?

An NPE happens when you use a null reference as if it pointed to an object: calling a method, reading a field, unboxing, or getting the length of a null array. Avoid it with null checks, by initialising fields, by returning empty collections instead of null, with Objects.requireNonNull(), and with Optional for return values. Since Java 14, helpful NPE messages tell you exactly what was null:

Output (compiled with javac -g):

City is not setException in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "city" is null
at NpeDemo.main(NpeDemo.java:9)

72. What happens if an exception is not handled?

The JVM’s default handler prints the exception name, message, and stack trace, then terminates that thread. If it is the main thread and no other non-daemon threads are running, the program ends, and any code after the failing line never runs.

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero	at Unhandled.main(Unhandled.java:3)

73. What is try-with-resources?

Introduced in Java 7, try-with-resources automatically closes any object that implements AutoCloseable (files, streams, database connections) when the block ends, even if an exception is thrown. Resources close in reverse order of opening. It replaces long finally { close(); } code.

Output:

Open fileOpen db
Using resources
Close db
Close file

Collections Interview Questions

74. What is the Java Collections Framework?

It is a set of interfaces (Collection, List, Set, Queue, Deque, and the separate Map), implementations (ArrayList, HashSet, HashMap, ArrayDeque, and so on), and algorithms (in the Collections utility class) for storing and processing groups of objects. Map is part of the framework but does not extend Collection.

75. What is the difference between List, Set, and Map?

  • List: ordered by index, allows duplicates. Examples: ArrayList, LinkedList.
  • Set: no duplicates. Order depends on the implementation: HashSet (no order), LinkedHashSet (insertion order), TreeSet (sorted).
  • Map: key-value pairs, unique keys, values may repeat. Examples: HashMap, LinkedHashMap, TreeMap.

Fun fact for interviews: HashSet is backed by a HashMap internally.

76. What is the difference between ArrayList and LinkedList?

  • Structure: ArrayList uses a resizable array. LinkedList is a doubly linked list.
  • get(index): O(1) for ArrayList, O(n) for LinkedList (it must walk the nodes).
  • Add at end: amortised O(1) for ArrayList, O(1) for LinkedList.
  • Insert/remove in the middle: O(n) for ArrayList because elements shift. For LinkedList it is O(n) to reach the position and O(1) to relink once you are there (for example, through a ListIterator).
  • Memory: ArrayList is compact. LinkedList uses more, because each node stores two extra references.
  • Default choice: ArrayList in almost all cases. Consider LinkedList only for frequent insert/remove at the ends or at an iterator position. For queues, ArrayDeque is usually better still.

77. What is the difference between HashMap and Hashtable?

  • Thread safety: HashMap isn’t synchronized. Hashtable is (every method is locked), so it is slower.
  • Nulls: HashMap allows one null key and many null values. Hashtable allows neither.
  • Status: Hashtable is a legacy class. For thread-safe maps, use ConcurrentHashMap.

Output:

02
2
Hashtable does not allow null keys

78. How does HashMap work internally?

  1. A HashMap stores entries in an array of buckets (16 by default).
  2. On put(key, value), it calls key.hashCode(), spreads the bits, and picks a bucket index.
  3. If the bucket is empty, the entry goes in. If not (a collision), it compares keys with equals(): an equal key has its value replaced, and otherwise the new entry is added to that bucket’s chain.
  4. Since Java 8, a bucket with many entries (more than 8, when the table has at least 64 buckets) turns from a linked list into a red-black tree, so lookups in that bucket are O(log n) instead of O(n).
  5. When the size passes capacity × load factor (0.75), the table doubles and entries are redistributed.

Average get and put are O(1). This is why keys need a correct equals()/hashCode() (see Q50) and should be immutable.

79. What is the difference between HashSet and TreeSet?

  • Order: HashSet has no guaranteed order. TreeSet keeps elements sorted (natural order or a Comparator).
  • Structure: HashSet uses a hash table (a HashMap). TreeSet uses a red-black tree (a TreeMap).
  • Speed: HashSet add/contains is O(1) on average. TreeSet is O(log n).
  • Nulls: HashSet allows one null. TreeSet doesn’t allow null with natural ordering (it throws NullPointerException).

80. What is the difference between Iterator and ListIterator?

  • Iterator: works on every Collection, moves forward only, supports hasNext(), next(), and remove().
  • ListIterator: works only on List, moves forward and backward (hasPrevious(), previous()), and also supports add(), set(), and index methods.

Removing from a list inside a for-each loop throws ConcurrentModificationException. Use Iterator.remove() (or removeIf) instead:

Output:

ConcurrentModificationException[1, 3]

81. What is the difference between Comparable and Comparator?

  • Comparable (java.lang): the class defines its own natural order by implementing compareTo(T o). There is one order per class.
  • Comparator (java.util): a separate object defines a custom order with compare(T a, T b). You can have many, and you can sort classes you can’t modify.

Output:

[1-Neha, 2-Amit, 3-Ravi][2-Amit, 1-Neha, 3-Ravi]

82. What is a Vector?

Vector is a legacy, resizable array like ArrayList, but every method is synchronized, so it is slower for single-threaded use. It doubles its capacity when full, while ArrayList grows by about 50%. Prefer ArrayList, or CopyOnWriteArrayList / Collections.synchronizedList() when you need thread safety.

83. What is a Stack in Java?

A stack is a LIFO (last in, first out) structure with push, pop, and peek. Java has a legacy Stack class (it extends Vector), but the recommended modern choice is Deque<Integer> stack = new ArrayDeque<>();.

84. What is a Queue in Java?

A queue is usually FIFO (first in, first out). Methods: offer/add (insert), poll/remove (take from the head), peek/element (look at the head). The first method in each pair returns null/false on failure, and the second throws an exception. Common implementations are ArrayDeque, LinkedList, and PriorityQueue, which orders by priority, not FIFO.

Output:

3020
10
20

Multithreading Interview Questions

85. What is multithreading?

Multithreading means running several threads, which are independent paths of execution, inside one program at the same time. It improves responsiveness (a UI stays usable while a download runs) and can use multiple CPU cores. Threads share the process’s heap, so access to shared data must be coordinated.

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

  • Memory: each process has its own memory space. Threads share their process’s memory (heap), but each has its own stack.
  • Cost: creating or switching a process is heavy. Threads are lighter.
  • Communication: between processes it needs IPC (pipes, sockets). Between threads it is direct, through shared objects.
  • Failure: a crash in one process doesn’t affect others. A badly behaving thread can affect the whole process.

87. What are the ways to create a thread in Java?

  1. Extend Thread and override run().
  2. Implement Runnable and pass it to a Thread. This is preferred: your class stays free to extend another class, and the task is separate from the thread.
  3. Use an ExecutorService (thread pool) to submit Runnable or Callable tasks. This is what real applications use.

Always call start(), not run(). start() creates a new thread, while calling run() directly just runs the method in the current thread.

88. What is the thread lifecycle in Java?

The official Thread.State enum has six states: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED. There is no separate “RUNNING” state. A thread that is actually running on a CPU is reported as RUNNABLE.

Whiteboard
Loading diagram...

A thread starts as NEW, becomes RUNNABLE after start(), may move into BLOCKED, WAITING, or TIMED_WAITING and back, and ends as TERMINATED once run() finishes.

Output:

NEWTIMED_WAITING
TERMINATED

89. What is a daemon thread?

A daemon thread is a low-priority background helper, such as the garbage collector’s threads. The JVM exits as soon as all non-daemon (user) threads finish, even if daemon threads are still running. Mark one with t.setDaemon(true) before start(). Calling it afterwards throws IllegalThreadStateException.

90. What is the difference between sleep() and wait()?

  • Defined in: sleep() is a static method of Thread. wait() is an instance method of Object.
  • Lock: sleep() keeps any lock it holds. wait() releases the object’s lock.
  • Where: sleep() can be called anywhere. wait() must be called inside a synchronized block on that object, or it throws IllegalMonitorStateException.
  • Wake-up: sleep() ends after the time or on interrupt. wait() ends on notify()/notifyAll(), a timeout, or an interrupt.
  • Purpose: sleep() pauses execution. wait() coordinates threads (producer-consumer).

91. What are thread priorities?

Each thread has a priority from 1 to 10: Thread.MIN_PRIORITY = 1, NORM_PRIORITY = 5 (the default), MAX_PRIORITY = 10, set with setPriority(). Priority is only a hint to the OS scheduler. It doesn’t guarantee execution order, so never rely on it for correctness.

92. What is synchronization in Java?

Synchronization allows only one thread at a time to run a critical section, so shared data isn’t corrupted by race conditions. Mark a method or block synchronized, and the thread must hold the object’s lock (monitor) to enter. Without synchronized, the program below often prints less than 20000, because count++ isn’t atomic.

Output:

20000

Alternatives include AtomicInteger, ReentrantLock, and concurrent collections.

Garbage Collection and Memory Interview Questions

93. What is garbage collection, and why is it needed?

Garbage collection (GC) is the JVM’s automatic process of finding heap objects that are no longer reachable from any live reference and reclaiming their memory. It removes manual free/delete, prevents dangling-pointer bugs, reduces memory leaks, and keeps long-running applications stable. System.gc() only requests a collection. The JVM may ignore it.

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

  • Stores: the heap holds objects and arrays (and the String pool). The stack holds method frames: local primitives and references to heap objects.
  • Shared by: the heap is shared by all threads. Each thread has its own stack.
  • Managed by: the garbage collector for the heap. For the stack, frames are pushed on call and popped on return.
  • Errors: heap exhaustion gives OutOfMemoryError. Stack exhaustion (for example, deep recursion) gives StackOverflowError.
  • Speed: stack allocation is very fast. Heap allocation is slower and needs GC.

95. What is a memory leak in Java?

A leak happens when objects you no longer need are still referenced, so the GC can’t free them and memory keeps growing until OutOfMemoryError. Common causes are ever-growing static collections or caches, listeners that are never removed, unclosed resources, and ThreadLocal values that are never cleared. To prevent leaks, remove unused references, bound your caches, use try-with-resources, and profile with tools like VisualVM or Java Flight Recorder.

96. When does an object become eligible for garbage collection?

When no live thread can reach it. Typical cases:

  1. The reference is set to null.
  2. The reference is reassigned to another object.
  3. The object was created inside a method that has returned.
  4. Anonymous objects, such as new Student().show();.
  5. Islands of isolation: objects that only reference each other, with no outside reference.

Eligible doesn’t mean collected right away. The JVM decides when to run GC.

Java Keywords Interview Questions

97. What is the difference between final, finally, and finalize()?

  • final: a keyword. A final variable can’t be reassigned, a final method can’t be overridden, and a final class can’t be extended.
  • finally: a block after try/catch that runs for cleanup.
  • finalize(): an old Object method the GC might call before reclaiming an object. It is unpredictable and deprecated for removal (since Java 18). Use try-with-resources or Cleaner instead.

98. What are the uses of the final keyword?

  1. final variable: assigned once. A blank final field must be assigned exactly once, in a constructor or an instance initializer block (or a static block for static final).
  2. final method: can’t be overridden.
  3. final class: can’t be subclassed (for example, String, Integer).

Output:

 7 Java

A final reference can’t point to a new object, but the object itself can still change (for example, final List<String> list still allows list.add()).

99. What is the static keyword? Can static methods be overloaded or overridden?

static makes a member belong to the class: static variables are shared, static methods are called with the class name, static blocks run once, and static nested classes don’t need an outer object. Static methods can’t use this or access instance members directly.

  • Overloading static methods: yes. It is resolved at compile time.
  • Overriding static methods: no. A child’s static method with the same signature hides the parent’s. The reference type decides which one runs.

Output:

Base staticDerived instance

100. What is the transient keyword?

transient marks a field that should be skipped during serialization. After deserialization, the field holds its default value (null, 0, false). Use it for passwords, caches, or fields that can’t be serialized.

Output:

ravi
null

Java Coding Interview Questions for Freshers

All five programs below are in one tested file, CodingQuestions.java (Q101–Q104, Q106) and SwapDemo.java (Q105).

Output:

truefalse
0 1 1 2 3 5 8 13
[2, 4]
{b=1, a=3, n=2}
120
1

101. How do you check whether a String is a palindrome?

Compare characters from both ends with two pointers and move inward. Stop at the first mismatch. This takes O(n) time and O(1) extra space. “madam” gives true and “java” gives false. Follow-up: to ignore case and spaces, normalise first with s.replaceAll("\\s", "").toLowerCase().

102. How do you print the Fibonacci series?

Keep two variables, a (current) and b (next). Print a, then shift: next = a + b; a = b; b = next;. The first 8 terms are 0 1 1 2 3 5 8 13. This iterative version is O(n). The naive recursive version is O(2ⁿ), and interviewers often ask why.

Dry run (first 4 iterations):

  • i = 0: a = 0, b = 1, prints 0, then a = 1, b = 1
  • i = 1: prints 1, then a = 1, b = 2
  • i = 2: prints 1, then a = 2, b = 3
  • i = 3: prints 2, then a = 3, b = 5

103. How do you find duplicate elements in an array?

Add each element to a HashSet. add() returns false when the element is already present, which marks a duplicate. Collect duplicates in a LinkedHashSet so each is reported once, in first-seen order. For {4, 2, 7, 2, 4, 9, 4} the result is [2, 4]. This is O(n) time and O(n) space, compared with O(n²) for nested loops.

104. How do you count the frequency of each character in a String?

Loop over the characters and use map.put(ch, map.getOrDefault(ch, 0) + 1). A LinkedHashMap keeps the first-seen order, so “banana” gives {b=1, a=3, n=2}. This is O(n) time.

105. How do you swap two numbers without a third variable?

Output:

a = 9, b = 5 

Mention the catch: a + b can overflow for very large values. An XOR swap avoids that, but a temporary variable is clearer in real code.

106. Bonus: how do you find the factorial of a number?

Multiply from 2 up to n in a long (an int overflows after 12!). factorial(5) is 120, and factorial(0) is 1 by definition, which is a common edge case. For n > 20, even long overflows, so use BigInteger.

Common Mistakes Freshers Make in Java Interviews

  1. Comparing Strings with ==. if (input == "yes") may be false even when the text matches. Fix: "yes".equals(input), which is also null-safe.
  2. Comparing Integer objects with ==. It works for −128 to 127 and fails above that (Q23). Fix: a.equals(b).
  3. Removing from a list inside for-each. It throws ConcurrentModificationException (Q80). Fix: iterator.remove() or list.removeIf(...).
  4. Calling run() instead of start(). No new thread is created. Fix: thread.start().
  5. Saying “Java is pass-by-reference for objects.” Wrong. The reference is passed by value (Q16).
  6. Listing “RUNNING” as a Thread.State. The official states are the six in Q88.
  7. Overriding equals() without hashCode(). HashSet and HashMap then break (Q50).

How to Prepare for a Java Fresher Interview

  1. Revise in this article’s order: basics, OOP, Strings, arrays, exceptions, collections, threads, memory.
  2. For each comparison question, prepare a one-line answer plus one difference you can explain with code.
  3. Type and run every snippet here yourself, and change one line to see what breaks.
  4. Practise 10–15 small programs (palindrome, Fibonacci, duplicates, frequency, reverse words, prime check, second-largest element) on paper and in an editor.
  5. Prepare a 2-minute walk-through of one Java project you built: what it does, the classes involved, and one bug you fixed.

Practice Problems

  1. (Easy) Predict the output of System.out.println(10 / 4 + " " + 10 / 4.0);. Hint: integer division vs floating-point division.
  2. (Easy) Write a program that counts vowels in a String. Hint: "aeiouAEIOU".indexOf(ch) >= 0.
  3. (Medium) Find the second-largest number in an int[] in one pass. Hint: track first and second, and handle duplicates and arrays shorter than 2.
  4. (Medium) Reverse the order of words in “Java is fun” to get “fun is Java”. Hint: split("\\s+"), then build the result backwards with a StringBuilder.
  5. (Medium) Create a Student class with equals()/hashCode() based on roll number and prove that a HashSet keeps only one copy of two students with the same roll number. Hint: reuse the pattern from Q50.

Article Summary

  • Java compiles to bytecode that any JVM can run. JDK = JRE + tools, and JRE = JVM + libraries.
  • OOP questions centre on the four pillars, overloading vs overriding, abstract class vs interface, and constructor rules.
  • Strings are immutable and pooled. Use equals() for content and StringBuilder for building strings.
  • Know the trade-offs between ArrayList and LinkedList, HashMap and Hashtable, HashSet and TreeSet, and the equals/hashCode contract.
  • Exceptions are checked or unchecked. Use try-with-resources for cleanup, and know when finally can be skipped.
  • Threads have six official states, and synchronized prevents race conditions on shared data.

Conclusion

These 105 Java interview questions for freshers cover what campus and entry-level interviews ask most: JVM basics, OOP, Strings, arrays, exceptions, collections, threads, memory, and short coding programs. Run every example yourself and practise explaining each answer in two or three sentences. Then move on to the next level with Java Intermediate Interview Questions and Answers.

For a structured path through every topic, follow the Tech ExamAdda Java Roadmap.

Previous lesson: Roadmap of Java Language
Next lesson: Java Intermediate Interview Questions and Answers

Related: Advanced Java Interview Questions · Scenario-Based Java Interview Questions · Your First Java Program · Variables and Data Types

References

Last updated: October 30, 2026 · Code tested on OpenJDK 21.0.12

4. Series links

LinkPlacementStatus
Roadmap of Java Language (previous)Prerequisites, conclusion, PreviousVerified (sidebar and Previous button)
Java Intermediate Interview Questions (next)Conclusion, NextVerified (sidebar and Next button)
How Java WorksPrerequisitesVerified (sidebar)
Features of JavaQ3Verified
Java Ecosystem (/java/jdk)Q6Verified
Primitive Types, Reference TypesQ17Verified
Type CastingQ21Verified
OperatorsQ27Verified
Advanced, Scenario-Based, First Program, Variables & Data TypesRelated lineVerified
OOP, Strings, Collections, Exception Handling, Multithreading lessons—Suggestion: these exist in the sidebar but have no lesson URLs yet. Link Q32–Q51, Q52–Q57, Q74–Q84, Q64–Q73, and Q85–Q92 once they are published.

5. Change log

Factual and code errors fixed (9):

  1. Q3 Security Manager: the article listed it as a current security feature. As of JDK 24, the Security Manager is permanently disabled. It is now noted as removed. oracle
  2. Q9 ClassLoader: the article said “Extension ClassLoader”. The extension class loader has been renamed; it is now the platform class loader. That rename happened in Java 9. notion
  3. Q88 Thread lifecycle: the diagram had a “RUNNING” state and left out TIMED_WAITING. The official enum lists NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED. The diagram is redrawn, and a getState() demo now shows the real output. oracle
  4. Q76 LinkedList: insert/delete was listed as O(1) without qualification. It is O(1) only once you are at the node; reaching an index is O(n).
  5. Q34 Class memory: the article said a class uses no memory until an object is created. The JVM stores class metadata and static fields when the class is loaded.
  6. Q60 Zero indexing: “for performance” was overstated. It is now explained as offset arithmetic, a convention inherited from C.
  7. Q32: the unclear phrase “purely object-oriented inspired” is replaced with “Java is not purely OO, because of primitives and static members.”
  8. Q98 Blank final: the article said blank finals can only be assigned in a constructor. They can also be assigned in an instance initializer block. This is now demonstrated and tested.
  9. Q11 main not static: the error message was abbreviated. It now shows the real JDK 21 message, plus the Java 25 change: the main() method – whether in conventional or compact source files – no longer needs to be static or public, and the args parameter is also optional. happycoders

Also softened: “compile-time polymorphism is faster” was removed as an unsupported claim. finalize() is now described as “deprecated for removal”.

Added from research (15 new questions): Q1 What is Java, Q13 Java vs C++, Q15 access modifiers, Q16 pass-by-value, Q24 var, Q31 switch expressions, Q40 interface, Q41 abstract class vs interface, Q50 equals/hashCode contract, Q51 static/instance block order, Q73 try-with-resources, Q78 HashMap internals, Q92 synchronization, and Q101–Q106 coding programs. The Integer cache, Java 14 helpful NPE messages, and ConcurrentModificationException were added inside existing answers. New sections: an answer-first intro, prerequisites, Key Takeaways, Common Mistakes, preparation tips, practice problems, summary, conclusion, previous/next links, and references.

Restructured: duplicates were merged into one question each: main static and not static (11), the two package questions (14), casting and widening/narrowing (21), the two wrapper questions (22), runtime and compile-time polymorphism into Q37, StringBuffer into Q53, array types and jagged arrays (61), the two GC questions (93), and static overload/override (99). No original question was removed. 98 original questions plus 15 new ones, minus 9 merges and adding the bonus Q106, gives 105.

Code testing: all 36 programs were compiled and run on OpenJDK 21.0.12. Every output shown is the real output. The Q11 error and the Q71 NPE message were also captured from real runs (Q71 compiled with javac -g). None of the code uses features newer than Java 21. The Java 25 instance-main behaviour is described from JEP 512 and was not run, because only JDK 21 is installed here.

Reference matrix: you gave no reference articles, so it’s empty (0 added, 0 expanded, 0 covered, 0 excluded).

Fix on the live page: it shows May 11, 2026 as the date, but the meta tag says Sep 5, 2026. Show a single “Last updated” date.

6. Image plan

  1. Java execution flow (Q2): render the Mermaid diagram. Alt text: “Java source compiled by javac into bytecode, loaded and run by the JVM on any OS”.
  2. Exception hierarchy (Q66). Alt text: “Java exception hierarchy showing Throwable, Error, checked exceptions and RuntimeException”.
  3. Thread lifecycle (Q88). Alt text: “Java thread lifecycle with the six Thread.State values”.
  4. Optional: a HashMap bucket diagram for Q78. Alt text: “HashMap buckets with a collision chain and treeified bucket”.

7. Sources