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.
What must every Java statement end with?
- A colon
- A full stop
- Nothing
- A semicolon
Which tool turns a .java file into bytecode?
- java
- javac
- jvm
- jar
If your file is called
Game.java, what must the public class be called?- Game
- Main
- game
- Any name
What does
7 / 2give in Java?- 3.5
- 4
- 3
- An error
What must the file containing
public class Mainbe called?- Main.java
- main.java
- Main.class
- Any name
Which part produces a value?
- tickets - sold
- The closing class brace
- A comment
What determines an if block boundary?
- Indentation
- Braces
- The filename
What does print add after its argument?
- Nothing automatically
- Always a newline
- Always a space
What does %.2f control?
- Two fractional digits in the displayed number
- The number stored in the variable
- Two integers
Which comment supports generated API documentation?
- /** ... */
- // ...
- A printed string
Can ordinary block comments nest?
- No
- Yes, without limits
- Only inside main
Which keyword makes a variable impossible to change?
- static
- final
- const
- fixed
How is a single character written in Java?
- "A"
A- (A)
- 'A'
Why does
Stringstart 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
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");
Which keyword makes a variable's value unchangeable?
- final
- static
- const
- fixed
Which identifier is valid?
- 2items
- item-count
- itemCount2
What does final guarantee for an array variable?
- The reference cannot be reassigned
- Every element is immutable
- The array has no elements
How many primitive types does Java have?
- Eight
- Seven
- Nine
What does 7 / 2 evaluate to with int operands?
- 3
- 3.5
- 4
What is inferred for var count = 6?
- int
- Object
- A changing dynamic type
What does (int) -7.9 produce?
- -7
- -8
- A rounded value chosen randomly
When is a && b true?
- When both are true
- When either is true
- When both are false
Which expression includes ages 18 through 65?
- age >= 18 && age <= 65
- age > 18 && age < 65
- age >= 18 || age <= 65
What does
%calculate?- A percentage
- Division with decimals
- A power
- The remainder after division
What is
(int) 7.9?- 7
- 8
- 7.9
- An error
What does
Math.pow(3, 2)return?- 6
- 9.0
- 9
- 8.0
What does
count++do?- Doubles count
- Adds count to itself
- Compares count with one
- Adds one to count
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
Which operation groups first in 2 + 3 * 4?
- Multiplication
- Addition
- Assignment
When does false && right skip right?
- Always
- Only for numeric right operands
- Never
Which package contains the Scanner class?
- java.io
- java.lang
- java.input
- java.util
What does
nextInt()return?- A String
- A double
- A char
- An int
What happens if the user types
abcwhennextInt()is waiting?- It throws an InputMismatchException
- It returns 0
- It returns -1
- It waits forever
What does
%dmean in a printf template?- A decimal number with two places
- A date
- A whole number
- A double quote
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
What does next read by default?
- One whitespace-delimited token
- An entire line including spaces
- Every remaining line
Does hasNextInt consume the token?
- No
- Yes
- Only when invalid
What is the type of each args element?
- String
- int whenever it contains digits
- char[]
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
What index does the first character of a Java String have?
- 1
- 0
- -1
- It depends on the length
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
What does
"hello".charAt(1)return?- 'e'
- "h"
- "e"
- 'h'
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
What does
"Zoo".compareTo("apple")return?- A negative number, because capital letters sort before lower-case ones
- 0
- A positive number
- An error
Which method compares String content?
- equals
- == in every situation
- A numeric cast
What does "Count: " + 2 + 3 produce?
- Count: 23
- Count: 5
- A compilation error
Which specifier is for a whole number?
- %s
- %f
- %n
- %d
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
What does
%05ddo to the number 7?- 7.00000
- 00007
- 70000
- 5
How do you print a percent sign in a format string?
- \%
- %%
- %p
- "%"
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
Where does the condition of an if statement go?
- In curly braces
- After a colon
- In round brackets
- In square brackets
How should you check whether two Strings contain the same text?
- a == b
- a.equals(b)
- a = b
- a.compare(b)
What does
!trueevaluate to?- false
- true
- 0
- An error
In a switch statement, when does
defaultrun?- Always, after the matching case
- When none of the cases match
- Before any case
- Only for numbers
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
How many matching branches can an else-if chain execute?
- One
- Every true branch
- None even if true
What does if (ready); introduce?
- An empty controlled statement
- A required separator
- An else branch
What runs when no case matches?
- The first case
- Nothing ever
- The default case
- The last case
Do arrow cases (
case x ->) fall through?- No, they never fall through
- Yes, always
- Only without default
- Only for strings
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
How do you match "Sat" and "Sun" in one arrow case?
- case "Sat" || "Sun" ->
- case ["Sat", "Sun"] ->
- case "Sat" and "Sun" ->
- case "Sat", "Sun" ->
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
Which keyword supplies a value from a switch-expression block?
- yield
- continue
- package
Do arrow rules fall through automatically?
- No
- Yes
- Only when printing
What is the index of the first element of a Java array?
- 1
- 0
- -1
- It depends on the type
What does
continuedo 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
How do you get the number of elements in an array named
items?- items.size()
- items.count
- items.length
- length(items)
What is the last value of
iprinted byfor (int i = 0; i < 10; i += 3) System.out.println(i);?- 6
- 10
- 12
- 9
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
Which loop checks its condition after the first body execution?
- do-while
- while
- Basic for
What values does i take inside for (int i = 0; i < 3; i++)?
- 0, 1, 2
- 1, 2, 3
- 0, 1, 2, 3
Which loop is convenient when only element values are needed?
- Enhanced for
- An unrelated empty while
- A loop requiring a nonexistent index
What does assigning to an enhanced-loop int variable change?
- Only the local variable
- The original array element automatically
- The array length
Which keyword skips only the current iteration?
- continue
- break
- return from the method
What does an ordinary break leave in nested loops?
- The innermost loop
- Every enclosing loop
- Only the current if block
What does
voidmean 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
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
Where must methods be declared?
- Inside main
- Outside any class
- Inside a class, outside other methods
- In a separate file only
What happens to code after a
returnstatement 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
What does
voidmean 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
How does Java pass arguments?
- By value
- By reference for every object
- By parameter name
Which declaration returns no value?
- void show()
- int show()
- String show()
Which change can create a valid overload?
- Changing the parameter count
- Changing only the return type
- Changing only a parameter name
What does return; do inside a void method?
- Ends that method call
- Leaves only the current if block
- Repeats the call
Where is a local declared inside an if block available?
- Within its block after declaration
- Every method in the class
- All source files
What does this.name identify when a parameter is also named name?
- The instance field
- The parameter
- An unrelated local
What prevents further recursive calls for the smallest input?
- A base case
- A class filename
- An output label
Does Java guarantee tail-call optimization?
- No
- Yes for every recursive method
- Only when printing
What is the last valid index of an array with 10 elements?
- 9
- 10
- 11
- 1
What is the default value in a new
String[]array?- ""
- "null"
- 0
- null
Which method turns an array into readable text?
- a.toString()
- Arrays.toString(a)
- String.valueOf(a)
- a.print()
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
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
For an array of length four, what is the last valid index?
- 3
- 4
- 5
What does assigning to an enhanced-for int variable change?
- Only that local loop variable
- The current array element automatically
- The array length
What does Arrays.equals compare?
- Corresponding element values
- Only reference identity
- Only array lengths
Which positions does sort(array, 1, 4) include?
- 1, 2 and 3
- 1, 2, 3 and 4
- Only 4
Which keyword creates a new object?
- new
- create
- make
- object
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
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
What does
thisrefer to inside an instance method?- The class itself
- The main method
- The previous object created
- The object the method was called on
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
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
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
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
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
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
For these Java 17 examples, where must this(...) appear?
- As the first constructor statement
- After all field assignments
- Only inside main
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);
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
Which access level is used when a member has no access keyword?
- Package access
- public
- protected
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
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
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
What does Outer.this identify?
- The enclosing Outer instance
- The anonymous class's constructor
- A static class variable named Outer
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
Does java.util.* include java.util.concurrent types?
- No
- Yes recursively
- Only when main is static
Where should a classpath root point for packaged output?
- Above the package directory tree
- Inside the last package directory
- At the Java source method
Why save the result of strip?
- String is immutable and strip returns a value
- strip changes only static strings
- strip requires a mutable array
Which method interprets its pattern as a regular expression?
- replaceAll
- replace with CharSequence arguments
- contains
What does capacity measure?
- Available storage before expansion is needed
- The number of currently visible characters only
- The maximum permitted lifetime length
Which class is normally preferable for a local unshared builder?
- StringBuilder
- StringBuffer because every call must synchronize
- String because append mutates it
How should two non-null Integer contents be compared?
- With equals
- By assuming == always compares numeric content
- By comparing their source filenames
What does Integer.parseInt return?
- A primitive int
- An Integer array
- A nullable String
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
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
Why write
List<String> list = new ArrayList<>();instead ofArrayList<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
What does
list.indexOf("x")return if "x" isn't in the list?- -1
- 0
- null
- An exception
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
Why can a get(i) loop be slow on LinkedList?
- Each indexed lookup may traverse nodes
- LinkedList rejects loops
- Every element is automatically sorted
Which interface do both ArrayList and LinkedList implement?
- List
- Map
- SortedSet
What does
map.get(key)return when the key doesn't exist?- null
- 0
- An empty string
- It throws an exception
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
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
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
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
What determines TreeMap key order?
- Natural order or its supplied comparator
- Insertion order in all cases
- Value hashes
What does entrySet provide?
- A backed view of key-value entries
- A deep copy of every key and value
- Only sorted values
Why declare
List<String> names = new ArrayList<>();rather thanArrayList<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
Which collection keeps items in the order they were added, without duplicates?
- HashSet
- LinkedHashSet
- TreeSet
- PriorityQueue
Which method removes and returns the front of a Queue?
- peek()
- push()
- poll()
- get()
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
Which class does Java's documentation recommend instead of Stack?
- ArrayDeque
- LinkedList
- Vector
- PriorityQueue
What does new ArrayList<>(source) copy?
- The collection structure and element references
- Every element's complete object graph
- The source's later structural changes
Does List.of support add?
- No, it is unmodifiable
- Yes, unless it contains strings
- Only before get is called
What does adding an existing equal element return?
- false
- true
- The existing index
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
When can supported remove be called?
- After next, once for that returned element
- Before the first next
- Repeatedly without advancing
Does fail-fast iteration guarantee thread safety?
- No
- Yes for every ArrayList
- Only when hasNext is called twice
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
What does comparingInt(...).reversed().thenComparing(...) reverse?
- The primary numeric ordering only
- Every later tie-breaker automatically
- The original source list before comparison
How many classes can a Java class extend directly?
- One
- Two
- As many as you like
- None
Where must
super(...)appear in a constructor?- Anywhere
- As the first statement
- As the last statement
- Outside the constructor
Which class does every Java class ultimately extend?
- Object
- Main
- Class
- Base
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
What does
finalon a method mean?- It can't be called
- Subclasses can't override it
- It runs last
- It returns a constant
Which relationship usually suggests composition?
- A report uses a printer
- A savings account satisfies an account contract
- A specialized label satisfies a label contract
How many direct superclasses can a Java class extend?
- One
- Any number
- One per constructor
Can an override reduce public access to private?
- No
- Yes if the return type is unchanged
- Yes if @Override is omitted
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
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
Can you write
new Comparable()?- Yes
- Only inside a list
- No, an interface can't be instantiated directly
- Only with generics
What does
compareToreturn when two objects are equal in order?- true
- 0
- 1
- -1
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
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
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
Which type can be instantiated in the reading example?
- Temperature
- Reading
- The abstract describe method
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
Can an enum have fields and methods?
- No
- Only static methods
- Yes, plus a constructor called once per constant
- Only in Java 21
What happens with
Size.valueOf("HUGE")if HUGE isn't a constant?- It returns null
- It returns SMALL
- It creates HUGE
- It throws IllegalArgumentException
Inside
switch (size), how do you write the case for Size.SMALL?- case SMALL ->
- case Size.SMALL ->
- case "SMALL" ->
- case 0 ->
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
What happens for State.valueOf("open") here?
- IllegalArgumentException
- It returns OPEN automatically
- It returns null
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
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
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
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
What does "producer extends, consumer super" describe?
- Inheritance rules
- Thread safety
- Constructor order
- When to use ? extends (reading) and ? super (writing) wildcards
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
Can a generic argument be int?
- No, use Integer
- Yes when the diamond is empty
- Only inside a private class
Why avoid raw Box variables?
- They lose useful generic checks and can introduce unchecked operations
- They are always faster
- They create a different constructor
Which keyword signals an exception yourself?
- throws
- catch
- raise
- throw
What's the difference between
throwandthrows?- 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
When does a finally block run?
- Only after an exception
- Only without an exception
- In both cases, even after a return
- Only in main
Which class do unchecked exceptions extend?
- RuntimeException
- Error
- IOException
- Throwable directly
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
What is an exception cause?
- The earlier failure leading to this failure
- Always its superclass
- Always its message string
Where should a useful catch normally be placed?
- At a boundary that understands recovery or reporting
- Around every statement blindly
- Only inside the constructor
What does throw do?
- Raises a specific exception object now
- Lists possible failures only
- Automatically retries the operation
Why avoid returning from finally?
- It can replace a result or hide a failure
- Java never permits it
- It always doubles the result
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
What should a translated exception retain?
- The original cause when useful
- Only the method filename
- No contextual information
What remains primary when both body and close throw?
- The body exception
- The close exception always
- No exception
Does a variable remaining in scope mean its reader is open?
- No
- Always
- Only for StringReader
What does the second deleteIfExists return in the example?
- false
- true
- The deleted file contents
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
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
Does Files.exists reserve the entry for a later read?
- No
- Yes
- Only for regular files
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
A buffered read returns three bytes into an eight-byte buffer. How many should be written?
- Three
- Eight
- Zero until the buffer is full
Does append mode add a newline automatically?
- No
- Yes, for every file extension
- Only when the appended byte is positive
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
Does readLine keep the original newline character in the returned String?
- No
- Always
- Only for UTF-8
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
Does declaring the same serialVersionUID prove every class edit is safe?
- No
- Yes, regardless of field types
- Only if the class name is short
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
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
What should a semantic JSON round-trip test compare?
- The meaningful parsed values
- Only whitespace and property order
- Only the number of source lines
Which class represents a file's location?
- File
- Folder
- Path
- Location
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
Which exception means the file wasn't found?
- FileMissingError
- NoSuchFileException
- NullPointerException
- EOFException
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
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
In
LocalDate.of(2024, 3, 1), which month is it?- February
- March
- April
- January
What does
MMMMshow in a date pattern?- Minutes
- The month number
- Milliseconds
- The full month name, such as July
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
Which exception does parsing badly formatted text throw?
- DateTimeParseException
- NumberFormatException
- IOException
- NullPointerException
What does
withZoneSameInstantdo?- 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
Which amount is suitable for a three-month calendar interval?
- Period
- Duration.ofHours(2160)
- ZoneOffset
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
What does
filterdo in a stream?- Changes every item
- Keeps only the items that match a condition
- Sorts the items
- Counts the items
What does
mapdo in a stream?- Transforms each item into a new value
- Creates a HashMap
- Removes duplicates
- Groups items
What is
String::toUpperCase?- A variable
- A static import
- A comment
- A method reference, shorthand for s -> s.toUpperCase()
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
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
Which interface is suitable for an operation that prints a String and returns nothing?
- Consumer<String>
- Predicate<String>
- Function<String, Boolean>
Why is the labels list copied into an ArrayList?
- List.sort needs a modifiable list
- Comparators require arrays
- List.of cannot contain strings
What is the only behavior the FareRule lambda replaces?
- centsFor
- unit
- Both methods
Which type avoids the Integer boxing contract for int-to-int calculations?
- IntUnaryOperator
- Function<Object, Object>
- Consumer<Integer>
Which reference fits a String-to-integer parser?
- Integer::parseInt
- String::concat
- System.out::println
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
Which collector counts elements for each classification key?
- groupingBy with counting
- joining
- toList alone
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
What happens when filter rejects a present value?
- The result becomes empty
- It returns null
- The original value becomes an exception
What is a clearer return for a successful search finding no list items?
- An empty list
- A null Optional
- An Optional containing null
Which API makes user search text literal?
- Pattern.quote
- Matcher.quoteReplacement
- Integer.parseInt
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
What makes @Label("text") shorthand valid?
- Its required element is named value
- All annotation elements are positional
- The annotation has no target
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
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
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
Can the same Thread object be started again after termination?
- No
- Yes, after join
- Yes, if it has a new name
Does join alone prevent two workers losing increments?
- No; updates still need coordination
- Yes; it makes every write atomic
- Only for int fields
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
Which operation must a reservation lock protect?
- The availability check and subtraction together
- Only printing the result
- Only reading the requested count
What does shutdown do first?
- Stop accepting new tasks
- Erase all results
- Immediately kill every thread
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
Which update safely increments a map count per key?
- merge(key, 1, Integer::sum)
- put(key, get(key) + 1)
- get(key) alone
When should a semaphore permit be released?
- After successful acquisition, in cleanup
- Before acquisition to increase capacity
- Only when the program exits
What preserves an exception for logging?
- Passing the Throwable to log
- Logging only getMessage
- Discarding the cause
What should come first when debugging?
- A reproducible input and expected result
- Renaming unrelated classes
- Turning every log into SEVERE
Which version of Java made records a standard feature?
- Java 8
- Java 11
- Java 16
- Java 21
Which methods does a record generate?
- Only a constructor
- A constructor, accessors, equals, hashCode and toString
- Setters and getters
- main
Can a record extend another class?
- Yes
- Only abstract classes
- Only other records
- No, but it can implement interfaces
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()
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
Where do test classes go in a Maven or Gradle project?
- src/main/java
- The project root
- A tests.txt file
- src/test/java
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
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
Which command runs the tests in a Maven project?
- java test
- junit run
- javac -test
- mvn test
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
What does Runtime.version describe?
- The runtime executing the program
- The editor version
- Only the source file age
Why use javac --release 17?
- To target Java 17 language, bytecode, and platform APIs
- To install Java 17
- To bypass all errors
What does changing $env:Path in PowerShell affect?
- The current session and its child processes
- Every computer on the network
- All stored files permanently
What is the launch command for SetupCheck.class in the current directory?
- java SetupCheck
- java SetupCheck.class
- javac SetupCheck.class
What protects args[0] when no arguments were supplied?
- Checking args.length
- Adding a package statement
- Making the variable static
What does java ParcelLabel.java use on a supported JDK?
- Source-file launching
- A direct class-file launch
- The jar tool
What does an import change?
- Source name resolution
- The downloaded libraries
- The current runtime directory
Which separator joins Windows classpath entries?
- Semicolon
- Comma
- A package dot
What does a test-scoped dependency describe?
- A library needed for test compilation and execution
- A guaranteed production runtime dependency
- An operating-system installer
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
Where does ShippingFeeTest belong?
- src/test/java
- target only
- The dependency cache
Should one unit test rely on another having run first?
- No
- Yes, if names are alphabetical
- Yes, if both pass once
Which command requests local-variable debug information?
- javac -g
- java -jar
- javadoc -quiet
What should remain after a successful debugging fix?
- A regression test for the failing behavior
- Only a screenshot of variables
- An unchanged defective comparison
What does git add do?
- Stages selected file content
- Compiles Java source
- Publishes every branch
What makes a commit easier to review?
- One coherent change with relevant validation
- Every unrelated experiment at once
- Only generated class files
What happens for null in an instanceof String pattern?
- The match is false
- It binds an empty string
- It throws solely because of instanceof
Which finalized feature needs Java 21 rather than these Java 17 examples?
- Type patterns in switch
- Records
- Instanceof patterns
Which directive exposes a public API package?
- exports
- opens only
- imports
What does the slash separate in the -m launch form?
- Module name and main class name
- Two filesystem drives
- Source and output directory
What growth does repeated halving illustrate?
- O(log n)
- O(n squared)
- O(n factorial)
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
How is a missing library result converted to an insertion point?
- -result - 1
- result + 1
- result squared
Which index does the linear example return for the first eight?
- 0
- 2
- -1
What does LibrarySortDemo preserve?
- The original array order
- No duplicated values
- Every object through deep cloning
Why prefer Integer.compare to subtraction in a comparator?
- Subtraction can overflow
- Comparators forbid integers
- It automatically removes ties
Why does )(a fail the parentheses checker?
- It closes before any opening is available
- It contains a letter
- All expressions need two pairs
Which structure follows priority rather than arrival order?
- PriorityQueue
- ArrayDeque used as FIFO
- An ordinary waiting line
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
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
Which map gives insertion-oriented encounter order?
- LinkedHashMap
- HashMap by universal guarantee
- ConcurrentHashMap sorted by key
What distinguishes a missing HashMap entry from a stored null?
- containsKey
- hashCode alone
- The filename
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
What is the worst-case search time in a plain unbalanced BST?
- O(n)
- Always O(log n)
- O(1)
Which method retrieves and removes the current priority head?
- poll()
- peek()
- iterator()
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
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
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
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
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
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
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
What does a rejected room entry change?
- Nothing in visitors
- It increases capacity
- It resets visitors
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
Why begin the rise loop at one?
- Index zero has no predecessor
- Index zero is always invalid
- Arrays start at one
What supplies deterministic group-key output?
- TreeMap ordering
- Map by universal insertion order
- Integer::sum alone
What sum results from changing value <= 4 to value < 4?
- 6
- 10
- 4
Which class supplies an overridden instance method at runtime?
- The actual object class
- Only the variable declared type
- The source filename
What does adding directly to List.of("A", "B") do?
- Throws UnsupportedOperationException
- Adds a third item
- Returns a new list automatically
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
Which stream operation triggers the described traversal?
- A terminal operation such as count
- Every map call immediately
- Only the package import
What does join guarantee for a completed worker?
- The caller waits for its termination
- Every worker update was atomic
- The worker never threw
What is the best width-two sum for -5, -2, -8?
- -7
- 0
- -2
Which update slides a fixed-width sum?
- Add the incoming value and subtract the outgoing value
- Sort every window
- Reset to zero every time
Which pair has different purposes despite similar spelling?
- final and finally
- class and class
- int and int
Are const and goto available as ordinary identifiers?
- No; they remain reserved
- Yes, because their statements are unused
- Only inside main
Which method distinguishes a missing HashMap key from a stored null?
- containsKey
- get alone
- size alone
What must be true before Collections.binarySearch?
- The list is sorted under the matching ordering
- The list has no duplicates
- The list is unmodifiable
What is the last valid index of a nonempty array?
- length - 1
- length
- 1 for every array
What should follow a concrete error repair?
- A regression test for the original failure
- Only hiding the message
- Changing every class name
What does final List prevent?
- Reassignment of that variable
- All list element changes
- Every call to add
Does volatile count++ guarantee no lost updates?
- No
- Always
- Only if count starts at zero
What does the second borrowed.add("Atlas") return?
- false
- true
- null
What belongs in the README?
- Java version and build and run instructions
- Only a screenshot
- Only generated class files
Do adjacent half-open slots overlap?
- No
- Always
- Only if their names match
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
Does timing out on Future.get automatically cancel the task?
- No
- Always
- Only for integer results
What makes the batch output order deterministic?
- Reading the returned futures in task order
- The pool always starts jobs alphabetically
- Only one task exists
Why does RoadmapUniqueness print two?
- A set stores T7 once and T8 once
- The third add always fails
- HashSet sorts away every second item
When should a learner revisit foundations?
- When a checkpoint or project reveals a gap
- Never after reading them once
- Only after learning reflection
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
Beginner
- 1Java Introduction
- 2Java Syntax and Statements Explained
- 3Java Output with print, println and printf
- 4Java Comments and Code Structure
- 5Java Variables and Data Types
- 6Java Variables, Identifiers and Constants
- 7Java Primitive Data Types Explained
- 8Java Type Casting and the var Keyword
- 9Java Boolean Values and Expressions
- 10Java Operators and Math
- 11Java Operators and Operator Precedence
- 12Java User Input
- 13Java User Input with Scanner
- 14Java Command-Line Arguments Explained
- 15Java Strings
- 16Java Strings, Concatenation and Special Characters
- 17Java String Formatting and StringBuilder
- 18Java if, else if and else
- 19Java if, else if and Nested Conditions
- 20Java switch
- 21Java switch Statements and switch Expressions
- 22Java Loops
- 23Java for, while and do-while Loops
- 24Java Nested Loops and Enhanced for Loops
- 25Java break and continue Explained
- 26Java Methods
- 27Java Methods and Parameters Explained
- 28Java Return Values and Method Overloading
- 29Java Variable Scope Explained with Examples
- 30Java Recursion Explained for Beginners
Intermediate
- 31Java Arrays
- 32Java Single and Multidimensional Arrays
- 33Java Array Operations and Sorting
- 34Java Classes and Objects
- 35Java Classes and Objects Explained
- 36Java Fields, Attributes and Methods
- 37Java Constructors and Constructor Overloading
- 38Java this Keyword Explained with Examples
- 39Java Access and Non-Access Modifiers
- 40Java Encapsulation and Validation
- 41Java Inner and Anonymous Classes
- 42Java Packages and Imports
- 43Java String Methods Reference
- 44Java StringBuilder and StringBuffer
- 45Java Wrapper Classes and Autoboxing
- 46Java ArrayList
- 47Java List, ArrayList and LinkedList
- 48Java HashMap
- 49Java HashMap, TreeMap and LinkedHashMap
- 50Java Collections
- 51Java Collections Framework Explained
- 52Java HashSet, TreeSet and LinkedHashSet
- 53Java Iterators and the Iterable Interface
- 54Java Collections Sorting and Comparators
- 55Java Inheritance
- 56Java Inheritance and the super Keyword
- 57Java Polymorphism and Method Overriding
- 58Java Interfaces and Abstract Classes
- 59Java Abstraction and Interfaces
- 60Java Enums
- 61Java Enums and Enum Constructors
- 62Java Generics
- 63Java Generics and Generic Classes
Files and I/O
- 64Java Exceptions
- 65Java Exception Types and Hierarchy Explained with Examples
- 66Java try, catch, finally and throw Explained with Examples
- 67Java Custom and Multiple Exceptions Explained with Examples
- 68Java Try-with-Resources Explained with Examples
- 69Java File Handling Explained with Examples
- 70Java Path and Files APIs Explained with Examples
- 71Java Byte Streams and Character Streams Explained
- 72Java FileInputStream and FileOutputStream Examples
- 73Java BufferedReader and BufferedWriter with Examples
- 74Java Serialization and Deserialization Explained
- 75Java JSON Processing with Jackson Examples
- 76Java File Handling
Advanced
- 77Java Dates and Times
- 78Java Date and Time API Explained with Examples
- 79Java Lambdas and Streams
- 80Java Lambda Expressions Explained with Examples
- 81Java Functional Interfaces Explained with Examples
- 82Java Method References Explained with Examples
- 83Java Stream API and Collectors Explained with Examples
- 84Java Optional Explained with Examples
- 85Java Regular Expressions Explained with Examples
- 86Java Annotations Explained with Examples
- 87Java Reflection API Explained with Examples
- 88Java Threads and Lifecycle Explained with Examples
- 89Java Synchronization and Race Conditions Explained with Examples
- 90Java ExecutorService and Thread Pools Explained with Examples
- 91Java Concurrency Utilities Explained with Examples
- 92Java Debugging and Logging Explained with Examples
Developer Tools
- 93Java Records
- 94Unit Testing with JUnit
- 95Java JDK, JRE and JVM Explained with Examples
- 96Installing Java and the JDK Explained with Examples
- 97Compiling and Running Java Programs Explained with Examples
- 98Java Classpath and Packages Explained with Examples
- 99Java Maven and Gradle Basics Explained with Examples
- 100Java Unit Testing with JUnit Explained with Examples
- 101Debugging Java Applications Explained with Examples
- 102Git for Java Projects Explained with Examples
- 103Modern Java Features Explained with Examples
- 104Java Modules Explained with Examples
Java DSA
- 105Java Time and Space Complexity Explained with Examples
- 106Java Linear and Binary Search Explained with Examples
- 107Java Sorting Algorithms Explained with Examples
- 108Java Stacks and Queues Explained with Examples
- 109Java Linked List Data Structures Explained with Examples
- 110Java Hash Tables and Hashing Explained with Examples
- 111Java Trees and Binary Search Trees with Examples
- 112Java Heaps and Priority Queues with Examples
- 113Java Graphs, Breadth-First Search and Depth-First Search
- 114Java Recursion and Backtracking with Worked Examples
- 115Java Dynamic Programming Basics with Worked Examples
Practice and Projects
- 116Java Examples Library with Explained Programs
- 117Java Exercises by Topic with Solutions
- 118Java Quizzes by Chapter with Answers
- 119Java Coding Challenges with Explained Solutions
- 120Java Keywords Reference for Java 17
- 121Java String, Math and Collection Methods Reference
- 122Common Java Errors and How to Fix Them
- 123Java Interview Questions with Explained Answers
- 124Beginner Java Projects Explained with Examples
- 125Intermediate Java Projects Explained with Examples
- 126Advanced Java Projects Explained with Examples
- 127Java Learning Roadmap and Study Plan Explained with Examples