Programmer II Chapter 2: Annotations Flashcards

1
Q

What types can annotation elements be declared with?

A
primitives
String
Class
enum
another annotation
array of above types
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Which annotations can be used in a shorthand form?

public @interface Sleep {
   int value();
   String hours();
}
public @interface Wake {
   String hours();
}
A

Neither.
The first declaration contains two required elements, while the second annotation does not include an element named value().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Given an annotation below, which uses of it are legal?

public @interface Music {
String[] genres();
}

public class Giraffe {
   @Music(genres={"Rock and roll"}) String mostDisliked;
   @Music(genres="Classical") String favorite;
}
A

Both.
The first annotation is considered the regular form, as it is clear the usage is for an array. The second annotation is the shorthand notation, where the array braces ({}) are dropped for convenience. Keep in mind that this is still providing a value for an array element; the compiler is just inserting the missing array braces for you

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Which lines will compile?

public @interface BadAnnotation {
       String name() default new String("");
       String address() default "";
       String title() default null;
}
A

only address()

name() does not compile because it is not a constant expression, while title() does not compile because it is null. Only address() compiles. Notice that while null is not permitted as a default value, the empty String “” is.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Will this compile?

public @interface Material {}

public @interface Fluffy {
   int cuteness();
   public abstract int softness() default 11;
   protected Material material();
   private String friendly();
   final boolean isBunny();
}
A

material(), friendly(), isBunny() contain compilation errors

The elements cuteness() and softness() are both considered abstract and public, even though only one of them is marked as such. The elements material() and friendly() do not compile because the access modifier conflicts with the elements being implicitly public. The element isBunny() does not compile because, like abstract methods, it cannot be marked final.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What modifier is used to mark that an annotation element is required?

A. optional
B. default
C. required
D. *
E. None of the above
A

E.
In an annotation, an optional element is specified with the default modifier, followed by a constant value. Required elements are specified by not providing a default value. Therefore, the lack of the default term indicates the element is required. For this reason, option E is correct.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Which of the following lines of code do not compile? (Choose all that apply.)

  1: import java.lang.annotation.Documented;
  2: enum Color {GREY, BROWN}
  3: @Documented public @interface Dirt {
  4: boolean wet();
  5: String type() = "unknown";
  6: public Color color();
  7: private static final int slippery = 5;
  8: }
A. Line 2
B. Line 3
C. Line 4
D. Line 5
E. Line 6
F. Line 7
G. All of the lines compile.
A

D, F.
Line 5 does not compile because = is used to assign a default value, rather than the default modifier. Line 7 does not compile because annotation and interface constants are implicitly public and cannot be marked private. The rest of the lines do not contain any compilation errors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Which built-in annotations can be applied to an annotation declaration? (Choose all that apply.)

A. @Override
B. @Deprecated
C. @Document
D. @Target
E. @Repeatable
F. @Functional
A

B, D, E.
The annotations @Target and @Repeatable are specifically designed to be applied to annotations, making options D and E correct. Option B is also correct, as @Deprecated can be applied to almost any declaration. Option A is incorrect because @Override can be applied only to methods. Options C and F are incorrect because they are not the names of built-in annotations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Given an automobile sales system, which of the following information is best stored using an annotation?

A. The price of the vehicle
B. A list of people who purchased the vehicle
C. The sales tax of the vehicle
D. The number of passengers a vehicle is rated for
E. The quantity of models in stock

A

D.
Annotations should include metadata (data about data) that is relatively constant, as opposed to attribute data, which is part of the object and can change frequently. The price, sales, inventory, and people who purchased a vehicle could fluctuate often, so using an annotation would be a poor choice.On the other hand, the number of passengers a vehicle is rated for is extra information about the vehicle and unlikely to change once established. Therefore, it is appropriate metadata and best served using an annotation

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Which of the following lines of code do not compile? (Choose all that apply.)

  1: import java.lang.annotation.*;
  2: class Food {}
  3: @Inherited public @interface Unexpected {
  4: public String rsvp() default null;
  5: Food food();
  6: public String[] dessert();
  7: final int numberOfGuests = 5;
  8: long startTime() default 0L;
  9: }
A. Line 3
B. Line 4
C. Line 5
D. Line 6
E. Line 7
F. Line 8
G. All of the lines compile
A

B, C.
Line 4 does not compile because the default value of an element must be a non-null constant expression. Line 5 also does not compile because an element type must be one of the predefined immutable types: a primitive, String, Class, enum, another annotation, or an array of these types.The rest of the lines do not contain any compilation errors

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Which annotations, when applied independently, allow the following program to compile? (Choose all that apply.)

      import java.lang.annotation.*;
      @Documented @Deprecated
      public @interface Driver {
      	int[] directions();
      	String name() default "";
      }
      \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ class Taxi {}
A. @Driver
B. @Driver(1)
C. @Driver(3,4)
D. @Driver({5,6})
E. @Driver(directions=7)
F. @Driver(directions=8,9)
G. @Driver(directions={0,1})
H. None of the above
A
E, G. 
The annotation declaration includes one required element, making option A incorrect. Options B, C, and D are incorrect because the Driver declaration does not contain an element named value().
If directions() were renamed in Driver to value(), then options B and D would be correct. The correct answers are options E and G. Option E uses the shorthand form in which the array braces ({}) can be dropped if there is only one element. Options C and F are not valid annotation uses, regardless of the annotation declaration. In this question, the @Documented and @Deprecated annotations have no impact on the solution.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Annotations can be applied to which of the following? (Choose all that apply.)

A. Class declarations
B. Constructor parameters
C. Local variable declarations
D. Cast operations
E. Lambda expression parameters
F. Interface declarations
G. None of the above
A

A, B, C, D, E, F.
Annotations can be applied to all of the declarations listed. If there is a type name used, an annotation can be applied.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Fill in the blanks with the correct answers that allow the entire program to compile. (Choose all that apply.)

@interface FerociousPack {
__________________; // m1
}

      @Repeatable(\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_)  // m2
      public @interface Ferocious {}
      @Ferocious @Ferocious class Lion {}
A. Ferocious value() on line m1.
B. Ferocious[] value() on line m1.
C. Object[] value() on line m1.
D. @FerociousPack on line m2.
E. FerociousPack on line m2.
F. FerociousPack.class on line m2.
G. None of the above. The code will not compile due to its use of the Lion class
A

B, F.
In this question, Ferocious is the repeatable annotation, while FerociousPack is the containing type annotation. The containing type annotation should contain a single value() element that is an array of the repeatable annotation type. For this reason, option B is correct. Option A would allow FerociousPack to compile, but not Ferocious. Option C is an invalid annotation element type.

The repeatable annotation needs to specify the class name of its containing type annotation, making option F correct. While it is expected for repeatable annotations to contain elements to differentiate its usage, it is not required. For this reason, the usage of @Ferocious is a valid marker annotation on the Lion class, making option G incorrect.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What properties must be true to use an annotation with an element value, but no element name? (Choose all that apply.)

A. The element must be named values().
B. The element must be required.
C. The annotation declaration must not contain any other elements.
D. The annotation must not contain any other values.
E. The element value must not be array.
F. None of the above

A

D.
To use an annotation with a value but not element name, the element must be declared with the name value(), not values(), making option A incorrect. The value() annotation may be required or optional, making option B incorrect. The annotation declaration may contain other elements, provided none is required, making option C incorrect. Option D is correct, as the annotation must not include any other values. Finally, option E is incorrect, as this is not a property of using a value() shorthand.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Which statement about the following code is correct?

      import java.lang.annotation.*;
      @Target(ElementType.TYPE) public @interface Furry {
         public String[] value();
         boolean cute() default true;
      }
      class Bunny {
         @Furry("Soft") public static int hop() {
            return 1;
         }
      }

A. The code compiles without any changes.
B. The code compiles only if the type of value() is changed to a String in the annotation declaration.
C. The code compiles only if cute() is removed from the annotation declaration.
D. The code compiles only if @Furry includes a value for cute().
E. The code compiles only if @Furry includes the element name for value.
F. The code compiles only if the value in @Furry is changed to an array.
G. None of the above

A

G.
Furry is an annotation that can be applied only to types. In Bunny, it is applied to a method; therefore, it does not compile. If the @Target value was changed to ElementType.METHOD (or @Target removed entirely), then the rest of the code would compile without issue. The use of the shorthand notation for specifying a value() of an array is correct.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What properties of applying @SafeVarargs are correct? (Choose all that apply.)

A. By applying the annotation, the compiler verifies that all operations on parameters are safe.
B. The annotation can be applied to abstract methods.
C. The annotation can be applied to method and constructor declarations.
D. When the annotation is applied to a method, the method must contain a varargs parameter.
E. The annotation can be applied to method and constructor parameters.
F. The annotation can be applied to static methods.

A

C, D, F.
The @SafeVarargs annotation can be applied to a constructor or private, static, or final method that includes a varargs parameter. For these reasons, options C, D, and F are correct. Option A is incorrect, as the compiler cannot actually enforce that the operations are safe. It is up to the developer writing the method to verify that. Option B is incorrect as the annotation can be applied only to methods that cannot be overridden and abstract methods can always be overridden. Finally,option E is incorrect, as it is applied to the declaration, not the parameters.

17
Q

Which of the following lines of code do not compile? (Choose all that apply.)

  1: import java.lang.annotation.*;
  2: enum UnitOfTemp { C, F }
  3: @interface Snow { boolean value(); }
  4: @Target(ElementType.METHOD) public @interface Cold {
  5: private Cold() {}
  6: int temperature;
  7: UnitOfTemp unit default UnitOfTemp.C;
  8: Snow snow() default @Snow(true);
  9: }
A. Line 4
B. Line 5
C. Line 6
D. Line 7
E. Line 8
F. All of the lines compile.
A

B, C, D.
Annotations cannot have constructors, so line 5 does not compile. Annotations can have variables, but they must be declared with a constant value. For this reason, line 6 does not compile.
Line 7 does not compile as the element unit is missing parentheses after the element name. Lines 8compiles and shows how to use annotation type with a default value

18
Q

Which statements about an optional annotation element are correct? (Choose all that apply.)

A. The annotation declaration always includes a default value.
B. The annotation declaration may include a default value.
C. The annotation always includes a value.
D. The annotation may include a value.
E. The annotation must not include a value.
F. None of the above

A

A, D.
An optional annotation element is one that is declared with a default value that may be optionally replaced when used in an annotation. For these reasons, options A and D are correct

19
Q

Fill in the blanks: The ____________ annotation determines whether annotations are discarded at runtime, while the _______________ annotation determines whether they are discarded in generated Javadoc.

A. @Target, @Deprecated
B. @Discard, @SuppressWarnings
C. @Retention, @Generated
D. @Retention, @Documented
E. @Inherited, @Retention
F. @Target, @Repeatable
G. None of the above
A

D.
The @Retention annotation determines whether annotations are discarded when the code is compiled, at runtime, or not at all. The presence, or absence, of the @Documented annotation determines whether annotations are discarded within generated Javadoc. For these reasons, option Dis correct

20
Q

What statement about marker annotations is correct?

A. A marker annotation does not contain any elements or constant variables.
B. A marker annotation does not contain any elements but may contain constant variables.
C. A marker annotation does not contain any required elements but may include optional elements.
D. A marker annotation does not contain any optional elements but may include required elements.
E. A marker annotation can be extended.

A

B.
A marker annotation is an annotation with no elements. It may or may not have constant variables,making option B correct. Option E is incorrect as no annotation can be extended.

21
Q

Which options, when inserted into the blank in the code, allow the code to compile without anywarnings? (Choose all that apply.)

      import java.util.*;
      import java.lang.annotation.*;
      public class Donkey {
         \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
          public String kick(List... t) {
            t[0] = new ArrayList();
            t[0].add(1);
            return (String)t[0].get(0);
         }
      }
A. @SafeVarargs
B. @SafeVarargs("unchecked")
C. @Inherited
D. @SuppressWarnings
E. @SuppressWarnings("ignore")
F. @SuppressWarnings("unchecked")
G. None of the above
A

F.
The @SafeVarargs annotation does not take a value and can be applied only to methods that cannot be overridden (marked private, static, or final). For these reasons, options A and B produce compilation errors. Option C also does not compile, as this annotation can be applied only to other annotations. Even if you didn’t remember that, it’s clear it has nothing to do with hiding a compiler warning. Option D does not compile as @SuppressWarnings requires a value. Both options E and Fallow the code to compile without error, although only option F will cause a compile without warnings. The unchecked value is required when performing unchecked generic operations.

22
Q

What motivations would a developer have for applying the @FunctionalInterface annotation to an interface? (Choose all that apply.)

A. To allow the interface to be used in a lambda expression
B. To provide documentation to other developers
C. To allow the interface to be used as a method reference
D. There is no reason to use this annotation.
E. To trigger a compiler error if the annotation is used incorrectly

A

B, E.
The @FunctionalInterface marker annotation is used to document that an interface is a valid functional interface that contains exactly one abstract method, making option B correct. It is also useful in determining whether an interface is a valid functional interface, as the compiler will report an error if used incorrectly, making option E correct. The compiler can detect whether an interface is a functional interface even without the annotation, making options A and C incorrect.

23
Q

Which of the following lines of code do not compile? (Choose all that apply.)

  1: @interface Strong {
  2: int force(); }
  3: @interface Wind {
  4: public static final int temperature = 20;
  5: Boolean storm() default true;
  6: public void kiteFlying();
  7: protected String gusts();
  8: Strong power() default @Strong(10);
  9: }
A. Line 2
B. Line 4
C. Line 5
D. Line 6
E. Line 7
F. Line 8
G. All of the lines compile
A

C, D, E, F.
Line 5 and 6 do not compile because Boolean and void are not supported annotation element types. It must be a primitive, String, Class, enum, another annotation, or an array of these types. Line 7 does not compile because annotation elements are implicitly public. Finally, line 8 does not compile because the Strong annotation does not contain a value() element, so the shorthand notation cannot be used. If line 2 were changed from force() to value(), then line 8 would compile.Without the change, though, the compiler error is on line 8. The rest of the lines do not contain any compilation errors, making options C, D, E, and F correct

24
Q

Which annotations can be added to an existing method declaration but could cause a compiler error depending on the method signature? (Choose all that apply.)

A. @Override
B. @Deprecated
C. @FunctionalInterface
D. @Repeatable
E. @Retention
F. @SafeVarargs
A

A, F.
The @Override annotation can be applied to a method but will trigger a compiler error if the method signature does not match an inherited method, making option A correct. The annotation@Deprecated can be applied to a method but will not trigger any compiler errors based on the method signature. The annotations @FunctionalInterface, @Repeatable, and @Retention cannot be applied to methods, making these options incorrect. Finally, @SafeVarargs can be applied to a method but will trigger a compiler error if the method does not contain a varargs parameter or is able to be overridden (not marked private, static, or final).

25
Q

Given the Floats annotation declaration, which lines in the Birch class contain compiler errors? (Choose all that apply.)

// Floats.java
      import java.lang.annotation.*;
      @Target(ElementType.TYPE_USE)
      public @interface Floats {
         int buoyancy() default 2;
      }

// Birch.java

  1: import java.util.function.Predicate;
  2: interface Wood {}
  3: @Floats class Duck {}
  4: @Floats
  5: public class Birch implements @Floats Wood {
  6: @Floats(10) boolean mill() {
  7: Predicate t = (@Floats Integer a) -> a> 10;
  8: return (@Floats) t.test(12);
  9: } }
A. Line 3
B. Line 4
C. Line 5
D. Line 6
E. Line 7
F. Line 8
G. None of the above. All of the lines compile without issue.
A

D, F.
Line 6 contains a compiler error since the element name buoyancy is required in the annotation. If the element were renamed to value() in the annotation declaration, then the element name would be optional. Line 8 also contains a compiler error. While an annotation can be used in a cast operation, it requires a type. If the cast expression was changed to (@Floats boolean), then it would compile.The rest of the code compiles without issue.

26
Q

Fill in the blanks: The ______________ annotation determines what annotations from a superclass or interface are applied, while the _________________ annotation determines what declarations an annotation can be applied to.

A. @Target, @Retention
B. @Inherited, @ElementType
C. @Documented, @Deprecated
D. @Target, @Generated
E. @Repeatable, @Element
F. @Inherited, @Retention
G. None of the above
A

G.
The @Inherited annotation determines whether or not annotations defined in a super type are automatically inherited in a child type. The @Target annotation determines the location or locations an annotation can be applied to. Since this was not an answer choice, option G is correct. Note that ElementType is an enum used by @Target, but it is not an annotation.

27
Q

Which annotation can cancel out a warning on a method using the @Deprecated API at compile time?

A. @FunctionalInterface
B. @Ignore
C. @IgnoreDeprecated
D. @Retention
E. @SafeVarargs
F. @SuppressWarnings
G. None of the above
A

F.
If @SuppressWarnings(“deprecation”) is applied to a method that is using a deprecated API,then warnings related to the usage will not be shown at compile time, making option F correct. Note that there are no built-in annotations called @Ignore or @IgnoreDeprecated.

28
Q

The main() method in the following program reads the annotation value() of Plumber at runtime on each member of Team. It compiles and runs without any errors. Based on this, how many times isMario printed at runtime?

      import java.lang.annotation.*;
      import java.lang.reflect.Field;
      @interface Plumber {
         String value() default "Mario";
      }
      public class Team {
         @Plumber("") private String foreman = "Mario";
         @Plumber private String worker = "Kelly";
         @Plumber("Kelly") private String trainee;
         public static void main(String[] args) {
            var t = new Team();
            var fields = t.getClass().getDeclaredFields();
            for (Field field : fields)
               if(field.isAnnotationPresent(Plumber.class))
                  System.out.print(field.getAnnotation(Plumber.class)                     .value());
         }
      }
A. Zero
B. One
C. Two
D. Three
E. The answer cannot be determined until runtime.
A

A.
This question, like some questions on the exam, includes extraneous information that you do not need to know to solve it. Therefore, you can assume the reflection code is valid. That said, this code is not without problems. The default retention policy for all annotations is RetentionPolicy.CLASS if not explicitly stated otherwise. This means the annotation information is discarded at compile time and not available at runtime. For this reason, none of the members will print anything, making option A correct.

If @Retention(RetentionPolicy.RUNTIME) were added to the declaration of Plumber, then the worker member would cause the default annotation value(), Mario, to be printed at runtime, and option B would be the correct answer. Note that foreman would not cause Mario to be printed even with the corrected retention annotation. Setting the value of the annotation is not the same as setting the value of the variable foreman.

29
Q

Which annotations, when applied independently, allow the following program to compile? (Choose all that apply.)

      public @interface Dance {
         long rhythm() default 66;
         int[] value();
         String track() default "";
         final boolean fast = true;
      }
      class Sing {
        \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ String album;
      }
A. @Dance(77)
B. @Dance(33, 10)
C. @Dance(value=5, rhythm=2, fast=false)
D. @Dance(5, rhythm=9)
E. @Dance(value=5, rhythm=2, track="Samba")
F. @Dance()
G. None of the above
A

A, E.
The annotation includes only one required element, and it is named value(), so it can be used without an element name provided it is the only value in the annotation. For this reason, option A is correct, and options B and D are incorrect. Since the type of the value() is an array, option B would work if it was changed to @Dance({33, 10}). Option C is incorrect because it attempts to assign a value to fast, which is a constant variable not an element. Option E is correct and is an example of an annotation replacing all of the optional values. Option F is incorrect, as value() is a required element.

30
Q

When using the @Deprecated annotation, what other annotation should be used and why?

A. @repeatable, along with a containing type annotation
B. @retention, along with a location where the value should be discarded
C. @deprecated, along with a reason why and a suggested alternative
D. @SuppressWarnings, along with a cause
E. @Override, along with an inherited reference

A

C.
The Javadoc @deprecated annotation should be used, which provides a reason for the deprecation and suggests an alternative. All of the other answers are incorrect, with options A and B having the wrong case too. Those annotations should be written @Repeatable and @Retention since they are Java annotations.