Programmer I Chapter 7: Methods and Encapsulation Flashcards
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);
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
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: }
17
21
22
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: } }
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”).
Which method do you think is called if we pass an int[]?
public void fly(int[] lengths) {}
public void fly(int… lengths) {}
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.
Which method is called if we invoke fly(3) ?
public void fly(int numMiles) {}
public void fly(Integer numMiles) {}
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.
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); }}
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.
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)); }
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.
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")); } }
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.
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:
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.
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, 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
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, 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.
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, 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.
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]);
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.
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.
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.
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
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.