Java Exercises with Answers
Practise Java with 329 interactive exercises: multiple choice, fill-in-the-blank, output prediction and debugging. Every exercise gives instant feedback, a hint and the full solution.
Topic All topics Introduction Syntax and Statements Output: print() vs. println() Comments and Code Structure Variables & Data Types Variables, Identifiers and Constants Primitive Data Types Type Casting and var Boolean Expressions Operators & Math Operators and Precedence User Input (Scanner) User Input with Scanner Command-Line Arguments Strings Strings, Concatenation and Escapes Formatting & StringBuilder if / else if, else if and Nested Conditions switch & Switch Expressions switch Expressions and Statements Loops for, while and do-while Loops Nested and Enhanced for Loops break and continue Methods Methods and Parameters Return Values and Method Overloading Variable Scope Recursion: Base Cases and Calls Arrays Single and Multidimensional Arrays Array Operations and Sorting Classes & Objects Classes and Objects Explained Fields, Attributes and Methods Constructors and Constructor Overloading this Keyword Access and Non-Access Modifiers Encapsulation and Validation Inner and Anonymous Classes Packages and Imports String Methods Reference StringBuilder and StringBuffer Wrapper Classes and Autoboxing ArrayList List, ArrayList and LinkedList HashMap & HashSet HashMap, TreeMap and LinkedHashMap Collections Collections Framework Explained HashSet, TreeSet and LinkedHashSet Iterators and the Iterable Interface Collections Sorting and Comparators Inheritance Inheritance and the super Keyword Polymorphism and Method Overriding Interfaces & Abstract Abstraction and Interfaces Enums Enums and Enum Constructors Generics Generics and Generic Classes Exceptions Exception Types and Hierarchy try, catch, finally, throw and throws Custom Exceptions and Multi-Catch Try-with-Resources File Handling: Create, Read, Write, Delete Path and Files APIs Byte Streams and Character Streams FileInputStream and FileOutputStream BufferedReader and BufferedWriter Serialization and Deserialization JSON Processing in Java Files & I/O Dates & Times Date and Time API: java.time Lambdas & Streams Lambda Expressions Functional Interfaces Method References Stream API: map, filter and reduce Optional: Handling Missing Values Regular Expressions Annotations Explained Reflection API Multithreading and Thread Lifecycle Synchronization and Race Conditions ExecutorService and Thread Pools Concurrency Utilities Debugging and Logging Basics Records Unit Testing (JUnit) JDK, JRE and JVM Explained Installing Java and Setting Up the JDK Compiling and Running Java Programs Classpath and Package Layout Maven and Gradle Basics Unit Testing with JUnit Debugging Java Applications Step by Step Git Basics for Java Projects Modern Java: Records, Sealed Classes and Patterns Modules and module-info.java Time and Space Complexity Linear Search and Binary Search Sorting Algorithms Explained Stacks and Queues with ArrayDeque Linked Lists: Nodes and Links Hashing and Hash Tables Trees and Binary Search Trees Heaps and Priority Queues Graphs, BFS and DFS Recursion and Backtracking Dynamic Programming Basics Examples Library for Beginners Exercises by Topic Quizzes by Chapter Coding Challenges with Test Cases Keywords Reference and Glossary String, Math and Collections Methods Common Java Errors and Solutions Interview Questions and Answers Beginner Java Projects with Practice Steps Intermediate Java Projects: Collections and Files Advanced Java Projects: Testing and Concurrency Learning Roadmap and Study Plan
All types Fill in the blanks Predict the output Multiple choice
Any level Easy Medium Hard
Score 0 / 329
Complete the line so it prints Hi and moves to a new line.
System . out . ( "Hi" ) ;
println prints and then starts a new line.
Check answer Show solution
System . out . print ( "A" ) ;
System . out . print ( "B" ) ;
System . out . println ( "C" ) ;
A A, B and C on separate lines B A B C C ABC D AB then C on the next line
print stays on the same line, so all three letters appear together.
Show answer
System . out . println ( "Result: " + 4 + 2 ) ;
A Result: 6 B Result: 42 C Result: 4 2 D An error
Text + 4 makes text, then + 2 joins again. Use brackets for maths.
Show answer
Where does a Java program start running?
A In the main method B At the first line of the file C In the constructor D In the class with the shortest name
Java starts at public static void main(String[] args).
Show answer
Which line prints text and moves to a new line?
A System.out.print("Hi"); B console.log("Hi"); C print("Hi") D System.out.println("Hi");
println adds a line break after the text; print doesn't.
Show answer
What does TicketCount print if sold becomes 4?
A 4 B 5 C 8
Eight minus four is four; the initializer is evaluated with the new input.
Show answer
Why does DoorMessage still print Check complete when open is false?
A That statement is outside the if block B False runs every block C The filename forces it
Only statements within the controlled block are skipped.
Show answer
What does "Total: " + (2 + 3) print?
A Total: 5 B Total: 23 C 5 Total:
Parentheses complete numeric addition before concatenation.
Show answer
Why might a string ending in \n followed by println create an extra blank line?
A Both the string and println supply a line ending B println removes text C All strings require blank lines
Two successive line endings leave an empty displayed line.
Show answer
Which type should store the value true?
A int B String C boolean D char
boolean holds true or false.
Show answer
double d = 7.8 ;
int i = ( int ) d;
System . out . println ( i) ;
A 8 B 7.8 C An error D 7
Casting to int drops the decimal part without rounding.
Show answer
String a = "5" ;
int b = 5 ;
System . out . println ( a + b) ;
A 10 B 55 C 5 5 D An error
a is text, so + joins rather than adds.
Show answer
int a = 7 ;
double b = a;
System . out . println ( b) ;
A 7 B 7.00 C 7.0 D An error
An int is widened to a double automatically, and doubles print with .0.
Show answer
Why can int unreadMessages = 6 be read immediately?
A Its declaration initializes it B All method locals default to zero C Its camel-case name sets a value
The initializer supplies a value before use.
Show answer
Which assignment is prohibited for a final array reference?
A Replacing it with a new array B Changing an existing element C Reading its length
final prevents reference reassignment, not element mutation.
Show answer
What happens in long total = 50000 * 50000?
A The int multiplication overflows before assignment B The destination prevents all overflow C Java automatically throws
Use a long operand before the multiplication.
Show answer
Which declaration represents a true-or-false state?
A boolean ready = true B int ready = true C char ready = true
Java does not interchange boolean values with numeric primitives.
Show answer
What does (double) (5 / 2) produce?
A 2.0 B 2.5 C 5.2
The integer quotient is computed before the conversion.
Show answer
Which var declaration is valid?
A var title = "Ready" B var title; C var title = null
A suitable initializer is required for local type inference.
Show answer
Is score >= 0 || score <= 100 a valid closed-range test?
A No, values outside the range can pass B Yes, OR requires both boundaries C Only for negative scores
A valid closed range needs both comparisons to hold.
Show answer
What is !(false || true)?
A false B true C null
The OR is true, then NOT reverses it.
Show answer
Complete the code so it prints the remainder of 17 divided by 5.
System . out . println ( 17 5 ) ;
% is the remainder operator: 17 % 5 is 2.
Check answer Show solution
System . out . println ( 9 / 2 ) ;
A 4.5 B 5 C 4 D 4.0
Both values are ints, so the decimal part is dropped.
Show answer
int x = 10 ;
x += 5 ;
x /= 4 ;
System . out . println ( x) ;
A 3.75 B 4 C 15 D 3
15 / 4 is integer division, giving 3.
Show answer
Which expression gives 2.5?
A 5 / 2 B (double) 5 / 2 C (double) (5 / 2) D (int) 5.0 / 2
Cast before dividing; casting after, as in (double)(5 / 2), gives 2.0.
Show answer
Which line gives a random whole number from 1 to 6?
A int r = (int) Math.random() * 6 + 1; B int r = Math.random(1, 6); C int r = (int) (Math.random() * 6) + 1; D int r = (int) Math.random(6);
Without brackets, (int) Math.random() is always 0, so the option without brackets around Math.random() * 6 always gives 1.
Show answer
What is the result of (2 + 3) * 4?
A 20 B 14 C 24
The parenthesized sum is five, which is multiplied by four.
Show answer
Why check text != null before text.isEmpty()?
A The method call needs a nonnull reference B The comparison changes the text C isEmpty parses numbers
Short-circuit AND avoids the unsafe call when text is null.
Show answer
What does java GreetingTool Ada pass at args[0]?
A Ada B GreetingTool C java
The launcher does not include its own command or the class name.
Show answer
Why validate a parsed quantity after parseInt?
A Numeric syntax can be valid while the value violates the domain B parseInt accepts no digits C Array length becomes negative
Parsing and business-range checks answer different questions.
Show answer
Complete the code so it prints the number of characters in city.
String city = "Lisbon" ;
System . out . println ( city. ( ) ) ;
length() returns the number of characters.
Check answer Show solution
System . out . println ( "Computer" . substring ( 3 , 6 ) ) ;
A mput B pute C omp D put
Start at index 3 ("p") and stop before index 6.
Show answer
String s = "banana" ;
System . out . println ( s. indexOf ( "an" ) + " " + s. lastIndexOf ( "an" ) ) ;
A 2 4 B 1 4 C 1 3 D 0 3
"an" first appears at index 1 and last at index 3.
Show answer
Which line correctly checks whether color holds the text "red", ignoring case?
A color.equalsIgnoreCase("red") B color == "red" C color.equals("RED") D color.compareTo("red")
equalsIgnoreCase compares text and ignores capital letters.
Show answer
String [ ] parts = "a,b,,c" . split ( "," ) ;
System . out . println ( parts. length ) ;
A 3 B 4 C 5 D 1
The two commas in a row create an empty string between them: a, b, "", c.
Show answer
What remains in original after original.replace is called without storing its result?
A The original text B The replacement text C Always null
String is immutable and replace returns its result.
Show answer
Which ordinary literal displays one backslash?
A "\\" B "/" C "\n"
The escaped backslash represents one literal backslash.
Show answer
int x = 15 ;
if ( x > 10 ) {
System . out . println ( "A" ) ;
} else if ( x > 5 ) {
System . out . println ( "B" ) ;
} else {
System . out . println ( "C" ) ;
}
A A B B C A and B D C
The first true branch runs and the rest are skipped.
Show answer
Which condition is true only when both hasKey and doorClosed are true?
A hasKey || doorClosed B !hasKey && doorClosed C hasKey && doorClosed D hasKey == doorClosed
&& requires both sides to be true.
Show answer
int score = 45 ;
String result = score >= 50 ? "Pass" : "Retry" ;
System . out . println ( result) ;
A Retry B Pass C true D 45
45 >= 50 is false, so the value after the colon is chosen.
Show answer
int t = 25 ;
System . out . println ( t > 30 ? "hot" : t > 20 ? "warm" : "cool" ) ;
A hot B cool C An error D warm
25 isn't above 30 but is above 20.
Show answer
What category does score 95 receive if >=70 is checked before >=90?
A The >=70 branch category B Both categories C Always the >=90 category
The first true branch wins in an else-if chain.
Show answer
What happens to an if body when a stray semicolon follows its condition?
A The following block is independent B The block becomes an else C The comparison changes to equality
The semicolon forms the actual empty controlled statement.
Show answer
Complete the classic case so the code doesn't fall through to the next case.
case "red" :
System . out . println ( "Stop" ) ;
;
break leaves the switch after the matching case.
Check answer Show solution
int n = 3 ;
String word = switch ( n) {
case 1 -> "one" ;
case 2 , 3 -> "a few" ;
default -> "many" ;
} ;
System . out . println ( word) ;
A one B many C a few D 3
3 matches the case with labels 2 and 3.
Show answer
int x = 1 ;
switch ( x) {
case 1 : System . out . print ( "A" ) ;
case 2 : System . out . print ( "B" ) ; break ;
case 3 : System . out . print ( "C" ) ;
}
A AB B A C ABC D B
Case 1 falls through into case 2, which then breaks.
Show answer
A Ends the program B Returns a value from a block inside a switch expression C Skips to the next case D Pauses a loop
It's used when a case needs several lines.
Show answer
Which type can't be used in a switch?
A int B String C char D double
Floating point values can't be switched on.
Show answer
What happens after selecting case 6, 7 -> "Weekend"?
A The expression supplies Weekend B The next case automatically runs C main always returns
A selected arrow expression contributes its value without fall-through.
Show answer
What does yield end in DeliveryCharge?
A The selected switch expression B The entire main method C The class declaration
The assigned result can still be printed afterward.
Show answer
Predict the outputeasy Loops How many times does this print "Hi"?
for ( int i = 2 ; i <= 10 ; i += 2 ) {
System . out . println ( "Hi" ) ;
}
A 5 B 4 C 8 D 10
i takes the values 2, 4, 6, 8 and 10.
Show answer
Predict the outputmedium Loops
int [ ] a = { 3 , 1 , 4 , 1 , 5 } ;
int max = a[ 0 ] ;
for ( int x : a) {
if ( x > max) {
max = x;
}
}
System . out . println ( max) ;
A 3 B 4 C 5 D 14
The loop keeps the largest value seen so far.
Show answer
Multiple choicemedium Loops Which loop always runs its body at least once?
A for B while C enhanced for D do-while
do-while checks its condition after the body.
Show answer
Predict the outputmedium Loops
for ( int i = 10 ; i > 0 ; i -= 3 ) {
System . out . print ( i + " " ) ;
}
A 10 7 4 1 -2 B 10 7 4 1 C 10 7 4 D 7 4 1
After 1, i becomes -2 and the condition i > 0 fails.
Show answer
How many iterations occur for i = 0; i < 1; i++?
A One B Zero C Two
Only the initial value zero passes the condition.
Show answer
Where should a running total be initialized?
A Before the loop B At the start of every iteration C After all additions
Its accumulated value must survive across iterations.
Show answer
How many cells are visited in rows of lengths 2, 1 and 3?
A Six B Nine C Three
Using each current row length visits the sum of the row lengths.
Show answer
Which form can replace an array element directly?
A An indexed assignment to values[index] B Reassigning an enhanced-loop int variable C Changing the array length field
An indexed slot assignment changes stored data.
Show answer
What does FirstMatchingIndex do after finding index 1?
A Ends the search loop B Finds every later match C Leaves main immediately
break stops this loop while later method code remains reachable.
Show answer
In a basic for loop, what happens after continue?
A The update expression runs B The method returns C The update is always skipped
The loop then checks its condition for the next iteration.
Show answer
static String shout ( String s) {
return s. toUpperCase ( ) + "!" ;
}
System . out . println ( shout ( "hey" ) ) ;
A HEY! B hey! C HEY D shout(hey)
The method upper-cases the text and adds an exclamation mark.
Show answer
Which return type should a method use if it only prints something?
A int B void C String D null
void means the method returns nothing.
Show answer
static int f ( int x) { return x + 1 ; }
static int f ( int x, int y) { return x * y; }
System . out . println ( f ( 3 ) + f ( 3 , 4 ) ) ;
A 7 B 13 C 12 D 16
f(3) is 4 and f(3, 4) is 12, so 4 + 12 = 16.
Show answer
Which pair of methods is valid overloading?
A int area(int s) and double area(int s) B int area(int s) and int area(int side) C int area(int s) and int area(int w, int h) D void area() and void area()
Overloads must differ in their parameters, not just the return type or names.
Show answer
What is count after increase(count) when it began at 5?
A 5 B 6 C 0
The method incremented its own copied int parameter.
Show answer
Why does mark change original[0] but not replace original?
A The copied reference first points to the same array B Arrays are passed by reference C All assignments are ignored
Object mutation and local reference reassignment affect different state.
Show answer
Which maximum overload is selected for 3.5 and 7.25?
A The double-parameter overload B The int-parameter overload C Neither, because return type is ignored
The double arguments match the double signature.
Show answer
Can changing only parameter names create an overload?
A No B Yes C Only when returning int
Names do not distinguish parameter lists by type or count.
Show answer
Can a variable declared inside an if block be named after its closing brace?
A No B Yes, if it is int C Yes, if the condition was true
Its lexical scope ends at that block boundary.
Show answer
Why does BranchAssignment compile without an initializer at declaration?
A Both branches assign before the read B Locals automatically start empty C println initializes the variable
The compiler can establish definite assignment.
Show answer
What does factorial(0) return in the example?
A 1 B 0 C A new recursive call
The base case uses the mathematical value of zero factorial.
Show answer
How does RecursiveArraySum approach its base case?
A It advances the index toward the length B It repeatedly uses index zero C It reduces the array length field
Each call reduces the unvisited suffix by one element.
Show answer
Complete the line so it prints the number of elements.
int [ ] nums = { 4 , 8 , 15 } ;
System . out . println ( nums. ) ;
Arrays have a length field, with no brackets.
Check answer Show solution
double [ ] d = new double [ 2 ] ;
System . out . println ( d[ 1 ] ) ;
A null B 1 C An error D 0.0
New double arrays are filled with 0.0.
Show answer
Predict the outputmedium Arrays
int [ ] a = { 3 , 1 , 2 } ;
int [ ] b = a;
Arrays . sort ( b) ;
System . out . println ( Arrays . toString ( a) ) ;
A [3, 1, 2] B [2, 1, 3] C [1, 2, 3] D An error
a and b are the same array, so sorting b sorts a.
Show answer
Predict the outputmedium Arrays
int [ ] [ ] g = { { 1 , 2 , 3 } , { 4 , 5 , 6 } } ;
System . out . println ( g. length + " " + g[ 1 ] [ 2 ] ) ;
A 2 6 B 3 5 C 2 5 D 6 2
There are 2 rows, and row 1, column 2 holds 6.
Show answer
Which line creates an independent copy of int[] a?
A int[] b = a; B int[] b = new int[a]; C int[] b = Arrays.copyOf(a, a.length); D int[] b = a.length;
copyOf builds a new array with the same values.
Show answer
Which loop respects ragged row lengths?
A Loop over each row and then that row's length B Use the first row's length for every row C Assume all rows contain the outer length
Every row is an independent array and may have a different length.
Show answer
What does cloning int[][] copy first?
A The outer array of row references B Every nested row automatically C Every object anywhere in the graph
Array clone is shallow, so row references remain shared.
Show answer
Which operation preserves an int array's original order before sorting?
A Clone it, then sort the clone B Assign a second reference and sort it C Call sort without saving anything
A clone creates separate primitive element storage; a reference assignment creates an alias.
Show answer
What must be true before binarySearch?
A The array is sorted according to the search order B The array has no duplicates C The array has odd length
Binary search relies on the sorted-order precondition.
Show answer
Complete the code that creates a new Book object.
Book b = Book ( "Dune" ) ;
new builds an object by calling the class's constructor.
Check answer Show solution
Complete the constructor so it stores the title in the field.
class Book {
String title;
Book ( String title) {
. title = title;
}
}
this.title is the field; title on its own is the parameter.
Check answer Show solution
What is the difference between a class and an object?
A They are the same thing B A class is a blueprint; an object is one instance built from it C An object is a blueprint; a class is an instance D Classes hold data and objects hold methods
You can create many objects from one class.
Show answer
Rectangle r = new Rectangle ( 2 , 3 ) ;
r. width = 5 ;
System . out . println ( r. area ( ) ) ;
A 6.0 B 10.0 C 15.0 D An error
Changing the width field changes the area: 5 x 3 = 15.
Show answer
Why make fields private and add getters?
A It's required by Java B Private fields are faster C Getters save memory D Other code can't change the data directly, so the class controls its own rules
This is encapsulation.
Show answer
Two variables are assigned the same Card reference. Which operation changes the shared card?
A Updating its visits field through either variable B Reassigning one variable to a new Card C Setting one reference variable to null
Both references initially identify the same object, so an update through either reaches the same field. Reassigning one variable changes only that variable's reference.
Show answer
What does == compare for two non-null object references?
A Whether they refer to the same object B Whether every field has equal contents C Whether their class declarations have equal source text
Reference equality tests identity. Content equality requires an appropriate equals implementation.
Show answer
A tank's level must survive between add calls. Where should it be stored?
A In an instance field B Only in the add parameter C In an uninitialized local variable
An instance field remains attached to that tank between calls. Parameters and locals belong to individual calls.
Show answer
Which declaration shares one value across instances?
A static int count; B int count; C A method parameter named count
A static field belongs to the class. An ordinary instance field belongs to each object.
Show answer
What happens after adding only Ticket(String title)?
A new Ticket() requires a separately declared no-argument constructor B Java always adds a public no-argument constructor C The parameter is automatically optional
The implicit default constructor exists only when the class declares no constructors.
Show answer
Which constructors have different signatures?
A Ticket(String title) and Ticket(String title, int seats) B Ticket(String title) and Ticket(String name) C Ticket() and void Ticket()
Overloads differ by parameter types and arity, not parameter names. void Ticket is a method, not a constructor.
Show answer
In a constructor with a parameter named code, what does this.code = code assign?
A The parameter value to the current object's code field B The field value to the parameter C The code field of every instance
The qualifier selects the instance field on the left. The unqualified name selects the parameter on the right.
Show answer
A constructor stores "Q-8". rename("Q-9") contains code = code instead of this.code = code. What remains in the field?
A Q-8 B Q-9 C null
The self-assignment affects only the parameter. It does not replace the value stored during construction.
Show answer
Which modifier prevents a method from being overridden?
A final B static C public
A final instance method cannot be overridden. static methods are hidden rather than overridden.
Show answer
Why can final List values still accept add?
A final restricts reference reassignment, not list mutation B final applies only to primitive values C add ignores all modifiers
The variable remains bound to one list while the list's contents can change.
Show answer
Why copy a mutable constructor argument?
A To prevent later structural changes through the caller's original list B To make all elements new objects automatically C To change every element's type
A collection copy separates collection structures; it does not automatically deep-copy their elements.
Show answer
Which method order preserves a count on invalid input?
A Validate first, then update B Update first, then validate C Always update inside the getter
A rejection before assignment preserves the previous state.
Show answer
How is a member inner Reader constructed for outer?
A outer.new Reader() B new outer.Reader() C Reader.new outer()
A member inner instance needs an enclosing object; the qualified construction syntax supplies it.
Show answer
Which variables may an anonymous class capture?
A Final or effectively final local variables B Any local variable repeatedly reassigned C Only static fields
Captured locals cannot be reassigned after initialization; the referenced object's contents may still be mutable.
Show answer
A Allows selected types or members to be referenced by shorter names B Downloads a library from the internet C Makes private classes public
Imports guide name resolution; dependency installation and accessibility are separate.
Show answer
Which name identifies a packaged class completely?
A Its package plus simple class name B Only its source filename C Only the final directory name
A qualified name includes the package and type name.
Show answer
What does substring(1, 4) include?
A Indices 1, 2 and 3 B Indices 1 through 4 C Only index 4
The ending index is exclusive.
Show answer
Which method compares text contents?
A equals B == C hashCode alone
equals compares content; reference identity and hash codes cannot substitute for it.
Show answer
What does toString return from a builder?
A An immutable String snapshot of its current contents B The same mutable builder under another name C A live string view that updates after appends
Later builder changes do not alter the already returned String.
Show answer
Which range does delete(2, 5) remove?
A Indices 2, 3 and 4 B Indices 2 through 5 C Only index 5
The upper bound is exclusive.
Show answer
What happens when a null Integer is used in addition?
A Unboxing throws NullPointerException B It automatically becomes zero C It produces NumberFormatException
Arithmetic requires a primitive value; unboxing null cannot provide one.
Show answer
Which generic element declaration is valid?
A List<Integer> B List<int> C List<primitive int>
Generic type arguments are reference types; Integer wraps int.
Show answer
List < String > l = new ArrayList < > ( List . of ( "a" , "b" , "c" ) ) ;
l. remove ( 0 ) ;
System . out . println ( l. size ( ) + " " + l. get ( 0 ) ) ;
A 3 a B 2 a C 2 b D 2 c
Removing index 0 shifts "b" into position 0.
Show answer
List < Integer > n = new ArrayList < > ( List . of ( 10 , 20 , 30 ) ) ;
n. set ( 1 , 25 ) ;
n. add ( 0 , 5 ) ;
System . out . println ( n) ;
A [10, 25, 30, 5] B [5, 25, 20, 30] C [10, 20, 30] D [5, 10, 25, 30]
set replaces 20 with 25, then 5 is inserted at the front.
Show answer
How do you get the number of items in an ArrayList called list?
A list.size() B list.length C list.length() D list.count()
Collections use size(); arrays use length.
Show answer
Which is the safe way to remove every empty string from a list while looping?
A Call list.remove() inside an enhanced for loop B list.removeIf(String::isEmpty) C list.clear() D list.remove("")
remove("") only removes the first empty string, and removing inside a for-each loop throws an exception.
Show answer
What does set(1, value) do?
A Replaces the existing second element B Always increases size by one C Changes the first element
List indices are zero-based and set replaces rather than inserts.
Show answer
Which call removes the Integer value one?
A remove(Integer.valueOf(1)) B remove(1) C get(1)
An Integer argument selects remove(Object); an int selects remove(int).
Show answer
Map < String , Integer > m = new HashMap < > ( ) ;
m. put ( "a" , 1 ) ;
m. put ( "a" , 5 ) ;
System . out . println ( m. size ( ) + " " + m. get ( "a" ) ) ;
A 1 5 B 2 1 C 2 5 D 1 1
Keys are unique, so the second put replaces the value.
Show answer
Set < Integer > s = new HashSet < > ( List . of ( 3 , 1 , 3 , 2 , 1 ) ) ;
System . out . println ( s. size ( ) + " " + s. add ( 2 ) ) ;
A 5 true B 3 true C 3 false D 5 false
Only 1, 2 and 3 are stored, and adding 2 again returns false.
Show answer
Which map keeps its keys in sorted order?
A HashMap B LinkedHashMap C SortedList D TreeMap
TreeMap sorts keys; LinkedHashMap keeps insertion order.
Show answer
Which collection best answers "has this username already been taken?" quickly?
A ArrayList<String> B HashSet<String> C String[] D TreeMap<Integer, String>
HashSet.contains is very fast and enforces uniqueness.
Show answer
What happens when put uses an existing key?
A Its value is replaced B A duplicate key entry is appended C The map always throws
A map has at most one association per key.
Show answer
Which method distinguishes a null mapping from a missing key?
A containsKey B get alone C size of the String key
Presence is separate from the retrieved value when null values are permitted.
Show answer
Complete the line so the set keeps its items sorted.
Set < String > names = new < > ( ) ;
TreeSet stores its items in sorted order.
Check answer Show solution
Which collection rejects duplicate items?
A ArrayList B ArrayDeque C HashSet D LinkedList
Sets only hold unique items.
Show answer
Deque < Integer > d = new ArrayDeque < > ( ) ;
d. push ( 1 ) ; d. push ( 2 ) ; d. push ( 3 ) ;
System . out . println ( d. pop ( ) ) ;
A 1 B 3 C 2 D [3, 2, 1]
As a stack, the last item pushed is popped first.
Show answer
Queue < Integer > pq = new PriorityQueue < > ( List . of ( 8 , 3 , 6 ) ) ;
System . out . println ( pq. poll ( ) ) ;
A 8 B 6 C [3, 6, 8] D 3
A PriorityQueue gives the smallest item first.
Show answer
Which Comparator sorts players by score, highest first?
A Comparator.comparing(Player::score) B Comparator.reverse(Player::score) C Collections.sort(Player::score) D Comparator.comparing(Player::score).reversed()
comparing sorts ascending; reversed flips it.
Show answer
Which contract permits duplicate positional elements?
A List B Set C Map keys
A List represents a sequence and normally permits duplicates.
Show answer
Which framework type associates keys with values?
A Map B Queue C A raw iterator
Map represents key-value associations and is separate from Collection.
Show answer
Which set preserves insertion order?
A LinkedHashSet B HashSet C TreeSet under every comparator
LinkedHashSet preserves first insertion order in these Java 17 examples.
Show answer
What decides TreeSet uniqueness?
A Comparison returning zero B Only reference identity C Always String.equals regardless of comparator
TreeSet uses its ordering comparison to identify an existing element.
Show answer
Which type supplies an iterator?
A Iterable B Iterator's current element C Every static method
Iterable defines how a traversal is obtained.
Show answer
Which operation advances an ordinary iterator?
A next B hasNext C size
next returns the next element and advances the traversal.
Show answer
When does thenComparing run its secondary rule?
A When the earlier comparison returns zero B Before every primary comparison C Only after the list is sorted
Tie-breakers apply when earlier keys compare equal.
Show answer
What does List.sort change?
A The order of the supplied mutable list B Only the comparator object C Every object's class
The list is sorted in place, not automatically copied.
Show answer
Complete the class so Dog inherits from Animal.
class Dog Animal {
}
extends names the superclass.
Check answer Show solution
Complete the constructor so the parent sets the name.
Dog ( String name) {
( name) ;
}
super(...) calls the superclass constructor and must come first.
Check answer Show solution
class A { String hi ( ) { return "A" ; } }
class B extends A { @Override String hi ( ) { return "B" ; } }
A obj = new B ( ) ;
System . out . println ( obj. hi ( ) ) ;
A A B B C AB D A compile error
The actual object is a B, so B's override runs.
Show answer
Which access modifier lets subclasses use a field while hiding it from unrelated classes in other packages?
A private B public C protected D final
protected is visible to subclasses and the same package.
Show answer
A Makes the method run faster B Hides the parent's method from other classes C Is required for every method D Asks the compiler to check that the method really overrides a superclass method
It catches typos and wrong parameter lists.
Show answer
What does super(...) invoke?
A A constructor of the direct superclass B A second constructor of a new child object C Any public method named super
super(...) initializes the superclass portion of the current object.
Show answer
A Label reference holds a FragileLabel. Which text override runs?
A FragileLabel.text B Always Label.text C Neither because the types differ
An overridden instance call uses the runtime receiver's implementation.
Show answer
A To make the compiler check the intended override B To permit any different parameter list C To force calls to the parent body
The annotation detects mismatched signatures instead of silently creating an overload.
Show answer
Which operation uses runtime dispatch?
A Calling an overridden instance method B Reading a hidden field C Selecting an overloaded signature
Runtime dispatch selects an implementation of an already selected instance method signature.
Show answer
Complete the class so it keeps the Drawable contract.
class Logo Drawable {
public void draw ( ) { System . out . println ( "Drawing logo" ) ; }
}
A class uses implements to promise it provides an interface's methods.
Check answer Show solution
Complete the declaration of a method subclasses must implement.
abstract class Animal {
String sound ( ) ;
}
An abstract method has no body; subclasses must provide it.
Check answer Show solution
How many interfaces can one class implement?
A Only one B Two at most C Any number D None, if it extends a class
A class can extend one class and implement many interfaces.
Show answer
interface Greeter {
String name ( ) ;
default String greet ( ) { return "Hi " + name ( ) ; }
}
Greeter g = ( ) -> "Zoe" ;
System . out . println ( g. greet ( ) ) ;
A Hi Zoe B Hi C Zoe D A compile error
The lambda provides name(), and the default greet() uses it.
Show answer
Which can an abstract class have that an interface can't?
A Methods with bodies B Static methods C Constructors and instance fields that hold state D Public methods
Interfaces can have default and static methods, but no constructors or instance state.
Show answer
Why must Receipt.text be public when implementing Printable.text?
A The interface method's public contract cannot be narrowed B All methods in every class must be public C public creates the interface automatically
An ordinary interface abstract method is public; its implementation must preserve accessibility.
Show answer
Can an abstract class contain concrete methods?
A Yes B Only if it has no fields C Only if it is final
Abstract classes can combine implemented behavior with abstract operations.
Show answer
Fill in the blankseasy Enums Complete the declaration of an enum for a traffic light.
Light { RED, AMBER, GREEN }
The enum keyword declares a fixed set of constants.
Check answer Show solution
How should two enum values be compared?
A equals() only B With compareTo() C With == D By their names as strings
Each constant exists once, so == is correct and fast.
Show answer
Predict the outputmedium Enums
enum Size { SMALL, MEDIUM, LARGE }
System . out . println ( Size . LARGE . ordinal ( ) ) ;
A 3 B 2 C LARGE D 1
Ordinals start at 0.
Show answer
Multiple choicemedium Enums What does Size.values() return?
A A list of names as strings B The number of constants C A map D An array of every constant in declaration order
Loop over it to visit every constant.
Show answer
Why doesn't a switch expression over every enum constant need a default?
A The compiler can see that every possible value is handled B Enums don't support default C Java adds one automatically D Switch expressions never need default
Add a constant later and the compiler flags the switch.
Show answer
Why is ordinal a poor durable storage code?
A Reordering constants changes their positions B ordinal is always negative C Enums cannot be stored at all
The declaration index is positional, so it may change during evolution. Explicit stable codes are safer.
Show answer
Can callers create Speed with new Speed(3)?
A No B Yes if the constructor has an int C Yes if days is final
Enum instances are the declared constants; outside callers cannot create additional instances.
Show answer
Complete the declaration of a generic class with one type parameter.
class Box < > {
private T item;
}
T is the conventional name for a single type parameter.
Check answer Show solution
What does the diamond <> in new ArrayList<>() do?
A Creates an empty type B Makes the list immutable C Allows any type D Lets Java infer the type from the variable declaration
List<String> x = new ArrayList<>() infers String.
Show answer
Where does a generic method declare its type parameter?
A After the method name B In the class name only C Before the return type, as in static <T> T pick(...) D After the parameters
The <T> comes right before the return type.
Show answer
What does largest(List.of("kiwi", "banana", "fig")) return, using the lesson's method?
A banana B fig C An error D kiwi
Strings compare alphabetically, and "kiwi" comes last.
Show answer
Which parameter type lets a method add Integers to a List<Object>?
A List<? super Integer> B List<Integer> C List<? extends Integer> D List<int>
Consumer super: the list must accept Integers.
Show answer
A A type parameter declared by the class B A required class literally named T C A primitive numeric variable
T stands for a reference type selected through a type argument.
Show answer
Which declaration can read Integer-list elements as Number?
A List<? extends Number> B List<Number> assigned directly from List<Integer> C List<int>
The upper-bounded wildcard accepts suitable subtype lists while preserving safe reads.
Show answer
try {
int [ ] a = new int [ 2 ] ;
a[ 5 ] = 1 ;
System . out . println ( "A" ) ;
} catch ( ArrayIndexOutOfBoundsException e) {
System . out . println ( "B" ) ;
}
A A B B C A then B D Nothing
The exception is thrown before "A" is printed.
Show answer
try {
System . out . println ( "1" ) ;
} finally {
System . out . println ( "2" ) ;
}
System . out . println ( "3" ) ;
A 1, 2, then 3 B 1 then 3 C 2 then 3 D 1 then 2
finally runs even when no exception happens.
Show answer
Which exception is checked?
A NullPointerException B ArithmeticException C IOException D IllegalArgumentException
IOException must be caught or declared with throws.
Show answer
What does try-with-resources do?
A Retries the code if it fails B Closes the declared resources automatically when the block ends C Catches every exception D Makes the code run in parallel
It works with any class that implements AutoCloseable.
Show answer
Which branch contains ArithmeticException?
A RuntimeException B IOException C A type outside Throwable
ArithmeticException is an unchecked RuntimeException subtype.
Show answer
What does a throws declaration do?
A Advertises possible checked failures to callers B Automatically recovers from failures C Closes every resource
A declaration states the contract rather than executing recovery.
Show answer
Which statement is skipped after the parser throws in CatchFlow?
A The Port print inside try B The matching catch C All code after the catch forever
The exception leaves the try before its later statement.
Show answer
Why does Cleanup step print before twelve?
A finally runs before the pending return completes B main prints in reverse order C The arithmetic runs after printing
The return value is retained while cleanup executes.
Show answer
Why store available stock as a field in the exception?
A Callers can inspect it without parsing the message B It makes the exception checked automatically C It prevents every possible failure
Structured context supports a reliable programmatic response.
Show answer
Which parent produces an unchecked custom argument exception?
A IllegalArgumentException B IOException C Exception directly
IllegalArgumentException belongs to the RuntimeException family.
Show answer
Which interface makes a resource eligible for this construct?
A AutoCloseable B Iterable only C Serializable only
Try-with-resources requires a closeable contract.
Show answer
Which resource closes first when declared first then second?
A second B first C Neither automatically
Cleanup reverses successful initialization order.
Show answer
What does createFile do when the entry already exists?
A Throws an existence-related failure B Always appends text C Only creates a Path object
Its contract creates a new entry rather than silently reusing an existing one.
Show answer
What keeps the first line during the second write?
A StandardOpenOption.APPEND B Calling resolve C The filename extension
APPEND changes the write policy from truncation to addition at the end.
Show answer
What does resolve("week.txt") do to this relative base?
A Adds a child component B Creates the file immediately C Reads its contents
resolve is a path calculation rather than a filesystem write.
Show answer
Does normalize access the filesystem?
A No B Always C Only for txt names
The operation is lexical and can simplify nonexistent paths.
Show answer
What should copy a PNG file without interpreting its content?
A Byte streams B A Reader using an arbitrary charset C A String split into words
Binary copying preserves the exact bytes rather than decoding them into text.
Show answer
UTF-8 encodes Café into five bytes. Does its Java String length have to be five?
A No; the shown word has four UTF-16 code units B Yes; every byte is a char C No; it must always be twice the byte length
Encoding length and UTF-16 string length measure different representations.
Show answer
What does readLine return for a blank line?
A An empty String B null C An IOException every time
Null marks the end of input, while an empty String is a supplied line with no characters.
Show answer
NumericLinesExample reads 11, a blank line, and 7. How many measurements are accepted?
A Two B Three C Zero
Its explicit policy skips the whitespace-only line rather than treating it as a zero measurement.
Show answer
Which field is omitted by default serialization?
A A transient preview reference B Every ordinary String field C Every field declared after the constructor
The transient modifier excludes that field from the ordinary default saved form.
Show answer
What happens to Workspace.preview after the shown round trip?
A It becomes null B It automatically becomes Expanded C It becomes the workspace name
Ordinary deserialization does not rerun that field initializer; the excluded reference has its default value.
Show answer
Which JSON value has a numeric type?
A 24 B "24" C "pieces"
Quotation marks make 24 a string, even though its characters look numeric.
Show answer
What category describes {"pieces":"ten"} under the shown validator?
A Valid JSON with an invalid field type B Malformed JSON syntax C A valid nonnegative integer quantity
The document parses, but its string does not satisfy the required integral-number contract.
Show answer
Complete the line that reads a whole file into one String.
String text = Files . ( Path . of ( "story.txt" ) ) ;
Files.readString reads the entire file as text.
Check answer Show solution
What happens to a file's contents when you call Files.writeString(path, "hi")?
A "hi" is added to the end B Nothing, if the file exists C The contents are replaced with "hi" D An exception is always thrown
Use the APPEND option to add instead.
Show answer
Which is best for counting lines in a 5 GB log file?
A Files.lines in try-with-resources B Files.readString C Files.readAllLines D Reading it into an array
Files.lines reads lazily, one line at a time.
Show answer
What kind of exception is IOException?
A Unchecked: you can ignore it B Checked: you must catch it or declare throws C An Error that can't be caught D A compile error
Java forces you to handle possible file problems.
Show answer
A file contains three lines. What does Files.readAllLines(p).get(3) do?
A Returns the third line B Returns an empty string C Returns null D Throws IndexOutOfBoundsException
Indexes run from 0 to 2.
Show answer
Complete the code so it creates the date 25 December 2024.
LocalDate xmas = LocalDate . ( 2024 , 12 , 25 ) ;
LocalDate.of(year, month, day) creates a specific date.
Check answer Show solution
Which class holds a date with no time?
A LocalDate B LocalTime C Instant D Duration
LocalDate holds year, month and day.
Show answer
LocalDate d = LocalDate . of ( 2024 , 1 , 31 ) . plusMonths ( 1 ) ;
System . out . println ( d) ;
A 2024-02-31 B 2024-02-29 C 2024-03-02 D 2024-03-01
February 2024 has 29 days, so Java uses the last valid day.
Show answer
Which gives the total number of days between two dates?
A Period.between(a, b).getDays() B a.minus(b) C Duration.between(a, b).getDays() D ChronoUnit.DAYS.between(a, b)
Period's getDays() is only the leftover days part.
Show answer
What should you store for "when was this order created?" in a system used worldwide?
A An Instant (UTC) B A LocalDateTime C A formatted String D A LocalTime
An Instant is an exact moment that can be shown in any zone.
Show answer
Which type fits an ordinary birthday?
A LocalDate B Duration C Instant
A birthday is a calendar date without a clock time or zone.
Show answer
What happens to arrival after arrival.plusDays(2)?
A It remains unchanged B It becomes March first C It loses its year
The method returns a new LocalDate because the original is immutable.
Show answer
Complete the lambda so it doubles a number.
Function < Integer , Integer > doubler = x x * 2 ;
A lambda's parameters and body are separated by an arrow.
Check answer Show solution
System . out . println ( List . of ( 1 , 2 , 3 , 4 , 5 ) . stream ( ) . filter ( n -> n % 2 == 1 ) . toList ( ) ) ;
A [2, 4] B [1, 2, 3, 4, 5] C 3 D [1, 3, 5]
Only the odd numbers pass the filter.
Show answer
int total = List . of ( 3 , 4 , 5 ) . stream ( ) . map ( n -> n * n) . reduce ( 0 , Integer : : sum) ;
System . out . println ( total) ;
A 12 B 50 C 144 D 60
9 + 16 + 25 = 50.
Show answer
Which is a terminal operation?
A filter B map C collect D sorted
Terminal operations produce the result and run the pipeline.
Show answer
What is a functional interface?
A An interface with no methods B An interface that only contains static methods C Any interface in java.util D An interface with exactly one abstract method, which a lambda can implement
Examples include Runnable, Comparator and Predicate.
Show answer
Which change prevents the threshold predicate from compiling?
A Reassigning minimum after its initialization B Calling test twice C Supplying a smaller argument
A captured local variable must remain final or effectively final.
Show answer
What does lateCharge.apply(6) return?
A 12 B 6 C 18
Six billable days at two units each produce the maximum charge of twelve.
Show answer
Why does VisitorRules safely test an empty string?
A The length predicate fails before charAt executes B charAt returns a space for empty strings C and catches index exceptions
Predicate.and short-circuits when its first predicate returns false.
Show answer
Which interface produces a value without receiving an input?
A Supplier<T> B Consumer<T> C Predicate<T>
Supplier.get has no parameter and returns its supplied value.
Show answer
In String::length assigned to Function<String, Integer>, what becomes the receiver?
A The String supplied to apply B A newly constructed empty String C The Function object
The unbound reference uses the functional argument as the receiver of length.
Show answer
When does ArrayList::new assigned to Supplier create a list?
A When get is called B When the source file is compiled C Only when add is called
The reference describes a construction operation that Supplier.get invokes.
Show answer
Which operation starts traversal in PricePipeline?
A toList B filter C stream
toList is terminal; the earlier calls describe the pipeline.
Show answer
What does reducing an empty integer stream with zero and Integer::sum return?
A 0 B null C An exception
No elements are combined, so the identity is the result.
Show answer
Which factory accepts a nullable value?
A Optional.ofNullable B Optional.of C Optional.get
ofNullable produces an empty container when its argument is null.
Show answer
Why does the first orElseGet call not print a fallback message?
A Its Optional already contains Lena B Suppliers never execute C Print statements are ignored inside suppliers
orElseGet invokes its supplier only for absence.
Show answer
Which Matcher method searches within a longer sentence?
A find B matches C compile
find locates the next matching region instead of requiring the entire input to match.
Show answer
What does group(0) contain?
A The entire match B The first parenthesized capture only C The original input before matching
Capture numbering starts with the whole matched region at zero.
Show answer
Which retention policy supports getAnnotation at runtime?
A RUNTIME B SOURCE C CLASS by default
Runtime reflection requires the metadata to survive with runtime visibility.
Show answer
What does @Override verify?
A A method implements or overrides an inherited contract B A method runs on another thread C A method must be public
It catches signature mismatches for intended overriding.
Show answer
Which lookup includes public inherited methods?
A getMethod B getDeclaredMethod only C getSuperclass only
getMethod searches public methods across the applicable inherited API.
Show answer
What wraps an exception thrown by a reflected method?
A InvocationTargetException B ClassNotFoundException C NoSuchMethodException
InvocationTargetException separates target failure from lookup and access failures.
Show answer
Which operation requests execution on a new thread?
A start B run directly C getState
start initiates the thread lifecycle; run is an ordinary method call.
Show answer
Why is Finished printed after Packing complete?
A join waits for worker termination B The JVM alphabetizes output C Thread names control priority
The completion wait precedes the final main-thread print.
Show answer
What monitor does a synchronized instance method use?
A The receiving instance B A new monitor for each call C Every object in the JVM
Calls on the same instance coordinate through that instance monitor.
Show answer
Why is a volatile int insufficient for an atomic increment?
A The read-modify-write sequence remains compound B volatile fields cannot store numbers C volatile prevents reads
Visibility of individual accesses does not merge them into one update.
Show answer
Which task interface can return a value?
A Callable<T> B Runnable only C Thread.State
Callable.call returns its declared result type and may throw checked exceptions.
Show answer
Where does a submitted task failure become visible to its caller?
A Through Future.get as ExecutionException B Only during compilation C Automatically in shutdown
The Future records the worker failure and get exposes it.
Show answer
Which operation waits for a latch count to reach zero?
A await B countDown C getState
await is the waiting side; countDown reports an event.
Show answer
Why is END not printed by QueueTransfer?
A It is recognized as the termination sentinel B The queue discards every second item C take returns null for END
The consumer checks the protocol value before entering the loop body.
Show answer
What makes an order log useful?
A A meaningful event and relevant identifier B Only the word error C Every available secret
Context connects a message to the operation without unnecessary sensitive data.
Show answer
Why is Message constructed absent?
A The INFO level is disabled before supplier evaluation B All lambda bodies are skipped C Logging stops main
The supplier overload defers message construction for accepted records.
Show answer
Complete the declaration of a record with a title and a year.
Film ( String title, int year) { }
The record keyword declares an immutable data class.
Check answer Show solution
How do you read the title of Film f?
A f.title() B f.getTitle() C f.title D f.get("title")
Record accessors are named after the components.
Show answer
record Pair ( int a, int b) { }
System . out . println ( new Pair ( 1 , 2 ) . equals ( new Pair ( 1 , 2 ) ) ) ;
A false B Pair[a=1, b=2] C true D A compile error
Records compare their component values.
Show answer
Where do you validate a record's values?
A In a setter B In a compact constructor C In toString() D Records can't be validated
The compact constructor runs before fields are assigned.
Show answer
Which is the best choice for a bank account whose balance changes?
A A regular class B A record C An enum D An interface
Records are immutable; changing state belongs in a class.
Show answer
Complete the annotation that marks a method as a JUnit test.
void addsTwoNumbers ( ) {
assertEquals ( 4 , 2 + 2 ) ;
}
@Test tells JUnit to run the method as a test.
Check answer Show solution
In assertEquals(a, b), which argument is the expected value?
A a, the first one B b, the second one C Either D Neither
Expected first, actual second.
Show answer
How do you check that withdraw(-5) throws IllegalArgumentException?
A assertThrows(IllegalArgumentException.class, () -> account.withdraw(-5)) B assertEquals(IllegalArgumentException, withdraw(-5)) C try { withdraw(-5); } catch (Exception e) {} D @Test(exception) withdraw(-5)
assertThrows runs the lambda and checks the exception type.
Show answer
What does @BeforeEach do?
A Runs once before all tests B Runs before every single test method C Runs only when a test fails D Skips the next test
It gives each test a fresh setup.
Show answer
A @ParameterizedTest has 5 rows in its @CsvSource. How many tests does the report show for it?
A 5 B 1 C 10 D It depends on the method name
Each row is reported as its own test.
Show answer
Which tool compiles Java source to class files?
A javac B java only C javadoc only
javac is the JDK compiler; java launches the application.
Show answer
Which component executes bytecode?
A JVM B A source-code editor C The package declaration
The JVM loads and executes compatible class-file instructions.
Show answer
What should a development installation provide?
A Both java and javac B Only a text editor C Only browser support
The launcher runs applications and the compiler builds source.
Show answer
Where should JAVA_HOME point?
A The JDK home containing bin B The source directory C A .class file
Tools commonly append bin to the configured JDK home.
Show answer
Which command targets Java 17 while compiling?
A javac --release 17 ParcelLabel.java B java --compile 17 ParcelLabel C javac ParcelLabel.class
--release constrains the platform target during compilation.
Show answer
What does -cp out select?
A A classpath root for launch lookup B An output message prefix C A package named cp
The runtime searches that location for the named class.
Show answer
Where is the classpath root for out/museum/labels/Ticket.class?
A out B out/museum/labels C Ticket.class
The package path is resolved beneath the root.
Show answer
Which launch name matches package museum.labels?
A museum.labels.Ticket B Ticket.java C out.Ticket
The launcher needs the qualified binary name.
Show answer
Where does Maven normally compile main Java source from?
A src/main/java B target/classes C The local dependency cache
The conventional source root holds authored application code.
Show answer
Which lifecycle phase creates the configured artifact?
A package B validate only C clean only
package includes earlier required phases and then assembles the artifact.
Show answer
Which case catches a strict comparison mistake at the threshold?
A A subtotal of exactly 40 B A subtotal of 100 C A subtotal of 200
The exact boundary distinguishes >= from >.
Show answer
Which assertion verifies a particular rejected-input exception?
A assertThrows B assertEquals(true, true) C System.out.println
assertThrows checks that the supplied action fails with the expected type.
Show answer
Which input distinguishes quantity > 10 from quantity >= 10?
A 10 B 11 C 100
Only the exact threshold follows different branches in these two comparisons.
Show answer
What does the call stack show?
A The current method and its callers B Only imported packages C Every past value forever
Frames connect the current execution point to the calls that reached it.
Show answer
Which command shows the patch selected for the next commit?
A git diff --staged B java -version C git diff only
The staged diff describes the snapshot the commit will record.
Show answer
Which directory is normally generated Maven output?
A target B src/main/java C The repository root README
Maven recreates target from authored inputs.
Show answer
What is the generated accessor for a record component named label?
A label() B getLabel() automatically C setLabel()
Record accessors use the component names directly.
Show answer
What does permits describe?
A Allowed direct subtypes of a sealed type B Every imported class C Only runtime objects already created
The declaration constrains the direct inheritance family.
Show answer
What is the descriptor filename?
A module-info.java B package-info.class only C Module.java automatically
The module declaration is compiled from the specially named descriptor.
Show answer
Which module is implicitly read by every named module?
A java.base B java.sql C java.logging
Fundamental platform APIs are available through the implicit base dependency.
Show answer
What is the auxiliary space of LinearVisits?
A O(1) B O(n squared) C O(log n) automatically
A fixed number of counters does not grow with input length.
Show answer
How many pairs does PairVisits count when n is 5?
A 25 B 10 C 5
Each of five outer iterations executes five inner iterations.
Show answer
What is the crucial precondition for binary search here?
A Sorted input under the same comparison rule B At least one duplicate C An odd array length
Discarding half the interval depends on the established order.
Show answer
Why does the loop use low <= high?
A To check a final single candidate B To force a match C To skip index zero
Inclusive bounds still contain one candidate when equal.
Show answer
What is finalized after each selection-sort pass?
A The next position in the sorted prefix B Every element at once C Only the final array slot
The minimum remaining element is placed at the current position.
Show answer
Why does insertion sort save value before shifting?
A Shifts overwrite array positions B Java cannot compare array values C Saving changes the array length
The saved value must remain available for insertion afterward.
Show answer
Which action is removed first from UndoStack?
A Add image B Add heading C Neither until sorting
A stack removes the most recently pushed item.
Show answer
What does poll return on an empty ArrayDeque queue?
A null B An empty string C A compulsory exception
The special-value queue operation uses null to represent absence.
Show answer
What terminates traversal in the singly linked examples?
A A null next reference B An array length field C A value of zero
The chain ends when the traversal reference becomes null.
Show answer
Why save next before redirecting current.next?
A To preserve access to the unprocessed chain B To sort values C To create an extra copy of every node
Changing the link would otherwise lose the forward traversal reference.
Show answer
What must be true for equal keys?
A Their hash codes must be equal B Their object references must be identical C Their hashes must be globally unique
The equality and hashing contract requires equal keys to share a hash.
Show answer
Why do CollisionKeys entries remain distinct?
A Their record equality compares different text values B HashMap ignores hashCode entirely C Only one entry is actually stored
Collisions do not imply equality.
Show answer
Where should 25 be inserted into a tree with root 40 and left child 20?
A As the right child of 20 B As the right child of 40 C As the left child of 20
25 is smaller than 40 but larger than 20, so both comparisons determine its position.
Show answer
Insert 3, then 4, then 5 into the unbalanced tree. What shape results?
A A chain of right children B A root with two equally sized subtrees C A chain of left children
Every new key is larger than all existing keys and follows right references until an empty branch.
Show answer
A natural-order integer queue contains 15, 6 and 10. What does peek return?
A 6, without removing it B 15, because it arrived first C 10, while removing it
Natural ordering puts the smallest integer at the head. peek observes that head without changing the queue.
Show answer
Two jobs compare as equal and the comparator has no tie-breaker. What can you assume?
A Either equal-priority job may be removed first B Their insertion order is guaranteed C One job is discarded as a duplicate
PriorityQueue permits duplicates and does not provide stable ordering among elements that compare equally.
Show answer
An undirected connection joins Library and Cafe. What should its adjacency lists contain?
A Cafe under Library and Library under Cafe B Cafe under Library only C Neither endpoint, because the edge is undirected
Both directions must be represented when traversal looks up outgoing neighbors.
Show answer
Entry lists Hall before Studio; Hall leads to Exit. Which order does BFS print?
A Entry, Hall, Studio, Exit B Entry, Hall, Exit, Studio C Exit, Hall, Studio, Entry
Exit is appended behind Studio, which was already waiting in the FIFO queue.
Show answer
Why does the subset example remove the final chosen card after its recursive call?
A To restore the list before exploring another branch B To delete the card from the input array C To erase the previously printed output
Sibling calls share the chosen-list object. Restoration gives each sibling the correct partial selection.
Show answer
How many permutations does the distinct array A, B, C have?
A Six B Eight C Three
There are three choices for the first position, two for the second and one for the third: 3 × 2 × 1.
Show answer
What does ways(0) = 1 mean in the staircase problem?
A There is one empty sequence of moves B A person takes one physical step C Zero-step inputs are always errors
Counting the empty sequence makes it a valid base case from which larger counts can be constructed.
Show answer
Using unlimited coins 1, 3 and 4, what is the minimum count for amount 6?
A Two, using 3 and 3 B Three, using 4, 1 and 1 C One, because a table entry stores one answer
The table compares candidate counts and chooses two; storing one answer does not mean using one coin.
Show answer
How many six-item trays are needed for seven items?
A 2 B 1 C 7
One full tray and one remainder require two trays.
Show answer
Which collection preserves first-seen uniqueness here?
A LinkedHashSet B HashSet by guaranteed order C ArrayList alone
LinkedHashSet combines equal-value uniqueness with insertion order.
Show answer
What remains after splitting seventeen tokens among five players?
A 2 B 3 C 5
The remainder is seventeen modulo five, while three is the base share.
Show answer
Do equal adjacent values count as a rising step?
A No B Always C Only for positive integers
The contract requires a strict greater-than comparison.
Show answer
What is 25 / 4 when both operands are int?
A 6 B 6.25 C 7
Integer division discards the fractional part for these positive operands.
Show answer
Why is the first QuizStringIdentity output false?
A The two new expressions create different objects B The text has different letters C equals always returns false
Reference identity differs even though the String contents match.
Show answer
How does the run encoder represent aba?
A a1b1a1 B a2b1 C aba3
Only consecutive equal letters are grouped.
Show answer
Why scan the original text in the unique-character second pass?
A To preserve first-occurrence order B To sort the alphabet C Because maps cannot count
The result index is defined by source order, not map iteration.
Show answer
Which item is a boolean literal rather than a keyword?
A true B boolean C return
true represents a boolean value; boolean declares its primitive type.
Show answer
What does yield do in KeywordContext?
A Supplies the switch arm result B Returns from main C Starts a thread
The enclosing switch expression receives the yielded value.
Show answer
What is the end convention of substring(start, end)?
A Exclusive end B Inclusive end C End must equal the string length
The returned slice includes indices before end, not end itself.
Show answer
How do you remove integer value two from ArrayList<Integer>?
A remove(Integer.valueOf(2)) B remove(2) for every case C set(2, null)
The wrapper argument selects value removal rather than the index overload.
Show answer
Which failure can happen before execution because of source type mismatch?
A incompatible types B A task-specific timeout C An ordinary missing user value
The compiler checks assignments and expressions against their declared types.
Show answer
Why is quantity zero not a NumberFormatException?
A It parses as an integer but violates a domain rule B Zero cannot be stored in int C parseInt ignores zero
Numeric representation and positive-quantity validation are separate checks.
Show answer
Why does InterviewArguments print count as three?
A The int parameter receives a copied value B Java forbids changing int C The method did not execute
Assigning the parameter does not reassign the caller variable.
Show answer
Why does inspect(signal) choose the Signal overload?
A The argument expression is declared Signal B Alert cannot inherit methods C Overloads use only object names
Overload resolution uses compile-time type information.
Show answer
Which pair tests a started-block parking boundary?
A 30 and 31 minutes B 3 and 4 minutes C 45 and 46 minutes
Thirty minutes uses one block, while thirty-one starts a second block.
Show answer
Why reject an empty score array before reading scores[0]?
A There is no first element to initialize the maximum B Arrays cannot contain repeated scores C Every maximum is zero
The initial element access requires at least one score.
Show answer
What stays invariant after a successful prototype transfer?
A The combined balance B The source balance alone C The destination balance alone
The same amount is subtracted and added under one protected operation.
Show answer
Which key is evicted after A is accessed and C is inserted?
A B B A C C
Access order makes A recent and leaves B as the eldest entry.
Show answer
What is stronger evidence than finishing a page?
A Writing and explaining a tested variation B Only scrolling to the bottom C Remembering the filename
A variation shows the concept can be applied beyond the original example.
Show answer
What does RoadmapStorage.charge return?
A The charge beyond the first three free units B The complete unit count C A customer identifier
The method returns four charge units for each stored unit beyond the free allowance.
Show answer
No exercises match those filters.