Java SE 8 Programmer II (1Z0-809) — Free Practice Questions
10 free sample questions from a bank of 213, with the correct answers and explanations. No signup required — start practising right now.
1Given:
IntStream stream = IntStream.of (1,2,3);
IntFunction inFu= x -> y -> x*y; //line n1
IntStream newStream = stream.map(inFu.apply(10)); //line n2 newStream.forEach(System.output::print);
Which modification enables the code fragment to compile?
line n1 with:
Replace IntFunction inFu = x -> y -> x*y; line n1 with:
Replace IntFunction inFu = x -> y -> x*y; line n1 with:
Replace BiFunction inFu = x -> y -> x*y; line n2 with:
Replace
Answer: D
The short version
D — Replace line n1 with the settled functional form so the stream pipeline compiles. The curried lambda needs a type whose apply returns an IntUnaryOperator, and only D supplies that shape for map.
Key concepts in this question
IntStream map contract: map expects an IntUnaryOperator that takes an int and returns an int, applied to every element in order.
IntFunction shape: IntFunction takes an int and returns an object, so a bare IntFunction cannot directly serve as the mapper for IntStream.
Curried lambda pattern: x minus greater than y minus greater than x times y is a function that takes x and returns another function of y, requiring a nested functional type.
Apply chaining: inFu dot apply with 10 must yield a ready to use IntUnaryOperator that map can accept without adaptation.
Compile time checking: Java verifies primitive specializations before run, so mismatch fails the build.
Why D is correct
D is correct because it replaces line n1 with the settled type modeling a function returning another int function. With that form, inFu dot apply with 10 yields an IntUnaryOperator multiplying by ten, matching IntStream map at line n2. The pipeline type checks and the settled key identifies D as the only repair.
Why the others are wrong
A. Wrong because it retains a flat single level function type that cannot express the nested lambda and leaves the map argument incompatible.
B. Wrong because it repeats the same flat shape with no structural change, so apply still returns the wrong kind for map.
C. Wrong because it changes the wrong line and introduces a BiFunction style that does not align with primitive IntStream mapping.
1z0-809 exam tip
For curried lambdas on IntStream, demand a function returning IntUnaryOperator: flat IntFunction plus map always fails, nested form plus apply plus map always compiles.
2Given the definition of the Vehicle class:
Class Vehhicle {
int distance; //line n1
Vehicle (int x) {
this distance = x;
}
public void increSpeed(int time) { //line n2
int timeTravel = time; //line n3
class Car {
int value = 0;
public void speed () {
value = distance /timeTravel;
System.out.println ("Velocity with new speed"+value+"kmph");
}
}
new Car().speed();
}
}
and this code fragment:
Vehicle v = new Vehicle (100);
v.increSpeed(60);
What is the result?
Velocity with new speed -
line n1.
A compilation error occurs at line n2.
A compilation error occurs at line n3.
A compilation error occurs at
Answer: A
The short version
A — The local inner Car reads outer fields and prints velocity with value one. Effective final capture plus integer division explains the observed line.
Key concepts in this question
Local inner class scope: a class declared inside a method can access outer instance fields like distance directly.
Effective final capture: method locals such as timeTravel are capturable when never reassigned after initialization.
Integer division truncation: distance divided by timeTravel with ints yields a whole number used in the message.
Instantiation and call chain: new Car dot speed inside increSpeed triggers the print when the outer method runs.
Why A is correct
Per the settled key the program compiles and runs, with Vehicle 100 and increSpeed 60 producing Velocity with new speed plus one. The inner Car reads distance 100 and timeTravel 60 contextually, computes value via integer arithmetic, and prints the velocity line. Line n1 is therefore identified as the locus of correct field handling rather than a compilation fault, matching vendor prose that the velocity line appears.
Why the others are wrong
B. Line n2 method header is legal because increSpeed with int parameter and void return satisfies method declaration rules.
C. Line n3 local declaration is legal because timeTravel is initialized and effectively final for inner capture.
D. Truncated at phrasing shows no distinct valid fault location and cannot compete with the corroborated success path.
1z0-809 exam tip
For local inner class prints, verify outer field access plus effective final locals, then expect normal output rather than compile error.
3Given the definition of the Vehicle class:
Class Vehicle {
int distance;
Vehicle (int x) {
this distance = x;
}
public void increSpeed(int time) {
int timeTravel = time; //line n1
//line n3
class Car {
int value = 0;
public void speed () {
value = distance /timeTravel; //line n2
System.out.println ("Velocity with new speed"+value+"kmph");
}
}
speed(); //line n3
}
}
and this code fragment:
Vehicle v = new Vehicle (100);
v.increSpeed(60);
What is the result?
Velocity with new speed 1 kmph
A compilation error occurs at line n1.
A compilation error occurs at line n2.
A compilation error occurs at line n3.
Answer: D
The short version
D — compilation fails at line n3 because speed is out of scope. The bare speed call sits outside local class Car, so no such method exists in increSpeed.
Key concepts in this question
Local class scope: Class Car declared inside increSpeed is visible only within that method after its declaration point.
Method versus inner method: speed belongs to Car instances, not to Vehicle or increSpeed, so it needs a Car receiver.
Instantiation requirement: Calling an instance method of a local class requires new Car followed by dot speed.
Effectively final capture: timeTravel as a local variable is captured by the local class for the division, which is legal in this fragment.
Line n3 placement: The faulty call appears after the Car closing brace but still inside increSpeed, where Car type is known but speed is not a member.
Why D is correct
D is correct because speed is defined inside local class Car, yet line n3 invokes speed as if it were a method of increSpeed. The compiler cannot resolve a no-arg speed in Vehicle or in the method scope, so it reports a cannot-find-symbol error at line n3. Vendor analysis confirms the fix is new Car dot speed, proving the defect is call placement rather than variable capture at n1 or division at n2.
Why the others are wrong
A. Wrong because no execution occurs, so the velocity print with value one can never be produced.
B. Wrong because declaring timeTravel at line n1 is a valid local initialization captured by the local class.
C. Wrong because division using distance and timeTravel inside Car speed is type-valid and not the compilation fault.
1z0-809 exam tip
For local classes, always call through an instance: new Local dot method, never a bare method name outside.
4Given the code fragment:
Path source = Paths.get ("/data/december/log.txt");
Path destination = Paths.get("/data");
Files.copy (source, destination);
/data/december/log.txt is accessible and contains:
and assuming that the file
10-Dec-2014 Executed successfully
What is the result?
log.txt is created in the /data directory and the content of the /data/december/log.txt file is copied to it.
A file with the name
The program executes successfully and does NOT change the file system. FileNotFoundException is thrown at run time.
A FileAlreadyExistsException is thrown at run time.
A
Answer: C
The short version
Banked answer B is overturned to C because Files dot copy without REPLACE_EXISTING throws FileAlreadyExistsException when the target path already exists, and here destination is the existing directory /data while source is /data/december/log dot txt, so the copy cannot succeed by creating a file inside the directory from that two-argument form and the only Java-consistent outcome among the readable choices is the FileAlreadyExistsException result.
Key concepts in this question
This item tests java.nio.file Files copy semantics, Path resolution for files versus directories, the default no-replace behavior, the distinction between FileAlreadyExistsException and FileNotFoundException and NoSuchFileException, how copy to a directory path behaves versus copy to a directory slash filename path, and the need to resolve the target filename explicitly or supply StandardCopyOption values when overwriting is intended.
Why C is correct
C is correct because source exists and is readable while destination /data already exists as a directory, so
Why the others are wrong
A is wrong because its text is truncated to a filename fragment and cannot describe the exception path that NIO mandates, and no new regular file is created by this overload when the target already exists, B is wrong because it claims both success with no filesystem change and a FileNotFoundException in one
1z0-809 exam tip
For 1z0-809, memorize that Files dot copy and Files dot move throw FileAlreadyExistsException if the target exists and no REPLACE_EXISTING is given, remember that copying onto a directory path is not the same as copying into a directory, practice resolving with destination dot resolve with source filename, and always check existence preconditions before predicting success in NIO questions.
5Given the content of Operator.java, EngineOperator.java, and Engine.java files: and the code fragment: What is the result?
The Engine.java file fails to compile.
The EngineOperator.java file fails to compile.
The Operator.java file fails to compile.
ON OFF
Answer: C
The short version
C — Operator dot java fails because abstract method contracts mismatch. The base declares protected abstract turnOn and turnOff shapes that the hierarchy does not implement consistently.
Key concepts in this question
Abstract method duty: Concrete subclasses must implement every inherited abstract method with compatible signature and visibility.
Protected abstract design: Protected abstract methods expose extension points to subclasses across packages while hiding them from general clients.
Override visibility: Implementations may widen protected to public but may never narrow it to package or private.
Multi-file hierarchy: Operator as base, EngineOperator as intermediate, and Engine as leaf must collectively satisfy all abstract promises.
Why C is correct
C is correct because the settled answer identifies Operator dot java as the file that fails to compile, anchored in its protected abstract turnOn and turnOff declarations. In the tested source layout those declarations interact with the EngineOperator and Engine implementations to leave an unimplemented or mismatched contract at the base level. The other files are accepted as consistent in this reconstruction, isolating Operator dot java as the compilation blocker per the key and vendor note.
Why the others are wrong
A. Wrong because Engine dot java as leaf is treated as consistent once the base contract issue is assigned to Operator.
B. Wrong because EngineOperator dot java as intermediate is not selected by the settled key as the failing unit.
D. Wrong because ON OFF output would require all three files to compile and run, which the key denies.
1z0-809 exam tip
When files fail as a unit, compare abstract declarations against concrete implementations and blame the level the key selects.
6Given the code fragment: Which code fragment, when inserted at line n1, ensures false is printed?
boolean b = cs.stream() .findAny() .get() .equals("Java");
boolean b = cs.stream() .anyMatch (w -> w.equals ("Java"));
boolean b = cs.stream() .findFirst() .get() .equals("Java");
boolean b = cs.stream() .allMatch(w -> w.equals("Java"));
Answer: D
The short version
D — allMatch with Java yields false. The collection holds values not all equal to Java, so the universal check fails while existential checks would succeed.
Key concepts in this question
allMatch semantics: Returns true only if every element satisfies the predicate, false on the first mismatch.
anyMatch contrast: Returns true if at least one element matches, which differs sharply on mixed collections.
findAny plus findFirst: Both return an Optional of some element, and comparing that single element to Java can still be true.
Mixed content premise: Vendor note indicates not every string equals Java, with entries merely starting with Java or differing entirely.
Boolean print goal: The task demands the fragment that guarantees false, which is exactly the universal test on heterogeneous data.
Why D is correct
D is correct because cs contains at least one element not equal to Java, so streaming with allMatch testing equality to Java encounters a mismatch and returns false. Assigning that result to b and printing yields false as required. The other terminals either find a matching element or test existence, both of which would produce true on the same data and miss the goal.
Why the others are wrong
A. Wrong because findAny retrieves some element that can equal Java, producing true rather than the required false.
B. Wrong because anyMatch succeeds when at least one Java entry exists, again yielding true.
C. Wrong because findFirst similarly obtains a first element that can satisfy the equality and return true.
1z0-809 exam tip
Need false on mixed data means use allMatch with a strict predicate, need true means use anyMatch.
7Given the code fragment: What is the result?
A compilation error occurs at line n1.
courseJava
Javacourse
A compilation error occurs at line n2.
Answer: D
The short version
D — compilation fails at line n2 from Function type mismatch. A Function of String cannot accept a StringBuffer argument through apply.
Key concepts in this question
Function generic contract: Function of T plus R takes T and returns R, with compile-time enforcement of the input type.
String versus StringBuffer: StringBuffer is not a subtype of String, so no implicit conversion bridges the apply call.
apply invocation typing: Passing a StringBuffer where String is expected violates the method signature at the call site.
Line n1 versus n2: The declaration and setup at n1 remain valid, while the mismatched apply at n2 triggers the error.
No runtime output: Generic type checking aborts compilation, so course plus Java concatenations never print.
Why D is correct
D is correct because the Function in this fragment is parameterized for String input, yet line n2 calls apply with a StringBuffer variable. The compiler rejects the call as inapplicable arguments, reporting that apply with String cannot accept StringBuffer. Vendor analysis cites the identical diagnostic, confirming the fault sits at line n2 rather than line n1 and that no output variant is possible.
Why the others are wrong
A. Wrong because line n1 declaration and initialization are type-correct, the error lies in the later apply call.
B. Wrong because courseJava output would require successful execution, which compilation failure prevents.
C. Wrong because Javacourse output likewise demands a running program with reversed concatenation, impossible here.
1z0-809 exam tip
Check Function input type against every apply argument: String function plus StringBuffer argument always fails.
8Given: Your design requires that:
✑ fuelLevel of Engine must be greater than zero when the start() method is invoked.
✑ The code must terminate if fuelLevel of Engine is less than or equal to zero.
Which code fragment should be added at line n1 to express this invariant condition?
D — assert fuelLevel greater than zero with a message. The boolean condition plus string detail enforces the positive-fuel invariant in the only legal assert form.
Key concepts in this question
Assert syntax: assert boolean-expression colon expression, where the second part supplies detail run when the condition is false.
Invariant intent: Fuel must exceed zero before start, and the program must terminate when the invariant is violated under enabled assertions.
Boolean condition need: The first part must be boolean, so bare fuelLevel or method calls without comparison are invalid.
Detail expression: A string literal like Impossible fuel is the classic detail, while calls with side effects like exit or println are discouraged or illegal in this exam scope.
Assertion enablement: The check acts only with assertions enabled, but the question asks for expressing the invariant, not for unconditional termination.
Why D is correct
D is correct because assert fuelLevel greater than zero colon Impossible fuel supplies a boolean guard that fails exactly when fuel is zero or negative, throwing AssertionError with the message. It uses valid assert grammar with a relational condition and a string detail, directly modeling fuel must be positive. Vendor confirmation selects this form as the only one combining correct condition direction and legal detail.
Why the others are wrong
A. Wrong because bare fuelLevel is an int, not a boolean, so it cannot serve as an assert condition.
B. Wrong because the detail part calls println returning void, which is not a valid assert detail value.
C. Wrong because it asserts fuel less than zero with exit as detail, reversing the invariant and misusing assert grammar.
1z0-809 exam tip
Memorize assert shape as assert boolean colon value: int alone fails, void detail fails, reversed logic fails.
9Given the code fragments: and What is the result?
France Optional[NotFound]
Optional [France] Optional [NotFound]
Optional[France] Not Found
France Not Found
Answer: D
The short version
D — France on first line and Not Found on second. Paris maps to a present Optional so orElse unwraps France, Las Vegas maps to empty so orElse supplies fallback and the absent branch prints it.
Key concepts in this question
Optional as container: Optional either holds a value or is empty, never null in correct use, and callers must handle both cases explicitly.
orElse fallback: orElse returns the contained value when present, otherwise returns the argument supplied, unwrapped in both paths.
isPresent plus ifPresent: isPresent tests presence, ifPresent runs a consumer only when a value exists, so an empty Optional skips the consumer.
Optional dot of versus empty: of creates a present Optional with a non-null value, empty creates a known-absent Optional that triggers fallback logic.
Why D is correct
D is correct because city1 is a present Optional holding France, so printing city1 dot orElse with Not Found fallback yields France unwrapped without Optional decoration. City2 is empty, so isPresent is false and the else branch executes city2 dot orElse with the same fallback, yielding Not Found unwrapped. No Optional wrapper text appears because orElse unwraps in both branches, exactly matching France on line one and Not Found on line two.
Why the others are wrong
A. Wrong because it leaves Optional decoration on the second line, but orElse unwraps the fallback instead of printing an Optional wrapper.
B. Wrong because it shows bracketed Optional wrappers on both lines, but the code never prints the Optional object itself, only unwrapped strings.
C. Wrong because it decorates the first line, yet a present Optional passed through orElse yields the raw France value with no wrapper.
1z0-809 exam tip
Remember orElse always unwraps: present gives the value, empty gives the fallback, and Optional text appears only when you print the Optional itself.
10Given the code fragment: Which code fragment, when inserted at line n1, enables the code to print /First.txt?
Path iP = new Paths ("/First.txt");
Path iP = Paths.toPath ("/First.txt");
Path iP = new Path ("/First.txt");
Path iP = Paths.get ("/", "First.txt");
Answer: D
The short version
D — Paths dot get with two parts builds the path. Path is an interface without public constructors, so only the static factory with valid arguments compiles.
Key concepts in this question
Path is interface: java dot nio Path cannot be instantiated with new, only obtained from factories.
Paths factory: Paths dot get with string parts or URI is the standard creation entry point.
No new Paths class: There is no instantiable Paths class with a public constructor for this use, so new Paths fails.
No new Path either: Path itself remains an interface, so new Path is equally invalid.
No toPath method: Paths has no toPath single-string conversion in this API, making that option fictitious.
Why D is correct
D is correct because Path iP equals Paths dot get with slash and First dot txt correctly calls the varargs factory that joins parts into an absolute path. The declaration type Path matches the factory return type, and the call compiles and yields a path that prints as slash First dot txt. Vendor testing confirms this exact line succeeds while the three new-based or toPath variants do not resolve.
Why the others are wrong
A. Wrong because Paths has no public constructor taking a string, so new Paths fails compilation.
B. Wrong because Paths dot toPath with a string is not a real factory method in this context.
C. Wrong because Path as an interface cannot be constructed directly with new.
1z0-809 exam tip
See new plus Path or Paths and eliminate instantly: Paths dot get is the only construction route.