Programmer I Chapter 7: Methods and Encapsulation Flashcards

1
Q

what will this print? The class is declared like this:

public class Koala {
   public static int count = 0;
}

5: Koala k = new Koala();
6: System.out.println(k.count);
7: k = null;
8: System.out.println(k.count);

A

0
0

The compiler checks for the type of the reference and uses that instead of the object—which is sneaky of Java. This code is perfectly legal

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

what lines contain compilation errors assuming this code is inside a class declaration?

14: private static int one;
15: private static final int two;
16: private static final int three = 3;
17: private static final int four;
18: static {
19: one = 1;
20: two = 2;
21: three = 3;
22: two = 4;
23: }

A

17
21
22

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

what lines contain compilation errors?

1: import static java.util.Arrays;
2: import static java.util.Arrays.asList;
3: static import java.util.Arrays.*;
4: public class MyClass {
5: public static void main(String[] args) {
6: Arrays.asList(“one”);
7: } }

A

1
3
6

Line 1 tries to use a static import to import a class. Remember that static imports are only for importing static members. Regular imports are for importing a class. Line 3 tries to see whether you are paying attention to the order of keywords. The syntax is import static and not vice versa. Line 6 is sneaky. The as List method is imported online 2. However, the Arrays class is not imported anywhere. This makes it okay to write asList(“one”) but not Arrays.asList(“one”).

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

Which method do you think is called if we pass an int[]?

public void fly(int[] lengths) {}
public void fly(int… lengths) {}

A

Trick question! Remember that Java treats varargs as if they were an array. This means that the method signature is the same for both methods. Since we are not allowed to overload methods with the same parameter list, this code doesn’t compile. Even though the code doesn’t look the same, it compiles to the same parameter list.

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

Which method is called if we invoke fly(3) ?

public void fly(int numMiles) {}
public void fly(Integer numMiles) {}

A

Java will match the int numMiles version. Java tries to use the most specific parameter list it can find. When the primitive int version isn’t present, it will autobox. However, when the primitive int version is provided, there is no reason for Java to do the extra work of autoboxing.

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

what will this print?

public class ReferenceTypes {
   public void fly(String s) {
      System.out.print("string");
   }
   public void fly(Object o) {
      System.out.print("object");
   }
   public static void main(String[] args) {
      ReferenceTypes r = new ReferenceTypes();
      r.fly("test");
      System.out.print("-");
      r.fly(56);
   }}
A

string-object

The first call is a String and finds a direct match. There’s no reason to use the Object version when there is a nice String parameter list just waiting to be called. The second call looks for an int parameter list. When it doesn’t find one, it autoboxes to Integer. Since it still doesn’t find a match, it goes to the Object one.

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

What does this print?

public static void print(Iterable i) {
   System.out.print("I");
}
public static void print(CharSequence c) {
   System.out.print("C");
}
public static void print(Object o) {
   System.out.print("O");
}
public static void main(String[] args){
   print("abc");
   print(new ArrayList<>());
   print(LocalDate.of(2019, Month.JULY, 4));
}
A

CIO

The code is due for a promotion! The first call to print() passes a String. As you learned in Chapter 5, String and StringBuilder implement the CharSequence interface.T
he second call to print() passes an ArrayList. Remember that you get to assume unknown APIs do what they sound like. In this case, Iterable is an interface for classes you can iterate over.
The final call to print() passes a LocalDate. This is another class you might not know, but that’s okay. It clearly isn’t a sequence of characters or something to loop through. That means the Object method signature is used.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does this print?

public class Glider2 {
   public static String glide(String s) {
      return "1";
   }
   public static String glide(String... s) {
      return "2";
   }
   public static String glide(Object o) {
      return "3";
   }
   public static String glide(String s, String t) {
      return "4";
   }
   public static void main(String[] args) {
      System.out.print(glide("a"));
      System.out.print(glide("a", "b"));
      System.out.print(glide("a", "b", "c"));
   }
}
A

142

The first call matches the signature taking a single String because that is the most specific match. The second call matches the signature, taking two String parameters since that is an exact match. It isn’t until the third call that the varargs version is used since there are no better matches.

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

Which of the following can fill in the blank in this code to make itcompile? (Choose all that apply.)

public class Ant {
\_\_\_\_\_\_ void method() {}
}
A. default
B. final
C. private
D. Public
E. String
F. zzz:
A

B, C.

The keyword void is a return type. Only the access modifier or optional specifiers are allowed before the return type. Option C is correct, creating a method with private access. Option B is also correct, creating a method with default access and the optional specifier final. Since default access does not require a modifier,we get to jump right to final. Option A is incorrect because default access omits the access modifier rather than specifying default. Option D is incorrect because Java is case sensitive. It would have been correct if public were the choice. Option E is incorrect because the method already has a void return type.Option F is incorrect because labels are not allowed for methods.

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

Which of the following methods compile? (Choose all that apply.)

A. final static void method4() {}
B. public final int void method() {}
C. private void int method() {}
D. static final void method3() {}
E. void final method() {}
F. void public method() {}
A

A, D.
Options A and D are correct because the optional specifiers are allowed in any order. Options B and C are incorrect because they each have two return types. Options E and F are incorrect because the return type is before the optional specifier and access modifier, respectively

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

Which of the following methods compile? (Choose all that apply.)

A. public void methodA() { return;}
B. public int methodB() { return null;}
C. public void methodC() {}
D. public int methodD() { return 9;}
E. public int methodE() { return 9.0;}
F. public int methodF() { return;}
A

A, C, D.
Options A and C are correct because a void method is optionally allowed to have a return statement as long as it doesn’t try to return a value. Option B does not compile because null requires a reference object as the return type. Since int is primitive, it is not a reference object. Option D is correct because it returns an int value. Option E does not compile because it tries to return a double when the return type is int. Since a double cannot be assigned to an int, it cannot be returned as one either.Option F does not compile because no value is actually returned.

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

Which of the following methods compile? (Choose all that apply.)

A. public void moreA(int… nums) {}
B. public void moreB(String values, int… nums) {}
C. public void moreC(int… nums, String values) {}
D. public void moreD(String… values, int… nums) {}
E. public void moreE(String[] values, …int nums) {}
F. public void moreG(String[] values, int[] nums) {}

A

A, B, F.
Options A and B are correct because the single varargs parameter is the last parameter declared. Option F is correct because it doesn’t use any varargs parameters. Option C is incorrect because the varargs parameter is not last. Option D is incorrect because two varargs parameters are not allowed in the same method. Option E is incorrect because the … for a varargs must be after the type, not before it.

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

Given the following method, which of the method calls return 2?(Choose all that apply.)

public int howMany(boolean b, boolean… b2) {
return b2.length;
}

A. howMany();
B. howMany(true);
C. howMany(true, true);
D. howMany(true, true, true);
E. howMany(true, {true, true});
F. howMany(true, new boolean[2]);
A

D, F.
Option D passes the initial parameter plus two more to turn into a varargs array of size 2. Option F passes the initial parameter plus an array of size 2. Option A does not compile because it does not pass the initial parameter. Option E does not compile because it does not declare an array properly. It should be new boolean[] {true, true}. Option B creates a varargs array of size 0, and option C creates a varargs array of size 1.

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

Which of the following statements is true?

A. Package-private access is more lenient than protected access.
B. A public class that has private fields and package-private methods is not visible to classes outside the package.
C. You can use access modifiers so only some of the classes in a package see a particular package-private class.
D. You can use access modifiers to allow access to all methods and not any instance variables.
E. You can use access modifiers to restrict access to all classes that begin with the word Test.
A
D. 
This is the common implementation for encapsulation by setting all fields to be private and all methods to be public. Option A is incorrect because protected access allows everything that package-private access allows and additionally allows subclasses access. Option B is incorrect because the class is public. This means that other classes can see the class. However,they cannot call any of the methods or read any of the fields. It is essentially a useless class. Option C is incorrect because package-private access applies to the whole package. Option E is incorrect because Java has no such wildcard access capability.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Given the following my.school.Classroom and my.city.Schoolclass definitions, which line numbers in main() generate acompiler error? (Choose all that apply.)

1: package my.school;
2: public class Classroom {
3: private int roomNumber;
4: protected static String teacherName;
5: static int globalKey = 54321;
6: public static int floor = 3;
7: Classroom(int r, String t) {
8: roomNumber = r;
9: teacherName = t; } }

1: package my.city;
2: import my.school.*;
3: public class School {
4: public static void main(String[] args) {
5: System.out.println(Classroom.globalKey);
6: Classroom room = new Classroom(101, “Mrs. Anderson”);
7: System.out.println(room.roomNumber);
8: System.out.println(Classroom.floor);
9: System.out.println(Classroom.teacherName); } }

A. None, the code compiles fine.
B. Line 5
C. Line 6
D. Line 7
E. Line 8
F. Line 9
A

B, C, D, F.
The two classes are in different packages, which means private access and default (package-private) access will not compile. This causes compile errors in lines 5, 6, and 7, making options B, C, and D correct answers. Additionally, protected access will not compile since School does not inherit from Classroom. This causes the compiler error on line 9, making option F a correct answer as well.

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

Which of the following are true about encapsulation? (Choose all that apply.)

A. It allows getters.
B. It allows setters.
C. It requires specific naming conventions.
D. It uses package-private instance variables.
E. It uses private instance variables.

A

A, B, E.
Encapsulation allows using methods to get and set instance variables so other classes are not directly using them,making options A and B correct. Instance variables must be private for this to work, making option E correct and option D incorrect. While there are common naming conventions, they are not required, making option C incorrect.

17
Q

Which pairs of methods are valid overloaded pairs? (Choose all that apply.)

A. 
public void hiss(Iterable i) {}
and
public int hiss(Iterable i) { return 0; }
B. 
public void baa(CharSequence c) {}
and
public void baa(String s) {}
C. 
public var meow(List < String > l) {}
and
public var meow(String s) {}
D. 
public void moo(Object o) {}
and
public void moo(String s) {}
E. 
public void roar(List < Boolean > b) {}
and
public void roar(List < Character > c) {}
F. 
public void woof(boolean[] b1) {}
and
public void woof(Boolean[] b) {}
A
B, D, F. 
Option A is incorrect because the methods differ only in return type. Option C is tricky. It is incorrect because var is not a valid return type. Remember that var can be used only for local variables. Option E is incorrect because the method signature is identical once the generic types are erased. Options B and D are
correct because they represent interface and superclass relationships. Option F is correct because the arrays are of different types.
18
Q

What is the output of the following code?

1: package rope;
2: public class Rope {
3: public static int LENGTH = 5;
4: static {
5: LENGTH = 10;
6: }
7: public static void swing() {
8: System.out.print(“swing “);
9: } }

1: import rope.;
2: import static rope.Rope.
;
3: public class Chimp {
4: public static void main(String[] args) {
5: Rope.swing();
6: new Rope().swing();
7: System.out.println(LENGTH);
8: } }

A. swing swing 5
B. swing swing 10
C. Compiler error on line 2 of Chimp
D. Compiler error on line 5 of Chimp
E. Compiler error on line 6 of Chimp
F. Compiler error on line 7 of Chimp
A
B. 
Rope runs line 3, setting LENGTH to 5, and then immediately after runs the static initializer, which sets it to 10. Line 5 in the Chimp class calls the static method normally and prints swing and a space. Line 6 also calls the static method. Java allows calling a static method through an instance variable although it is not recommended. Line 7 uses the static import on line 2 to reference LENGTH.
19
Q

Which statements are true of the following code? (Choose all that apply.)

1: public class Rope {
2: public static void swing() {
3: System.out.print(“swing”);
4: }
5: public void climb() {
6: System.out.println(“climb”);
7: }
8: public static void play() {
9: swing();
10: climb();
11: }
12: public static void main(String[] args) {
13: Rope rope = new Rope();
14: rope.play();
15: Rope rope2 = null;
16: System.out.println(“-“);
17: rope2.play();
18: } }

A. The code compiles as is.
B. There is exactly one compiler error in the code.
C. There are exactly two compiler errors in the code.
D. If the line(s) with compiler errors are removed, the output is swing-climb.
E. If the line(s) with compiler errors are removed, the output is swing-swing.
F. If the line(s) with compile errors are removed, the code throws a NullPointerException.

A

B, E.
Line 10 does not compile because static methods are not allowed to call instance methods. Even though we are calling play() as if it were an instance method and an instance exists,Java knows play() is really a static method and treats it as such.If line 10 is removed, the code works. It does not throw a NullPointerException on line 17 because play() is a static method. Java looks at the type of the reference for rope2 and translates the call to Rope.play().

20
Q

What is the output of the following code?

import rope.*;
import static rope.Rope.*;
public class RopeSwing {
private static Rope rope1 = new Rope();
private static Rope rope2 = new Rope();
{
System.out.println(rope1.length);
}
public static void main(String[] args) {
rope1.length = 2;
rope2.length = 8;
System.out.println(rope1.length);
}}
package rope;
public class Rope {
public static int length = 0;
}
A. 02
B. 08
C. 2
D. 8
E. The code does not compile.
F. An exception is thrown.
A

D.
There are two details to notice in this code. First, note that RopeSwing has an instance initializer and not a static initializer. Since RopeSwing is never constructed, the instance initializer does not run. The other detail is that length is static. Changes from one object update this common static variable.

21
Q

How many lines in the following code have compiler errors?

1: public class RopeSwing {
2: private static final String leftRope;
3: private static final String rightRope;
4: private static final String bench;
5: private static final String name = “name”;
6: static {
7: leftRope = “left”;
8: rightRope = “right”;
9: }
10: static {
11: name = “name”;
12: rightRope = “right”;
13: }
14: public static void main(String[] args) {
15: bench = “bench”;
16: }
17: }

A. 0
B. 1
C. 2
D. 3
E. 4
F. 5
A

E.
If a variable is static final, it must be set exactly once, and it must be in the declaration line or in a static initialization block.
Line 4 doesn’t compile because bench is not set in either of these locations. Line 15 doesn’t compile because final variables are not allowed to be set after that point. Line 11 doesn’t compile because name is set twice: once in the declaration and again in the static block. Line 12 doesn’t compile because right Rope is set twice as well. Both are in static initialization blocks.

22
Q

Which of the following can replace line 2 to make this code compile? (Choose all that apply.)

1: import java.util.*;
2: // INSERT CODE HERE
3: public class Imports {
4: public void method(ArrayList < String > list) {
5: sort(list);
6: }
7: }

A. import static java.util.Collections;
B. import static java.util.Collections.;
C. import static java.util.Collections.sort(ArrayList < String > );
D. static import java.util.Collections;
E. static import java.util.Collections.
;
F. static import java.util.Collections.sort(ArrayList < String > );

A

B.
The two valid ways to do this are import static java.util.Collections.*; and import static java.util.Collections.sort;. Option A is incorrect because you can do a static import only on static members. Classes such as Collections require a regular import. Option C is nonsense as method parameters have no business in an import. Options D, E,and F try to trick you into reversing the syntax of import static.

23
Q

What is the result of the following statements?

1: public class Test {
2: public void print(byte x) {
3: System.out.print(“byte-“);
4: }
5: public void print(int x) {
6: System.out.print(“int-“);
7: }
8: public void print(float x) {
9: System.out.print(“float-“);
10: }
11: public void print(Object x) {
12: System.out.print(“Object-“);
13: }
14: public static void main(String[] args) {
15: Test t = new Test();
16: short s = 123;
17: t.print(s);
18: t.print(true);
19: t.print(6.789);
20: }
21: }

A. byte-float-Object-
B. int-float-Object-
C. byte-Object-float-
D. int-Object-float-
E. int-Object-Object-
F. byte-Object-Object-
A

E.
The argument on line 17 is a short. It can be promoted to an int, so print() on line 5 is invoked. The argument on line 18 is a boolean. It can be autoboxed to a Boolean, so print() on line 11 is invoked. The argument on line 19 is a double. It can be autoboxed to a Double, so print() on line 11 is invoked. Therefore, the output is int-Object-Object-, and the correct answer is option E.

24
Q

What is the result of the following program?

1: public class Squares {
2: public static long square(int x) {
3: var y = x * (long) x;
4: x = -1;
5: return y;
6: }
7: public static void main(String[] args) {
8: var value = 9;
9: var result = square(value);
10: System.out.println(value);
11: } }

A. -1
B. 9
C. 81
D. Compiler error on line 9
E. Compiler error on a different line
A

B.
Since Java is pass-by-value and the variable on line 8 never gets reassigned, it stays as 9. In the method square, x starts as 9.The y value becomes 81, and then x gets set to –1. Line 9 does set result to 81. However, we are printing out value and that is still 9.

25
Q

Which of the following are output by the following code? (Choose all that apply.)

public class StringBuilders {
public static StringBuilder work(StringBuilder a,StringBuilder b) {
a = new StringBuilder("a");
b.append("b");
return a;
}
public static void main(String[] args) {
var s1 = new StringBuilder("s1");
var s2 = new StringBuilder("s2");
var s3 = work(s1, s2);
System.out.println("s1 = " + s1);
System.out.println("s2 = " + s2);
System.out.println("s3 = " + s3);
}}
A. s1 = a
B. s1 = s1
C. s2 = s2
D. s2 = s2b
E. s3 = a
F. The code does not compile
A

B, D, E.
Since Java is pass-by-value, assigning a new object to a does not change the caller. Calling append() does affect the caller because both the method parameter and the caller have a reference to the same object. Finally, returning a value does pass the reference to the caller for assignment to s3.

26
Q

Which of the following will compile when independently inserted in the following code? (Choose all that apply.)

1: public class Order3 {
2: final String value1 = “red”;
3: static String value2 = “blue”;
4: String value3 = “yellow”;
5: {
6: // CODE SNIPPET 1
7: }
8: static {
9: // CODE SNIPPET 2
10: } }

A. Insert at line 6: value1 = "green";
B. Insert at line 6: value2 = "purple";
C. Insert at line 6: value3 = "orange";
D. Insert at line 9: value1 = "magenta";
E. Insert at line 9: value2 = "cyan";
F. Insert at line 9: value3 = "turquoise";
A

B, C, E.
The variable value1 is a final instance variable. It can beset only once: in the variable declaration, an instance initializer,or a constructor. Option A does not compile because the final variable was already set in the declaration. The variable value2 is a static variable. Both instance and static initializers are able to access static variables, making options B and E correct. The variable value3 is an instance variable. Options D and F do not compile because a static initializer does not have access to instance variables.

27
Q

Which of the following are true about the following code? (Choose all that apply.)

public class Run {
static void execute() {
System.out.print("1-");
}
static void execute(int num) {
System.out.print("2-");
}
static void execute(Integer num) {
System.out.print("3-");
}
static void execute(Object num) {
System.out.print("4-");
}
static void execute(int... nums) {
System.out.print("5-");
}
public static void main(String[] args) {
Run.execute(100);
Run.execute(100L);
}}

A. The code prints out 2-4-.
B. The code prints out 3-4-.
C. The code prints out 4-2-.
D. The code prints out 4-4-.
E. The code prints 3-4- if you remove the method static voidexecute(int num).
F. The code prints 4-4- if you remove the constructor staticvoid execute(int num).

A

A, E.
The 100 parameter is an int and so calls the matching int method. When this method is removed, Java looks for the next most specific constructor. Java prefers autoboxing to varargs, so it chooses the Integer constructor. The 100L parameter is a long.Since it can’t be converted into a smaller type, it is autoboxed into a Long, and then the method for Object is called.

28
Q

Which pairs of methods are valid overloaded pairs? (Choose all that apply.)

A. 
public void hiss(Set s) {}
and
public void hiss(List < String > l) {}
B. 
public void baa(var c) {}
and
public void baa(String s) {}
C. 
public void meow(char ch) {}
and
public void meow(String s) {}
D. 
public void moo(char ch) {}
and
public void moo(char ch) {}
E. 
public void roar(long... longs){}
and
public void roar(long long) {}
F. 
public void woof(char... chars) {}
and
public void woof(Character c) {}
A

A, C, F.
Option B is incorrect because var cannot be a method
parameter. It must be a local variable or lambda parameter.Option D is incorrect because the method declarations are identical. Option E is tricky. The variable long is illegal because long is a reserved word. Options A, C, and F are correct because they represent different types

29
Q

Which can fill in the blank to create a properly encapsulated class? (Choose all that apply.)

public class Rabbits {
\_\_\_\_\_\_ int numRabbits = 0;
\_\_\_\_\_\_ void multiply() {
numRabbits *= 6;
}
\_\_\_\_\_\_ int getNumberOfRabbits() {
return numRabbits;
}
}

A. private, public, and public
B. private, protected, and private
C. private, private, and protected
D. public, public, and public
E. None of the above since multiply() does not begin with set
F. None of the above for a reason other than the multiply()method

A
A, B, C. 
Instance variables must include the private access modifier, making option D incorrect. While it is common for methods to be public, this is not required. Options A, B, and C are all correct, although some are more useful than others. Since the class can be written to be encapsulated, options E and F are incorrect