Java329 exercises

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.

Score0/ 329

1Introduction

Read the lesson
Fill in the blankseasyIntroduction

Complete the line so it prints Hi and moves to a new line.

System.out.("Hi");
Predict the outputeasyIntroduction

What does this print?

System.out.print("A");
System.out.print("B");
System.out.println("C");
Predict the outputmediumIntroduction

What does this print?

System.out.println("Result: " + 4 + 2);
Multiple choicemediumIntroduction

Where does a Java program start running?

Multiple choicemediumIntroduction

Which line prints text and moves to a new line?

2Syntax and Statements

Read the lesson
Multiple choiceeasySyntax and Statements

What does TicketCount print if sold becomes 4?

Multiple choicemediumSyntax and Statements

Why does DoorMessage still print Check complete when open is false?

3Output: print() vs. println()

Read the lesson

What does "Total: " + (2 + 3) print?

Multiple choicemediumOutput: print() vs. println()

Why might a string ending in \n followed by println create an extra blank line?

4Comments and Code Structure

Read the lesson
Multiple choiceeasyComments and Code Structure

Why is // Round up for a partial tray useful?

Multiple choicemediumComments and Code Structure

Which tag documents a method parameter?

5Variables & Data Types

Read the lesson
Fill in the blankseasyVariables & Data Types

Complete the declarations.

 score = 10;
 player = "Mia";
Multiple choiceeasyVariables & Data Types

Which type should store the value true?

Predict the outputmediumVariables & Data Types

What does this print?

double d = 7.8;
int i = (int) d;
System.out.println(i);
Predict the outputmediumVariables & Data Types

What does this print?

String a = "5";
int b = 5;
System.out.println(a + b);
Predict the outputmediumVariables & Data Types

What does this print?

int a = 7;
double b = a;
System.out.println(b);

6Variables, Identifiers and Constants

Read the lesson

Why can int unreadMessages = 6 be read immediately?

Which assignment is prohibited for a final array reference?

7Primitive Data Types

Read the lesson
Multiple choiceeasyPrimitive Data Types

What happens in long total = 50000 * 50000?

Multiple choicemediumPrimitive Data Types

Which declaration represents a true-or-false state?

8Type Casting and var

Read the lesson
Multiple choiceeasyType Casting and var

What does (double) (5 / 2) produce?

Multiple choicemediumType Casting and var

Which var declaration is valid?

9Boolean Expressions

Read the lesson
Multiple choiceeasyBoolean Expressions

Is score >= 0 || score <= 100 a valid closed-range test?

Multiple choicemediumBoolean Expressions

What is !(false || true)?

10Operators & Math

Read the lesson
Fill in the blankseasyOperators & Math

Complete the code so it prints the remainder of 17 divided by 5.

System.out.println(17  5);
Predict the outputeasyOperators & Math

What does this print?

System.out.println(9 / 2);
Predict the outputmediumOperators & Math

What does this print?

int x = 10;
x += 5;
x /= 4;
System.out.println(x);
Multiple choicemediumOperators & Math

Which expression gives 2.5?

Multiple choicehardOperators & Math

Which line gives a random whole number from 1 to 6?

11Operators and Precedence

Read the lesson
Multiple choiceeasyOperators and Precedence

What is the result of (2 + 3) * 4?

Multiple choicemediumOperators and Precedence

Why check text != null before text.isEmpty()?

12User Input (Scanner)

Read the lesson
Fill in the blankseasyUser Input (Scanner)

Complete the line that creates a Scanner reading from the keyboard.

Scanner input = new (System.);
Multiple choiceeasyUser Input (Scanner)

Which method reads a whole line of text, including spaces?

Predict the outputmediumUser Input (Scanner)

The user types Sam Lee. What does this print?

String first = input.next();
System.out.println("Hi " + first);
Predict the outputmediumUser Input (Scanner)

What does this print?

System.out.printf("%.1f%n", 7.0 / 2);
Multiple choicehardUser Input (Scanner)

Why might nextLine() return an empty string right after nextInt()?

13User Input with Scanner

Read the lesson
Multiple choiceeasyUser Input with Scanner

Why does the first nextLine after reading 21 return an empty string?

Multiple choicemediumUser Input with Scanner

Which operation advances past the rejected token oops?

14Command-Line Arguments

Read the lesson
Multiple choiceeasyCommand-Line Arguments

What does java GreetingTool Ada pass at args[0]?

Multiple choicemediumCommand-Line Arguments

Why validate a parsed quantity after parseInt?

Fill in the blankseasyStrings

Complete the code so it prints the number of characters in city.

String city = "Lisbon";
System.out.println(city.());
Predict the outputeasyStrings

What does this print?

System.out.println("Computer".substring(3, 6));
Predict the outputmediumStrings

What does this print?

String s = "banana";
System.out.println(s.indexOf("an") + " " + s.lastIndexOf("an"));
Multiple choicemediumStrings

Which line correctly checks whether color holds the text "red", ignoring case?

Predict the outputhardStrings

What does this print?

String[] parts = "a,b,,c".split(",");
System.out.println(parts.length);

16Strings, Concatenation and Escapes

Read the lesson

What remains in original after original.replace is called without storing its result?

Which ordinary literal displays one backslash?

17Formatting & StringBuilder

Read the lesson
Fill in the blankseasyFormatting & StringBuilder

Complete the format so the price shows two decimal places.

System.out.printf("£%%n", 4.5);
Predict the outputeasyFormatting & StringBuilder

What does this print?

System.out.println(String.format("%,d", 2500000));
Predict the outputmediumFormatting & StringBuilder

What does this print?

System.out.println("[" + String.format("%-5s", "ab") + "]");
Multiple choicemediumFormatting & StringBuilder

Why use StringBuilder inside a long loop?

Predict the outputhardFormatting & StringBuilder

What does this print?

StringBuilder sb = new StringBuilder("abc");
sb.append("d").insert(0, "x").reverse();
System.out.println(sb);

18if / else

Read the lesson
Fill in the blankseasyif / else

Complete the code so it prints "Even" for even numbers and "Odd" otherwise.

int n = 8;
 (n % 2 == 0) {
    System.out.println("Even");
}  {
    System.out.println("Odd");
}
Predict the outputeasyif / else

What does this print?

int x = 15;
if (x > 10) {
    System.out.println("A");
} else if (x > 5) {
    System.out.println("B");
} else {
    System.out.println("C");
}
Multiple choicemediumif / else

Which condition is true only when both hasKey and doorClosed are true?

Predict the outputmediumif / else

What does this print?

int score = 45;
String result = score >= 50 ? "Pass" : "Retry";
System.out.println(result);
Predict the outputmediumif / else

What does this print?

int t = 25;
System.out.println(t > 30 ? "hot" : t > 20 ? "warm" : "cool");

19if, else if and Nested Conditions

Read the lesson

What category does score 95 receive if >=70 is checked before >=90?

What happens to an if body when a stray semicolon follows its condition?

20switch & Switch Expressions

Read the lesson
Fill in the blankseasyswitch & Switch Expressions

Complete the classic case so the code doesn't fall through to the next case.

case "red":
    System.out.println("Stop");
    ;
Predict the outputeasyswitch & Switch Expressions

What does this print?

int n = 3;
String word = switch (n) {
    case 1 -> "one";
    case 2, 3 -> "a few";
    default -> "many";
};
System.out.println(word);
Predict the outputmediumswitch & Switch Expressions

What does this print?

int x = 1;
switch (x) {
    case 1: System.out.print("A");
    case 2: System.out.print("B"); break;
    case 3: System.out.print("C");
}
Multiple choicemediumswitch & Switch Expressions

What does yield do?

Multiple choicehardswitch & Switch Expressions

Which type can't be used in a switch?

21switch Expressions and Statements

Read the lesson

What happens after selecting case 6, 7 -> "Weekend"?

What does yield end in DeliveryCharge?

Fill in the blankseasyLoops

Complete the loop so it prints 0, 1, 2, 3 and 4.

 (int i = 0; i < 5; ) {
    System.out.println(i);
}
Predict the outputeasyLoops

How many times does this print "Hi"?

for (int i = 2; i <= 10; i += 2) {
    System.out.println("Hi");
}
Predict the outputmediumLoops

What does this print?

int[] a = {3, 1, 4, 1, 5};
int max = a[0];
for (int x : a) {
    if (x > max) {
        max = x;
    }
}
System.out.println(max);
Multiple choicemediumLoops

Which loop always runs its body at least once?

Predict the outputmediumLoops

What does this print?

for (int i = 10; i > 0; i -= 3) {
    System.out.print(i + " ");
}

23for, while and do-while Loops

Read the lesson

How many iterations occur for i = 0; i < 1; i++?

Multiple choicemediumfor, while and do-while Loops

Where should a running total be initialized?

24Nested and Enhanced for Loops

Read the lesson

How many cells are visited in rows of lengths 2, 1 and 3?

Multiple choicemediumNested and Enhanced for Loops

Which form can replace an array element directly?

25break and continue

Read the lesson
Multiple choiceeasybreak and continue

What does FirstMatchingIndex do after finding index 1?

Multiple choicemediumbreak and continue

In a basic for loop, what happens after continue?

Fill in the blankseasyMethods

Complete the method so it returns the sum of two ints.

static  sum(int a, int b) {
     a + b;
}
Predict the outputeasyMethods

What does this print?

static String shout(String s) {
    return s.toUpperCase() + "!";
}
// in main:
System.out.println(shout("hey"));
Multiple choicemediumMethods

Which return type should a method use if it only prints something?

Predict the outputmediumMethods

What does this print?

static int f(int x) { return x + 1; }
static int f(int x, int y) { return x * y; }
// in main:
System.out.println(f(3) + f(3, 4));
Multiple choicehardMethods

Which pair of methods is valid overloading?

27Methods and Parameters

Read the lesson
Multiple choiceeasyMethods and Parameters

What is count after increase(count) when it began at 5?

Multiple choicemediumMethods and Parameters

Why does mark change original[0] but not replace original?

28Return Values and Method Overloading

Read the lesson

Which maximum overload is selected for 3.5 and 7.25?

Can changing only parameter names create an overload?

29Variable Scope

Read the lesson
Multiple choiceeasyVariable Scope

Can a variable declared inside an if block be named after its closing brace?

Multiple choicemediumVariable Scope

Why does BranchAssignment compile without an initializer at declaration?

30Recursion: Base Cases and Calls

Read the lesson

What does factorial(0) return in the example?

Multiple choicemediumRecursion: Base Cases and Calls

How does RecursiveArraySum approach its base case?

Fill in the blankseasyArrays

Complete the line so it prints the number of elements.

int[] nums = {4, 8, 15};
System.out.println(nums.);
Predict the outputeasyArrays

What does this print?

double[] d = new double[2];
System.out.println(d[1]);
Predict the outputmediumArrays

What does this print?

int[] a = {3, 1, 2};
int[] b = a;
Arrays.sort(b);
System.out.println(Arrays.toString(a));
Predict the outputmediumArrays

What does this print?

int[][] g = {{1, 2, 3}, {4, 5, 6}};
System.out.println(g.length + " " + g[1][2]);
Multiple choicehardArrays

Which line creates an independent copy of int[] a?

32Single and Multidimensional Arrays

Read the lesson

Which loop respects ragged row lengths?

What does cloning int[][] copy first?

33Array Operations and Sorting

Read the lesson
Multiple choiceeasyArray Operations and Sorting

Which operation preserves an int array's original order before sorting?

Multiple choicemediumArray Operations and Sorting

What must be true before binarySearch?

34Classes & Objects

Read the lesson
Fill in the blankseasyClasses & Objects

Complete the code that creates a new Book object.

Book b =  Book("Dune");
Fill in the blanksmediumClasses & Objects

Complete the constructor so it stores the title in the field.

class Book {
    String title;
    Book(String title) {
        .title = title;
    }
}
Multiple choicemediumClasses & Objects

What is the difference between a class and an object?

Predict the outputmediumClasses & Objects

What does this print?

Rectangle r = new Rectangle(2, 3);
r.width = 5;
System.out.println(r.area());
Multiple choicemediumClasses & Objects

Why make fields private and add getters?

35Classes and Objects Explained

Read the lesson

Two variables are assigned the same Card reference. Which operation changes the shared card?

Multiple choicemediumClasses and Objects Explained

What does == compare for two non-null object references?

36Fields, Attributes and Methods

Read the lesson

A tank's level must survive between add calls. Where should it be stored?

Multiple choicemediumFields, Attributes and Methods

Which declaration shares one value across instances?

37Constructors and Constructor Overloading

Read the lesson

What happens after adding only Ticket(String title)?

Which constructors have different signatures?

38this Keyword

Read the lesson
Multiple choiceeasythis Keyword

In a constructor with a parameter named code, what does this.code = code assign?

Predict the outputmediumthis Keyword

A constructor stores "Q-8". rename("Q-9") contains code = code instead of this.code = code. What remains in the field?

39Access and Non-Access Modifiers

Read the lesson

Which modifier prevents a method from being overridden?

Multiple choicemediumAccess and Non-Access Modifiers

Why can final List values still accept add?

40Encapsulation and Validation

Read the lesson
Multiple choiceeasyEncapsulation and Validation

Why copy a mutable constructor argument?

Multiple choicemediumEncapsulation and Validation

Which method order preserves a count on invalid input?

41Inner and Anonymous Classes

Read the lesson
Multiple choiceeasyInner and Anonymous Classes

How is a member inner Reader constructed for outer?

Multiple choicemediumInner and Anonymous Classes

Which variables may an anonymous class capture?

42Packages and Imports

Read the lesson
Multiple choiceeasyPackages and Imports

What does an import do?

Multiple choicemediumPackages and Imports

Which name identifies a packaged class completely?

43String Methods Reference

Read the lesson
Multiple choiceeasyString Methods Reference

What does substring(1, 4) include?

Multiple choicemediumString Methods Reference

Which method compares text contents?

44StringBuilder and StringBuffer

Read the lesson

What does toString return from a builder?

Multiple choicemediumStringBuilder and StringBuffer

Which range does delete(2, 5) remove?

45Wrapper Classes and Autoboxing

Read the lesson

What happens when a null Integer is used in addition?

Multiple choicemediumWrapper Classes and Autoboxing

Which generic element declaration is valid?

46ArrayList

Read the lesson
Fill in the blankseasyArrayList

Complete the code so the list holds Strings and "Tea" is added.

List<> drinks = new ArrayList<>();
drinks.("Tea");
Predict the outputeasyArrayList

What does this print?

List<String> l = new ArrayList<>(List.of("a", "b", "c"));
l.remove(0);
System.out.println(l.size() + " " + l.get(0));
Predict the outputmediumArrayList

What does this print?

List<Integer> n = new ArrayList<>(List.of(10, 20, 30));
n.set(1, 25);
n.add(0, 5);
System.out.println(n);
Multiple choicemediumArrayList

How do you get the number of items in an ArrayList called list?

Multiple choicehardArrayList

Which is the safe way to remove every empty string from a list while looping?

47List, ArrayList and LinkedList

Read the lesson

What does set(1, value) do?

Multiple choicemediumList, ArrayList and LinkedList

Which call removes the Integer value one?

48HashMap & HashSet

Read the lesson
Fill in the blankseasyHashMap & HashSet

Complete the code that stores and reads a capital city.

Map<String, String> capitals = new HashMap<>();
capitals.("Japan", "Tokyo");
System.out.println(capitals.("Japan"));
Predict the outputeasyHashMap & HashSet

What does this print?

Map<String, Integer> m = new HashMap<>();
m.put("a", 1);
m.put("a", 5);
System.out.println(m.size() + " " + m.get("a"));
Predict the outputmediumHashMap & HashSet

What does this print?

Set<Integer> s = new HashSet<>(List.of(3, 1, 3, 2, 1));
System.out.println(s.size() + " " + s.add(2));
Multiple choicemediumHashMap & HashSet

Which map keeps its keys in sorted order?

Multiple choicehardHashMap & HashSet

Which collection best answers "has this username already been taken?" quickly?

49HashMap, TreeMap and LinkedHashMap

Read the lesson

What happens when put uses an existing key?

Which method distinguishes a null mapping from a missing key?

50Collections

Read the lesson
Fill in the blankseasyCollections

Complete the line so the set keeps its items sorted.

Set<String> names = new <>();
Multiple choiceeasyCollections

Which collection rejects duplicate items?

Predict the outputmediumCollections

What does this print?

Deque<Integer> d = new ArrayDeque<>();
d.push(1); d.push(2); d.push(3);
System.out.println(d.pop());
Predict the outputmediumCollections

What does this print?

Queue<Integer> pq = new PriorityQueue<>(List.of(8, 3, 6));
System.out.println(pq.poll());
Multiple choicehardCollections

Which Comparator sorts players by score, highest first?

51Collections Framework Explained

Read the lesson

Which contract permits duplicate positional elements?

Multiple choicemediumCollections Framework Explained

Which framework type associates keys with values?

52HashSet, TreeSet and LinkedHashSet

Read the lesson

Which set preserves insertion order?

What decides TreeSet uniqueness?

53Iterators and the Iterable Interface

Read the lesson

Which type supplies an iterator?

Which operation advances an ordinary iterator?

54Collections Sorting and Comparators

Read the lesson

When does thenComparing run its secondary rule?

What does List.sort change?

55Inheritance

Read the lesson
Fill in the blankseasyInheritance

Complete the class so Dog inherits from Animal.

class Dog  Animal {
}
Fill in the blanksmediumInheritance

Complete the constructor so the parent sets the name.

Dog(String name) {
    (name);
}
Predict the outputmediumInheritance

What does this print?

class A { String hi() { return "A"; } }
class B extends A { @Override String hi() { return "B"; } }
// in main:
A obj = new B();
System.out.println(obj.hi());
Multiple choicemediumInheritance

Which access modifier lets subclasses use a field while hiding it from unrelated classes in other packages?

Multiple choicehardInheritance

What does @Override do?

56Inheritance and the super Keyword

Read the lesson

What does super(...) invoke?

A Label reference holds a FragileLabel. Which text override runs?

57Polymorphism and Method Overriding

Read the lesson

Why add @Override?

Which operation uses runtime dispatch?

58Interfaces & Abstract

Read the lesson
Fill in the blankseasyInterfaces & Abstract

Complete the class so it keeps the Drawable contract.

class Logo  Drawable {
    public void draw() { System.out.println("Drawing logo"); }
}
Fill in the blanksmediumInterfaces & Abstract

Complete the declaration of a method subclasses must implement.

abstract class Animal {
     String sound();
}
Multiple choicemediumInterfaces & Abstract

How many interfaces can one class implement?

Predict the outputmediumInterfaces & Abstract

What does this print?

interface Greeter {
    String name();
    default String greet() { return "Hi " + name(); }
}
// in main:
Greeter g = () -> "Zoe";
System.out.println(g.greet());
Multiple choicehardInterfaces & Abstract

Which can an abstract class have that an interface can't?

59Abstraction and Interfaces

Read the lesson
Multiple choiceeasyAbstraction and Interfaces

Why must Receipt.text be public when implementing Printable.text?

Multiple choicemediumAbstraction and Interfaces

Can an abstract class contain concrete methods?

Fill in the blankseasyEnums

Complete the declaration of an enum for a traffic light.

 Light { RED, AMBER, GREEN }
Multiple choiceeasyEnums

How should two enum values be compared?

Predict the outputmediumEnums

What does this print?

enum Size { SMALL, MEDIUM, LARGE }
System.out.println(Size.LARGE.ordinal());
Multiple choicemediumEnums

What does Size.values() return?

Multiple choicehardEnums

Why doesn't a switch expression over every enum constant need a default?

61Enums and Enum Constructors

Read the lesson
Multiple choiceeasyEnums and Enum Constructors

Why is ordinal a poor durable storage code?

Multiple choicemediumEnums and Enum Constructors

Can callers create Speed with new Speed(3)?

Fill in the blankseasyGenerics

Complete the declaration of a generic class with one type parameter.

class Box<> {
    private T item;
}
Multiple choiceeasyGenerics

What does the diamond <> in new ArrayList<>() do?

Multiple choicemediumGenerics

Where does a generic method declare its type parameter?

Predict the outputmediumGenerics

What does largest(List.of("kiwi", "banana", "fig")) return, using the lesson's method?

Multiple choicehardGenerics

Which parameter type lets a method add Integers to a List<Object>?

63Generics and Generic Classes

Read the lesson
Multiple choiceeasyGenerics and Generic Classes

What is T in Box<T>?

Multiple choicemediumGenerics and Generic Classes

Which declaration can read Integer-list elements as Number?

64Exceptions

Read the lesson
Fill in the blankseasyExceptions

Complete the code so the error is handled.

 {
    int n = Integer.parseInt("abc");
}  (NumberFormatException e) {
    System.out.println("Invalid");
}
Predict the outputeasyExceptions

What does this print?

try {
    int[] a = new int[2];
    a[5] = 1;
    System.out.println("A");
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("B");
}
Predict the outputmediumExceptions

What does this print?

try {
    System.out.println("1");
} finally {
    System.out.println("2");
}
System.out.println("3");
Multiple choicemediumExceptions

Which exception is checked?

Multiple choicehardExceptions

What does try-with-resources do?

65Exception Types and Hierarchy

Read the lesson

Which branch contains ArithmeticException?

Multiple choicemediumException Types and Hierarchy

What does a throws declaration do?

66try, catch, finally, throw and throws

Read the lesson

Which statement is skipped after the parser throws in CatchFlow?

Why does Cleanup step print before twelve?

67Custom Exceptions and Multi-Catch

Read the lesson

Why store available stock as a field in the exception?

Which parent produces an unchecked custom argument exception?

68Try-with-Resources

Read the lesson
Multiple choiceeasyTry-with-Resources

Which interface makes a resource eligible for this construct?

Multiple choicemediumTry-with-Resources

Which resource closes first when declared first then second?

69File Handling: Create, Read, Write, Delete

Read the lesson

What does createFile do when the entry already exists?

What keeps the first line during the second write?

70Path and Files APIs

Read the lesson
Multiple choiceeasyPath and Files APIs

What does resolve("week.txt") do to this relative base?

Multiple choicemediumPath and Files APIs

Does normalize access the filesystem?

71Byte Streams and Character Streams

Read the lesson

What should copy a PNG file without interpreting its content?

Predict the outputmediumByte Streams and Character Streams

UTF-8 encodes Café into five bytes. Does its Java String length have to be five?

72FileInputStream and FileOutputStream

Read the lesson

What does opening an existing file with ordinary FileOutputStream do?

Predict the outputmediumFileInputStream and FileOutputStream

The copy loop reads one byte into a two-byte buffer. Which write is correct?

73BufferedReader and BufferedWriter

Read the lesson

What does readLine return for a blank line?

Predict the outputmediumBufferedReader and BufferedWriter

NumericLinesExample reads 11, a blank line, and 7. How many measurements are accepted?

74Serialization and Deserialization

Read the lesson

Which field is omitted by default serialization?

Predict the outputmediumSerialization and Deserialization

What happens to Workspace.preview after the shown round trip?

75JSON Processing in Java

Read the lesson
Multiple choiceeasyJSON Processing in Java

Which JSON value has a numeric type?

Predict the outputmediumJSON Processing in Java

What category describes {"pieces":"ten"} under the shown validator?

76Files & I/O

Read the lesson
Fill in the blankseasyFiles & I/O

Complete the line that reads a whole file into one String.

String text = Files.(Path.of("story.txt"));
Multiple choiceeasyFiles & I/O

What happens to a file's contents when you call Files.writeString(path, "hi")?

Multiple choicemediumFiles & I/O

Which is best for counting lines in a 5 GB log file?

Multiple choicemediumFiles & I/O

What kind of exception is IOException?

Predict the outputhardFiles & I/O

A file contains three lines. What does Files.readAllLines(p).get(3) do?

77Dates & Times

Read the lesson
Fill in the blankseasyDates & Times

Complete the code so it creates the date 25 December 2024.

LocalDate xmas = LocalDate.(2024, 12, 25);
Multiple choiceeasyDates & Times

Which class holds a date with no time?

Predict the outputmediumDates & Times

What does this print?

LocalDate d = LocalDate.of(2024, 1, 31).plusMonths(1);
System.out.println(d);
Multiple choicemediumDates & Times

Which gives the total number of days between two dates?

Multiple choicehardDates & Times

What should you store for "when was this order created?" in a system used worldwide?

78Date and Time API: java.time

Read the lesson
Multiple choiceeasyDate and Time API: java.time

Which type fits an ordinary birthday?

Multiple choicemediumDate and Time API: java.time

What happens to arrival after arrival.plusDays(2)?

79Lambdas & Streams

Read the lesson
Fill in the blankseasyLambdas & Streams

Complete the lambda so it doubles a number.

Function<Integer, Integer> doubler = x  x * 2;
Predict the outputeasyLambdas & Streams

What does this print?

System.out.println(List.of(1, 2, 3, 4, 5).stream().filter(n -> n % 2 == 1).toList());
Predict the outputmediumLambdas & Streams

What does this print?

int total = List.of(3, 4, 5).stream().map(n -> n * n).reduce(0, Integer::sum);
System.out.println(total);
Multiple choicemediumLambdas & Streams

Which is a terminal operation?

Multiple choicehardLambdas & Streams

What is a functional interface?

80Lambda Expressions

Read the lesson
Multiple choiceeasyLambda Expressions

Which change prevents the threshold predicate from compiling?

Multiple choicemediumLambda Expressions

What does lateCharge.apply(6) return?

81Functional Interfaces

Read the lesson
Multiple choiceeasyFunctional Interfaces

Why does VisitorRules safely test an empty string?

Multiple choicemediumFunctional Interfaces

Which interface produces a value without receiving an input?

82Method References

Read the lesson
Multiple choiceeasyMethod References

In String::length assigned to Function<String, Integer>, what becomes the receiver?

Multiple choicemediumMethod References

When does ArrayList::new assigned to Supplier create a list?

83Stream API: map, filter and reduce

Read the lesson

Which operation starts traversal in PricePipeline?

What does reducing an empty integer stream with zero and Integer::sum return?

84Optional: Handling Missing Values

Read the lesson

Which factory accepts a nullable value?

Why does the first orElseGet call not print a fallback message?

85Regular Expressions

Read the lesson
Multiple choiceeasyRegular Expressions

Which Matcher method searches within a longer sentence?

Multiple choicemediumRegular Expressions

What does group(0) contain?

86Annotations Explained

Read the lesson
Multiple choiceeasyAnnotations Explained

Which retention policy supports getAnnotation at runtime?

Multiple choicemediumAnnotations Explained

What does @Override verify?

87Reflection API

Read the lesson
Multiple choiceeasyReflection API

Which lookup includes public inherited methods?

Multiple choicemediumReflection API

What wraps an exception thrown by a reflected method?

88Multithreading and Thread Lifecycle

Read the lesson

Which operation requests execution on a new thread?

Why is Finished printed after Packing complete?

89Synchronization and Race Conditions

Read the lesson

What monitor does a synchronized instance method use?

Why is a volatile int insufficient for an atomic increment?

90ExecutorService and Thread Pools

Read the lesson

Which task interface can return a value?

Where does a submitted task failure become visible to its caller?

91Concurrency Utilities

Read the lesson
Multiple choiceeasyConcurrency Utilities

Which operation waits for a latch count to reach zero?

Multiple choicemediumConcurrency Utilities

Why is END not printed by QueueTransfer?

92Debugging and Logging Basics

Read the lesson
Multiple choiceeasyDebugging and Logging Basics

What makes an order log useful?

Multiple choicemediumDebugging and Logging Basics

Why is Message constructed absent?

Fill in the blankseasyRecords

Complete the declaration of a record with a title and a year.

 Film(String title, int year) {}
Multiple choiceeasyRecords

How do you read the title of Film f?

Predict the outputmediumRecords

What does this print?

record Pair(int a, int b) {}
System.out.println(new Pair(1, 2).equals(new Pair(1, 2)));
Multiple choicemediumRecords

Where do you validate a record's values?

Multiple choicehardRecords

Which is the best choice for a bank account whose balance changes?

94Unit Testing (JUnit)

Read the lesson
Fill in the blankseasyUnit Testing (JUnit)

Complete the annotation that marks a method as a JUnit test.


void addsTwoNumbers() {
    assertEquals(4, 2 + 2);
}
Multiple choiceeasyUnit Testing (JUnit)

In assertEquals(a, b), which argument is the expected value?

Multiple choicemediumUnit Testing (JUnit)

How do you check that withdraw(-5) throws IllegalArgumentException?

Multiple choicemediumUnit Testing (JUnit)

What does @BeforeEach do?

Predict the outputhardUnit Testing (JUnit)

A @ParameterizedTest has 5 rows in its @CsvSource. How many tests does the report show for it?

95JDK, JRE and JVM Explained

Read the lesson
Multiple choiceeasyJDK, JRE and JVM Explained

Which tool compiles Java source to class files?

Multiple choicemediumJDK, JRE and JVM Explained

Which component executes bytecode?

96Installing Java and Setting Up the JDK

Read the lesson

What should a development installation provide?

Where should JAVA_HOME point?

97Compiling and Running Java Programs

Read the lesson

Which command targets Java 17 while compiling?

What does -cp out select?

98Classpath and Package Layout

Read the lesson
Multiple choiceeasyClasspath and Package Layout

Where is the classpath root for out/museum/labels/Ticket.class?

Multiple choicemediumClasspath and Package Layout

Which launch name matches package museum.labels?

99Maven and Gradle Basics

Read the lesson
Multiple choiceeasyMaven and Gradle Basics

Where does Maven normally compile main Java source from?

Multiple choicemediumMaven and Gradle Basics

Which lifecycle phase creates the configured artifact?

100Unit Testing with JUnit

Read the lesson
Multiple choiceeasyUnit Testing with JUnit

Which case catches a strict comparison mistake at the threshold?

Multiple choicemediumUnit Testing with JUnit

Which assertion verifies a particular rejected-input exception?

101Debugging Java Applications Step by Step

Read the lesson

Which input distinguishes quantity > 10 from quantity >= 10?

What does the call stack show?

102Git Basics for Java Projects

Read the lesson
Multiple choiceeasyGit Basics for Java Projects

Which command shows the patch selected for the next commit?

Multiple choicemediumGit Basics for Java Projects

Which directory is normally generated Maven output?

103Modern Java: Records, Sealed Classes and Patterns

Read the lesson

What is the generated accessor for a record component named label?

What does permits describe?

104Modules and module-info.java

Read the lesson
Multiple choiceeasyModules and module-info.java

What is the descriptor filename?

Multiple choicemediumModules and module-info.java

Which module is implicitly read by every named module?

105Time and Space Complexity

Read the lesson
Multiple choiceeasyTime and Space Complexity

What is the auxiliary space of LinearVisits?

Multiple choicemediumTime and Space Complexity

How many pairs does PairVisits count when n is 5?

106Linear Search and Binary Search

Read the lesson

What is the crucial precondition for binary search here?

Multiple choicemediumLinear Search and Binary Search

Why does the loop use low <= high?

107Sorting Algorithms Explained

Read the lesson
Multiple choiceeasySorting Algorithms Explained

What is finalized after each selection-sort pass?

Multiple choicemediumSorting Algorithms Explained

Why does insertion sort save value before shifting?

108Stacks and Queues with ArrayDeque

Read the lesson

Which action is removed first from UndoStack?

What does poll return on an empty ArrayDeque queue?

109Linked Lists: Nodes and Links

Read the lesson

What terminates traversal in the singly linked examples?

Multiple choicemediumLinked Lists: Nodes and Links

Why save next before redirecting current.next?

110Hashing and Hash Tables

Read the lesson
Multiple choiceeasyHashing and Hash Tables

What must be true for equal keys?

Multiple choicemediumHashing and Hash Tables

Why do CollisionKeys entries remain distinct?

111Trees and Binary Search Trees

Read the lesson

Where should 25 be inserted into a tree with root 40 and left child 20?

Predict the outputmediumTrees and Binary Search Trees

Insert 3, then 4, then 5 into the unbalanced tree. What shape results?

112Heaps and Priority Queues

Read the lesson
Multiple choiceeasyHeaps and Priority Queues

A natural-order integer queue contains 15, 6 and 10. What does peek return?

Predict the outputmediumHeaps and Priority Queues

Two jobs compare as equal and the comparator has no tie-breaker. What can you assume?

113Graphs, BFS and DFS

Read the lesson
Multiple choiceeasyGraphs, BFS and DFS

An undirected connection joins Library and Cafe. What should its adjacency lists contain?

Predict the outputmediumGraphs, BFS and DFS

Entry lists Hall before Studio; Hall leads to Exit. Which order does BFS print?

114Recursion and Backtracking

Read the lesson
Multiple choiceeasyRecursion and Backtracking

Why does the subset example remove the final chosen card after its recursive call?

Predict the outputmediumRecursion and Backtracking

How many permutations does the distinct array A, B, C have?

115Dynamic Programming Basics

Read the lesson
Multiple choiceeasyDynamic Programming Basics

What does ways(0) = 1 mean in the staircase problem?

Predict the outputmediumDynamic Programming Basics

Using unlimited coins 1, 3 and 4, what is the minimum count for amount 6?

116Examples Library for Beginners

Read the lesson

How many six-item trays are needed for seven items?

Multiple choicemediumExamples Library for Beginners

Which collection preserves first-seen uniqueness here?

117Exercises by Topic

Read the lesson
Multiple choiceeasyExercises by Topic

What remains after splitting seventeen tokens among five players?

Multiple choicemediumExercises by Topic

Do equal adjacent values count as a rising step?

118Quizzes by Chapter

Read the lesson
Multiple choiceeasyQuizzes by Chapter

What is 25 / 4 when both operands are int?

Multiple choicemediumQuizzes by Chapter

Why is the first QuizStringIdentity output false?

119Coding Challenges with Test Cases

Read the lesson

How does the run encoder represent aba?

Why scan the original text in the unique-character second pass?

120Keywords Reference and Glossary

Read the lesson

Which item is a boolean literal rather than a keyword?

Multiple choicemediumKeywords Reference and Glossary

What does yield do in KeywordContext?

121String, Math and Collections Methods

Read the lesson

What is the end convention of substring(start, end)?

How do you remove integer value two from ArrayList<Integer>?

122Common Java Errors and Solutions

Read the lesson

Which failure can happen before execution because of source type mismatch?

Why is quantity zero not a NumberFormatException?

123Interview Questions and Answers

Read the lesson

Why does InterviewArguments print count as three?

Multiple choicemediumInterview Questions and Answers

Why does inspect(signal) choose the Signal overload?

124Beginner Java Projects with Practice Steps

Read the lesson

Which pair tests a started-block parking boundary?

Why reject an empty score array before reading scores[0]?

125Intermediate Java Projects: Collections and Files

Read the lesson

Why does the file prototype use finally?

Why use Locale.ROOT in the word report?

126Advanced Java Projects: Testing and Concurrency

Read the lesson

What stays invariant after a successful prototype transfer?

Which key is evicted after A is accessed and C is inserted?

127Learning Roadmap and Study Plan

Read the lesson

What is stronger evidence than finishing a page?

Multiple choicemediumLearning Roadmap and Study Plan

What does RoadmapStorage.charge return?

Next steps