nerdexam
Oracle

1Z0-819 · Question #103

Which three annotation uses are valid? (Choose three.)

The correct answer is D. Function<String, String> func = (@NonNull Function<String, String> x) -> x.toUpperCase(); E. var str = (@NonNull String) str; F. var myObj = (@NonNull MyObject) myObj. Options D, E, and F are valid because Java type annotations (JSR 308) are permitted in two specific locations demonstrated here: explicitly-typed lambda parameters (D) and cast expressions (E, F). In D, @NonNull annotates the lambda parameter because the full type…

Annotations

Question

Which three annotation uses are valid? (Choose three.)

Options

  • AFunction<String, String> func = (@NonNull x) -> x.toUpperCase();
  • Bvar v = "Hello" + (@Interned) "World";
  • Cvar integers = new List<(@NonNull Integer) x>();
  • DFunction<String, String> func = (@NonNull Function<String, String> x) -> x.toUpperCase();
  • Evar str = (@NonNull String) str;
  • Fvar myObj = (@NonNull MyObject) myObj;

How the community answered

(29 responses)
  • A
    3% (1)
  • B
    3% (1)
  • C
    14% (4)
  • D
    79% (23)

Explanation

Options D, E, and F are valid because Java type annotations (JSR 308) are permitted in two specific locations demonstrated here: explicitly-typed lambda parameters (D) and cast expressions (E, F). In D, @NonNull annotates the lambda parameter because the full type Function<String, String> is explicitly declared - this is required for a parameter-level annotation in a lambda. In E and F, @NonNull annotates the cast type directly, which is a well-defined annotation target per the Java specification.

The distractors fail for distinct reasons: A is invalid because you cannot annotate an inferred lambda parameter - omitting the type (just x) means there is no type element to annotate, so the type must be written out explicitly as in D. B is syntactically malformed - (@Interned) has no type inside the parentheses, so it is not a valid cast expression (it would need to be (@Interned String) "World"). C is invalid because (@NonNull Integer) x is a cast expression placed inside a generic type argument position, which is not legal syntax - the correct form would be new ArrayList<@NonNull Integer>().

Memory tip: Type annotations need a type to attach to. Remember "No type, no annotation" - if the type is absent or the syntax puts the annotation where no type element exists (empty parens, inside <...> as a cast), the annotation is invalid.

Topics

#type annotations#lambda parameters#type casting#annotation placement

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice