Java MCQ

Test your Java knowledge with 100 multiple choice questions covering fundamentals to advanced concepts, with instant feedback and explanations.

100 Questions 41 Beginner 39 Intermediate 20 Advanced

How This Practice Test Works

Every question below expands right on this page — click a question to reveal its four options, pick the one you think is correct, and you'll get instant feedback along with the correct answer and a short explanation of the reasoning. Questions are grouped by difficulty, so start with the 41 beginner questions to confirm your fundamentals, work through the 39 intermediate ones, and finish with the 20 advanced questions that mirror what exams and technical screenings actually ask. There's no sign-up, no timer, and no limit — retake the test as often as you like.

Curated by Tech Baithak Editorial Team  ·  Last updated: June 2026

1

What does JVM stand for?

A

Correct Answer

Java Virtual Machine

Explanation

JVM stands for Java Virtual Machine, the runtime environment that executes Java bytecode on any platform.

2

Which of the following is NOT a Java primitive type?

B

Correct Answer

String

Explanation

String is a class in Java, not a primitive type. Java's eight primitives are byte, short, int, long, float, double, boolean, and char.

3

What is the correct signature of the main method in Java?

C

Correct Answer

public static void main(String[] args)

Explanation

The JVM looks for public static void main(String[] args) as the entry point. All modifiers — public, static, and the void return type — are required.

4

Which keyword is used to create an object in Java?

C

Correct Answer

new

Explanation

The new keyword allocates memory for a new object and calls its constructor.

5

What is the default value of an int variable in Java?

D

Correct Answer

0

Explanation

Instance variables of type int are automatically initialized to 0 if no value is assigned.

6

Which symbol is used for single-line comments in Java?

B

Correct Answer

//

Explanation

In Java, // starts a single-line comment. /* ... */ is used for multi-line comments.

7

What keyword is used for inheritance in Java?

C

Correct Answer

extends

Explanation

The extends keyword creates a subclass that inherits fields and methods from a superclass.

8

Which keyword is used to implement an interface?

D

Correct Answer

implements

Explanation

A class uses implements to fulfill the contract defined by an interface.

9

What is the superclass of all Java classes?

B

Correct Answer

Object

Explanation

Every Java class implicitly extends java.lang.Object, which provides methods like toString(), equals(), and hashCode().

10

What does the final keyword do when applied to a variable?

C

Correct Answer

Prevents the variable from being reassigned

Explanation

A final variable can only be assigned once; attempting to reassign it causes a compile-time error.

11

What is the size of an int in Java?

B

Correct Answer

4 bytes

Explanation

In Java, int is always 32 bits (4 bytes) regardless of the underlying platform, unlike C/C++.

12

What is a constructor?

B

Correct Answer

A special method used to initialize objects

Explanation

A constructor has the same name as the class, no return type, and is called automatically when an object is created with new.

13

What does method overloading mean?

C

Correct Answer

Multiple methods share the same name but differ in parameters

Explanation

Method overloading allows the same method name with different parameter lists, enabling compile-time polymorphism.

14

Which access modifier makes a member visible only within its class?

D

Correct Answer

private

Explanation

private restricts access to within the declaring class only; it is the most restrictive access modifier.

15

What does the static keyword mean on a method?

B

Correct Answer

The method belongs to the class, not to any instance

Explanation

Static methods belong to the class itself and can be called without creating an instance, e.g., Math.sqrt().

16

Which package is automatically imported in every Java program?

C

Correct Answer

java.lang

Explanation

java.lang is implicitly imported in every Java file, providing core classes like String, Math, System, and Object.

17

What is the output of: System.out.println(10 / 3)?

C

Correct Answer

3

Explanation

Integer division in Java truncates the decimal part, so 10 / 3 yields 3, not 3.33.

18

Which loop is guaranteed to execute at least once?

C

Correct Answer

do-while loop

Explanation

A do-while loop checks its condition after executing the body, ensuring the body runs at least once.

19

What does the instanceof operator do?

C

Correct Answer

Tests whether an object is an instance of a given type

Explanation

instanceof returns true if the object on the left is an instance of the class or interface on the right.

20

What is an abstract class?

B

Correct Answer

A class that cannot be instantiated directly and may have abstract methods

Explanation

An abstract class is declared with the abstract keyword and cannot be instantiated. It may contain abstract methods that subclasses must implement.

21

How do you print to the console in Java?

C

Correct Answer

System.out.println("Hello")

Explanation

System.out.println() writes text followed by a newline to the standard output stream.

22

What is the boolean default value in Java?

D

Correct Answer

false

Explanation

Instance boolean variables default to false when not explicitly initialized.

23

Which of these is a valid Java identifier?

B

Correct Answer

_myVar

Explanation

Java identifiers must start with a letter, underscore, or dollar sign. _myVar is valid; 2count starts with a digit, class is a keyword, and my-var contains a hyphen.

24

What is an array in Java?

B

Correct Answer

A fixed-size container of elements of the same type

Explanation

A Java array is a fixed-length data structure that holds elements of the same type, accessed by index starting at 0.

25

What does JDK stand for?

A

Correct Answer

Java Development Kit

Explanation

JDK (Java Development Kit) includes the compiler (javac), JRE, and tools needed to develop Java applications.

26

Which operator is used to compare two values in Java?

C

Correct Answer

==

Explanation

== compares primitive values or object references for equality. For object content comparison, use equals().

27

What is the range of the byte data type in Java?

B

Correct Answer

-128 to 127

Explanation

byte is an 8-bit signed integer with a range of -128 to 127.

28

What is method overriding?

C

Correct Answer

A subclass providing a specific implementation of a method defined in the parent class

Explanation

Overriding occurs when a subclass provides its own implementation of an inherited method with the same signature.

29

Which collection class allows duplicate elements and maintains insertion order?

C

Correct Answer

ArrayList

Explanation

ArrayList implements List and allows duplicates, maintaining the order elements were inserted.

30

What does the void return type mean?

C

Correct Answer

The method returns nothing

Explanation

void indicates that a method does not return any value.

31

Which keyword prevents a class from being subclassed?

D

Correct Answer

final

Explanation

Declaring a class final prevents inheritance. For example, String is a final class.

32

What is the ternary operator in Java?

A

Correct Answer

condition ? valueIfTrue : valueIfFalse

Explanation

The ternary operator takes three operands: a condition, a value if true, and a value if false, all in one expression.

33

What exception is thrown when an array index is out of bounds?

B

Correct Answer

ArrayIndexOutOfBoundsException

Explanation

ArrayIndexOutOfBoundsException is thrown when code tries to access an array element at a negative index or an index >= array.length.

34

How do you declare a constant in Java?

B

Correct Answer

static final int MAX = 10;

Explanation

Java uses static final (by convention in ALL_CAPS) to declare constants. const is a reserved word but not used.

35

What is the length of a String s = "Hello"?

C

Correct Answer

s.length()

Explanation

String.length() returns the number of characters in the string. Note: arrays use .length (property), but String uses .length() (method).

36

What is autoboxing in Java?

B

Correct Answer

Automatic conversion of a primitive to its wrapper class

Explanation

Autoboxing automatically converts a primitive (e.g., int) to its wrapper (Integer) when needed, and unboxing does the reverse.

37

Which of these correctly creates an array of 5 integers?

B

Correct Answer

int[] arr = new int[5]

Explanation

In Java, arrays are declared with [] and allocated with new type[size].

38

What does the this keyword refer to?

C

Correct Answer

The current object instance

Explanation

this refers to the current object instance and is used to distinguish instance variables from local variables with the same name.

39

What is the output of: System.out.println("5" + 3)?

B

Correct Answer

53

Explanation

When a String is added to an int, Java concatenates them. "5" + 3 produces "53".

40

Which exception is the parent of all checked exceptions?

C

Correct Answer

Exception

Explanation

Exception is the superclass of all checked exceptions. RuntimeException (unchecked) and Error also extend Throwable.

41

What does the super keyword do?

B

Correct Answer

Refers to the parent class and is used to call parent methods or constructors

Explanation

super() calls the parent constructor, and super.method() calls an overridden method in the parent class.

1

What is the difference between == and equals() when comparing Strings?

B

Correct Answer

== checks reference equality; equals() checks content equality

Explanation

== compares memory addresses (references) while equals() compares the actual character sequences. Two distinct String objects with the same content are == false but equals() true.

2

What is the purpose of the try-catch-finally block?

C

Correct Answer

Exception handling; finally always runs regardless of whether an exception occurred

Explanation

try contains code that might throw, catch handles specific exceptions, and finally always executes — useful for cleanup like closing streams.

3

What is the difference between ArrayList and LinkedList?

B

Correct Answer

ArrayList uses a dynamic array (fast random access); LinkedList uses doubly-linked nodes (fast insert/delete)

Explanation

ArrayList offers O(1) indexed access but O(n) insert/delete. LinkedList offers O(1) insert/delete at ends but O(n) random access.

4

What is a checked exception?

B

Correct Answer

An exception that must be declared with throws or caught at compile time

Explanation

Checked exceptions (e.g., IOException) must be either caught or declared in the method signature with throws, enforced by the compiler.

5

What does the synchronized keyword do?

C

Correct Answer

Ensures only one thread executes the method or block at a time

Explanation

synchronized acquires a monitor lock on the object (or class), preventing concurrent access and race conditions.

6

What is the purpose of the interface keyword?

B

Correct Answer

To define a contract of method signatures that implementing classes must fulfill

Explanation

An interface defines a contract. Since Java 8, interfaces can also include default and static methods with implementations.

7

What is the difference between HashMap and TreeMap?

B

Correct Answer

HashMap is unordered O(1) operations; TreeMap maintains sorted key order with O(log n) operations

Explanation

HashMap uses hashing for O(1) average performance but no order. TreeMap uses a Red-Black Tree, keeping keys sorted but at O(log n) cost.

8

What is a lambda expression in Java 8+?

B

Correct Answer

A shorthand for implementing a functional interface with a concise anonymous function

Explanation

Lambda expressions (e.g., (x) -> x * 2) provide a concise way to implement functional interfaces, enabling functional programming patterns.

9

What does the volatile keyword guarantee?

C

Correct Answer

Reads and writes to the variable are visible to all threads immediately (no CPU caching)

Explanation

volatile ensures that reads and writes go directly to main memory, preventing threads from caching a stale value, but does not provide atomicity for compound operations.

10

Which method must be implemented by a class implementing the Runnable interface?

C

Correct Answer

run()

Explanation

Runnable has a single abstract method run() which defines the code that runs in the new thread.

11

What is the purpose of the Optional class in Java 8?

B

Correct Answer

To represent a value that may or may not be present, avoiding NullPointerException

Explanation

Optional<T> forces callers to handle the absent-value case explicitly, reducing NullPointerExceptions.

12

What is the Stream API used for in Java 8?

B

Correct Answer

Functional-style sequential or parallel operations on collections

Explanation

The Stream API enables declarative data processing with operations like filter, map, reduce, and collect, optionally in parallel.

13

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

B

Correct Answer

A class can implement multiple interfaces but can only extend one abstract class

Explanation

Java supports multiple interface implementation but single class inheritance. Abstract classes can have constructors, state, and concrete methods.

14

What is the purpose of the @Override annotation?

B

Correct Answer

It tells the compiler to check that this method is actually overriding a parent method

Explanation

@Override is a compile-time check. If the annotated method doesn't actually override a parent method, the compiler reports an error.

15

What is the difference between throw and throws?

B

Correct Answer

throw is used to actually throw an exception; throws declares that a method may throw an exception

Explanation

throw new SomeException() is the statement that raises an exception. throws in a method signature tells callers which checked exceptions the method may propagate.

16

What is the significance of the hashCode() contract?

B

Correct Answer

Equal objects must have the same hashCode

Explanation

The contract says: if a.equals(b) is true, then a.hashCode() == b.hashCode(). The reverse is not required; different objects can share a hash code (collision).

17

What is garbage collection in Java?

B

Correct Answer

The automatic reclamation of memory used by objects no longer referenced

Explanation

The JVM's garbage collector identifies objects with no live references and frees their memory, so developers don't need to manually deallocate.

18

What is the purpose of the Comparable interface?

B

Correct Answer

To define a natural ordering for objects of a class via compareTo()

Explanation

Implementing Comparable<T> and its compareTo() method defines the natural ordering used by Collections.sort() and TreeSet.

19

What does String.intern() do?

C

Correct Answer

Returns a canonical representation from the string pool

Explanation

intern() checks the string pool; if an equal string exists, it returns the pooled reference. This allows == comparison for interned strings.

20

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

B

Correct Answer

final=keyword modifier; finally=exception block that always runs; finalize=method called before GC

Explanation

final modifies classes/methods/variables. finally is a block that always runs after try-catch. finalize() is a deprecated method called by GC before object cleanup.

21

What is a functional interface?

B

Correct Answer

An interface with exactly one abstract method, usable as a lambda target

Explanation

A functional interface (annotated with @FunctionalInterface) has exactly one abstract method. Examples: Runnable, Callable, Comparator, and the java.util.function types.

22

What is the purpose of Collections.unmodifiableList()?

C

Correct Answer

Returns a view that throws UnsupportedOperationException on mutating operations

Explanation

unmodifiableList wraps a list so that add/remove/set throw UnsupportedOperationException. The underlying list can still be mutated through the original reference.

23

What does the transient keyword do?

B

Correct Answer

Prevents a field from being serialized

Explanation

Fields marked transient are skipped during Java serialization, useful for sensitive data or non-serializable objects.

24

What is the difference between Iterator and ListIterator?

B

Correct Answer

ListIterator can traverse in both directions and supports add/set; Iterator only moves forward

Explanation

ListIterator extends Iterator with hasPrevious(), previous(), add(), and set(), enabling bidirectional traversal and modification.

25

What happens when you catch a parent exception type before a child type?

B

Correct Answer

A compile-time error occurs because the child catch is unreachable

Explanation

Java requires more specific exceptions to be caught before broader ones. Placing a parent type first makes child-type catch blocks unreachable, which is a compile-time error.

26

What is method chaining?

C

Correct Answer

Each method returns this, allowing multiple calls on the same object in one expression

Explanation

Method chaining (fluent interface) returns this from each method, enabling patterns like StringBuilder.append("a").append("b").toString().

27

What does Collections.sort() use internally by default?

C

Correct Answer

TimSort (merge + insertion sort hybrid)

Explanation

Java's Arrays.sort() and Collections.sort() use TimSort, a hybrid stable sorting algorithm derived from merge sort and insertion sort.

28

What is the purpose of the Executor framework?

B

Correct Answer

To manage thread pools and decouple task submission from execution mechanics

Explanation

Executor and ExecutorService provide thread pool management, reducing overhead of creating new threads for each task.

29

What is a deadlock in Java?

B

Correct Answer

A situation where two or more threads wait for each other's locks indefinitely

Explanation

Deadlock occurs when Thread A holds lock X and waits for lock Y, while Thread B holds lock Y and waits for lock X — both block forever.

30

What is the difference between StringBuilder and StringBuffer?

B

Correct Answer

StringBuilder is not thread-safe but faster; StringBuffer is thread-safe but slower

Explanation

StringBuffer methods are synchronized, making it thread-safe but slower. StringBuilder is unsynchronized and preferred for single-threaded string manipulation.

31

What is the Singleton design pattern?

B

Correct Answer

A pattern ensuring a class has only one instance with global access

Explanation

Singleton restricts instantiation to one object, typically using a private constructor and a static getInstance() method.

32

What is the purpose of the Iterable interface?

B

Correct Answer

To allow use in a for-each (enhanced for) loop by providing an iterator()

Explanation

Iterable<T> requires implementing iterator(), which the enhanced for loop calls. Collections like ArrayList implement it.

33

What does AtomicInteger provide over volatile int?

B

Correct Answer

Thread-safe compound operations like compareAndSet and incrementAndGet

Explanation

volatile ensures visibility but not atomicity for compound operations. AtomicInteger uses CPU compare-and-swap (CAS) for lock-free atomic increments and conditional updates.

34

What is the output of Integer.parseInt("10", 2)?

C

Correct Answer

2 (binary "10" = 2 in decimal)

Explanation

parseInt(String s, int radix) parses the string in the given base. "10" in base 2 equals 2 in decimal.

35

Which Java collection is backed by a hash table and maintains insertion order?

C

Correct Answer

LinkedHashMap

Explanation

LinkedHashMap extends HashMap and uses a doubly-linked list to maintain the insertion-order of entries.

36

What does the default keyword in a Java 8 interface do?

B

Correct Answer

Provides a method implementation directly in the interface so implementing classes need not override it

Explanation

Default methods allow new methods to be added to interfaces without breaking existing implementations.

37

What is the difference between String.format() and StringBuilder for repeated concatenation?

B

Correct Answer

StringBuilder is faster for repeated concatenation because it avoids creating intermediate String objects

Explanation

Concatenating with + in a loop creates O(n^2) String objects. StringBuilder.append() is O(n). String.format() is convenient but allocates more than direct StringBuilder use.

38

What is the purpose of the java.util.concurrent package?

B

Correct Answer

Providing high-level concurrency utilities: thread pools, atomic variables, concurrent collections, and synchronizers

Explanation

java.util.concurrent provides ExecutorService, ConcurrentHashMap, CountDownLatch, Semaphore, LinkedBlockingQueue, and much more for robust multithreaded programming.

39

What is the try-with-resources statement?

B

Correct Answer

A try block that automatically closes AutoCloseable resources declared in its header when the block exits

Explanation

try (InputStream in = new FileInputStream(f)) { } automatically calls in.close() on exit, equivalent to a manual finally block but more concise and correct.

1

What is the Java Memory Model (JMM) and why does it matter?

B

Correct Answer

A specification defining how threads interact through memory and which executions are legal

Explanation

The JMM defines happens-before relationships, ensuring developers can reason about visibility and ordering across threads when using synchronization, volatile, and locks.

2

What is a phantom reference in Java?

B

Correct Answer

The weakest reference type; the referent has been finalized and enqueued in a ReferenceQueue but not yet reclaimed

Explanation

Phantom references are used for pre-mortem cleanup. PhantomReference.get() always returns null; you detect collection via the ReferenceQueue.

3

What is the G1 garbage collector's primary design goal?

C

Correct Answer

Meet user-specified pause-time goals while maximizing throughput

Explanation

G1 (Garbage First) divides the heap into equal-size regions and targets a maximum pause time set via -XX:MaxGCPauseMillis, balancing throughput and low latency.

4

What problem does the double-checked locking pattern solve, and what Java feature makes it correct?

B

Correct Answer

Reduces lock contention for lazy singleton initialization; requires volatile on the instance field

Explanation

Without volatile, the JIT can reorder writes so another thread sees a partially constructed object. volatile establishes a happens-before, making DCL safe.

5

What is the difference between ClassLoader.loadClass() and Class.forName()?

B

Correct Answer

loadClass() does not initialize the class; Class.forName() initializes it by default

Explanation

ClassLoader.loadClass() loads but does not initialize (no static blocks run). Class.forName(name, true, loader) initializes by default, running static initializers.

6

What is bytecode instrumentation and when is it used?

B

Correct Answer

Modifying .class bytecode at load time or compile time to add cross-cutting behavior like logging or profiling

Explanation

Frameworks like AspectJ, Mockito, and many APM agents use bytecode instrumentation (via java.lang.instrument or ASM) to inject code without modifying source.

7

What is the purpose of the ForkJoinPool?

B

Correct Answer

To execute recursive divide-and-conquer tasks using work-stealing for load balancing

Explanation

ForkJoinPool implements work-stealing: idle threads steal tasks from busy threads' deques, maximizing CPU utilization for RecursiveTask/RecursiveAction workloads.

8

What is an escape analysis optimization in the JVM?

B

Correct Answer

Determining whether an object's reference escapes the allocating method, enabling stack allocation or lock elision

Explanation

If the JIT proves an object never escapes a method, it may allocate the object on the stack (avoiding GC) or elide unnecessary locks, boosting performance.

9

What does the invokedynamic bytecode instruction enable?

B

Correct Answer

Dynamic method dispatch for languages on the JVM, underpinning Java lambdas and method handles

Explanation

Introduced in Java 7, invokedynamic defers method linkage to a bootstrap method at runtime. Java 8 lambdas are desugared to invokedynamic calls, enabling efficient functional constructs.

10

What is a StackOverflowError and how can it be triggered?

B

Correct Answer

Occurs when the call stack exceeds its limit, typically from unbounded recursion

Explanation

Each method call pushes a frame onto the thread stack. Infinite or too-deep recursion exhausts the stack space, throwing StackOverflowError (an Error, not Exception).

11

What is the significance of Project Loom's virtual threads?

B

Correct Answer

They are JVM-managed lightweight threads that enable high concurrency without the overhead of OS threads

Explanation

Virtual threads (JEP 444, GA in Java 21) are cheap, JVM-scheduled threads. Millions can exist simultaneously, unblocking blocking I/O calls without consuming OS threads.

12

What is the difference between WeakReference and SoftReference?

B

Correct Answer

WeakReference is cleared at the next GC; SoftReference is cleared only when memory is low

Explanation

WeakReference objects are eligible for collection as soon as no strong references exist. SoftReference objects are kept alive until the JVM needs memory, making them suitable for caches.

13

What is the Happens-Before relationship in Java concurrency?

B

Correct Answer

A JMM guarantee that all effects of action A are visible to action B if A happens-before B

Explanation

The JMM's happens-before relation (§17.4.5) defines when one action's results are guaranteed visible to another — established by synchronized, volatile, thread start/join, etc.

14

What is inlining in JIT compilation?

B

Correct Answer

Replacing a method call site with the method body to eliminate call overhead and enable further optimizations

Explanation

Inlining is the JIT's most impactful optimization. It removes call overhead and exposes the inlined code to further optimizations like constant folding and escape analysis.

15

What is the purpose of the java.lang.instrument package?

B

Correct Answer

To allow Java agents to transform class bytecode at load time via a ClassFileTransformer

Explanation

Java agents use Instrumentation.addTransformer() to hook into class loading and modify bytecode before the class is defined, powering APM tools, coverage agents, and mocking frameworks.

16

What does the Sealed Classes feature (Java 17) restrict?

B

Correct Answer

Which classes or interfaces may directly extend or implement a sealed type

Explanation

A sealed class uses permits to explicitly list subclasses. This enables exhaustive pattern matching and makes class hierarchies easier to reason about.

17

What is a record in Java 14+?

B

Correct Answer

A concise immutable data carrier that auto-generates constructor, accessors, equals, hashCode, and toString

Explanation

Records (GA in Java 16) reduce boilerplate for simple data carriers. Their components are final and exposed as accessor methods matching the component name.

18

What is the difference between checked and unchecked exceptions from an API design perspective?

B

Correct Answer

Checked exceptions represent recoverable conditions callers are expected to handle; unchecked represent programming errors

Explanation

Effective Java (Bloch) advises using checked exceptions for conditions a caller can reasonably recover from and runtime exceptions for programming errors or precondition violations.

19

What is the CompletableFuture and how does it differ from Future?

B

Correct Answer

CompletableFuture supports non-blocking composition (thenApply, thenCompose); Future only offers blocking get()

Explanation

CompletableFuture (Java 8) enables asynchronous pipelines with thenApply, thenCompose, whenComplete, etc. Future.get() blocks the calling thread until completion.

20

What is the purpose of the --add-opens JVM flag?

B

Correct Answer

To relax the Java module system's encapsulation, granting deep reflective access to a module's non-public members

Explanation

The JPMS (introduced in Java 9) encapsulates internals. --add-opens module/package=ALL-UNNAMED grants reflective access, commonly needed for legacy frameworks that rely on internal APIs.