Java MCQ Questions and Answers: 40 Practice Questions with Explanations
By AbairTech Solution · For exams, interviews and self-study
Published by AbairTech Solution · Reviewed November 2026 · Editorial policy
How to use this page. The questions cover core Java plus the modern features (lambdas, streams, var and records) that current interviews expect. Try each one before opening Show answer; the explanations point out the traps examiners like to set.
Java study notes
Java is a statically typed, object-oriented language used for enterprise back ends, Android apps and large banking and telecom systems. Its motto, “write once, run anywhere”, comes from how it runs: the compiler turns .java source into .class bytecode, and the Java Virtual Machine (JVM) on each platform runs that bytecode.
Term
What it is
JVM
Runs bytecode and manages memory and garbage collection
JRE
JVM plus the standard libraries needed to run programs
JDK
JRE plus development tools such as the javac compiler
Primitives vs objects. Java has 8 primitive types (byte, short, int, long, float, double, char, boolean). Everything else, including String and arrays, is an object accessed through a reference.
== vs equals(). For objects, == compares references (are these the same object?), while equals() compares content. Always compare strings with equals().
Four OOP pillars. Encapsulation (private fields, public methods), inheritance (extends), polymorphism (overriding, decided at run time) and abstraction (abstract classes and interfaces).
Exceptions. Checked exceptions (such as IOException) must be caught or declared with throws; unchecked exceptions (RuntimeException and subclasses) need not be.
It compiles directly to machine code for every platform
It compiles to bytecode, which any platform’s JVM can run
It only runs on Windows
It is interpreted from source code each time
Show answer
Answer: B. The same .class files run on Windows, Linux or macOS. The JVM’s JIT compiler then turns hot code into fast native code.
2. Which component contains the javac compiler?
JVM
JRE
The operating system
JDK
Show answer
Answer: D – JDK. Developers install the JDK; it includes everything needed to compile, run and debug Java programs.
3. Which is the correct signature of the program entry point?
public static void main(String[] args)
public void main(String args)
static int main()
private static void Main(String[] args)
Show answer
Answer: A. It must be public (callable by the JVM) and static (no object needed). Newer Java versions add simpler entry points for small programs, but this form works everywhere.
4. How many bits does an int use in Java?
16
64
32
It depends on the platform
Show answer
Answer: C – 32. Unlike C, Java fixes primitive sizes on every platform. long is 64 bits, short 16 and byte 8.
5. What is the default value of an int field in a class?
null
0
1
It has no value and causes a compile error
Show answer
Answer: B – 0. Fields get defaults (0, false, null). Local variables do not – using one before assigning it is a compile error.
6. Which statement about String is true?
String objects are immutable
Strings are primitive types
Strings can be changed in place with setCharAt
Strings are compared with == by default
Show answer
Answer: A. Methods such as toUpperCase() return a new String. Immutability makes strings safe to share between threads and to use as map keys.
7. How should you compare the contents of two strings?
s1 == s2
s1 = s2
s1.compare(s2)
s1.equals(s2)
Show answer
Answer: D. == may work for string literals because of the string pool, but fails for strings built at run time. Use equalsIgnoreCase() to ignore case.
8. Which class is best for building a string in a loop with many appends?
String
Character
StringBuilder
Scanner
Show answer
Answer: C. Concatenating String objects in a loop creates a new object each time. StringBuilder changes one buffer. StringBuffer is the older, synchronized version.
9. Which of these is NOT a primitive type?
char
String
boolean
double
Show answer
Answer: B – String. String is a class in java.lang. Note the capital S – primitive type names are all lowercase.
10.Integer a = 1000, b = 1000; What does a == b usually return?
true, because the values are equal
A compile error
A NullPointerException
false, because == compares references and 1000 is outside the cached range
Show answer
Answer: D. Java caches Integer objects from -128 to 127, so the same test with 100 returns true. Always use equals() for wrapper objects.
Questions 11–20: object-oriented programming
11. Which practice best describes encapsulation?
Creating many subclasses
Writing all code in main
Making fields private and exposing controlled access through methods
Using static methods only
Show answer
Answer: C. A setter can then validate input, for example rejecting a negative salary.
12. Which keyword makes one class inherit from another?
extends
implements
inherits
super
Show answer
Answer: A.class Manager extends Employee. A class can extend only one class.
13. Which keyword does a class use to adopt an interface?
extends
implements
uses
interface
Show answer
Answer: B. A class can implement many interfaces: class Invoice implements Printable, Comparable<Invoice>.
14. Does Java support multiple inheritance?
Yes, a class can extend several classes
No, not in any form
Only for abstract classes
Not for classes, but a class can implement multiple interfaces
Show answer
Answer: D. This avoids the “diamond problem” of conflicting inherited state. Default methods in interfaces bring limited multiple inheritance of behaviour.
15. What is method overriding?
Two methods in one class with the same name but different parameters
Calling a method twice
A subclass providing its own version of a parent method with the same signature
Making a method private
Show answer
Answer: C. The version called is chosen at run time from the actual object type (runtime polymorphism). Option A describes overloading, decided at compile time. Use @Override so the compiler checks the signature.
16. What does final mean on a class?
The class cannot be extended
The class cannot be instantiated
All methods are static
The class is loaded first
Show answer
Answer: A. String is a final class. A final method cannot be overridden, and a final variable cannot be reassigned.
17. Which statement about abstract classes is true?
They cannot have constructors
They cannot be instantiated directly but can have both abstract and concrete methods
All their methods must be abstract
They cannot have fields
Show answer
Answer: B. Use an abstract class when subclasses share state and some code; use an interface to define a capability many unrelated classes can have.
18. A static method:
Can only be called once
Runs in a separate thread
Cannot have parameters
Belongs to the class and can be called without creating an object
Show answer
Answer: D.Math.max(a, b) is an example. Static methods cannot use this or instance fields directly.
19. What does super.calculate() do inside a subclass method?
Calls the subclass’s own calculate method recursively
Creates a parent object
Calls the parent class’s version of calculate
Makes calculate static
Show answer
Answer: C. Commonly used to extend, not replace, the parent’s behaviour. super(...) calls a parent constructor and must be the first statement.
20. Which statement about constructors is true?
A constructor has the same name as the class and no return type
A constructor must return void
Every class must declare at least two constructors
Constructors can be called like normal methods at any time
Show answer
Answer: A. If you write no constructor, Java adds a default no-argument one. Writing any constructor removes that default.
Questions 21–30: exceptions and collections
21. Which of these is a checked exception?
NullPointerException
IOException
ArithmeticException
ArrayIndexOutOfBoundsException
Show answer
Answer: B. The compiler forces you to catch or declare IOException. The others extend RuntimeException and are unchecked.
22. When does a finally block run?
Only if an exception is thrown
Only if no exception is thrown
Only if there is no return statement
Almost always – after try or catch, even if they return (unless the JVM exits)
Show answer
Answer: D. finally is for clean-up. Avoid returning from finally, as it hides exceptions.
23. What does try-with-resources do?
Automatically closes resources that implement AutoCloseable
Retries the block if it fails
Catches every exception
Runs the block in a new thread
Show answer
Answer: A.try (Connection c = ds.getConnection()) { … } closes the connection even when an exception occurs.
24. What is the difference between throw and throws?
They are the same
throws creates an exception object
throw raises an exception; throws declares in a method signature which exceptions it may raise
25. When is ArrayList usually a better choice than LinkedList?
When you insert at the start of the list constantly
When you need fast access by index, which is most of the time
When you need a thread-safe list
When the list must never contain duplicates
Show answer
Answer: B. ArrayList uses an array, so get(i) is fast, and it is cache-friendly. In practice ArrayList is the default list in Java.
26. How many null keys can a HashMap hold?
None
Unlimited
Two
One
Show answer
Answer: D – one. It can hold many null values. Hashtable and ConcurrentHashMap allow no null keys or values.
27. Which collection type does not allow duplicate elements?
Set
List
ArrayList
Queue
Show answer
Answer: A – Set. HashSet has no order, LinkedHashSet keeps insertion order and TreeSet keeps sorted order.
28. You use your own Customer class as a HashMap key. What must you override?
toString() only
compareTo() only
Both equals() and hashCode(), consistently
Nothing
Show answer
Answer: C. If two equal objects have different hash codes, the map cannot find the key. Records generate both methods automatically.
29. Removing items from an ArrayList inside a for-each loop throws which exception?
NullPointerException
ConcurrentModificationException
IllegalStateException
No exception
Show answer
Answer: B. Use Iterator.remove() or simply list.removeIf(x -> x.isExpired()).
30. What is the main benefit of generics, as in List<String>?
Faster execution
Less memory use
Automatic sorting
Type safety checked at compile time, without casts
Show answer
Answer: D. Adding an Integer to a List<String> becomes a compile error instead of a ClassCastException at run time.
Questions 31–40: lambdas, streams, threads and modern Java
31. A lambda expression can be assigned to:
A functional interface – an interface with exactly one abstract method
Any class
An int variable
An abstract class with several abstract methods
Show answer
Answer: A. Examples are Runnable, Comparator, Predicate and Function. @FunctionalInterface asks the compiler to check this.
32. For a list 1 to 6, what does list.stream().filter(n -> n % 2 == 0).count() return?
6
2
3
12
Show answer
Answer: C – 3. The even numbers are 2, 4 and 6. Streams do not change the original list.
33. What is Optional mainly used for?
Making parameters optional
Representing a value that may be absent, to avoid returning null
Speeding up streams
Creating threads
Show answer
Answer: B.findCustomer(id).orElseThrow() makes “not found” explicit. Use it for return types, not fields.
34. What is the difference between calling thread.start() and thread.run()?
There is no difference
run() creates two threads
start() runs the code in the current thread
start() creates a new thread that calls run(); calling run() directly runs it in the current thread
Show answer
Answer: D. In modern code, ExecutorService and virtual threads (Java 21) are preferred over creating Thread objects by hand.
35. What does the synchronized keyword do?
Allows only one thread at a time to run the code that holds the same lock
Makes code run faster
Runs code on every CPU core
Prevents exceptions
Show answer
Answer: A. It prevents race conditions on shared data. Classes in java.util.concurrent, such as AtomicInteger and ConcurrentHashMap, are often simpler.
36. Which statement about garbage collection is true?
You must free memory manually
System.gc() always frees memory immediately
Objects with no remaining references become eligible for automatic collection
Garbage collection only runs when the program ends
Show answer
Answer: C. System.gc() is only a request. Memory leaks are still possible if you keep references you no longer need, for example in static collections.
37. For two object references, what does == compare?
Their contents
Whether they point to the same object
Their hash codes
Their class names
Show answer
Answer: B. This is the core reason to use equals() for strings and wrapper types.
38. What is a record (standard since Java 16)?
A database row
A logging class
A mutable JavaBean
A concise, immutable data class with generated constructor, accessors, equals, hashCode and toString
Show answer
Answer: D.record Point(int x, int y) {} replaces dozens of lines of boilerplate.
39. What does var do in var list = new ArrayList<String>();?
Lets the compiler infer the local variable’s type – it is still statically typed
Makes the variable dynamically typed
Creates a global variable
Makes the variable constant
Show answer
Answer: A. var (Java 10+) works only for local variables with an initializer. The type is fixed at compile time.
40. Accessing arr[5] on an array of length 5 throws:
NullPointerException
IndexOutOfMemoryError
ArrayIndexOutOfBoundsException
Nothing; it returns 0
Show answer
Answer: C. Valid indexes are 0 to length − 1, so the last index here is 4.
What to practise next
The questions that trip people up most are 7, 10, 15 and 28 – all about equality and identity. If those were easy, you have a solid grasp of core Java. Continue with the SQL MCQs, since nearly every Java back-end role works with databases, or the JavaScript MCQs. All topics are on the Programming MCQs hub.
Need an API or back-end integration?
AbairTech builds REST APIs, integrations and business systems that connect your apps, devices and Oracle databases.
This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.
Strictly Necessary Cookies
Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.
If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.