OCA : SCJP : Quick Notes - 2

OCA : SCJP : Quick Notes - 2 




5.Loop Constructs

-break & continue can be used in Loops & if statements
- In loops null==null allow
       String x = null;
       while(x==null){}
- labels: only allowed in Loops , Not in If's

8. Which of the following statements is/are true?
I. A traditional for loop can iterate through an array starting from index 0.
II. A traditional for loop can iterate through an array starting from the end.
A. Only I
B. Only II
C. Both statements
D. Neither statement
C. With a traditional for loop, you control the order in which indexes are visited in code. This means you can loop through an array in ascending or descending order, and Option C is correct.

9. Which of the following statements is/are true?
I. A for-each loop can iterate through an array starting from index 0.
II. A for-each loop can iterate through an array starting from the end.
A. Only I
B. Only II
C. Both statements
D. Neither statement
A. With a for-each loop, the loop order is determined for you. With an array, this means starting with index 0, and Option A is correct. A traditional for loop allows you to control the order and iterate in either order.


16. What is the output of the following code?
package chicago;
public class Loop {
private static int count;
private static String[] stops = new String[] { "Washington",
"Monroe", "Jackson", "LaSalle" };
public static void main(String[] args) {
while (count < stops.length) {
if (stops[count++].length() < 8) {
break;
}
}
System.out.println(count);
}
}
A. 1
B. 2
C. 4
D. The code does not compile.
B. Since count is a class variable that isn’t specifically initialized, it defaults to 0. On the first iteration of the loop, "Washington", is 11 characters and count is set to 1. The if statement’s body is not run. The loop then proceeds to the next iteration. This time, the post-increment operator uses index 1 before setting count to 2. "Monroe" is checked, which is only 6 characters. The break statement sends the execution to after the loop and 2 is output. Option B is correct.

23. How many of these statements can be inserted after the println to have the code flow follow the arrow in this diagram?
break;
break letters;
break numbers;
 --->letters: for (char ch='a'; ch<='z'; ch++) {
|             numbers: for (int n=0; n<=10; n++) {
|                    System.out.println(ch);
--------------
}
}
A. None
B. One
C. Two
D. Three
 C. In this figure, we want to end the inner loop and resume execution at the letters label.This means we only want to break out of the inner loop. A break statement does just that.It ends the current loop and resumes execution immediately after the loop, making break;a correct answer. The break numbers; statement explicitly says which loop to end, which does the same thing, making it correct as well. By contrast, break letters; ends the outer loop, causing the code only to run the println() once. Therefore, two statements correctly match the diagram, and Option C is correct.

24. Using the diagram in the previous question, how many of these statements can be inserted after the println to have the code flow follow the arrow in the diagram?
continue;
continue letters;
continue numbers;
A. None
B. One
C. Two
D. Three
B. In this figure, we want to end the inner loop and resume execution at the letters label.The continue letters; statement does that. The other two statements resume execution at the inner loop. Therefore, only the second statement correctly matches the diagram, and Option B is correct.

30. What is the result of the following?
int count = 10;
List<Character> chars = new ArrayList<>();
do {
chars.add('a');
for (Character x : chars) count -=1;
} while (count > 0);
System.out.println(chars.size());
A. 3
B. 4
C. The code does not compile.
D. None of the above
B. On the first iteration through the outer loop, chars becomes 1 element. The inner loop is run once and count becomes 9. On the second iteration through the outer loop, chars becomes 2 elements. The inner loop runs twice so count becomes 7. On the third iteration through the outer loop, chars becomes 3 elements. The inner loop runs three times so count becomes 4. On the fourth iteration through the outer loop, chars becomes 4 elements. The inner loop runs four times so count becomes 0. Then both loops end. Therefore, Option B is correct.

36. What is the output of the following?
public class Shoelaces {
public static void main(String[] args) {
String tie = null;
while (tie == null)
tie = "shoelace";
System.out.print(tie);
}
}
A. null
B. shoelace
C. shoelaceshoelace
D. None of the above
B. The first time the loop condition is checked, the variable tie is null. The loop body executes, setting tie. Despite the indention, there are no brackets surrounding the loop body so the print does not run yet. Then the loop condition is checked and tie is not null. The print runs after the loop, printing out shoelace once, making Option B correct.

37. The following code outputs a single letter x. What happens if you remove lines 25 and 28?
23: String race = "";
24: loop:
25: do {
26: race += "x";
27: break loop;
28: } while (true);
29: System.out.println(race);
A. It prints an empty string.
B. It still outputs a single letter x.
C. It no longer compiles.
D. It becomes an infinite loop.
C. Line 27 refers to a loop label. While the label is still present, it no longer points to a loop. This causes the code to not compile, and Option C is correct.

38. What is the output of the following code?
package chicago;
public class Loop {
private static int count;
private static String[] stops = new String[] { "Washington",
"Monroe", "Jackson", "LaSalle" };
public static void main(String[] args) {
while (count < stops.length) {
if (stops[count++].length() < 8) {
continue;
}
}
System.out.println(count);
}
}
A. 1
B. 2
C. 4
D. The code does not compile
 C. The continue statement is useless here since there is no code later in the loop to skip.The continue statement merely resumes execution at the next iteration of the loop, which is what would happen if the if-then statement was empty. Therefore, count increments for each element of the array. The code outputs 4, and Option C is correct.

48. What is the output of the following?
12: int result = 8;
13: for: while (result > 7) {
14: result++;
15: do {
16: result--;
17: } while (result > 5);
18: break for;
19: }
20: System.out.println(result);
A. 5
B. 8
C. The code does not compile.
D. The code compiles but throws an exception at runtime
C. Remember to look for basic errors before wasting time tracking the flow. In this case,the label of the loop is trying to use the keyword for. This is not allowed, so the code does not compile. If the label was valid, Option A would be correct.

49. What is the output of the following?
boolean baloonInflated = false;
do {
if (!baloonInflated) {
baloonInflated = true;
System.out.print("inflate-");
}
} while (baloonInflated);
System.out.println("done");
A. done
B. inflate-done
C. The code does not compile.
D. This is an infinite loop.
D. On the first iteration of the loop, the if statement executes printing inflate-. Then the loop condition is checked. The variable baloonInflated is true, so the loop condition is true and the loop continues. The if statement no longer runs, but the variable never changes state again, so the loop doesn’t end.

6.Methods and Encapsulation

-static imports are used with members of the class, not a class name.





4. What is true about the following program?
public class Dolls {
       public void nested() {
              nested(2, true);// g1
       }
       public int nested(int level, boolean height) {
              return nested(level);
       }
       public int nested(int level) {
              return level + 1;// g2
       };
       public static void main(String[] outOfTheBox) {
              System.out.print(new Dolls().nested());
       }
}
A. It compiles successfully and prints 3 at runtime.
B. It does not compile because of line g1.
C. It does not compile because of line g2.
D. It does not compile for some other reason.
D. The no-argument version of the nested() method does not return a value, and trying to output a void return type in the print() method throws an exception at runtime.

9. Fill in the blank: A variable is always available to all instances of the class.
A. public
B. local
C. static
D. instance
 C. The only variables always available to all instances of the class are those declared static; therefore, Option C is the correct answer. Option A may seem correct, but public variables are only available if a reference to the object is maintained among all instances. Option B is incorrect because there is no local keyword in Java. Option D is also incorrect because a private instance variable is only accessible within the instance that created it.

10. Which line of code, inserted at line p1, causes the application to print 5?
public class Jump {
private int rope = 1;
protected boolean outside;
public Jump() {
// p1
outside = true;
}
public Jump(int rope) {
this.rope = outside ? rope : rope+1;
}
public static void main(String[] bounce) {
System.out.print(new Jump().rope);
}
}
A. this(4);
B. new Jump(4);
C. this(5);
D. rope = 4;
A. the default initialization of a boolean instance variable is false, making outside false at line p1. Therefore, this(4) will cause rope to be set to 5, while this(5) will cause rope to be set to 6.

12. Given the following class, what should be inserted into the two blanks to ensure the class data is properly encapsulated?
public class Box {
public String stuff;
String () {
return stuff;
}
public void setStuff(String stuff) {
this.stuff = stuff;
}
}
A. public and getStuff
B. private and isStuff
C. public and setStuff
D. None of the above
 D. The class data, stuff, is declared public, allowing any class to modify the stuff variable and making the implementation inherently unsafe for encapsulation. Therefore, there are no values that can be placed in the two blanks to ensure the class properly encapsulates its data, making Option D correct. Note that if stuff was declared private, Options A, B, and C would all be correct. Encapsulation does not require JavaBean syntax, just that the internal attributes are protected from outside access, which all of these sets of values do achieve.

15. Given the following application, which diagram best represents the state of the mySkier,mySpeed, and myName variables in the main() method after the call to the slalom() method?
package slopes;
public class Ski {
private int age = 18;
private static void slalom(Ski racer, int[] speed, String name) {
racer.age = 18;
name = "Wendy";
speed = new int[1];
speed[0] = 11;
racer = null;
}
public static void main(String... mountain) {
final Ski mySkier = new Ski();
mySkier.age = 16;
final int[] mySpeed = new int[1];
final String myName = "Rosie";
slalom(mySkier,mySpeed,myName);
}
}//IMG
 C. To solve this problem, it helps to remember that Java is a pass-by-value language in which copies of primitives and object references are sent to methods. This also means that an object’s data can be modified within a method and shared with the caller, but not the reference to the object. Any changes to the object’s reference within the method are not carried over to the caller. In the slalom() method, the Ski object is updated with an age value of 18. Although, the last line of the slalom() method changes the variable value to null, it does not affect the mySkier object or reference in the main() method. Therefore,the mySkier object is not null and the age variable is set to 18, making Options A and D incorrect. Next, the name variable is reassigned to the Wendy object, but this does not change the reference in the main() method, so myName remains Rosie. Finally, the speed array is assigned a new object and updated. Since the array is updated after the reference is reassigned, it does not affect the mySpeed array in the main() method. The result is that mySpeed continues to have a single element with the default int value of 0. For these reasons,Option B is incorrect, and Option C is correct.

18. Which of the following data types can be modified after they are passed to a method as an argument?
A. int[]
B. String
C. long
D. boolean
 A. Option B is incorrect because String values are immutable and cannot be modified.Options C and D are also incorrect since variables are passed by value, not reference, in Java. Option A is the correct answer. The contents of an array can be modified when passed to a method, since a copy of the reference to the object is passed. For example, the method can change the first element of a non-empty array.

20. Given a method with one of the following return types, which data type prevents the return statement from being used within the method?
A. byte
B. String
C. void
D. None of the above
D. Options A and B are incorrect because a method with a non-void return type requires that the method return a value using the return statement. Option C is also incorrect since a method with a void return type can still call the return command with no values and exit the method. Therefore, Option D is the correct answer.

21. How many final modifiers would need to be removed for this application to compile?
public final class Games {
public final static int finish(final int score) {
final int win = 3;
final int result = score++ < 5 ? 2 : win;
return result+=win;
}
public static void main(final String[] v) {
System.out.print(finish(Integer.parseInt(v[0])));
}
}
A. None
B. One
C. Two
D. The code will not compile regardless of the number of final modifiers that are removed 
C. The finish() method modifies two variables that are marked final, score and result. The score variable is modified by the post-increment ++ operator, while the result variable is modified by the compound addition += operator. Removing both final modifiers allows the code to compile. For this reason, Option C is the correct answer

24. Which statement(s) about the following class would help to properly encapsulate the data in the class?
package shield;
public class Protect {
private String material;
protected int strength;
public int getStrength() {
return strength;
}
public void setStrength(int strength) {
this.strength = strength;
}
}
I. Change the access modifier of strength to private.
II. Add a getter method for material.
III. Add a setter method for material.
A. I
B. II and III
C. I, II, and III
D. None, the data in the class is already encapsulated.
 A. The access modifier of strength is protected, so  Changing the value to private would improve encapsulation. Alternatively, the second and third statements do not improve the encapsulation of the class.Therefore, OptionA is the correct answer.

26. Which of the following lines of code can be inserted in the line below that would allow the
class to compile?
package farm;
public class Coop {
public final int static getNumberOfChickens() {
// INSERT CODE HERE
}
}
A. return 3.0;
B. return 5L;
C. return 10;
D. None of the above
 D. The code does not compile, regardless of what is inserted into the line because the method signature is invalid. The return type, int, should go before the method name and after any access, final, or static modifiers. Therefore, Option D is the correct answer. If
the method was fixed, by swapping the order of int and static in the method declaration, then Option C would be the correct answer. Options A and B are still incorrect, though, since each uses a return type that cannot be implicitly converted to int.

27. Which of the following is a true statement about passing data to a method?
A. A change made to a primitive value passed to a method is reflected in the calling method.
B. A change made to the data within an object passed to a method is reflected in the calling method.
C. Reassigning an object reference passed to a method is reflected in the calling method.
D. A change made to a boolean value passed to a method is reflected in the calling method.
 B. Java uses pass-by-value, so changes made to primitive values and object references passed to a method are not reflected in the calling method. For this reason, Options A and C are incorrect statements. Option D is also an invalid statement because it is a special case of Option A. Finally, Option B is the correct answer. Changes to the data within an object are visible to the calling method since the object that the copied reference points to is the same.

30. Given the following two classes, each in a different package, which line inserted below allows the second class to compile?
package clothes;
public class Store {
public static String getClothes() { return "dress"; }
}
package wardrobe;
// INSERT CODE HERE
public class Closet {
public void borrow() {
System.out.print("Borrowing clothes: "+getClothes());
}
}
A. static import clothes.Store.getClothes;
B. import clothes.Store.*;
C. import static clothes.Store.getClothes;
D. import static clothes.Store;
 C. Option A is incorrect because the keywords static and import are reversed. The Closet class uses the method getClothes() without a reference to the class name Store, therefore a static import is required. For this reason, Option B is incorrect since it is missing the static keyword. Option D is also incorrect since static imports are used with members of the class, not a class name. Finally, Option C is the correct answer since it properly imports the method into the class using a static import.

31. What access modifier is used to mark class members package-private?
A. private
B. default
C. protected
D. None of the above
 D. In Java, the lack of an access modifier indicates that the member is package-private,therefore Option D is correct. Note that the default keyword is used for interfaces and switch statements, and is not an access modifier.

32. How many lines of the following program contain compilation errors?
package sky;
public class Stars {
private int inThe = 4;
public void Stars() {
super();
}
public Stars(int inThe) {
this.inThe = this.inThe;
}
public static void main(String[] endless) {
System.out.print(new sky.Stars(2).inThe);
}
}
A. None
B. One
C. Two
D. Three B.
The code does not compile, so Option A is incorrect. The class contains constructor and one method. The first method, Stars(), looks a lot like a no-argument constructor, but since it has a return value of void, it is a method, not a constructor. Since only constructors
can call super(), the code does not compile due to this line. The only constructor in this class, which takes an int value as input, performs a pointless assignment, assigning a variable to itself. While this assignment has no effect, it does not prevent the code from compiling. Finally, the main() method compiles without issue since we just inserted the full package name into the class constructor call. This is how a class that does not use an import statement could call the constructor. Since the method is in the same class, and therefore the same package, it is redundant to include the package name but not disallowed. Because only one line causes the class to fail to compile, Option B is correct.


35. Which of the following statements about overloaded methods are true?
I. Overloaded methods must have the same name.
II. Overloaded methods must have the same return type.
III. Overloaded methods must have a different list of parameters.
A. I
B. I and II
C. I and III
D. I, II, and III
 C. Overloaded methods have the same name but a different list of parameters, can have the same or different return types. Therefore, Option C is the correct answer.

36. How many lines of code would need to be removed for the following class to compile?
public class Week {
private static final String monday;
String tuesday;
final static wednesday = 3;
final protected int thursday = 4;
}
A. One
B. Two
C. Three
D. The code will not compile regardless of the number of lines removed.
C. The declaration of monday does not compile, because the value of a static final variable must be set when it is declared or in a static initialization block. The declaration of tuesday is fine and compiles without issue. The declaration of wednesday does not compile because there is no data type for the variable. Finally, the declaration of thursday does not compile because the final modifier cannot appear before the access modifier. For these reasons, Option C is the correct answer.

37. What is the output of the following application?
public class Puppy {
public static int wag = 5; // q1
public void Puppy(int wag) { // q2
this.wag = wag;
}
public static void main(String[] tail) {
System.out.print(new Puppy(2).wag); // q3
}
}
A. 2
B. It does not compile because of line q1.
C. It does not compile because of line q2.
D. It does not compile because of line q3.
 D. The Puppy class does not declare a constructor, so the default no-argument constructor is automatically inserted by the compiler. What looks like a constructor in the class is actually a method that has a return type of void. Therefore, the line in the main() method to create the new Puppy(2) object does not compile, since there is no constructor capable of taking an int value, making D correct.

39. What is the output of the following application?
public class Phone {
private int size;
public Phone(int size) {this.size=size;}
public static void sendHome(Phone p, int newSize) {
p = new Phone(newSize);
p.size = 4;
}
public static final void main(String... params) {
final Phone phone = new Phone(3);
sendHome(phone,7);
System.out.print(phone.size);
}
}
A. 3
B. 4
C. 7
D. The code does not compile.
A. The code compiles without issue, so Option D is incorrect. The key here is that Java uses pass by value to send object references to methods. Since the Phone reference p was reassigned in the first line of the sendHome() method, any changes to the p reference were made to a new object. In other words, no changes in the sendHome() method affected the object that was passed in. Therefore, the value of size was the same before and after the method call, making the output 3 and Option A the correct answer.
43. Which of the following is not a true statement?
A. The first line of every constructor is a call to the parent constructor via the super() command.
B. A class does not have to have a constructor explicitly defined.
C. A constructor may pass arguments to the parent constructor.
D. final instance variable whose value is not set when they are declared or in an initialization block should be set by the constructor.
 A. Option A is the correct answer because the first line of a constructor could be this() or super(), making it an untrue statement. Option B is a true statement because the compiler will insert the default no-argument constructor if one is not defined. Option C is also a true statement, since zero or more arguments may be passed to the parent constructor, if the parent class defines such constructors. Option D is also true. The value of a final instance variable should be set when it is declared, in an initialization block, or in a constructor.

47. What is the output of the following application?
public class Football {
public static Long getScore(Long timeRemaining) {
return 2*timeRemaining; // m1
}
public static void main(String[] refs) {
final int startTime = 4;
System.out.print(getScore(startTime)); // m2
}
}
A. 8
B. The code does not compile because of line m1.
C. The code does not compile because of line m2.
D. The code compiles but throws an exception at runtime.
 C. The variable startTime can be automatically converted to Integer by the compiler, but Integer is not a subclass of Long. Therefore, the code does not compile due the wrong variable type being passed to the getScore() method on line m2, and Option C is correct.

7. Inheritance

-Default methods overriding possible in concrete class with same method signature by removing 'default' keyword.
-one class implement two interfaces that both define the same default method signature leads to a compiler error, unless the class overrides the default method

1. How many lines of the following program contain compilation errors?
class Cinema {
private String name;
public Cinema(String name) {this.name = name;}
}
public class Movie extends Cinema {
public Movie(String movie) {}
public static void main(String[] showing) {
System.out.print(new Movie("Another Trilogy").name);
}
}
A. None
B. One
C. Two
D. Three
C. The code does not compile, so Option A is incorrect. This code does not compile for two reasons. First, the name variable is marked private in the Cinema class, which means it cannot be accessed directly in the Movie class. Next, the Movie class defines a constructor that is missing an explicit super() statement. Since Cinema does not include a no-argument constructor, the no-argument super() cannot be inserted automatically by the compiler without a compilation error. For these two reasons, the code does not compile, and Option C is the correct answer.

7. What is the output of the following application?
class Automobile {
private final String drive() { return "Driving vehicle"; }
}
class Car extends Automobile {
protected String drive() { return "Driving car"; }
}
public class ElectricCar extends Car {
public final String drive() { return "Driving electric car"; }
public static void main(String[] wheels) {
final Car car = new ElectricCar();
System.out.print(car.drive());
}
}
A. Driving vehicle
B. Driving electric car
C. Driving car
D. The code does not compile.
The drive() method in the Car class does not override the version in the Automobile class since the method is not visible to the Car class. Therefore, the final attribute in the Automobile class does not prevent the Car class from implementing a method with the same signature. The drive() method in the ElectricCar class is a valid override of the method in the Car class, with the access modifier expanding in the subclass. For these reasons, the code compiles, and Option D is incorrect. In the main() method, the object created is an ElectricCar, even if it is assigned to a Car reference. Due to polymorphism, the method from the ElectricCar will be invoked, making Option B the correct answer.

9. How many changes need to be made to the classes below to properly override the watch()method?
class Television {
protected final void watch() {}
}
public class LCD extends Television {
Object watch() {}
}
A. One
B. Two
C. Three
D. None; the code compiles as is.
C. There are three problems with this method override. First, the watch() method is marked final in the Television class. The final modifier would have to be removed from the method definition in the Television class in order for the method to compile in the LCD class. Second, the return types void and Object are not covariant. One of them would have to be changed for the override to be compatible. Finally, the access modifier in the child class must be the same or broader than in the parent class. Since package-private is narrower than protected, the code will not compile. For these reasons, C is the correct.

14. What is the output of the following application?
interface Run {
default void walk() {
System.out.print("Walking and running!");
}
}
interface Jog {
default void walk() {
System.out.print("Walking and jogging!");
}
}
public class Sprint implements Run, Jog {
public void walk() {
System.out.print("Sprinting!");
}
public static void main() {
new Sprint().walk();
}
}
A. Walking and running!
B. Walking and jogging!
C. Sprinting!
D. The code does not compile.
C. Having one class implement two interfaces that both define the same default method signature leads to a compiler error, unless the class overrides the default method. In this case, the Sprint class does override the walk() method correctly, therefore the code compiles without issue, and C is correct.

18. Which statement about the following class is correct?
package shapes;
abstract class Triangle {
abstract String getDescription();
}
class RightTriangle extends Triangle {
protected String getDescription() { return "rt"; } // g1
}
public abstract class IsoscelesRightTriangle extends RightTriangle { // g2
public String getDescription() { return "irt"; }
public static void main(String[] edges) {
final Triangle shape = new IsoscelesRightTriangle(); // g3
System.out.print(shape.getDescription());
}
}
A. The code does not compile due to line g1.
B. The code does not compile due to line g2.
C. The code does not compile due to line g3.
D. The code compiles and runs without issue.
C. The code does not compile, so Option D is incorrect. The IsoscelesRightTriangle class is abstract; therefore, it cannot be instantiated on line g3.

19. Given that Short and Integer extend Number, what type can be used to fill in the blank in the class below to allow it to compile?
interface Horn { public Integer play(); }
abstract class Woodwind { public Short play() {return 3;} }
public final class Saxophone extends Woodwind implements Horn {
public ___ play() {
return null;
}
}
A. Integer
B. Short
C. Number
D. None of the above
D. The play() method is overridden in Saxophone for both Horn and Woodwind, so the return type must be covariant with both. Unfortunately, the inherited methods must also be compatible with each other. Since Integer is not a subclass of Short, and vice versa, there is no subclass that can be used to fill in the blank that would allow the code to compile. In other words, the Saxophone class cannot compile regardless of its implementation of play(), making Option D the correct answer.

25. Which of the following statements is correct?
A. A reference to a class can be assigned to a subclass reference without an explicit cast.
B. A reference to a class can be assigned to a superclass reference without an explicit cast.
C. A reference to an interface can be assigned to a reference of a class that implements the interface without an explicit cast.
D. A reference to a class that implements an interface can be assigned to an interface reference only with an explicit cast.
B. A reference to a class can be implicitly assigned to a superclass reference without an explicit class, making Option B the correct answer. Assigning a reference to a subclass,though, requires an explicit cast, making Option A incorrect. Option C is also incorrect because an interface does not inherit from a class. A reference to an interface requires an explicit cast to be assigned to a reference of any class, even one that implements the interface.An interface reference requires an explicit cast to be assigned to a class reference.Finally, Option D is incorrect. An explicit cast is not required to assign a reference to a class that implements an interface to a reference of the interface.

29. What is the output of the following application?
abstract class Ball {
protected final int size;
public Ball(int size) {
this.size = size;
}
}
interface Equipment {}
public class SoccerBall extends Ball implements Equipment {
public SoccerBall() {
super(5);
}
public Ball get() { return this; }
public static void main(String[] passes) {
Equipment equipment = (Equipment)(Ball)new SoccerBall().get();
System.out.print(((SoccerBall)equipment).size);
}
}
A. 5
B. The code does not compile due an invalid cast.
C. The code does not compile for a different reason.
D. The code compiles but throws a ClassCastException at runtime.
A. Although the casting is a bit much, the object in question is a SoccerBall. Since SoccerBall extends Ball and implements Equipment, it can be explicitly cast to any of those types, so no compilation error occurs. At runtime, the object is passed around and,due to polymorphism, can be read using any of those references since the underlying object is a SoccerBall. In other words, casting it to a different reference variable does not modify the object or cause it to lose its underlying SoccerBall information. Therefore, the code compiles without issue, and Option A is correct.

30. Fill in the blanks: A class that defines an instance variable with the same name as___ a variable in the parent class is referred to as a variable, while a class that defines a static method with the same signature as a static method in a parent class is referred to as a___method.
A. hiding, overriding
B. overriding, hiding
C. hiding, hiding
D. replacing, overriding
C. Both of these descriptions refer to variable and static method hiding, respectively,making Option C correct. Only instance methods can be overridden, making Options A and B incorrect. Option D is also incorrect because replacing is not a real term in this context.

31. Which statement about the following class is correct?
abstract class Parallelogram {
private int getEqualSides() {return 0;}
}
abstract class Rectangle extends Parallelogram {
public static int getEqualSides() {return 2;} // x1
}
public final class Square extends Rectangle {
public int getEqualSides() {return 4;} // x2
public static void main(String[] corners) {
final Square myFigure = new Square(); // x3
System.out.print(myFigure.getEqualSides());
}
}
A. The code does not compile due to line x1.
B. The code does not compile due to line x2.
C. The code does not compile due to line x3.
D. The code compiles and runs without issue.
B. The code does not compile, so Option D is incorrect. The issue here is that the override of getEqualSides() in Square is invalid. A static method cannot override a non-static method and vice versa. For this reason, Option B is the correct answer

35. How many compiler errors does the following code contain?
interface CanFly {
public void fly() {}
}
final class Bird {
public int fly(int speed) {}
}
public class Eagle extends Bird implements CanFly {
public void fly() {}
}
A. None
B. One
C. Two
D. Three
D. First of all, interfaces can only contain abstract, final, and default methods. The method fly() defined in CanFly is not marked static or default and defines an implementation, an empty {}, meaning it cannot be assumed to be abstract; therefore, the code does not compile. Next, the implementation of fly(int speed) in the Bird class also does not compile, but not because of the signature. The method body fails to return an int value. Since it is an overloaded method, if it returned a value it would compile without
issue. Finally, the Eagle class does not compile because it extends the Bird class, which is marked final and therefore, cannot be extended. For these three reasons, Option D is the correct answer.

40. What is the output of the following application?
class Math {
public final double secret = 2;
}
class ComplexMath extends Math {
public final double secret = 4;
}
public class InfiniteMath extends ComplexMath {
public final double secret = 8;
public static void main(String[] numbers) {
Math math = new InfiniteMath();
System.out.print(math.secret);
}
}
A. 2
B. 4
C. 8
D. The code does not compile.
A. The code compiles without issue, so Option D is incorrect. Java allows methods to be overridden, but not variables. Therefore, marking them final does not prevent them from being reimplemented in a subclass. Furthermore, polymorphism does not apply in the same way it would to methods as it does to variables. In particular, the reference type determines the version of the secret variable that is selected, making the output 2 and Option A the correct answer.

41. Given the following method and the fact that FileNotFoundException is a subclass of IOException, which of the following method signatures is a valid override by a subclass?
protected void dance() throws FileNotFoundException {}
A. void dance() throws IOException
B. public void dance() throws IOException
C. private void dance() throws FileNotFoundException
D. public final void dance()
D. Options A and C are incorrect because an overridden method cannot reduce the visibility of the inherited method. Option B is incorrect because an overridden method cannot declare a broader checked exception than the inherited method. Finally, Option D is the correct answer. The removal of the checked exception, the application of a broader access modifier, and the addition of the final attribute are allowed for overridden methods.

45. Fill in the blanks:___ methods must have a different list of parameters,while___ methods must have the exact same return type.
A. Overloaded, overridden
B. Inherited, overridden
C. Overridden, overloaded
D. None of the above
D. Trick question! Option A seems like the correct answer, but the second part of the sentence is false, regardless of whether you insert overloaded or overridden. Overridden methods must have covariant return types, which may not be exactly the same as the type in the parent class. so, D is correct answer.

46. Which of the following statements about no-argument constructors is correct?
A. If a parent class does not include a no-argument constructor, a child class cannot declare one.
B. If a parent class does not include a no-argument constructor (nor a default one inserted by the compiler), a child class must contain at least one constructor definition.
C. If a parent class contains a no-argument constructor, a child class must contain a no-argument constructor.
D. If a parent class contains a no-argument constructor, a child class must contain at least one constructor.
B. If a parent class does not include a no-argument constructor, a child class can still explicitly declare one; it just has to call an appropriate parent constructor with super(),making Option A incorrect. If a parent class does not include a no-argument constructor,the child class must explicitly declare a constructor, since the compiler will not be able to insert the default no-argument constructor, making Option B correct. Option C is incorrect because a parent class can have a no-argument constructor, while its subclasses do not. If Option C was true, then all classes would be required to have no-argument constructors since they all extend java.lang.Object, which has a no-argument constructor. Option D is also incorrect. The default no-argument constructor can be inserted into any class that directly extends a class that has a no-argument constructor. Therefore, no constructors in the subclass are required.

47. Fill in the blanks: The___ determines which attributes exist in memory, while the___ determines which attributes are accessible
by the caller.
A. reference type, signature
B. object type, superclass
C. reference type, object type
D. object type, reference type
D. The object type relates to the attributes of the object that exist in memory, while the reference type dictates how the object is able to be used by the caller. For these reasons, Option D is correct.

48. Given that Integer and Long are subclasses of Number, what type can be used to fill in the blank in the class below to allow it to compile?
package orchestra;
interface MusicCreator { public Number play(); }
abstract class StringInstrument { public Long play() {return 3L;} }
public class Violin extends StringInstrument implements MusicCreator {
public___ play() {
return 12;
}
}
A. Long
B. Integer
C. Long or Integer
D. Long or Number
A. The play() method is overridden in Violin for both MusicCreator and StringInstrument, so the return type must be covariant with both. Long is a subclass of Number, and therefore, it is covariant with the version in MusicCreator. Since it matches the type in StringInstrument, it can be inserted into the blank and the code would compile.While Integer is a subclass of Number, meaning the override for MusicCreator is valid, it is not a subclass of Long used in StringInstrument. Therefore, using Integer would cause the code to not compile. Finally, Number is compatible with the version of the method in MusicCreator but not with the version in StringInstrument, because Number is a superclass of Long, not a subclass. For these reasons, Long is the only class that allows the code to compile, making Option A the correct answer.

r.

8.Exception Handling

- we can declare Throwable in catch block
- try,catch,finally all should have {} even though they has single statement. otherwise C.E
- Check the Keywords properly, check the class extends and method exceptions should be lesser or non, check all throw with new keyword, check classes extends Exception classes not implement, check exception variable names in inner try/catch blocks

5. What is the output of the following application?
package game;
public class Baseball {
public static void main(String... teams) {
try {
int score = 1;
System.out.print(score++);
} catch (Throwable t) {
System.out.print(score++);
} finally {
System.out.print(score++);
}
System.out.print(score++);
}
}
A. 123
B. 124
C. 12
D. None of the above
D. The application does not compile because score is defined only within the try block.The other three places it is referenced, in the catch block, in the finally block, and outside the try-catch-finally block at the end, are not in scope for this variable and each does not compile. so, the correct answer is Option D.

10. What is the result of compiling and running the following application?
package castles;
public class Fortress {
public void openDrawbridge() throws Exception { // p1
try {
throw new Exception("Circle");
} catch (Exception e) {
System.out.print("Opening!");
} finally {
System.out.print("Walls"); // p2
}
}
public static void main(String[] moat) {
new Fortress().openDrawbridge(); // p3
}
}
A. The code does not compile because of line p1.
B. The code does not compile because of line p2.
C. The code does not compile because of line p3.
D. The code compiles, but a stack trace is printed at runtime.
The issue here is how the openDrawbridge() method is called from within the main() method on line p3. The openDrawbridge() method declares the checked exception, Exception, but the main() method from which it is called does not handle or declare the exception. In order for this code to compile, the main() method would have to have a try-catch statement around line p3 that properly handles the checked exception, or the main() would have to be updated to declare a compatible checked exception. For these reasons, line p3 does not compile, and Option C is the correct answer.

12. What is the output of the following application?
package game;
public class BasketBall {
public static void main(String[] dribble) {
try {
System.out.print(1);
throw new ClassCastException();
} catch (ArrayIndexOutOfBoundsException ex) {
System.out.print(2);
} catch (Throwable ex) {
System.out.print(3);
} finally {
System.out.print(4);
}
System.out.print(5);
}
}
A. 1345
B. 1235
C. The code does not compile.
D. The code compiles but throws an exception at runtime.
A. The code compiles and runs without issues, so Options C and D are incorrect. The try block throws a ClassCastException. Since ClassCastException is not a subclass of ArrayIndexOutOfBoundsException, the first catch block is skipped. For the second catch block, ClassCastException is a subclass of Throwable, so that block is executed.Afterward, the finally block is executed and then control returns to the main() method with no exception being thrown. The result is that 1345 is printed, so  A correct

13. Which of the following statements about a finally block is true?
A. Every line of the finally block is guaranteed to be executed.
B. The finally block is executed only if the related catch block is also executed.
C. The finally statement requires brackets {}.
D. The finally block cannot throw an exception.
C. A finally block can throw an exception, in which case not every line of the finally block would be executed. For this reason, Options A and D are incorrect. Option B is also incorrect The finally block is called regardless of whether or not the related catch block is executed. Option C is the correct answer. Unlike an if-then statement, which can take a single statement, a finally statement requires brackets {}.

16. Which statement about the role of exceptions in Java is incorrect?
A. Exceptions are often used when things “go wrong” or deviate from the expected path.
B. An application that throws an exception will terminate.
C. Some exceptions can be avoided programmatically.
D. An application that can properly handle its exception may recover from unexpected
problems.
B. Option A is a true statement about exceptions and when they are often applied.Option B is the false statement and the correct answer. An application that throws an exception can choose to handle the exception and avoid termination. Option C is also a true statement. For example, a NullPointerException can be avoided on a null object by testing whether or not the object is null before attempting to use it. Option D is also a correct statement. Attempting to recover from unexpected problems is an important
aspect of proper exception handling.

17. What is the output of the following application?
package harbor;
class CapsizedException extends Exception {}
class Transport {
public int travel() throws CapsizedException { return 2; };
}
public class Boat {
public int travel() throws Exception { return 4; }; // j1
public static void main(String... distance) throws Exception{
try {
System.out.print(new Boat().travel());
} catch (Exception e) (
System.out.print(8);
)
}
}
A. 4
B. 8
C. The code does not compile due to line j1.
D. The code does not compile for another reason.
D. The code does not compile because the catch block uses parentheses () instead of brackets {}, making Option D the correct answer. Note that Boat does not extend Transport, so while the override on line j1 appears to be invalid since Exception is a broader checked exception than CapsizedException, that code compiles without issue.

19. Which import statement is required to be declared in order to use the Exception,RuntimeException, and Throwable classes in an application?
A. import java.exception.*;
B. import java.util.exception.*;
C. import java.lang.*;
D. None of the above
D. All three of those classes belong to the java.lang package, so Option C seems like the correct answer. The Java compiler, though, includes java.lang by default, so no import statement is actually required to use those

22. What is the result of compiling and running the following application?
package castles;
class CastleUnderSiegeException extends Exception {}
class KnightAttackingException extends CastleUnderSiegeException {}
public class Citadel {
public void openDrawbridge() throws RuntimeException { // q1
try {
throw new KnightAttackingException();
} catch (Exception e) {
throw new ClassCastException();
} finally {
throw new CastleUnderSiegeException(); // q2
}
}
public static void main(String[] moat) {
new Citadel().openDrawbridge(); // q3
}
}
A. The code does not compile because of line q1.
B. The code does not compile because of line q2.
C. The code does not compile because of line q3.
D. The code compiles, but a stack trace is printed at runtime.
B. The application does not compile, so Option D is incorrect. The checked KnightAttackingException thrown in the try block is handled by the associated catch block. The ClassCastException is an unchecked exception, so it is not required to be handled or declared and line q1 compiles without issue. The finally block throws a checked CastleUnderSiegeException, which is required to be handled or declared by the method, but is not. There is no try-catch around line q2, and the method does not declare a compatible
checked exception, only an unchecked exception. For this reason, line q2 does not compile,and Option B is the correct answer. Lastly, line q3 compiles without issue because theunchecked RuntimeException is not required to be handled or declared by the call in themain() method.

24. What is the output of the following application?
package system;
public class Computer {
public void compute() throws Exception {
throw new RuntimeException("Error processing request");
}
public static void main(String[] bits) {
try {
new Computer().compute();
System.out.print("Ping");
} catch (NullPointerException e) {
System.out.print("Pong");
throw e;
}
}
}
A. Ping
B. Pong
C. The code does not compile.
D. The code compiles but throws an exception at runtime.
C. The code does not compile due to the call to compute() in the main() method. Even though the compute() method only throws an unchecked exception, its method declaration includes the Exception class, which is a checked exception. For this reason, the checked exception must be handled or declared in the main() method in which it is called.While there is a try-catch block in the main() method, it is only for the unchecked NullPointerException. Since Exception is not a subclass of NullPointerException,the checked Exception is not properly handled or declared and the code does not compile, C correct answer

26. Fill in the blanks: A ___occurs when a program recurses too deeply
into an infinite loop, while a(n)___ occurs when a reference to a nonexistent object is acted upon.
A. NoClassDefFoundError, StackOverflowError
B. StackOverflowError, NullPointerException
C. ClassCastException, IllegalArgumentException
D. StackOverflowError, IllegalArgumentException
B. A StackOverflowError occurs when a program recurses too deeply into an infinite loop. It is considered an error because the JVM often runs out of memory and cannot recover. A NullPointerException occurs when an instance method or variable on a null reference is used. For these reasons, Option B is correct. A NoClassDefFoundError occurs when code available at compile time is not available at runtime. A ClassCastException occurs when an object is cast to an incompatible reference type.

27. Which of the following is not a reason to add checked exceptions to a method signature?
A. To force a caller to handle or declare its exceptions
B. To notify the caller of potential types of problems
C. To ensure that exceptions never cause the application to terminate
D. To give the caller a chance to recover from a problem
C. Checked exceptions are commonly used to force a caller to deal with an expected type of problem, such as the inability to write a file to the file system. Without dealing with all checked exceptions thrown by the method, the calling code does not compile, so Option A is a true statement. Option B is also a true statement. Declaring various different exceptions informs the caller of the potential types of problems the method can encounter. Option C is the correct answer. There may be no recourse in handling an exception other than to terminate the application. Finally, Option D is also a true statement because it gives the caller a chance to recover from an exception, such as writing file data to a backup location

31. Given a try statement, if both the catch block and the finally block each throw an
exception, what does the caller see?
A. The exception from the catch block
B. The exception from the finally block
C. Both the exception from the catch block and the exception from the finally block
D. None of the above
B. If both the catch and finally blocks throw an exception, the one from the finally block is propagated to the caller, with the one from the catch block being dropped, making Option B the correct answer. Note that Option C is incorrect due to the fact that only one exception can be thrown to the caller

32. What is the output of the following application?
package zoo;
class BigCat {
void roar(int level) throw RuntimeException { // m1
if(level<3) throw new IllegalArgumentException("Incomplete");
System.out.print("Roar!");
}
}
public class Lion extends BigCat {
public void roar() { // m2
System.out.print("Roar!!!");
}
public static void main(String[] cubs) {
final BigCat kitty = new Lion(); // m3
kitty.roar(2);
}
}
A. The code does not compile because of line m1.
B. The code does not compile because of line m2.
C. The code does not compile because of line m3.
D. The code compiles but a stack trace is printed at runtime.
A. The application does not compile because the roar() method in the BigCat class uses throw instead of throws, making Option A the correct answer. Note that if the correct keyword was used, the code would compile without issues, and Option D would be correct. Also the override of roar() in the Lion class is valid, since the overridden method has a broader access modifier and does not declare any new or broader checked exceptions

34. Which of the following classes will handle all types in a catch block?
A. Exception
B. Error
C. Throwable
D. RuntimeException
C. All exceptions in Java inherit from Throwable, making Option C the correct answer.Note that Error and Exception extend Throwable, and RuntimeException extends Exception.

40. What is the output of the following application?
package clothing;
public class Coat {
public Long zipper() throws Exception {
try {
String checkZipper = (String)new Object();
} catch (Exception e) {
throw RuntimeException("Broken!");
}
return null;
}
public static void main(String... warmth) {
try {
new Coat().zipper();
System.out.print("Finished!");
} catch (Throwable t) {}
}
}
A. Finished!
B. Finished!, followed by a stack trace
C. The application does not produce any output at runtime.
D. The code does not compile.
D. In this application, the throw RuntimeException(String) statement in the zipper() method does not include the new keyword. The new keyword is required to create the object being thrown, since RuntimeException(String) is a constructor. For this reason, the code does not compile, and Option D is correct. If the keyword new was inserted properly, then the try block would throw a CastClassException, which would be replaced with a RuntimeException to the calling method by the catch block. The catch block in the main() method would then be activated, and no output would be printed, Option C correct

42. Which of these method signatures is allowed in a class implementing the Outfielder interface?
class OutOfBoundsException extends BadCatchException {}
class BadCatchException extends Exception {}
public interface Outfielder {
public void catchBall() throws OutOfBoundsException;
}
A. public int catchBall() throws OutOfBoundsException
B. public int catchBall() throws BadCatchException
C. public int catchBall() throws Exception
D. None of the above
D. Trick question! Options A, B, and C are each invalid overrides of the method because the return type must be covariant with void. For this reason, Option D is the correct answer. If the return types were changed to be void, then Option A would be a valid override. Options B and C would still be incorrect, since overridden methods cannot throw broader checked exceptions than the inherited method

46. What is the output of the following application?
package broken;
class Problem implements RuntimeException {}
public class BiggerProblem extends Problem {
public static void main(String uhOh[]) {
try {
throw new BiggerProblem();
} catch (BiggerProblem re) {
System.out.print("Problem?");
} catch (Problem e) {
System.out.print("Handled");
} finally {
System.out.print("Fixed!");
}
}
}
A. Problem?Fixed!
B. Handled.Fixed!
C. Problem?Handled.Fixed!
D. The code does not compile.
D. The class RuntimeException is not an interface and it cannot be implemented. For this reason, the Problem class does not compile, and Option D is the correct answer. Note that this is the only compilation problem in the application. If implements was changed to extends, the code would compile and Problem?Fixed! would be printed, making Option A the correct answer.

48. Given an application that hosts a website, which of the following would most likely result
in a java.lang.Error being thrown?
A. Two users try to register an account at the same time.
B. The application temporarily loses connection to the network.
C. A user enters their password incorrectly.
D. The application runs out of memory.
D. A Java application tends to only throw an Error when the application has entered a final,unrecoverable state. Options A and C are incorrect. These types of errors are common and expected in most software applications, and should not cause the application to terminate. Option B uses the word temporarily, meaning the network connection will come back. In this case, a regular exception could be used to try to recover from this state. Option D is the correct answer because running out of memory is usually unrecoverable in Java.

49. Given that FileNotFoundException is a subclass of IOException, what is the output of
the following application?
package storage;
import java.io.*;
public class Backup {
public void performBackup() {
try {
throw new IOException("Disk not found");
} catch (Exception e) {
try {
throw new FileNotFoundException("File not found");
} catch (FileNotFoundException e) { // z1
System.out.print("Failed");
}
}
}
public static void main(String... files) {
new Backup().performBackup(); // z2
}
}
A. Failed
B. The application compiles but a stack trace is printed at runtime.
C. The code does not compile because of line z1.
D. The code does not compile because of line z2.
C. While a catch block is permitted to include an embedded try-catch block, the issue here is that the variable name e is already used by the first catch block. In the second catch block, it is equivalent to declaring a variable e twice. For this reason, line z1 does not compile, and Option C is the correct answer. If a different variable name was used for either catch block, then the code would compile without issue, and Option A would be the correct answer.

9.String,ArrayList,Date,Lambdas

-StringBuilder can be inserted next of its index, new StringBuilder("cl").insert(2, "own")_/

17. What does the following do?
public class Shoot {
interface Target {
boolean needToAim(double angle);
}
static void prepare(double angle, Target t) {
boolean ready = t.needToAim(angle); // k1
System.out.println(ready);
}
public static void main(String[] args) {
prepare(45, d -> d > 5 || d < -5); // k2
}
}
A. It prints true.
B. It prints false.
C. It doesn’t compile due to line k1.
D. It doesn’t compile due to line k2.
A. This is a correct example of code that uses a lambda. The interface has a single abstract method. The lambda correctly takes one double parameter and returns a boolean. This matches the interface. The lambda syntax is correct. Since 45 is greater than 5, Option A is correct.

13. Which portion of code can be removed so that this line of code continues to compile?
Predicate<StringBuilder> p = (StringBuilder b) -> {return true;};
A. Remove StringBuilder b
B. Remove ->
C. Remove { and ;}
D. Remove { return and ;}
13. D. Option A is tricky, but incorrect. While a lambda can have zero parameters, a Predicate cannot. A Predicate is defined as a type mapping to a boolean. Option B is clearly incorrect as -> separates the parts of a lambda. Options C and D are similar. Option C is incorrect because return is only allowed when the brackets are present. Option D is correct.

26. Which of the following can fill in the blank to make the code compile?
import java.util.function.*;
public class Card {
public static void main(String[] s) {
Predicate<String> pred = -> true;
}
}
A. (Integer i)
B. (Object o)
C. (String s)
D. None of the above
D. The type in the lambda must match the generic declared on the Predicate. In this case,that is String. Therefore, Options A and B are incorrect. While Option C is of the correct type, it uses the variable s, which is already in use from the main() method parameter.so, none of these are correct, and D is the answer.

28. What does the following output?
Predicate dash = c -> c.startsWith("-");
System.out.println(dash.test("–"));
A. true
B. false
C. The code does not compile.
D. The code compiles but throws an exception at runtime.
C. While it is common for a Predicate to have a generic type, it is not required. However,it is treated like a Predicate of type Object if the generic type is missing. Since startsWith() does not exist on Object, the first line does not compile, and Option C is correct.

31. Which equivalent code can replace i -> i != 0 in the following line?
Predicate<Integer> ip = i -> i != 0;
A. i -> { i != 0 }
B. i -> { i != 0; }
C. i -> { return i != 0 }
D. i -> { return i != 0; }
D. When you’re using brackets, both the return keyword and semicolon are needed for the lambda to compile, making Option D correct.

34. What does the following output?
Predicate clear = c -> c.equals("clear");
System.out.println(clear.test("pink"));
A. true
B. false
C. The code does not compile.
D. The code compiles but throws an exception at runtime.
B. While it is common for a Predicate to have a generic type, it is not required. When the generic is omitted, it is treated like a Predicate of type Object. Since the equals() method exists on Object, this is fine. Option B is correct because the Predicate tests as false.

47. How many lines does this code output?
import java.util.*;
import java.util.function.*;
public class PrintNegative {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("-5");
list.add("0");
list.add("5");
print(list, e -> e < 0);
}
public static void print(List<String> list, Predicate<Integer> p) {
for (String num : list)
if (p.test(num))
System.out.println(num);
}
}
A. One
B. Two
C. None. The code does not compile.
D. None. The code throws an exception at runtime.
C. Pay attention to the data types. The print() method is looping through a list of String objects. However, the Predicate expects an Integer. Since these don’t match, the if statement does not compile.

7. What is the result of the following code?
StringBuilder sb = new StringBuilder("radical")
.insert(sb.length(), "robots");
System.out.println(sb);
A. radicarobots
B. radicalrobots
C. The code does not compile.
D. The code compiles but throws an exception at runtime.
C. Calling the constructor and then insert() is an example of method chaining. However, the sb.length() call is a problem. The sb reference doesn’t exist until after the chained calls complete. Just because it happens to be on a separate line doesn’t change when the reference is created. Since the code does not compile, Option C is correct.

12. The author of this method forgot to include the data type. Which of the following reference
types can fill in the blank to complete this method?
public static void secret( mystery) {
mystery.add("metal");
String str = mystery.get(0);
int num = mystery.length();
}
A. ArrayList
B. ArrayList<String>
C. StringBuilder
D. None of the above
D. The add() and get() methods are available on ArrayList. However, ArrayList uses size rather than length to get the number of elements. Therefore, Option D is correct. If length was changed to size, Option B would compile if put in the blank. Option A still wouldn’t compile in the blank because a cast would be needed to store the value in str.

14. What is the output of the following?
20: List<Character> chars = new ArrayList<>();
21: chars.add('a');
22: chars.add('b');
23: chars.set(1, 'c');
24: chars.remove(0);
25: System.out.print(chars.size() + " " + chars.contains('b'));
A. 1 false
B. 1 true
C. 2 false
D. 2 true
A. Lines 20–22 create an ArrayList with two elements. Line 23 replaces the second one with a new value. Now chars is [a, c]. Then line 24 removes the first element, making it just [c]. Option A is correct because there is only one element, but it is not the value b.

15. What is the output of the following?
12: String b = "12";
13: b += "3";
14: b.reverse();
15: System.out.println(b.toString());
A. 12
B. 123
C. 321
D. The code does not compile.
D. Trick question. There is no reverse method on the String class. There is one on the StringBuilder class. Therefore, the code does not compile, and Option D is correct.

24. The author of this method forgot to include the data type. Which of the following reference
types can fill in the blank to complete this method?
public static void secret(___ mystery) {
mystery = mystery.replace("1", "8");
mystery.startsWith("paper");
String s = mystery.toString();
}
A. ArrayList
B. String
C. StringBuilder
D. None of the above
B. The toString() method call doesn’t help in narrowing things down as all Java objects have that method available. The other two methods are more helpful. String is the only type of these three to have a startsWith() method, making Option B correct. String also has the replace() method declared here. If you memorized the whole API, you might know that StringBuilder also has a replace() method, but it requires three parameters instead of two. Please don’t memorize the API in that level of detail. We included what you need to know in our study guide. If you do have this outside knowledge, be careful not to read into the questions!

27. What is the output of the following?
5: String line = new String("-");
6: String anotherLine = line.concat("-");
7: System.out.print(line == anotherLine);
8: System.out.print(" ");
9: System.out.print(line.length());
A. false 1
B. false 2
C. true 1
D. true 2
A. A String is immutable so a different object is returned on line 6. The object anotherLine points to is of length 2 after line 6 completes. However, the original line reference still points to an object of length 1. Therefore, Option A is correct.

29. Of the classes LocalDate, LocalDateTime, LocalTime, and LocalTimeStamp, how many include hours, minutes, and seconds?
A. One
B. Two
C. Three
D. Four
B. LocalDate only includes the date portion and not the time portion. There is no class named LocalTimeStamp. The other two, LocalDateTime and LocalTime, both include the time elements, making Option B correct.

32. What is the output of the following?
LocalDate xmas = LocalDate.of(2016, 12, 25);
xmas.plusDays(-1);
System.out.println(xmas.getDayOfMonth());
A. 24
B. 25
C. 26
D. None of the above
B. Java 8 date and time classes are immutable. The plusDays method returns a LocalDate object presenting Christmas Eve (December 24th). However, this return value is ignored. The xmas variable still represents the original value, so Option B is correct.

33. What is the output of the following?
1: public class Legos {
2: public static void main(String[] args) {
3: StringBuilder sb = new StringBuilder();
4: sb.append("red");
5: sb.deleteCharAt(0);
6: sb.delete(1, 2);
7: System.out.println(sb);
8: }
9: }
A. e
B. d
C. ed
D. None of the above
A. Line 3 creates an empty StringBuilder. Line 4 adds three characters to it. Line 5 removes the first character, resulting in ed. Line 6 deletes the characters starting at position 1 and ending right before position 2, which removes the character at index 1, which is d. The only character left is e, so A is correct.

40. Which is not a true statement about the Period class?
A. A Period is immutable.
B. A Period is typically used for adding or subtracting time from dates.
C. You can create a Period representing 2 minutes.
D. You can create a Period representing 5 years.
C. The Period class creates immutable objects and is usually used to add/subtract from a LocalDate or LocalDateTime object. It allows creating date, week, month, or year periods. Since it cannot be used for time, Option C is the answer

41. What is the output of the following class?
1: package rocket;
2: public class Countdown {
3: public static void main(String[] args) {
4: StringBuilder builder = new StringBuilder("54321");
5: builder.substring(2);
6: System.out.println(builder.charAt(1));
7: }
8: }
A. 1
B. 2
C. 3
D. 4
D. Line 4 creates a StringBuilder of length 5. Pay attention to the substring() method StringBuilder. It returns a String with the value 321. It does not change the StringBuilder itself. Then line 6 is retrieving the second indexed element from that unchanged value, which is 4. Therefore, Option D is correct.

43. The author of this method forgot to include the data type. Which of the following reference
types can best fill in the blank to complete this method?
public static void secret(__ mystery) {
char ch = mystery.charAt(3);
mystery = mystery.insert(1, "more");
int num = mystery.length();
}
A. ArrayList
B. String
C. StringBuilder
D. None of the above.
C. ArrayList has a size() method rather than a length() method, making Option A incorrect. The charAt() and length() methods are declared on both String and StringBuilder. However, the insert() method is only declared on a StringBuilder and not a String. Therefore, Option C is correct

45. What is the result of the following?
import java.time.*;
import java.time.format.*;
public class HowLong {
public static void main(String[] args) {
LocalDate newYears = LocalDate.of(2017, 1, 1);
Period period = Period.ofDays(1);
DateTimeFormatter format = DateTimeFormatter.ofPattern("mm-dd-yyyy");
System.out.print(format.format(newYears.minus(period)));
}
}
A. 01-01-2017
B. 12-31-2016
C. The code does not compile.
D. The code compiles but throws an exception at runtime.
D. When creating a formatter object, remember that MM represents month while mm represents minute. Since there are not minutes defined on a LocalDate object, the code throws an UnsupportedTemporalTypeException. You don’t need to know the name of the exception, but you do need to know that an exception is thrown.

46. Which of the following types can you pass as a parameter to the replace() method on the String class?
I. char
II. String
III. StringBuilder
A. I
B. I and II
C. II and III
D. I, II, and III
D. There are two signatures for the replace() method. One takes two char parameters.The other signature takes a CharSequence. Both String and StringBuilder implement this interface. This makes all three alternatives correct, and Option D is correct.

50. What is the result of the following?
LocalDate xmas = LocalDate.of(2016, 12, 25);
xmas.setYear(2017);
System.out.println(xmas.getYear());
A. 2016
B. 2017
C. The code does not compile.
D. The code compiles but throws an exception at runtime.
C. The Java 8 date and time classes are immutable. This means they do not contain setter
methods and the code does not compile.

java.util.function.Predicate is a functional interface that can be used as assignment target for lambda expression. The Predicate interface represents an operation that takes a single input and returns a boolean value.

Example #1:The following example shows how to use the test() method of the Predicate interface using lambda.
package com.boraji.tutorial.lambda;
import java.util.function.Predicate;
public class PredicateExample1 {
       public static void main(String[] args) {
              Predicate<String> predicateString = s -> {
                     return s.equals("Hello");
              };
              System.out.println(predicateString.test("Hello"));
              System.out.println(predicateString.test("Hello World"));

              Predicate<Integer> predicateInt = i -> {
                     return i > 0;
              };
              System.out.println(predicateInt.test(5));
              System.out.println(predicateInt.test(-5));
       }
}
true
false
true
false
Example #2:The following example shows how to use the default methods ( and, or and negate) of the Predicate interface.

import java.util.function.Predicate;
public class PredicateExample2 {
       public static void main(String[] args) {
              Predicate<String> predicate=s->{
                     return s.equals("Hello");
              };
             
              //AND logical operation 
              Predicate<String> predicateAnd=predicate.and(s->s.length()>4);
              System.out.println(predicateAnd.test("Hello"));
             
              //OR logical operation
              Predicate<String> predicateOr=predicate.or(s->s.length()==10);
              System.out.println(predicateOr.test("Hello"));
             
              //NEGATE logical operation
              Predicate<String> predicateNegate=predicate.negate();
              System.out.println(predicateNegate.test("Hello"));
       }
}
Output

true
true
false



2 Comments

Thank You

Previous Post Next Post