First 50 of 200 questions. Each one lists the choices, the correct answer, and an explanation. The checker at the top of this page saves progress in this browser when it is available.
Continue in the practice tool above to load more questions, 50 at a time.
Question 1Handling Date, Time, Text, Numeric and Boolean Values
Which java.time class models a date such as 2024-06-01 with no time-of-day and no time zone attached to it?
- LocalDate Correct answer.
- LocalDateTime
- LocalTime
- Instant
Explanation
LocalDate holds only a year, month and day, so it carries no clock time and no offset or zone. LocalTime holds only a time-of-day, while LocalDateTime and Instant both include a time component.
Question 2Handling Date, Time, Text, Numeric and Boolean Values
Which statement describes the behaviour of String.strip() for a string built from Latin-1 and other Unicode characters?
- It removes leading and trailing code points where Character.isWhitespace is true. Correct answer.
- It removes leading and trailing characters with a code point of U+0020 or lower.
- It removes only trailing whitespace and leaves the leading whitespace intact.
- It removes every whitespace character anywhere inside the text.
Explanation
strip() was added in Java 11 and delegates to a Unicode-aware whitespace test, Character.isWhitespace, on each leading and trailing code point. The older trim() method, in contrast, only strips characters whose value is U+0020 or below.
Question 3Handling Date, Time, Text, Numeric and Boolean Values
Which type is designed to express the amount between two LocalDate values as a number of years, months and days?
- Period Correct answer.
- Instant
- Duration
- ChronoUnit
Explanation
Period is the date-based amount type and stores separate year, month and day fields. Duration measures a time-based amount in seconds and nanoseconds and is used with time or instant values.
Question 4Handling Date, Time, Text, Numeric and Boolean Values
What does Boolean.parseBoolean("TRUE") evaluate to?
- true Correct answer.
- false
- null
- It throws IllegalArgumentException.
Explanation
parseBoolean compares the argument to the literal "true" ignoring case and returns a primitive boolean. The string "TRUE" matches case-insensitively, so the result is true.
Question 5Handling Date, Time, Text, Numeric and Boolean Values
Given LocalDate.of(2024, 1, 31).plusMonths(1), what date results?
- It throws DateTimeException.
- 2024-03-02
- 2024-02-28
- 2024-02-29 Correct answer.
Explanation
When the target month is shorter than the current day-of-month, plusMonths clamps to the last valid day of that month instead of overflowing. January 31 plus one month therefore becomes the last day of February 2024, and because 2024 is a leap year that day is the 29th.
Question 6Handling Date, Time, Text, Numeric and Boolean Values
What is the result of Duration.ofSeconds(90).toString()?
- PT1M30S Correct answer.
- P1M30S
- PT90S
- PT1.30S
Explanation
Duration.toString() produces an ISO-8601 time-based representation and normalises the value into hours, minutes and seconds. Ninety seconds therefore becomes one minute and thirty seconds, written as PT1M30S.
Question 7Handling Date, Time, Text, Numeric and Boolean Values
Which rule applies to the opening delimiter of a text block?
- Text blocks cannot contain double-quote characters unless escaped.
- The closing delimiter must appear on the same line as the last content line.
- Content may begin on the same line immediately after the opening delimiter.
- The opening delimiter must be followed by a line terminator. Correct answer.
Explanation
A text block starts with three double quotes that must be followed by a line terminator, otherwise the code does not compile. The content starts on the next line, and the closing delimiter may appear on its own line.
Question 8Handling Date, Time, Text, Numeric and Boolean Values
What is the value of new BigDecimal("1.0").equals(new BigDecimal("1.00"))?
- false Correct answer.
- true
- true, but only when the objects are created with BigDecimal.valueOf
- It throws NumberFormatException.
Explanation
BigDecimal.equals compares both the unscaled value and the scale, and the two literals have scales of 1 and 2 respectively. The equals method therefore returns false even though the numeric values are identical, while compareTo would return 0.
Question 9Handling Date, Time, Text, Numeric and Boolean Values
What does LocalDate.of(2024, 3, 5).format(DateTimeFormatter.ofPattern("dd/MM/yy")) return?
- 05/03/2024
- 05/03/24 Correct answer.
- 2024-03-05
- 5/3/24
Explanation
In a pattern, dd and MM are the two-digit zero-padded forms of day-of-month and month, and yy is the two-digit year. March 5, 2024 therefore formats as 05/03/24.
Question 10Handling Date, Time, Text, Numeric and Boolean Values
What does String.format("%.2f", 3.14159) return?
- 3.14 Correct answer.
- 3
- 3.142
- 3.1
Explanation
The precision in %.2f asks for exactly two digits after the decimal point, and the value is rounded half-up when the discarded digits are dropped. Rounding 3.14159 to two decimals gives 3.14.
Question 11Handling Date, Time, Text, Numeric and Boolean Values
What is the result of Period.between(LocalDate.of(2024, 1, 31), LocalDate.of(2024, 3, 1)).toString()?
- P1M1D Correct answer.
- P30D
- P1M2D
- P2M-30D
Explanation
Period.between first takes the whole-month difference, then adjusts because the end day-of-month is smaller than the start day-of-month. One month added to 2024-01-31 clamps to 2024-02-29, leaving a single remaining day, so the period is P1M1D.
Question 12Handling Date, Time, Text, Numeric and Boolean Values
What happens when LocalDate.parse("2024-02-30") is executed?
- It returns 2024-02-28, the last valid day of that month.
- It returns null because the date is invalid.
- It throws DateTimeParseException. Correct answer.
- It returns 2024-03-01 by rolling over the extra day.
Explanation
LocalDate.parse validates the parsed field values strictly and rejects a day that does not exist in the given month. Because February 2024 has only 29 days, parsing "2024-02-30" fails with a DateTimeParseException.
Question 13Handling Date, Time, Text, Numeric and Boolean Values
What is the value of "ab".repeat(3)?
- abab
- ababab Correct answer.
- ab3
- aaabbb
Explanation
String.repeat(int) concatenates the original string the requested number of times. Repeating "ab" three times yields six characters: ababab.
Question 14Handling Date, Time, Text, Numeric and Boolean Values
What is the value of Duration.ofHours(2).plusMinutes(30).toMinutes()?
- 150 Correct answer.
- 2.5
- 2
- 120
Explanation
Duration stores a single length of time, so hours and minutes are combined before the conversion. Two hours is 120 minutes and adding 30 minutes gives 150, which toMinutes() returns as a long.
Question 15Handling Date, Time, Text, Numeric and Boolean Values
Which statement about DateTimeFormatter instances is correct?
- They are thread-safe only when created by DateTimeFormatter.ofPattern.
- They keep the last formatted value as internal state.
- They are immutable and can be shared safely between threads. Correct answer.
- They are mutable and must not be shared between threads.
Explanation
DateTimeFormatter is an immutable, thread-safe class, so one instance can be stored in a static final field and reused by many threads. All factory methods, including ofPattern, return such immutable instances.
Question 16Handling Date, Time, Text, Numeric and Boolean Values
What is the value of Math.round(-2.5)?
- -1
- -2 Correct answer.
- -3
- -2.0
Explanation
Math.round(double) is defined as floor(value + 0.5) and returns a long. Adding 0.5 to -2.5 gives -2.0, whose floor is -2, so negatives are rounded towards positive infinity on an exact half.
Question 17Handling Date, Time, Text, Numeric and Boolean Values
What is the result of Integer.parseInt("+42")?
- 42 Correct answer.
- It throws IllegalArgumentException.
- It throws NumberFormatException.
- -42
Explanation
The parse methods accept an optional leading plus or minus sign, so the leading '+' is consumed as a sign rather than treated as an invalid character. The remaining digits 42 are parsed and returned as the int value 42.
Question 18Handling Date, Time, Text, Numeric and Boolean Values
What is the result of LocalDate.of(2024, 2, 29).plusYears(1)?
- 2025-03-01
- It throws DateTimeException.
- 2025-02-29
- 2025-02-28 Correct answer.
Explanation
Adding a year to a leap day produces an invalid date in the following, non-leap year, so the day-of-month is clamped to the last valid day. The result is therefore 2025-02-28, and no exception is raised.
Question 19Handling Date, Time, Text, Numeric and Boolean Values
Given the declaration Boolean flag = null; followed by boolean b = flag; what is the outcome?
- The code fails to compile because Boolean cannot be unboxed.
- A NullPointerException is thrown. Correct answer.
- b is assigned false because null is treated as false.
- b is assigned true because the wrapper was never initialised.
Explanation
Assigning a Boolean to a boolean triggers automatic unboxing through Boolean.booleanValue(). Calling that method on a null reference fails at run time with a NullPointerException.
Question 20Handling Date, Time, Text, Numeric and Boolean Values
What is the result of evaluating the expression Integer.valueOf(5).equals(Long.valueOf(5))?
- It throws a ClassCastException.
- true
- It fails to compile.
- false Correct answer.
Explanation
Integer and Long override equals() so that a value is equal only to another wrapper object of the same concrete class holding the same primitive value; a Long is never equal to an Integer, so the call returns false. Because equals(Object) takes an Object parameter, any wrapper can be passed without a cast, and nothing is unboxed during the comparison.
Question 21Controlling Program Flow
Which statement describes the arrow (->) form of a switch label?
- Only the matched label's expression or block is executed; control never falls through to the next label. Correct answer.
- Execution continues into following labels until a break statement is reached.
- Every arrow label must be followed by a block that supplies a value with yield.
- It may be used only inside a switch statement, never where a value is assigned.
Explanation
Arrow labels give each label its own implicit scope and never fall through, so no break is needed. A single expression supplies the value directly, while only a block body requires yield.
Question 22Controlling Program Flow
What is guaranteed about the body of a do-while loop?
- Its condition is evaluated before the body runs on every pass.
- Its condition must be a compile-time constant boolean expression.
- It cannot be exited early with a break statement.
- It executes at least once, even when the condition is false on the first evaluation. Correct answer.
Explanation
A do-while loop evaluates its condition after the body, so the body always runs once before the first test. The condition is an ordinary boolean expression evaluated at run time.
Question 23Controlling Program Flow
Inside a doubly nested loop, `outer:` labels the enclosing loop. What does the statement `break outer;` do?
- It skips the rest of the current iteration of the labelled loop and starts its next iteration.
- It exits only the innermost loop containing the break statement.
- It re-runs the labelled loop starting again from its initialization expression.
- It terminates the labelled loop and transfers control to the first statement after that loop. Correct answer.
Explanation
A labelled break abandons the labelled statement entirely, so control resumes after the loop carrying that label. It is not restricted to the innermost loop.
Question 24Controlling Program Flow
Given `int x = 5;` what is the value of `s` after `String s = x > 3 ? "big" : x > 1 ? "mid" : "small";`?
- the code does not compile because conditional expressions cannot be chained
- mid
- big Correct answer.
- small
Explanation
The conditional operator is right-associative, so the expression parses as `x > 3 ? "big" : (x > 1 ? "mid" : "small")`. Since x > 3 is true, the whole expression yields "big" and the nested part is not evaluated.
Question 25Controlling Program Flow
In the loop header `for (int i = 0; i < 3; i++) { ... }`, what is the scope of `i`?
- The entire enclosing method from the point of declaration onward.
- The rest of the enclosing block that follows the loop.
- The whole for statement, including the header and the body. Correct answer.
- Only the body between the braces, not the header.
Explanation
A variable declared in the initialization section of a for statement is scoped to the for statement itself, which includes the condition, the update, and the body. It is not visible after the loop ends.
Question 26Controlling Program Flow
How many times does the body of this loop execute?
int n = 10;
int c = 0;
while (n > 0) {
n -= 3;
c++;
}
- 5
- 3
- The loop never terminates.
- 4 Correct answer.
Explanation
The values of n at each test are 10, 7, 4 and 1, giving four iterations; after the fourth pass n becomes -2 and the test fails. Note that a negative value ends the loop rather than keeping it running.
Question 27Controlling Program Flow
A switch expression selects on a value of enum type E. Which statement about exhaustiveness is correct?
- It compiles only if the enum type declares at least one constant.
- Listing every enum constant is sufficient; no default label is needed. Correct answer.
- Exhaustiveness is enforced only when the switch is used as a statement, not as an expression.
- A default label is mandatory even when every enum constant is listed.
Explanation
A switch expression must produce a value for every possible selector value, and enumerating all constants of the enum achieves that. A default label becomes necessary only when some constant is not covered.
Question 28Controlling Program Flow
What is the value of r after the following code runs?
int k = 1;
int r = switch (k) {
case 1 -> { int t = 2; yield t * 3; }
default -> 0;
};
- The code does not compile because an arrow label may not be followed by a block.
- 6 Correct answer.
- 3
- 0
Explanation
An arrow label may be followed by a block, in which case the value is supplied by a yield statement. With k equal to 1, t becomes 2 and yield returns 2 * 3, which is 6.
Question 29Controlling Program Flow
What is the value of sum after this code runs?
int i = 0, sum = 0;
do {
i++;
if (i % 2 == 0) continue;
sum += i;
} while (i < 5);
- 6
- 15
- 9 Correct answer.
- 4
Explanation
In a do-while loop, continue jumps to the condition test rather than skipping it, so the loop still terminates normally. The odd values 1, 3 and 5 are accumulated, giving 9.
Question 30Controlling Program Flow
Where may the default label appear within a switch statement that uses colon labels?
- Only as the last label of the switch block.
- Only after all case labels that use constant expressions.
- Only as the first label of the switch block.
- Anywhere among the labels, since matching order does not depend on its position. Correct answer.
Explanation
The default label is chosen only when no case label matches, so its textual position is arbitrary. Position affects only fall-through behaviour once execution has entered the block.
Question 31Controlling Program Flow
After this code runs, what is the value of a[0]?
int[] a = {1, 2, 3};
for (int v : a) {
v = v * 2;
}
- 1 Correct answer.
- 4
- 6
- 2
Explanation
The enhanced for loop assigns each element's value to the loop variable, which is a separate local copy. Reassigning that variable changes nothing in the array, so a[0] keeps its original value of 1.
Question 32Controlling Program Flow
What does this code print?
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) continue outer;
System.out.print(i + "" + j + " ");
}
}
- 11 13 21 23 31 33
- 11 12 13 21 22 23 31 32 33
- 11 21 31 12 22 32
- 11 21 31 Correct answer.
Explanation
continue outer abandons the inner loop as soon as j reaches 2 and starts the next iteration of the labelled outer loop. Only the j == 1 iteration of each outer pass prints, yielding 11, 21 and 31.
Question 33Controlling Program Flow
What is the value of y after this code runs?
int x = 2, y = 0;
switch (x) {
case 1: y++;
case 2: y += 2;
case 3: y += 3; break;
default: y = 100;
}
- 2
- 100
- 5 Correct answer.
- 0
Explanation
Matching starts at case 2 with a colon label, and because there is no break before case 3 execution falls through both statements. That gives y = 0 + 2 + 3, and the break then exits the switch.
Question 34Controlling Program Flow
A switch statement has a default label, and its selector expression evaluates to null. What happens at run time?
- The switch completes normally without executing any label.
- A NullPointerException is thrown. Correct answer.
- The code fails to compile whenever a default label is present.
- The default label is executed.
Explanation
Evaluating the selector of a switch on a reference type requires unboxing or dereferencing-like handling, and a null selector always throws NullPointerException. The default label does not catch null unless the switch explicitly declares a null case label.
Question 35Controlling Program Flow
Which for-loop header is syntactically valid Java?
- for (int i = 0; int j = 5; i < j; i++, j--)
- for (int i = 0, int j = 5; i < j; i++, j--)
- for (int i = 0; i < 5; i++; j--)
- for (int i = 0, j = 5; i < j; i++, j--) Correct answer.
Explanation
Declarations in the initialization section share one type and are separated by commas, and the update section holds a comma-separated list of expressions. The three sections are separated by exactly two semicolons.
Question 36Controlling Program Flow
Which combination of switch label styles is permitted?
- Using arrow labels in a switch statement while using colon labels in a switch expression.
- Mixing arrow labels and colon labels inside a single switch block.
- Using only arrow labels, or only colon labels, throughout one switch block. Correct answer.
- Mixing the two styles only when the switch block also contains a default label.
Explanation
Java forbids mixing arrow and colon label styles within the same switch block, regardless of whether it is a statement or an expression. Different switch blocks may of course use different styles.
Question 37Controlling Program Flow
Which of these causes a compile-time error in a switch statement that uses colon labels?
- Declaring a local variable inside a case group that ends with a break statement.
- Declaring a local variable inside a block that forms an arrow-label case body.
- Declaring a local variable inside a case group that is never read afterwards.
- Declaring the same local variable name in two different colon-label case groups. Correct answer.
Explanation
All case groups of a colon-label switch share a single block scope, so the same name cannot be declared twice in it. Arrow-label bodies form separate scopes, and a variable that is never read is merely unused, not an error.
Question 38Controlling Program Flow
What does this code print?
for (int i = 0; i < 3; i++) {
switch (i) {
case 1: continue;
default: System.out.print(i);
}
System.out.print("-");
}
- 0-1-2-
- 012
- 0-
- 0-2- Correct answer.
Explanation
When i is 1 the switch executes continue, which targets the enclosing for loop and skips the rest of that iteration, including the separator. The other two iterations print the digit followed by a dash.
Question 39Controlling Program Flow
Given `int a = 1; long b = 2;` what is the compile-time type of `r` in `var r = true ? a : b;`?
- Integer
- long Correct answer.
- int
- It does not compile because the operands have different types.
Explanation
When both operands of the conditional operator are numeric, binary numeric promotion applies, so the int operand is promoted and the result type is long. var then infers long for r.
Question 40Controlling Program Flow
In a switch that uses type pattern labels, which construct is rejected at compile time?
- A guarded label such as `case String s when s.isEmpty()`.
- A `case Object o` label placed after a `case String s` label.
- A `default` label placed after a type pattern label.
- An unguarded `case String s` label placed after an unguarded `case Object o` label. Correct answer.
Explanation
A pattern label that is dominated by an earlier unguarded pattern is unreachable and therefore a compile-time error, and every String matches Object. Ordering the narrower pattern first, or adding a guard, removes the dominance problem.
Question 41Using Object-Oriented Concepts in Java
Which access modifier restricts a field so that it can be read and written only by code inside the class that declares it?
- protected
- private Correct answer.
- package-private (no modifier)
- public
Explanation
Encapsulation is usually implemented by making state private and exposing behaviour through methods. The private modifier is the most restrictive access level and limits visibility to the declaring top-level class body. Subclasses in other classes and classes in the same package cannot see the field.
Question 42Using Object-Oriented Concepts in Java
Which statement about a class declared with the abstract modifier is true?
- Every method it declares must be abstract.
- It can be instantiated as long as it declares no abstract methods.
- It cannot be instantiated directly, even if it declares no abstract methods. Correct answer.
- It must declare at least one abstract method.
Explanation
The abstract modifier on a class prevents direct instantiation with new, regardless of whether any abstract methods exist. Abstract classes may contain any mix of concrete and abstract methods, or only concrete ones. They exist to be extended and to hold state and shared behaviour.
Question 43Using Object-Oriented Concepts in Java
What is the effect of declaring a top-level class with the final modifier?
- Its methods can no longer be overridden.
- It cannot be extended by another class. Correct answer.
- It cannot be instantiated.
- Its fields become compile-time constants.
Explanation
The final modifier on a class prevents any other class from extending it, which is why classes such as String are final. Marking methods or fields final is a separate decision made per member. Instantiation is unaffected by a class being final.
Question 44Using Object-Oriented Concepts in Java
Inside a constructor, what does a statement of the form this(...) accomplish?
- It returns the current object to the caller.
- It creates a new instance of the current class.
- It calls a method named this on the superclass.
- It invokes another constructor of the same class. Correct answer.
Explanation
Constructor chaining is expressed with this(arguments), which must be the first statement of a constructor. It delegates initialization to another constructor of the same class, avoiding duplicated setup code. The compiler then does not insert an implicit super() call in that constructor.
Question 45Using Object-Oriented Concepts in Java
An interface declares a method using the default keyword and provides a body. What does this mean for classes that implement the interface?
- Implementing classes are forced to provide their own implementation.
- The method is implicitly static and is invoked on the interface name.
- Implementing classes inherit the body and may override the method. Correct answer.
- The method is visible only to code written inside the interface.
Explanation
A default method supplies an inherited implementation so that adding it does not break existing implementors. Implementing classes may use the inherited body unchanged or override it. It remains an instance method invoked on an object, not on the interface name.
Question 46Using Object-Oriented Concepts in Java
A method is declared inside an interface with no body and without the default or static modifier. What are its implicit modifiers?
- protected and abstract
- package-private and abstract
- public and final
- public and abstract Correct answer.
Explanation
Interface members are implicitly public, and a bodyless instance method is implicitly abstract. The compiler inserts both modifiers even though they are not written. Adding them explicitly is allowed but redundant.
Question 47Using Object-Oriented Concepts in Java
Given the declarations below, what is printed by the statements that follow them?
class A { static String name() { return "A"; } }
class B extends A { static String name() { return "B"; } }
A a = new B();
System.out.println(a.name());
- Compilation fails
- B
- A Correct answer.
- ClassCastException is thrown at runtime
Explanation
A static method with the same signature in a subclass hides the superclass version rather than overriding it. Static invocations are resolved at compile time from the declared type of the reference, which is A. No dynamic dispatch occurs, so A's version runs.
Question 48Using Object-Oriented Concepts in Java
A class declares both void m(long x) and void m(Integer x). A caller writes m(5) with an int literal 5. Which method is selected?
- m(Integer), because it is the most specific applicable type
- m(long), because widening is preferred over boxing Correct answer.
- m(Integer), because boxing is preferred over widening
- The call is ambiguous and fails to compile
Explanation
Overload resolution runs in phases: first without boxing or varargs, then with boxing, then with varargs. Since int widens to long in the first phase, that phase already finds an applicable method and later phases are never reached. Therefore the primitive long version is chosen.
Question 49Using Object-Oriented Concepts in Java
Two objects are considered equal by their equals method. What does the general contract require of their hashCode values?
- They must be different.
- There is no required relationship between them.
- They must be the same. Correct answer.
- They may differ if the objects are mutable.
Explanation
The contract states that if a.equals(b) is true then a.hashCode() must equal b.hashCode(). This keeps hash-based collections such as HashMap working correctly. The reverse does not hold: equal hash codes do not imply equal objects.
Question 50Using Object-Oriented Concepts in Java
A class is declared as sealed and lists exactly two permitted direct subclasses. What is required of those two subclasses?
- They must be declared in a different package from the sealed class.
- Each of them must be declared final, sealed, or non-sealed. Correct answer.
- They must be declared abstract.
- They must be declared as records.
Explanation
Every permitted subclass of a sealed class must state how it continues the hierarchy by being final, sealed, or non-sealed. Omitting that modifier is a compile-time error. Records and enums are implicitly final, so they satisfy the rule automatically.