AbairTechSolutionDIGITAL SOLUTIONS FOR A SMARTER TOMORROW

Menu

Home › Programming MCQs › Java

Java · 40 MCQs with explanations

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
1–10 Core language11–20 OOP21–30 Exceptions & collections31–40 Modern Java

Questions 1–10: JVM, data types and strings

1. What makes Java platform-independent?

  1. It compiles directly to machine code for every platform
  2. It compiles to bytecode, which any platform’s JVM can run
  3. It only runs on Windows
  4. 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?

  1. JVM
  2. JRE
  3. The operating system
  4. 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?

  1. public static void main(String[] args)
  2. public void main(String args)
  3. static int main()
  4. 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?

  1. 16
  2. 64
  3. 32
  4. 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?

  1. null
  2. 0
  3. 1
  4. 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?

  1. String objects are immutable
  2. Strings are primitive types
  3. Strings can be changed in place with setCharAt
  4. 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?

  1. s1 == s2
  2. s1 = s2
  3. s1.compare(s2)
  4. 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?

  1. String
  2. Character
  3. StringBuilder
  4. 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?

  1. char
  2. String
  3. boolean
  4. 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?

  1. true, because the values are equal
  2. A compile error
  3. A NullPointerException
  4. 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?

  1. Creating many subclasses
  2. Writing all code in main
  3. Making fields private and exposing controlled access through methods
  4. 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?

  1. extends
  2. implements
  3. inherits
  4. 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?

  1. extends
  2. implements
  3. uses
  4. interface
Show answer

Answer: B. A class can implement many interfaces: class Invoice implements Printable, Comparable<Invoice>.

14. Does Java support multiple inheritance?

  1. Yes, a class can extend several classes
  2. No, not in any form
  3. Only for abstract classes
  4. 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?

  1. Two methods in one class with the same name but different parameters
  2. Calling a method twice
  3. A subclass providing its own version of a parent method with the same signature
  4. 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?

  1. The class cannot be extended
  2. The class cannot be instantiated
  3. All methods are static
  4. 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?

  1. They cannot have constructors
  2. They cannot be instantiated directly but can have both abstract and concrete methods
  3. All their methods must be abstract
  4. 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:

  1. Can only be called once
  2. Runs in a separate thread
  3. Cannot have parameters
  4. 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?

  1. Calls the subclass’s own calculate method recursively
  2. Creates a parent object
  3. Calls the parent class’s version of calculate
  4. 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?

  1. A constructor has the same name as the class and no return type
  2. A constructor must return void
  3. Every class must declare at least two constructors
  4. 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?

  1. NullPointerException
  2. IOException
  3. ArithmeticException
  4. 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?

  1. Only if an exception is thrown
  2. Only if no exception is thrown
  3. Only if there is no return statement
  4. 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?

  1. Automatically closes resources that implement AutoCloseable
  2. Retries the block if it fails
  3. Catches every exception
  4. 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?

  1. They are the same
  2. throws creates an exception object
  3. throw raises an exception; throws declares in a method signature which exceptions it may raise
  4. throw is only for checked exceptions
Show answer

Answer: C. void read() throws IOException declares; throw new IllegalArgumentException("Bad id") raises.

25. When is ArrayList usually a better choice than LinkedList?

  1. When you insert at the start of the list constantly
  2. When you need fast access by index, which is most of the time
  3. When you need a thread-safe list
  4. 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?

  1. None
  2. Unlimited
  3. Two
  4. 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?

  1. Set
  2. List
  3. ArrayList
  4. 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?

  1. toString() only
  2. compareTo() only
  3. Both equals() and hashCode(), consistently
  4. 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?

  1. NullPointerException
  2. ConcurrentModificationException
  3. IllegalStateException
  4. 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>?

  1. Faster execution
  2. Less memory use
  3. Automatic sorting
  4. 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:

  1. A functional interface – an interface with exactly one abstract method
  2. Any class
  3. An int variable
  4. 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?

  1. 6
  2. 2
  3. 3
  4. 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?

  1. Making parameters optional
  2. Representing a value that may be absent, to avoid returning null
  3. Speeding up streams
  4. 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()?

  1. There is no difference
  2. run() creates two threads
  3. start() runs the code in the current thread
  4. 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?

  1. Allows only one thread at a time to run the code that holds the same lock
  2. Makes code run faster
  3. Runs code on every CPU core
  4. 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?

  1. You must free memory manually
  2. System.gc() always frees memory immediately
  3. Objects with no remaining references become eligible for automatic collection
  4. 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?

  1. Their contents
  2. Whether they point to the same object
  3. Their hash codes
  4. 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)?

  1. A database row
  2. A logging class
  3. A mutable JavaBean
  4. 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>();?

  1. Lets the compiler infer the local variable’s type – it is still statically typed
  2. Makes the variable dynamically typed
  3. Creates a global variable
  4. 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:

  1. NullPointerException
  2. IndexOutOfMemoryError
  3. ArrayIndexOutOfBoundsException
  4. 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.

API IntegrationMore MCQs