Programmer II Chapter 1: Java Fundamentals Flashcards

1
Q

Which statements about the final modifier are correct? (Choose all that apply.)

A. Instance and static variables can be marked final.
B. A variable is effectively final if it is marked final.
C. The final modifier can be applied to classes and interfaces.
D. A final class cannot be extended.
E. An object that is marked final cannot be modified.
F. Local variables cannot be declared with type var and the final modifier.
A
A, D. 
Instance and static variables can be marked final, making option A correct. Effectively final means a local variable is not marked final but whose value does not change after it is set,making option B incorrect. The final modifier can be applied to classes, but not interfaces, making option C incorrect. Remember, interfaces are implicitly abstract, which is incompatible with final.Option D is correct, as the definition of a final class is that it cannot be extended. Option E is incorrect, as final refers only to the reference to an object, not its contents. Finally, option F is incorrect, as var and final can be used together.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the result of the following program?

      public class FlavorsEnum {
         enum Flavors {
            VANILLA, CHOCOLATE, STRAWBERRY
            static final Flavors DEFAULT = STRAWBERRY;
         }
         public static void main(String[] args) {
            for(final var e : Flavors.values())
               System.out.print(e.ordinal()+" ");
         }
      }

A. 0 1 2
B. 1 2 3
C. Exactly one line of code does not compile.
D. More than one line of code does not compile.
E. The code compiles but produces an exception at runtime.
F. None of the above

A

C.
When an enum contains only a list of values, the semicolon (;) after the list is optional. When an enum contains any other members, such as a constructor or variable, then it is required. Since the code is missing the semicolon, it does not compile, making option C the correct answer. There are no other compilation errors in this code. If the missing semicolon was added, then the program would print 0 12 at runtime.

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

What is the result of the following code? (Choose all that apply.)

  1: public class Movie {
  2: private int butter = 5;
  3: private Movie() {}
  4: protected class Popcorn {
  5: private Popcorn() {}
  6: public static int butter = 10;
  7: public void startMovie() {
  8: System.out.println(butter);
  9: }
  10: }
  11: public static void main(String[] args) {
  12: var movie = new Movie();
  13: Movie.Popcorn in = new Movie().new Popcorn();
  14: in.startMovie();
  15: } }
A. The output is 5.
B. The output is 10.
C. Line 6 generates a compiler error.
D. Line 12 generates a compiler error.
E. Line 13 generates a compiler error.
F. The code compiles but produces an exception at runtime.
A

C.
Popcorn is an inner class. Inner classes are only allowed to contain static variables that are marked final. Since there are no other compilation errors, option C is the only correct answer. If the final modifier was added on line 6, then the code would print 10 at runtime. Note that private constructors can be used by any methods within the same class.

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

Which statements about default and private interface methods are correct? (Choose all that apply.)

A. A default interface method can be declared private.
B. A default interface method can be declared public.
C. A default interface method can be declared static.
D. A private interface method can be declared abstract.
E. A private interface method can be declared protected.
F. A private interface method can be declared static.

A

B, F.
A default interface method is always public, whether you include the identifier or not, making option B correct and option A incorrect. Interfaces cannot contain default static methods, making option C incorrect. Option D is incorrect, as private interface methods are not inherited and cannot be marked abstract. Option E is incorrect, as a method can’t be marked both protected and private. Finally, interfaces can include both private and private static methods, making option F correct.

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

Which of the following are valid lambda expressions? (Choose all that apply.)

A. (Wolf w, var c) -> 39
B. (final Camel c) -> {}
C. (a,b,c) -> {int b = 3; return 2;}
D. (x,y) -> new RuntimeException()
E. (var y) -> return 0;
F. () -> {float r}
G. (Cat a, b) -> {}
A

B, D.
Option B is a valid functional interface, one that could be assigned to a Consumerreference. Notice that the final modifier is permitted on variables in the parameter list. Option D is correct, as the exception is being returned as an object and not thrown. This would be compatible with a BiFunction that included RuntimeException as its return type.

Option A is incorrect because it mixes var and non-var parameters. If one argument uses var, then they all must use var. Option C is invalid because the variable b is used twice. Option E is incorrect,as a return statement is permitted only inside braces ({}). Option F is incorrect because the variable declaration requires a semicolon (;) after it. Finally, option G is incorrect. If the type is specified for one argument, then it must be specified for each and every argument.

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

What are some advantages of using private interface methods? (Choose all that apply.)

A. Improve polymorphism
B. Improve performance at runtime
C. Reduce code duplication
D. Backward compatibility
E. Encapsulate interface implementation
F. Portability
A

C, E.
You can reduce code duplication by moving shared code from default or static methods into a private or private static method. For this reason, option C is correct. Option E is also correct,as making interface methods private means users of the interface do not have access to them. The rest of the options are not related to private methods, although backward compatibility does apply to default methods.

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

What is the result of the following program?

      public class IceCream {
         enum Flavors {
            CHOCOLATE, STRAWBERRY, VANILLA
         }
         public static void main(String[] args) {
            Flavors STRAWBERRY = null;
            switch (STRAWBERRY) {
               case Flavors.VANILLA: System.out.print("v");
               case Flavors.CHOCOLATE: System.out.print("c");
               case Flavors.STRAWBERRY: System.out.print("s");
               break;
               default: System.out.println("missing flavor"); }
         }
      }

A. v
B. vc
C. s
D. missing flavor
E. Exactly one line of code does not compile.
F. More than one line of code does not compile.
G. The code compiles but produces an exception at runtime.

A

F.
When using an enum in a switch statement, the case statement must be made up of the enum values only. If the enum name is used in the case statement value, then the code does not compile. For example, VANILLA is acceptable but Flavors.VANILLA is not. For this reason, the three case statements do not compile, making option F the correct answer. If these three lines were corrected,then the code would compile and produce a NullPointerException at runtime.

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

Which statements about functional interfaces are true? (Choose all that apply.)

A. A functional interface can contain default and private methods.
B. A functional interface can be defined by a class or interface.
C. Abstract methods with signatures that are contained in public methods of java.lang.Object do not count toward the abstract method count for a functional interface.
D. A functional interface cannot contain static or private static methods.
E. A functional interface contains at least one abstract method.
F. A functional interface must be marked with the @FunctionalInterface annotation.
A

A, C.
A functional interface can contain any number of non abstract methods including default,private, static, and private static. For this reason, option A is correct, and option D is incorrect.Option B is incorrect, as classes are never considered functional interfaces. A functional interface contains exactly one abstract method, although methods that have matching signatures as public methods in java.lang.Object do not count toward the single method test. For these reasons, option C is correct, and option E is incorrect. Finally, option F is incorrect. While a functional interface can be marked with the @FunctionalInterface annotation, it is not required.

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

Which lines, when entered independently into the blank, allow the code to print Not scared at runtime? (Choose all that apply.)

  public class Ghost {

     public static void boo() {
        System.out.println("Not scared");
     }
         protected final class Spirit {
            public void boo() {
               System.out.println("Booo!!!");
            }
         }
         public static void main(String... haunt) {
            var g = new Ghost().new Spirit() {};
            \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_;
         }
      }
A. g.boo()
B. g.super.boo()
C. new Ghost().boo()
D. g.Ghost.boo()
E. new Spirit().boo()
F. Ghost.boo()
G. None of the above
A
G. 
Trick question—the code does not compile! The Spirit class is marked final, so it cannot be extended. The main() method uses an anonymous inner class that inherits from Spirit, which is not allowed. If Spirit was not marked final, then options C and F would be correct. Option A would print Booo!!!, while options B, D, and E would not compile for various reasons.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

The following code appears in a file named Ostrich.java. What is the result of compiling the sourcefile?

  1: public class Ostrich {
  2: private int count;
  3: private interface Wild {}
  4: static class OstrichWrangler implements Wild {
  5: public int stampede() {
  6: return count;
  7: } } }

A. The code compiles successfully, and one bytecode file is generated: Ostrich.class.
B. The code compiles successfully, and two bytecode files are generated: Ostrich.class and OstrichWrangler.class.
C. The code compiles successfully, and two bytecode files are generated: Ostrich.class and Ostrich$OstrichWrangler.class.
D. A compiler error occurs on line 4.
E. A compiler error occurs on line 6.

A
E. 
The code OstrichWrangler class is a static nested class; therefore, it cannot access the instance member count. For this reason, line 6 does not compile, and option E is correct. If the static modifier on line 4 was removed, then the class would compile and produce two files: Ostrich.class and Ostrich$OstrichWrangler.class. You don't need to know that $ is the syntax, but you do need to know the number of classes and that OstrichWrangler is not a top-level class.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the result of the following code?

  1: public interface CanWalk {
  2: default void walk() { System.out.print("Walking"); }
  3: private void testWalk() {}
  4: }
  5: public interface CanRun {
  6: abstract public void run();
  7: private void testWalk() {}
  8: default void walk() { System.out.print("Running"); }
  9: }
  10: public interface CanSprint extends CanWalk, CanRun {
  11: void sprint();
  12: default void walk(int speed) {
  13: System.out.print("Sprinting");
  14: }
  15: private void testWalk() {}
  16: }

A. The code compiles without issue.
B. The code will not compile because of line 6.
C. The code will not compile because of line 8.
D. The code will not compile because of line 10.
E. The code will not compile because of line 12.
F. None of the above

A

D.
In this example, CanWalk and CanRun both implement a default walk() method. The definition of CanSprint extends these two interfaces and therefore won’t compile unless the interface overrides both inherited methods. The version of walk() on line 12 is an overload, not an override, since it takes an int value. Since the interface doesn’t override the methods, the compiler can’t decide which default method to use, leading to a compiler error and making option D the correct answer.

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

What is the result of executing the following program?

      interface Sing {
         boolean isTooLoud(int volume, int limit);
      }
      public class OperaSinger {
         public static void main(String[] args) {
            check((h, l) -> h.toString(), 5);  // m1
         }
         private static void check(Sing sing, int volume) {
            if (sing.isTooLoud(volume, 10))   // m2
               System.out.println("not so great");
            else System.out.println("great");
         }
      }
A. great
B. not so great
C. Compiler error on line m1
D. Compiler error on line m2
E. Compiler error on a different line
F. A runtime exception is thrown.
A

C.
The functional interface takes two int parameters. The code on line m1 attempts to use them as if one is an Object, resulting in a compiler error and making option C the correct answer. It also tries to return String even though the return data type for the functional interface method is boolean. It is tricky to use types in a lambda when they are implicitly specified. Remember to check the interface for the real type.

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

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

  1: public interface Herbivore {
  2: int amount = 10;
  3: static boolean gather = true;
  4: static void eatGrass() {}
  5: int findMore() { return 2; }
  6: default float rest() { return 2; }
  7: protected int chew() { return 13; }
  8: private static void eatLeaves() {}
  9: }
A. All of the lines compile without issue.
B. Line 2
C. Line 3
D. Line 4
E. Line 5
F. Line 6
G. Line 7
H. Line 8
A

E, G.
For this question, it helps to remember which implicit modifiers the compiler will insert and which it will not. Lines 2 and 3 compile with interface variables assumed to be public, static, and final. Line 4 also compiles, as static methods are assumed to be public if not otherwise marked.Line 5 does not compile. Non-static methods within an interface must be explicitly marked private or default. Line 6 compiles, with the public modifier being added by the compiler. Line 7 does not compile, as interfaces do not have protected members. Finally, line 8 compiles, with no modifiers being added by the compiler.

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

What is printed by the following program?

      public class Deer {
         enum Food {APPLES, BERRIES, GRASS}
         protected class Diet {
            private Food getFavorite() {
               return Food.BERRIES;
            }
         }
         public static void main(String[] seasons) {
            switch(new Diet().getFavorite()) {
               case APPLES: System.out.print("a");
               case BERRIES: System.out.print("b");
               default: System.out.print("c");
            }
         }
      }

A. b
B. bc
C. abc
D. The code declaration of the Diet class does not compile.
E. The main() method does not compile.
F. The code compiles but produces an exception at runtime.
G. None of the above

A
E. 
Diet is an inner class, which requires an instance of Deer to instantiate. Since the main() method is static, there is no such instance. Therefore, the main() method does not compile, and option E is correct. If a reference to Deer were used, such as calling new Deer().new Diet(), then the code would compile and print bc at runtime
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Which of the following are printed by the Bear program? (Choose all that apply.)

      public class Bear {
         enum FOOD {
            BERRIES, INSECTS {
               public boolean isHealthy() { return true; }},
            FISH, ROOTS, COOKIES, HONEY;
            public abstract boolean isHealthy();
         }         public static void main(String[] args) {
            System.out.print(FOOD.INSECTS);
            System.out.print(FOOD.INSECTS.ordinal());
            System.out.print(FOOD.INSECTS.isHealthy());
            System.out.print(FOOD.COOKIES.isHealthy());
         }
      }
A. insects
B. INSECTS
C. 0
D. 1
E. false
F. true
G. The code does not compile.
A
G. 
The isHealthy() method is marked abstract in the enum; therefore, it must be implemented in each enum value declaration. Since only INSECTS implements it, the code does not compile, making option G correct. If the code were fixed to implement the isHealthy() method in each enum value,then the first three values printed would be INSECTS, 1, and true, with the fourth being determined by the implementation of COOKIES.isHealthy().
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Which of the following are valid functional interfaces? (Choose all that apply.)

      public interface Transport {
         public int go();
         public boolean equals(Object o);
      }
      public abstract class Car {
         public abstract Object swim(double speed, int duration);
      }
      public interface Locomotive extends Train {
         public int getSpeed();
      }
      public interface Train extends Transport {}
      abstract interface Spaceship extends Transport {
         default int blastOff();
      }
      public interface Boat {
         int hashCode();
         int hashCode(String input);
      }
A. Boat
B. Car
C. Locomotive
D. Transport
E. Train
F. Spaceship
G. None of these is a valid functional interface.
A

A, D, E.
A valid functional interface is one that contains a single abstract method, excluding any public methods that are already defined in the java.lang.Object class. Transport and Boat are valid functional interfaces, as they each contain a single abstract method: go() and hashCode(String), respectively. Since the other methods are part of Object, they do not count as abstract methods. Train is also a functional interface since it extends Transport and does not define any additional abstract methods.

Car is not a functional interface because it is an abstract class. Locomotive is not a functional interface because it includes two abstract methods, one of which is inherited. Finally, Spaceship is not a valid interface, let alone a functional interface, because a default method must provide a body.
A quick way to test whether an interface is a functional interface is to apply the@FunctionalInterface annotation and check if the code still compiles.

17
Q

Which lambda expression when entered into the blank line in the following code causes the program to print hahaha? (Choose all that apply.)

      import java.util.function.Predicate;
      public class Hyena {
         private int age = 1;
         public static void main(String[] args) {
            var p = new Hyena();
            double height = 10;
            int age = 1;
            testLaugh(p,\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_);
            age = 2;
         }
           static void testLaugh(Hyena panda, Predicate < Hyena >  joke) {
            var r = joke.test(panda) ? "hahaha" : "silence";            System.out.print(r);
         }
      }
A. var -> p.age <= 10
B. shenzi -> age==1
C. p -> true
D. age==1
E. shenzi -> age==2
F. h -> h.age < 5
G. None of the above, as the code does not compile.
A

A, F.
Option A is a valid lambda expression. While main() is a static method, it can access age since it is using a reference to an instance of Hyena, which is effectively final in this method.Remember from your 1Z0-815 studies that var is a reserved type, not a reserved word, and may be used for variable names. Option F is also correct, with the lambda variable being a reference to a Hyena object. The variable is processed using deferred execution in the testLaugh() method.

Options B and E are incorrect; since the local variable age is not effectively final, this would lead to a compilation error. Option C would also cause a compilation error, since the expression uses the variable name p, which is already declared within the method. Finally, option D is incorrect, as this is not even a lambda expression.

18
Q

Which of the following can be inserted in the rest() method? (Choose all that apply.)

      public class Lion {
         class Cub {}
         static class Den {}
         static void rest() {
            \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_;
         } }
A. Cub a = Lion.new Cub()
B. Lion.Cub b = new Lion().Cub()
C. Lion.Cub c = new Lion().new Cub()
D. var d = new Den()E. var e = Lion.new Cub()
F. Lion.Den f = Lion.new Den()
G. Lion.Den g = new Lion.Den()
H. var h = new Cub()
A
C, D, G. 
Option C is the correct way to create an instance of an inner class Cub using an instance of the outer class Lion. The syntax looks weird, but it creates an object of the outer class and then an object of the inner class from it. Options A, B, and E use incorrect syntax for creating an instance of the Cub class. Options D and G are the correct way to create an instance of the static nested Den class,as it does not require an instance of Lion, while option F uses invalid syntax. Finally, option H is incorrect since it lacks an instance of Lion. If rest() were an instance method instead of a static method, then option H would be correct.
19
Q

Given the following program, what can be inserted into the blank line that would allow it to print Swim! at runtime?

      interface Swim {
         default void perform() { System.out.print("Swim!"); }
      }
      interface Dance {
         default void perform() { System.out.print("Dance!"); }
      }
      public class Penguin implements Swim, Dance {
         public void perform() { System.out.print("Smile!"); }
         private void doShow() {
            \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
         }
         public static void main(String[] eggs) {
            new Penguin().doShow();
         }
      }

A. super.perform();
B. Swim.perform();
C. super.Swim.perform();
D. Swim.super.perform();
E. The code does not compile regardless of what is inserted into the blank.
F. The code compiles, but due to polymorphism, it is not possible to produce the requested output without creating a new object.

A
D. 
First off, if a class or interface inherits two interfaces containing default methods with the same signature, then it must override the method with its own implementation. The Penguin class does this correctly, so option E is incorrect. The way to access an inherited default method is by using the syntax Swim.super.perform(), making option D correct. We agree the syntax is bizarre, but you need to learn it. Options A, B, and C are incorrect and result in compiler errors.
20
Q

Which statements about effectively final variables are true? (Choose all that apply.)

A. The value of an effectively final variable is not modified after it is set.
B. A lambda expression can reference effectively final variables.
C. A lambda expression can reference final variables.
D. If the final modifier is added, the code still compiles.
E. Instance variables can be effectively final.
F. Static variables can be effectively final.

A

A, B, C, D.
Effectively final refers to local variables whose value is not changed after it is set. For this reason, option A is correct, and options E and F are incorrect. Options B and C are correct, as lambda expressions can access final and effectively final variables. Option D is also correct and is a common test for effectively final variables.

21
Q

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

  1: public interface BigCat {
  2: abstract String getName();
  3: static int hunt() { getName(); return 5; }
  4: default void climb() { rest(); }
  5: private void roar() { getName();  climb(); hunt(); }
  6: private static boolean sneak() { roar(); return true; }
  7: private int rest() { return 2; };
  8: }
A. Line 2
B. Line 3
C. Line 4
D. Line 5
E. Line 6
F. Line 7
G. None of the above
A

B, E.
Like classes, interfaces allow instance methods to access static members, but not vice versa.Non-static private, abstract, and default methods are considered instance methods in interfaces. Line 3 does not compile because the static method hunt() cannot access an abstract instance method getName(). Line 6 does not compile because the private static method sneak()cannot access the private instance method roar(). The rest of the lines compile without issue.

22
Q

What are some advantages of using default interface methods? (Choose all that apply.)

A. Automatic resource management
B. Improve performance at runtime
C. Better exception handling
D. Backward compatibility
E. Highly concurrent execution
F. Convenience in classes implementing the interface
A
D, F. 
Java added default methods primarily for backward compatibility. Using a default method allows you to add a new method to an interface without having to recompile a class that used an older version of the interface. For this reason, option D is correct. Option F is also correct, as default methods in some APIs offer a number of convenient methods to classes that implement the interface.The rest of the options are not related to default methods
23
Q

Which statements about the following enum are true? (Choose all that apply.)

  1: public enum AnimalClasses {
  2: MAMMAL(true), INVERTIBRATE(Boolean.FALSE), BIRD(false),
  3: REPTILE(false), AMPHIBIAN(false), FISH(false) {
  4: public int swim() { return 4; }
  5: }
  6: final boolean hasHair;
  7: public AnimalClasses(boolean hasHair) {
  8: this.hasHair = hasHair;
  9: }
  10: public boolean hasHair() { return hasHair; }
  11: public int swim() { return 0; }
  12: }
A. Compiler error on line 2
B. Compiler error on line 3
C. Compiler error on line 7
D. Compiler error on line 8
E. Compiler error on line 10
F. Compiler error on another line
G. The code compiles successfully.
A

C, F.
Enums are required to have a semicolon (;) after the list of values if there is anything else in the enum. Don’t worry, you won’t be expected to track down missing semicolons on the whole exam—only on enum questions. For this reason, line 5 should have a semicolon after it since it is the end of the list of enums, making option F correct. Enum constructors are implicitly private, making option C correct as well. The rest of the enum compiles without issue.

24
Q

Which lambdas can replace the new Sloth() call in the main() method and produce the same outputat runtime? (Choose all that apply.)

      import java.util.List;
      interface Yawn {
         String yawn(double d, List < Integer >  time);
      }
      class Sloth implements Yawn {
         public String yawn(double zzz, List < Integer >  time) {
            return "Sleep: " + zzz;
         }
      }
      public class Vet {
         public static String takeNap(Yawn y) {
            return y.yawn(10, null);
         }
         public static void main(String... unused) {
            System.out.print(takeNap(new Sloth()));
         }
      }

A. (z,f) -> { String x = “”; return “Sleep: “ + x }
B. (t,s) -> { String t = “”; return “Sleep: “ + t; }
C. (w,q) -> {“Sleep: “ + w}
D. (e,u) -> { String g = “”; “Sleep: “ + e }
E. (a,b) -> “Sleep: “ + (double)(b==null ? a : a)
F. (r,k) -> { String g = “”; return “Sleep:”; }
G. None of the above, as the program does not compile.

A

E.
Option A does not compile because the second statement within the block is missing a semicolon(;) at the end. Option B is an invalid lambda expression because t is defined twice: in the parameter list and within the lambda expression. Options C and D are both missing a return statement and semicolon. Options E and F are both valid lambda expressions, although only option E matches the behavior of the Sloth class. In particular, option F only prints Sleep:, not Sleep: 10.0.

25
Q

What does the following program print?

  1: public class Zebra {
  2: private int x = 24;
  3: public int hunt() {
  4: String message = "x is ";
  5: abstract class Stripes {
  6: private int x = 0;
  7: public void print() {
  8: System.out.print(message + Zebra.this.x);
  9: }
  10: }
  11: var s = new Stripes() {};
  12: s.print();
  13: return x;
  14: }
  15: public static void main(String[] args) {
  16: new Zebra().hunt();
  17: } }
A. x is 0
B. x is 24
C. Line 6 generates a compiler error.
D. Line 8 generates a compiler error.
E. Line 11 generates a compiler error.
F. None of the above
A
B. 
Zebra.this.x is the correct way to refer to x in the Zebra class. Line 5 defines an abstract local class within a method, while line 11 defines a concrete anonymous class that extends the Stripes class. The code compiles without issue and prints x is 24 at runtime, making option B the correct answer
26
Q

What interface members exist in Java 11? (6 items)

A

Constant variable

abstract method

default method

private method

static method

private static method