Java333 questions in the bank

Java Quiz: Test Your Java Knowledge

Pick how many questions you want, choose a difficulty and go. You'll see why each answer is right or wrong, then you can retry to beat your score.

Questions
Difficulty
Topic
Mode
  1. What must every Java statement end with?

    • A colon
    • A full stop
    • Nothing
    • A semicolon
  2. Which tool turns a .java file into bytecode?

    • java
    • javac
    • jvm
    • jar
  3. If your file is called Game.java, what must the public class be called?

    • Game
    • Main
    • game
    • Any name
  4. What does 7 / 2 give in Java?

    • 3.5
    • 4
    • 3
    • An error
  5. What must the file containing public class Main be called?

    • Main.java
    • main.java
    • Main.class
    • Any name
  6. Which part produces a value?

    • tickets - sold
    • The closing class brace
    • A comment
  7. What determines an if block boundary?

    • Indentation
    • Braces
    • The filename
  8. What does print add after its argument?

    • Nothing automatically
    • Always a newline
    • Always a space
  9. What does %.2f control?

    • Two fractional digits in the displayed number
    • The number stored in the variable
    • Two integers
  10. Which comment supports generated API documentation?

    • /** ... */
    • // ...
    • A printed string
  11. Can ordinary block comments nest?

    • No
    • Yes, without limits
    • Only inside main
  12. Which keyword makes a variable impossible to change?

    • static
    • final
    • const
    • fixed
  13. How is a single character written in Java?

    • "A"
    • A
    • (A)
    • 'A'
  14. Why does String start with a capital letter?

    • It's a class, not a primitive type
    • It's a constant
    • All types start with a capital letter
    • It's a mistake that Java allows
  15. Which line correctly turns the text "25" into the number 25?

    • int n = (int) "25";
    • int n = Integer.parseInt("25");
    • int n = "25".toInt();
    • int n = String.parse("25");
  16. Which keyword makes a variable's value unchangeable?

    • final
    • static
    • const
    • fixed
  17. Which identifier is valid?

    • 2items
    • item-count
    • itemCount2
  18. What does final guarantee for an array variable?

    • The reference cannot be reassigned
    • Every element is immutable
    • The array has no elements
  19. How many primitive types does Java have?

    • Eight
    • Seven
    • Nine
  20. What does 7 / 2 evaluate to with int operands?

    • 3
    • 3.5
    • 4
  21. What is inferred for var count = 6?

    • int
    • Object
    • A changing dynamic type
  22. What does (int) -7.9 produce?

    • -7
    • -8
    • A rounded value chosen randomly
  23. When is a && b true?

    • When both are true
    • When either is true
    • When both are false
  24. Which expression includes ages 18 through 65?

    • age >= 18 && age <= 65
    • age > 18 && age < 65
    • age >= 18 || age <= 65
  25. What does % calculate?

    • A percentage
    • Division with decimals
    • A power
    • The remainder after division
  26. What is (int) 7.9?

    • 7
    • 8
    • 7.9
    • An error
  27. What does Math.pow(3, 2) return?

    • 6
    • 9.0
    • 9
    • 8.0
  28. What does count++ do?

    • Doubles count
    • Adds count to itself
    • Compares count with one
    • Adds one to count
  29. What happens when an int goes past its maximum value?

    • Java throws an exception
    • It becomes a long
    • It wraps round to a large negative number
    • It stays at the maximum
  30. Which operation groups first in 2 + 3 * 4?

    • Multiplication
    • Addition
    • Assignment
  31. When does false && right skip right?

    • Always
    • Only for numeric right operands
    • Never
  32. Which package contains the Scanner class?

    • java.io
    • java.lang
    • java.input
    • java.util
  33. What does nextInt() return?

    • A String
    • A double
    • A char
    • An int
  34. What happens if the user types abc when nextInt() is waiting?

    • It throws an InputMismatchException
    • It returns 0
    • It returns -1
    • It waits forever
  35. What does %d mean in a printf template?

    • A decimal number with two places
    • A date
    • A whole number
    • A double quote
  36. What does hasNextInt() do?

    • Reads the next int
    • Checks whether the next input is a valid int, without reading it
    • Skips the next int
    • Converts the input to an int
  37. What does next read by default?

    • One whitespace-delimited token
    • An entire line including spaces
    • Every remaining line
  38. Does hasNextInt consume the token?

    • No
    • Yes
    • Only when invalid
  39. What is the type of each args element?

    • String
    • int whenever it contains digits
    • char[]
  40. What must happen before reading args[0] when input may be absent?

    • Check that the array has an element
    • Cast args to int
    • Print every argument twice
  41. What index does the first character of a Java String have?

    • 1
    • 0
    • -1
    • It depends on the length
  42. What does it mean that strings are immutable?

    • They can't be printed
    • They can only hold letters
    • They can't be compared
    • Once created they never change; methods return new strings
  43. What does "hello".charAt(1) return?

    • 'e'
    • "h"
    • "e"
    • 'h'
  44. When should you use StringBuilder?

    • For every string
    • When comparing strings
    • When building a string from many pieces, for example in a loop
    • When splitting text
  45. What does "Zoo".compareTo("apple") return?

    • A negative number, because capital letters sort before lower-case ones
    • 0
    • A positive number
    • An error
  46. Which method compares String content?

    • equals
    • == in every situation
    • A numeric cast
  47. What does "Count: " + 2 + 3 produce?

    • Count: 23
    • Count: 5
    • A compilation error
  48. Which specifier is for a whole number?

    • %s
    • %f
    • %n
    • %d
  49. What's the difference between printf and String.format?

    • There's none
    • String.format only works with numbers
    • printf prints immediately; String.format returns a String
    • printf can't use %d
  50. What does %05d do to the number 7?

    • 7.00000
    • 00007
    • 70000
    • 5
  51. How do you print a percent sign in a format string?

    • \%
    • %%
    • %p
    • "%"
  52. What does a text block do with the indentation shared by all its lines?

    • Keeps it
    • Converts it to tabs
    • Causes a compile error
    • Removes it
  53. Where does the condition of an if statement go?

    • In curly braces
    • After a colon
    • In round brackets
    • In square brackets
  54. How should you check whether two Strings contain the same text?

    • a == b
    • a.equals(b)
    • a = b
    • a.compare(b)
  55. What does !true evaluate to?

    • false
    • true
    • 0
    • An error
  56. In a switch statement, when does default run?

    • Always, after the matching case
    • When none of the cases match
    • Before any case
    • Only for numbers
  57. Why compare Strings with .equals() instead of ==?

    • == is slower
    • equals ignores capitals
    • == doesn't compile with Strings
    • == checks whether they're the same object, not whether the text matches
  58. How many matching branches can an else-if chain execute?

    • One
    • Every true branch
    • None even if true
  59. What does if (ready); introduce?

    • An empty controlled statement
    • A required separator
    • An else branch
  60. What runs when no case matches?

    • The first case
    • Nothing ever
    • The default case
    • The last case
  61. Do arrow cases (case x ->) fall through?

    • No, they never fall through
    • Yes, always
    • Only without default
    • Only for strings
  62. Why must a switch expression usually have a default?

    • Style rules
    • It must produce a value for every possible input
    • Java runs default first
    • To add a break
  63. How do you match "Sat" and "Sun" in one arrow case?

    • case "Sat" || "Sun" ->
    • case ["Sat", "Sun"] ->
    • case "Sat" and "Sun" ->
    • case "Sat", "Sun" ->
  64. Which situation suits if-else better than switch?

    • Choosing a menu option by number
    • Handling the days of the week
    • Giving grades based on score ranges like 70 and above
    • Reacting to an enum value
  65. Which keyword supplies a value from a switch-expression block?

    • yield
    • continue
    • package
  66. Do arrow rules fall through automatically?

    • No
    • Yes
    • Only when printing
  67. What is the index of the first element of a Java array?

    • 1
    • 0
    • -1
    • It depends on the type
  68. What does continue do in a loop?

    • Skips the rest of this pass and starts the next one
    • Ends the loop
    • Restarts the loop from the beginning
    • Pauses the program
  69. How do you get the number of elements in an array named items?

    • items.size()
    • items.count
    • items.length
    • length(items)
  70. What is the last value of i printed by for (int i = 0; i < 10; i += 3) System.out.println(i);?

    • 6
    • 10
    • 12
    • 9
  71. How is a do-while loop different from a while loop?

    • It's faster
    • Its body always runs at least once
    • It can't use break
    • It counts automatically
  72. Which loop checks its condition after the first body execution?

    • do-while
    • while
    • Basic for
  73. What values does i take inside for (int i = 0; i < 3; i++)?

    • 0, 1, 2
    • 1, 2, 3
    • 0, 1, 2, 3
  74. Which loop is convenient when only element values are needed?

    • Enhanced for
    • An unrelated empty while
    • A loop requiring a nonexistent index
  75. What does assigning to an enhanced-loop int variable change?

    • Only the local variable
    • The original array element automatically
    • The array length
  76. Which keyword skips only the current iteration?

    • continue
    • break
    • return from the method
  77. What does an ordinary break leave in nested loops?

    • The innermost loop
    • Every enclosing loop
    • Only the current if block
  78. What does void mean in a method declaration?

    • The method doesn't return a value
    • The method is empty
    • The method can't have parameters
    • The method is private
  79. What is method overloading?

    • Calling a method too many times
    • Several methods with the same name but different parameter lists
    • A method that calls itself
    • A method with too many lines
  80. Where must methods be declared?

    • Inside main
    • Outside any class
    • Inside a class, outside other methods
    • In a separate file only
  81. What happens to code after a return statement in the same block?

    • It runs after returning
    • It runs first
    • It runs only for void methods
    • It never runs, and Java reports it as unreachable
  82. What does void mean in a method declaration?

    • The method doesn't return a value
    • The method is empty
    • The method can't be called
    • The method is private
  83. How does Java pass arguments?

    • By value
    • By reference for every object
    • By parameter name
  84. Which declaration returns no value?

    • void show()
    • int show()
    • String show()
  85. Which change can create a valid overload?

    • Changing the parameter count
    • Changing only the return type
    • Changing only a parameter name
  86. What does return; do inside a void method?

    • Ends that method call
    • Leaves only the current if block
    • Repeats the call
  87. Where is a local declared inside an if block available?

    • Within its block after declaration
    • Every method in the class
    • All source files
  88. What does this.name identify when a parameter is also named name?

    • The instance field
    • The parameter
    • An unrelated local
  89. What prevents further recursive calls for the smallest input?

    • A base case
    • A class filename
    • An output label
  90. Does Java guarantee tail-call optimization?

    • No
    • Yes for every recursive method
    • Only when printing
  91. What is the last valid index of an array with 10 elements?

    • 9
    • 10
    • 11
    • 1
  92. What is the default value in a new String[] array?

    • ""
    • "null"
    • 0
    • null
  93. Which method turns an array into readable text?

    • a.toString()
    • Arrays.toString(a)
    • String.valueOf(a)
    • a.print()
  94. Can the size of a Java array change after it's created?

    • Yes, with add()
    • Only for int arrays
    • Only if it's empty
    • No, its length is fixed
  95. Why doesn't for (int s : scores) s *= 2; double the array's values?

    • Enhanced for loops can't do maths
    • scores must be final
    • s is a copy of each value, so changing it doesn't affect the array
    • It only works on ArrayList
  96. For an array of length four, what is the last valid index?

    • 3
    • 4
    • 5
  97. What does assigning to an enhanced-for int variable change?

    • Only that local loop variable
    • The current array element automatically
    • The array length
  98. What does Arrays.equals compare?

    • Corresponding element values
    • Only reference identity
    • Only array lengths
  99. Which positions does sort(array, 1, 4) include?

    • 1, 2 and 3
    • 1, 2, 3 and 4
    • Only 4
  100. Which keyword creates a new object?

    • new
    • create
    • make
    • object
  101. What is special about a constructor?

    • It returns the object with return
    • It has the same name as the class and no return type
    • It must be static
    • It can only take one parameter
  102. Why make fields private?

    • To make the program faster
    • So other code must use methods, which can check values before changing them
    • Because Java requires it
    • To hide them from the compiler
  103. What does this refer to inside an instance method?

    • The class itself
    • The main method
    • The previous object created
    • The object the method was called on
  104. What does this.name = name; do in a constructor?

    • Copies the parameter into the object's field with the same name
    • Compares two names
    • Creates a new object
    • Prints the name
  105. Why should a member's borrowed count usually be an instance field?

    • Each member needs an independent count
    • An instance field can never change
    • Static fields cannot store integers
  106. Two new Card objects have visits equal to zero. Are they identical objects?

    • No, they are distinct instances
    • Yes, equal field values make identity equal
    • Only after their fields are printed
  107. Why validate a negative addition before changing a tank field?

    • To preserve the previous state when rejecting the input
    • To make the field local
    • To prevent all future additions
  108. What is true about final and static?

    • They express different restrictions and can be combined
    • final always means class-wide ownership
    • static always makes an object immutable
  109. What does this(title, 1) do in a constructor?

    • Delegates to another constructor of the same object
    • Creates a second object with new
    • Calls a static method named this
  110. For these Java 17 examples, where must this(...) appear?

    • As the first constructor statement
    • After all field assignments
    • Only inside main
  111. Which Java 17 constructor body uses legal delegation?

    • A body whose first statement is this(10);
    • A body that prints a message and then calls this(10);
    • An instance method that calls this(10);
  112. What does record(this) pass to its method parameter?

    • A copied reference value identifying the current object
    • A newly cloned object with separate fields
    • The class name as a String
  113. Which access level is used when a member has no access keyword?

    • Package access
    • public
    • protected
  114. Can an ordinary top-level class be private?

    • No, it can be public or have package access
    • Yes, if main is public
    • Yes, if it is final
  115. What does List.copyOf protect in this roster?

    • The snapshot's structure against caller mutation
    • Every field of any possible element object
    • The original ArrayList from all changes
  116. Does a public unrestricted setter always preserve encapsulation?

    • No, it can bypass the object's rules
    • Yes, because the field remains private
    • Only if the setter returns void
  117. What does Outer.this identify?

    • The enclosing Outer instance
    • The anonymous class's constructor
    • A static class variable named Outer
  118. Why prefer a static nested helper when no outer state is needed?

    • It avoids an unnecessary enclosing-instance association
    • It automatically makes all helper methods synchronized
    • It permits arbitrary local captures
  119. Does java.util.* include java.util.concurrent types?

    • No
    • Yes recursively
    • Only when main is static
  120. Where should a classpath root point for packaged output?

    • Above the package directory tree
    • Inside the last package directory
    • At the Java source method
  121. Why save the result of strip?

    • String is immutable and strip returns a value
    • strip changes only static strings
    • strip requires a mutable array
  122. Which method interprets its pattern as a regular expression?

    • replaceAll
    • replace with CharSequence arguments
    • contains
  123. What does capacity measure?

    • Available storage before expansion is needed
    • The number of currently visible characters only
    • The maximum permitted lifetime length
  124. Which class is normally preferable for a local unshared builder?

    • StringBuilder
    • StringBuffer because every call must synchronize
    • String because append mutates it
  125. How should two non-null Integer contents be compared?

    • With equals
    • By assuming == always compares numeric content
    • By comparing their source filenames
  126. What does Integer.parseInt return?

    • A primitive int
    • An Integer array
    • A nullable String
  127. What's the main advantage of ArrayList over an array?

    • It's always faster
    • It can hold primitive ints directly
    • It can grow and shrink as items are added and removed
    • It doesn't need indexes
  128. What is Integer?

    • A keyword for whole numbers
    • The wrapper class for int, used in collections
    • A kind of ArrayList
    • A method that converts strings
  129. Why write List<String> list = new ArrayList<>(); instead of ArrayList<String> list?

    • It's required
    • It makes the list faster
    • It allows duplicate items
    • Coding to the List interface makes it easy to change the implementation later
  130. What does list.indexOf("x") return if "x" isn't in the list?

    • -1
    • 0
    • null
    • An exception
  131. What does Comparator.comparing(Product::price) do?

    • Sorts products alphabetically
    • Removes products with no price
    • Creates a rule that compares products by their price
    • Finds the cheapest product
  132. Why can a get(i) loop be slow on LinkedList?

    • Each indexed lookup may traverse nodes
    • LinkedList rejects loops
    • Every element is automatically sorted
  133. Which interface do both ArrayList and LinkedList implement?

    • List
    • Map
    • SortedSet
  134. What does map.get(key) return when the key doesn't exist?

    • null
    • 0
    • An empty string
    • It throws an exception
  135. What's the most efficient way to loop over keys and values together?

    • keySet() and get() for each key
    • values()
    • entrySet()
    • A normal for loop with an index
  136. Can a HashMap contain the same key twice?

    • Yes
    • Only for String keys
    • Only if the values differ
    • No, putting an existing key replaces its value
  137. What does merge(word, 1, Integer::sum) do?

    • Removes the word
    • Sets the count to 1 for a new word, or adds 1 to an existing count
    • Joins two maps
    • Sorts the map
  138. When should you use a LinkedHashMap instead of a HashMap?

    • When you need entries in the order they were inserted
    • When keys must be sorted
    • When values are numbers
    • When the map is very small
  139. What determines TreeMap key order?

    • Natural order or its supplied comparator
    • Insertion order in all cases
    • Value hashes
  140. What does entrySet provide?

    • A backed view of key-value entries
    • A deep copy of every key and value
    • Only sorted values
  141. Why declare List<String> names = new ArrayList<>(); rather than ArrayList<String> names?

    • Code depends only on the List interface, so the class can be swapped easily
    • It's faster
    • ArrayList can't be a variable type
    • It saves memory
  142. Which collection keeps items in the order they were added, without duplicates?

    • HashSet
    • LinkedHashSet
    • TreeSet
    • PriorityQueue
  143. Which method removes and returns the front of a Queue?

    • peek()
    • push()
    • poll()
    • get()
  144. What does Collections.frequency(list, "a") return?

    • Whether "a" is in the list
    • The index of "a"
    • A sorted list
    • How many times "a" appears in the list
  145. Which class does Java's documentation recommend instead of Stack?

    • ArrayDeque
    • LinkedList
    • Vector
    • PriorityQueue
  146. What does new ArrayList<>(source) copy?

    • The collection structure and element references
    • Every element's complete object graph
    • The source's later structural changes
  147. Does List.of support add?

    • No, it is unmodifiable
    • Yes, unless it contains strings
    • Only before get is called
  148. What does adding an existing equal element return?

    • false
    • true
    • The existing index
  149. Why avoid mutating hash-defining fields after insertion?

    • The stored bucket may no longer match the element's hash
    • Sets cannot contain objects
    • Every mutation automatically removes the element
  150. When can supported remove be called?

    • After next, once for that returned element
    • Before the first next
    • Repeatedly without advancing
  151. Does fail-fast iteration guarantee thread safety?

    • No
    • Yes for every ArrayList
    • Only when hasNext is called twice
  152. Why use Integer.compare instead of a-b?

    • Subtraction can overflow and give a wrong sign
    • compare always returns an array
    • Subtraction is forbidden in methods
  153. What does comparingInt(...).reversed().thenComparing(...) reverse?

    • The primary numeric ordering only
    • Every later tie-breaker automatically
    • The original source list before comparison
  154. How many classes can a Java class extend directly?

    • One
    • Two
    • As many as you like
    • None
  155. Where must super(...) appear in a constructor?

    • Anywhere
    • As the first statement
    • As the last statement
    • Outside the constructor
  156. Which class does every Java class ultimately extend?

    • Object
    • Main
    • Class
    • Base
  157. What is polymorphism?

    • Having many constructors
    • Copying a class
    • Calling the same method on different subclass objects and getting each one's own behaviour
    • Hiding fields
  158. What does final on a method mean?

    • It can't be called
    • Subclasses can't override it
    • It runs last
    • It returns a constant
  159. Which relationship usually suggests composition?

    • A report uses a printer
    • A savings account satisfies an account contract
    • A specialized label satisfies a label contract
  160. How many direct superclasses can a Java class extend?

    • One
    • Any number
    • One per constructor
  161. Can an override reduce public access to private?

    • No
    • Yes if the return type is unchanged
    • Yes if @Override is omitted
  162. Why can one Channel array hold Email and Text?

    • Both objects implement the Channel contract
    • The array ignores element types
    • Interfaces automatically copy all objects
  163. What is an interface in Java?

    • A class with no methods
    • A graphical window
    • A type of loop
    • A contract of methods that implementing classes must provide
  164. Can you write new Comparable()?

    • Yes
    • Only inside a list
    • No, an interface can't be instantiated directly
    • Only with generics
  165. What does compareTo return when two objects are equal in order?

    • true
    • 0
    • 1
    • -1
  166. What is a default method?

    • A method that runs automatically
    • The first method in a class
    • A method with no parameters
    • An interface method with a body that implementing classes inherit
  167. When is an abstract class a better choice than an interface?

    • When closely related classes share state and code but must each complete a few methods
    • When unrelated classes need the same ability
    • When a class needs several parents
    • Never
  168. What is a useful reason to choose an interface?

    • Unrelated classes can share a capability contract
    • Interfaces store independent instance fields
    • An interface permits direct new of the incomplete type
  169. Which type can be instantiated in the reading example?

    • Temperature
    • Reading
    • The abstract describe method
  170. What is an enum?

    • A list that can grow
    • A type with a fixed set of named constants
    • A kind of loop
    • A number format
  171. Can an enum have fields and methods?

    • No
    • Only static methods
    • Yes, plus a constructor called once per constant
    • Only in Java 21
  172. What happens with Size.valueOf("HUGE") if HUGE isn't a constant?

    • It returns null
    • It returns SMALL
    • It creates HUGE
    • It throws IllegalArgumentException
  173. Inside switch (size), how do you write the case for Size.SMALL?

    • case SMALL ->
    • case Size.SMALL ->
    • case "SMALL" ->
    • case 0 ->
  174. Why avoid storing ordinal() values permanently?

    • They're too large
    • They're private
    • They change every time the program runs
    • Reordering or inserting constants changes the numbers, breaking saved data
  175. What happens for State.valueOf("open") here?

    • IllegalArgumentException
    • It returns OPEN automatically
    • It returns null
  176. What does EXPRESS(2) initialize?

    • The EXPRESS instance's days field through its constructor
    • The ordinal of EXPRESS
    • Every instance's shared static days field
  177. What problem do generics solve?

    • Slow loops
    • Type errors that would otherwise only appear at run time, plus the need for casts
    • Memory leaks
    • Formatting numbers
  178. Why can't you write List<double>?

    • double is too large
    • Lists can't hold numbers
    • Generics only work with object types; use Double
    • You need a cast
  179. What does <T extends Number> mean?

    • T can be Number or any subclass, such as Integer or Double
    • T must be exactly Number
    • T extends the Number class at run time
    • T can be any type
  180. What does "producer extends, consumer super" describe?

    • Inheritance rules
    • Thread safety
    • Constructor order
    • When to use ? extends (reading) and ? super (writing) wildcards
  181. Why can't you write new T() inside a generic class?

    • T is always abstract
    • Constructors can't be generic
    • Type erasure removes T at run time, so Java doesn't know which class to create
    • It's only allowed in records
  182. Can a generic argument be int?

    • No, use Integer
    • Yes when the diamond is empty
    • Only inside a private class
  183. Why avoid raw Box variables?

    • They lose useful generic checks and can introduce unchecked operations
    • They are always faster
    • They create a different constructor
  184. Which keyword signals an exception yourself?

    • throws
    • catch
    • raise
    • throw
  185. What's the difference between throw and throws?

    • They're the same
    • throw raises an exception; throws declares that a method may raise one
    • throws raises an exception; throw declares one
    • throw is for checked exceptions only
  186. When does a finally block run?

    • Only after an exception
    • Only without an exception
    • In both cases, even after a return
    • Only in main
  187. Which class do unchecked exceptions extend?

    • RuntimeException
    • Error
    • IOException
    • Throwable directly
  188. Why must specific catch blocks come before general ones?

    • It's faster
    • Java sorts them automatically
    • General catches only run last anyway
    • The first matching catch wins, so a general one first would make the specific one unreachable
  189. What is an exception cause?

    • The earlier failure leading to this failure
    • Always its superclass
    • Always its message string
  190. Where should a useful catch normally be placed?

    • At a boundary that understands recovery or reporting
    • Around every statement blindly
    • Only inside the constructor
  191. What does throw do?

    • Raises a specific exception object now
    • Lists possible failures only
    • Automatically retries the operation
  192. Why avoid returning from finally?

    • It can replace a result or hide a failure
    • Java never permits it
    • It always doubles the result
  193. Why are IOException and NumberFormatException valid multi-catch alternatives?

    • Neither is a subtype of the other
    • Both are always checked
    • They have identical class names
  194. What should a translated exception retain?

    • The original cause when useful
    • Only the method filename
    • No contextual information
  195. What remains primary when both body and close throw?

    • The body exception
    • The close exception always
    • No exception
  196. Does a variable remaining in scope mean its reader is open?

    • No
    • Always
    • Only for StringReader
  197. What does the second deleteIfExists return in the example?

    • false
    • true
    • The deleted file contents
  198. When is reading the entire file into a String inappropriate?

    • When the input can be too large for the memory policy
    • Whenever UTF-8 is used
    • Only when the filename ends in txt
  199. Why is the directory result sorted explicitly?

    • Files.list does not promise alphabetic encounter order
    • Creation order is always alphabetical
    • Streams cannot contain Path values
  200. Does Files.exists reserve the entry for a later read?

    • No
    • Yes
    • Only for regular files
  201. Why does InputStream.read return int?

    • To represent byte values zero through 255 and a separate minus-one end marker
    • Because a file cannot contain zero
    • Because it always reads four bytes
  202. A buffered read returns three bytes into an eight-byte buffer. How many should be written?

    • Three
    • Eight
    • Zero until the buffer is full
  203. Does append mode add a newline automatically?

    • No
    • Yes, for every file extension
    • Only when the appended byte is positive
  204. Why reject a source path equal to the destination?

    • Opening the destination can erase the source before copying
    • Input streams sort identical filenames
    • Java prohibits reading any temporary file
  205. Does readLine keep the original newline character in the returned String?

    • No
    • Always
    • Only for UTF-8
  206. Why must a lines stream be consumed before its reader closes?

    • It obtains lines lazily from that reader
    • It copies the whole file immediately
    • It automatically opens another file
  207. Does declaring the same serialVersionUID prove every class edit is safe?

    • No
    • Yes, regardless of field types
    • Only if the class name is short
  208. Why does the filter example reject Integer?

    • It is not the permitted Note class
    • Seven cannot be stored in an Integer
    • ObjectOutputStream never writes numbers
  209. Why use writeValueAsString instead of concatenating quoted user text?

    • It escapes text and preserves JSON value types
    • It removes every property
    • It makes all Java classes safe to instantiate
  210. What should a semantic JSON round-trip test compare?

    • The meaningful parsed values
    • Only whitespace and property order
    • Only the number of source lines
  211. Which class represents a file's location?

    • File
    • Folder
    • Path
    • Location
  212. What does try-with-resources do?

    • Closes the resource automatically, even if an exception happens
    • Retries an operation
    • Opens several files at once
    • Hides exceptions
  213. Which exception means the file wasn't found?

    • FileMissingError
    • NoSuchFileException
    • NullPointerException
    • EOFException
  214. What does Files.createDirectories(Path.of("a", "b")) do?

    • Creates a file called b
    • Deletes the folders
    • Lists the folders
    • Creates folder a and folder b inside it, if they're missing
  215. Why avoid hard-coding a path like C:\Users\sam\data.csv?

    • Backslashes aren't allowed
    • Java can't read the C drive
    • That location won't exist on other people's computers or servers
    • Absolute paths are slower
  216. In LocalDate.of(2024, 3, 1), which month is it?

    • February
    • March
    • April
    • January
  217. What does MMMM show in a date pattern?

    • Minutes
    • The month number
    • Milliseconds
    • The full month name, such as July
  218. Why does d.plusDays(1) not change d?

    • It's a bug
    • plusDays needs a semicolon
    • java.time objects are immutable, so the method returns a new date
    • It only works on LocalDateTime
  219. Which exception does parsing badly formatted text throw?

    • DateTimeParseException
    • NumberFormatException
    • IOException
    • NullPointerException
  220. What does withZoneSameInstant do?

    • Changes the clock time but keeps the zone
    • Removes the time zone
    • Shows the same moment in a different time zone
    • Rounds to the nearest hour
  221. Which amount is suitable for a three-month calendar interval?

    • Period
    • Duration.ofHours(2160)
    • ZoneOffset
  222. Why inject a Clock into date-dependent code?

    • Tests can control the current instant and zone
    • It makes all dates mutable
    • It removes leap years
  223. What does filter do in a stream?

    • Changes every item
    • Keeps only the items that match a condition
    • Sorts the items
    • Counts the items
  224. What does map do in a stream?

    • Transforms each item into a new value
    • Creates a HashMap
    • Removes duplicates
    • Groups items
  225. What is String::toUpperCase?

    • A variable
    • A static import
    • A comment
    • A method reference, shorthand for s -> s.toUpperCase()
  226. Why do streams need a terminal operation?

    • For error handling
    • To close the collection
    • Streams are lazy; the pipeline only runs when a terminal operation asks for a result
    • To sort the results
  227. What does Collectors.groupingBy(Product::category, Collectors.counting()) produce?

    • A list of categories
    • A map from each category to the number of products in it
    • The total price per category
    • A sorted list of products
  228. Which interface is suitable for an operation that prints a String and returns nothing?

    • Consumer<String>
    • Predicate<String>
    • Function<String, Boolean>
  229. Why is the labels list copied into an ArrayList?

    • List.sort needs a modifiable list
    • Comparators require arrays
    • List.of cannot contain strings
  230. What is the only behavior the FareRule lambda replaces?

    • centsFor
    • unit
    • Both methods
  231. Which type avoids the Integer boxing contract for int-to-int calculations?

    • IntUnaryOperator
    • Function<Object, Object>
    • Consumer<Integer>
  232. Which reference fits a String-to-integer parser?

    • Integer::parseInt
    • String::concat
    • System.out::println
  233. What does a method reference do with exceptions thrown by its method?

    • They follow the ordinary invocation behavior
    • They are automatically converted to zero
    • They are always caught by the interface
  234. Which collector counts elements for each classification key?

    • groupingBy with counting
    • joining
    • toList alone
  235. Why should you avoid modifying the source in a pipeline?

    • Traversal requires a stable source contract
    • Streams always copy every source
    • Modification automatically sorts the source
  236. What happens when filter rejects a present value?

    • The result becomes empty
    • It returns null
    • The original value becomes an exception
  237. What is a clearer return for a successful search finding no list items?

    • An empty list
    • A null Optional
    • An Optional containing null
  238. Which API makes user search text literal?

    • Pattern.quote
    • Matcher.quoteReplacement
    • Integer.parseInt
  239. Does a match for two hour digits guarantee a valid hour?

    • No; numeric range validation is still needed
    • Yes; all two-digit numbers are hours
    • Only when find is used
  240. What makes @Label("text") shorthand valid?

    • Its required element is named value
    • All annotation elements are positional
    • The annotation has no target
  241. Does @Priority(1) automatically schedule a job?

    • No; a consumer must interpret it
    • Yes; the JVM prioritizes all annotated classes
    • Only if the class is static
  242. What is the target argument to invoke for an instance method?

    • The instance on which the method should run
    • The method name again
    • The ClassLoader only
  243. Which is preferable when the type is already known?

    • An ordinary typed method call
    • Reflection using string names for every call
    • Reading private fields first
  244. Can the same Thread object be started again after termination?

    • No
    • Yes, after join
    • Yes, if it has a new name
  245. Does join alone prevent two workers losing increments?

    • No; updates still need coordination
    • Yes; it makes every write atomic
    • Only for int fields
  246. What does join add to the counter examples?

    • It waits until both workers finish
    • It changes increments into atomic operations
    • It locks the Counter forever
  247. Which operation must a reservation lock protect?

    • The availability check and subtraction together
    • Only printing the result
    • Only reading the requested count
  248. What does shutdown do first?

    • Stop accepting new tasks
    • Erase all results
    • Immediately kill every thread
  249. What is risky in a one-worker pool?

    • A worker waiting for a child task submitted to the same pool
    • Reading a completed Future
    • Calling shutdown after results
  250. Which update safely increments a map count per key?

    • merge(key, 1, Integer::sum)
    • put(key, get(key) + 1)
    • get(key) alone
  251. When should a semaphore permit be released?

    • After successful acquisition, in cleanup
    • Before acquisition to increase capacity
    • Only when the program exits
  252. What preserves an exception for logging?

    • Passing the Throwable to log
    • Logging only getMessage
    • Discarding the cause
  253. What should come first when debugging?

    • A reproducible input and expected result
    • Renaming unrelated classes
    • Turning every log into SEVERE
  254. Which version of Java made records a standard feature?

    • Java 8
    • Java 11
    • Java 16
    • Java 21
  255. Which methods does a record generate?

    • Only a constructor
    • A constructor, accessors, equals, hashCode and toString
    • Setters and getters
    • main
  256. Can a record extend another class?

    • Yes
    • Only abstract classes
    • Only other records
    • No, but it can implement interfaces
  257. How do you "change" a value in a record?

    • Use a setter
    • Create a new record with the new value
    • Assign to the field
    • Call update()
  258. Why are records good HashMap keys?

    • Equal values give equal hash codes, and the values can't change after insertion
    • They're faster to create
    • Records are sorted
    • HashMap requires records
  259. Where do test classes go in a Maven or Gradle project?

    • src/main/java
    • The project root
    • A tests.txt file
    • src/test/java
  260. Why give assertEquals a delta when comparing doubles?

    • It makes tests faster
    • Doubles can't be compared otherwise
    • Floating point results can differ by tiny amounts
    • It's required for ints too
  261. What does assertAll do?

    • Runs several assertions and reports every failure, not just the first
    • Runs every test in the class
    • Asserts that a list contains all items
    • Skips failing assertions
  262. Which command runs the tests in a Maven project?

    • java test
    • junit run
    • javac -test
    • mvn test
  263. You've found a bug in total(). What's a good first step?

    • Delete the related tests
    • Write a test that fails because of the bug, then fix the code until it passes
    • Add a comment
    • Make the method private
  264. What does Runtime.version describe?

    • The runtime executing the program
    • The editor version
    • Only the source file age
  265. Why use javac --release 17?

    • To target Java 17 language, bytecode, and platform APIs
    • To install Java 17
    • To bypass all errors
  266. What does changing $env:Path in PowerShell affect?

    • The current session and its child processes
    • Every computer on the network
    • All stored files permanently
  267. What is the launch command for SetupCheck.class in the current directory?

    • java SetupCheck
    • java SetupCheck.class
    • javac SetupCheck.class
  268. What protects args[0] when no arguments were supplied?

    • Checking args.length
    • Adding a package statement
    • Making the variable static
  269. What does java ParcelLabel.java use on a supported JDK?

    • Source-file launching
    • A direct class-file launch
    • The jar tool
  270. What does an import change?

    • Source name resolution
    • The downloaded libraries
    • The current runtime directory
  271. Which separator joins Windows classpath entries?

    • Semicolon
    • Comma
    • A package dot
  272. What does a test-scoped dependency describe?

    • A library needed for test compilation and execution
    • A guaranteed production runtime dependency
    • An operating-system installer
  273. Why use a project wrapper?

    • To invoke a documented build-tool version
    • To remove the need for Java
    • To include all source in one class
  274. Where does ShippingFeeTest belong?

    • src/test/java
    • target only
    • The dependency cache
  275. Should one unit test rely on another having run first?

    • No
    • Yes, if names are alphabetical
    • Yes, if both pass once
  276. Which command requests local-variable debug information?

    • javac -g
    • java -jar
    • javadoc -quiet
  277. What should remain after a successful debugging fix?

    • A regression test for the failing behavior
    • Only a screenshot of variables
    • An unchanged defective comparison
  278. What does git add do?

    • Stages selected file content
    • Compiles Java source
    • Publishes every branch
  279. What makes a commit easier to review?

    • One coherent change with relevant validation
    • Every unrelated experiment at once
    • Only generated class files
  280. What happens for null in an instanceof String pattern?

    • The match is false
    • It binds an empty string
    • It throws solely because of instanceof
  281. Which finalized feature needs Java 21 rather than these Java 17 examples?

    • Type patterns in switch
    • Records
    • Instanceof patterns
  282. Which directive exposes a public API package?

    • exports
    • opens only
    • imports
  283. What does the slash separate in the -m launch form?

    • Module name and main class name
    • Two filesystem drives
    • Source and output directory
  284. What growth does repeated halving illustrate?

    • O(log n)
    • O(n squared)
    • O(n factorial)
  285. What must be specified before analyzing complexity?

    • Input size and the operation or resource being measured
    • Only the class name
    • Only whether a loop exists
  286. How is a missing library result converted to an insertion point?

    • -result - 1
    • result + 1
    • result squared
  287. Which index does the linear example return for the first eight?

    • 0
    • 2
    • -1
  288. What does LibrarySortDemo preserve?

    • The original array order
    • No duplicated values
    • Every object through deep cloning
  289. Why prefer Integer.compare to subtraction in a comparator?

    • Subtraction can overflow
    • Comparators forbid integers
    • It automatically removes ties
  290. Why does )(a fail the parentheses checker?

    • It closes before any opening is available
    • It contains a letter
    • All expressions need two pairs
  291. Which structure follows priority rather than arrival order?

    • PriorityQueue
    • ArrayDeque used as FIFO
    • An ordinary waiting line
  292. What is the cost of finding an arbitrary value in a singly linked list?

    • O(n) worst case
    • O(1) always
    • O(log n) without sorting
  293. What does head.next = head.next.next do in the constructed example?

    • Bypass the node containing five
    • Delete the head containing two
    • Reverse the entire list
  294. Which map gives insertion-oriented encounter order?

    • LinkedHashMap
    • HashMap by universal guarantee
    • ConcurrentHashMap sorted by key
  295. What distinguishes a missing HashMap entry from a stored null?

    • containsKey
    • hashCode alone
    • The filename
  296. Which traversal prints increasing keys from this strict BST?

    • Left subtree, current node, right subtree
    • Current node, left subtree, right subtree
    • Right subtree, current node, left subtree
  297. What is the worst-case search time in a plain unbalanced BST?

    • O(n)
    • Always O(log n)
    • O(1)
  298. Which method retrieves and removes the current priority head?

    • poll()
    • peek()
    • iterator()
  299. Why is changing a queued object's priority field dangerous?

    • The heap does not automatically restore ordering after the mutation
    • Java always prevents the field from changing
    • PriorityQueue turns the object into a copy
  300. Why mark a BFS vertex visited when it enters the queue?

    • To prevent another edge from enqueuing it again
    • To sort its neighbors alphabetically
    • To remove every cycle from the graph permanently
  301. When does ordinary BFS guarantee a lowest-cost path?

    • When every traversed edge has the same cost
    • For every graph with positive but unequal weights
    • Whenever the graph contains no self-loops
  302. Which operation safely stores an independent list of current selections?

    • results.add(new ArrayList<>(chosen))
    • results.add(chosen) followed by modifying chosen
    • chosen.clear() before storing its contents
  303. When is remaining < 0 a valid rejection rule for the package example?

    • When all remaining package sizes are positive
    • Even when later packages may have negative sizes
    • Only when the list is already sorted alphabetically
  304. How does memoization avoid repeated work?

    • It stores an answer under its state and reuses it
    • It removes the base cases
    • It converts every recursive problem into sorting
  305. A subproblem depends on both item index and remaining amount. What belongs in its cache key?

    • Both index and remaining amount
    • Remaining amount only
    • The total number of recursive calls so far
  306. What does a rejected room entry change?

    • Nothing in visitors
    • It increases capacity
    • It resets visitors
  307. Why does arrivals still have five entries?

    • The derived set does not modify the list
    • Sets always store five values
    • The list is automatically deduplicated
  308. Why begin the rise loop at one?

    • Index zero has no predecessor
    • Index zero is always invalid
    • Arrays start at one
  309. What supplies deterministic group-key output?

    • TreeMap ordering
    • Map by universal insertion order
    • Integer::sum alone
  310. What sum results from changing value <= 4 to value < 4?

    • 6
    • 10
    • 4
  311. Which class supplies an overridden instance method at runtime?

    • The actual object class
    • Only the variable declared type
    • The source filename
  312. What does adding directly to List.of("A", "B") do?

    • Throws UnsupportedOperationException
    • Adds a third item
    • Returns a new list automatically
  313. How must ordinary Java code handle IOException from a declared file operation?

    • Catch it or declare it
    • Ignore it because all exceptions are unchecked
    • Convert every method to static
  314. Which stream operation triggers the described traversal?

    • A terminal operation such as count
    • Every map call immediately
    • Only the package import
  315. What does join guarantee for a completed worker?

    • The caller waits for its termination
    • Every worker update was atomic
    • The worker never threw
  316. What is the best width-two sum for -5, -2, -8?

    • -7
    • 0
    • -2
  317. Which update slides a fixed-width sum?

    • Add the incoming value and subtract the outgoing value
    • Sort every window
    • Reset to zero every time
  318. Which pair has different purposes despite similar spelling?

    • final and finally
    • class and class
    • int and int
  319. Are const and goto available as ordinary identifiers?

    • No; they remain reserved
    • Yes, because their statements are unused
    • Only inside main
  320. Which method distinguishes a missing HashMap key from a stored null?

    • containsKey
    • get alone
    • size alone
  321. What must be true before Collections.binarySearch?

    • The list is sorted under the matching ordering
    • The list has no duplicates
    • The list is unmodifiable
  322. What is the last valid index of a nonempty array?

    • length - 1
    • length
    • 1 for every array
  323. What should follow a concrete error repair?

    • A regression test for the original failure
    • Only hiding the message
    • Changing every class name
  324. What does final List prevent?

    • Reassignment of that variable
    • All list element changes
    • Every call to add
  325. Does volatile count++ guarantee no lost updates?

    • No
    • Always
    • Only if count starts at zero
  326. What does the second borrowed.add("Atlas") return?

    • false
    • true
    • null
  327. What belongs in the README?

    • Java version and build and run instructions
    • Only a screenshot
    • Only generated class files
  328. Do adjacent half-open slots overlap?

    • No
    • Always
    • Only if their names match
  329. What should a storage round-trip test check?

    • Reloaded state matches the supported original state
    • Only that a file exists
    • Only the source line count
  330. Does timing out on Future.get automatically cancel the task?

    • No
    • Always
    • Only for integer results
  331. What makes the batch output order deterministic?

    • Reading the returned futures in task order
    • The pool always starts jobs alphabetically
    • Only one task exists
  332. Why does RoadmapUniqueness print two?

    • A set stores T7 once and T8 once
    • The third add always fails
    • HashSet sorts away every second item
  333. When should a learner revisit foundations?

    • When a checkpoint or project reveals a gap
    • Never after reading them once
    • Only after learning reflection
RelaxedNo clock. Read the explanation after each answer.
Timed30 seconds per question. Great for revision.
Exam modeNo feedback until the end, then a full review.

About the Java quiz

This Java quiz covers every lesson in the course, from System.out.println and variables to records, generics, streams and JUnit tests. Many questions show a short piece of Java and ask what it prints, which trains you to read code the way the compiler does. Others check the concepts behind the syntax, such as the difference between == and equals(), what static and void mean, or why int can't go in an ArrayList.

If you've only finished the beginner stage, pick Easy and a topic such as Strings or Loops. Once you've reached classes and collections, try Mixed with 10 questions, because real Java code mixes all of these ideas. When you've completed the advanced stage, use Exam mode for an honest check: the answers stay hidden until the end.

Java mistakes tend to come from a few classic traps: integer division dropping decimals, comparing strings with ==, going one step past the end of an array, forgetting super(...) in a constructor or calling nextLine() straight after nextInt(). When a question catches you out, read the explanation and revisit the linked lesson's common mistakes. Each trap you spot in a quiz is one you won't spend an evening debugging.

The question bank holds 333 questions drawn from 127 Java lessons: 132 easy, 176 medium and 25 hard. Every time you start, the quiz picks a fresh random selection that matches your settings, so retaking it is a good way to practise. After each answer, or at the end in exam mode, you'll see why the right answer is right, and every question you miss links back to the lesson that teaches it.

What the Java quiz covers