1.
Given:
1. public class Threads2 implements Runnable {
2.
3. public void run() {
4. System.out.println("run.");
5. throw new RuntimeException("Problem");
6. }
7. public static void main(String[] args) {
8. Thread t = new Thread(new Threads2());
9. t.start();
10. System.out.println("End of method.");
11. }
12. }
Which two can be results? (Choose two.)
Correct Answer(s)
D. End of method.
run.
java.lang.RuntimeException: Problem
E. Run.
java.lang.RuntimeException: Problem
End of method.
Explanation
The code creates a new thread and starts it. In the run() method of the Threads2 class, it prints "run." and then throws a RuntimeException with the message "Problem".
Since the new thread is started, it will execute concurrently with the main thread. So, the order of the output is not guaranteed.
The possible results are:
1. End of method. (printed by the main thread)
2. run. (printed by the new thread)
3. java.lang.RuntimeException: Problem (thrown by the new thread)
Therefore, the correct answers are:
- End of method.
- run.
- java.lang.RuntimeException: Problem
2.
Which two statements are true? (Choose two.)
Correct Answer(s)
A. It is possible for more than two threads to deadlock at once.
F. If a piece of code is capable of deadlocking, you cannot eliminate the possibility of deadlocking by inserting
invocations of Thread.yield().
Explanation
The first statement is true because deadlock can occur when multiple threads are waiting for resources that are held by other threads, resulting in a circular dependency. Therefore, it is possible for more than two threads to deadlock at once.
The last statement is also true because invoking Thread.yield() only gives a hint to the scheduler that the current thread is willing to yield its current use of the processor. It does not guarantee that deadlock will be eliminated if the code is already capable of deadlocking.
3.
Given:
7. void waitForSignal() {
8. Object obj = new Object();
9. synchronized (Thread.currentThread()) {
10. obj.wait();
11. obj.notify();
12. }
13. }
Which statement is true?
Correct Answer
B. This code can throw an IllegalMonitorStateException.
Explanation
The code can throw an IllegalMonitorStateException because the obj.wait() and obj.notify() methods can only be called within a synchronized block on the object that is being waited on or notified. In this case, the synchronized block is using Thread.currentThread() as the lock object, so calling obj.wait() and obj.notify() will result in an IllegalMonitorStateException.
4.
Given:
11. class PingPong2 {
12. synchronized void hit(long n) {
13. for(int i = 1; i < 3; i++)
14. System.out.print(n + "-" + i + " ");
15. }
16. }
17. public class Tester implements Runnable {
18. static PingPong2 pp2 = new PingPong2();
19. public static void main(String[] args) {
20. new Thread(new Tester()).start();
21. new Thread(new Tester()).start();
22. }
23. public void run() { pp2.hit(Thread.currentThread().getId()); }
24. }
Which statement is true?
Correct Answer
B. The output could be 6-1 6-2 5-1 5-2
Explanation
The output could be 6-1 6-2 5-1 5-2 because the hit() method is synchronized, which means only one thread can access it at a time. However, since there are two threads created in the main method, it is possible for the threads to interleave their execution. Therefore, it is possible for one thread to print "6-1" and "6-2" before the other thread prints "5-1" and "5-2".
5.
Given:
1. public class Threads4 {
2. public static void main (String[] args) {
3. new Threads4().go();
4. }
5. public void go() {
6. Runnable r = new Runnable() {
7. public void run() {
8. System.out.print("foo");
9. }
310-065
4
http://www.testkiller.com
http://www.troytec.com
10. };
11. Thread t = new Thread(r);
12. t.start();
13. t.start();
14. }
15. }
What is the result?
Correct Answer
B. An exception is thrown at runtime.
Explanation
The code will throw an exception at runtime because the start() method of a Thread can only be called once. In this code, the start() method is called twice on the same Thread object, which is not allowed and will result in an exception being thrown.
6.
Given:
11. public abstract class Shape {
12. private int x;
13. private int y;
14. public abstract void draw();
15. public void setAnchor(int x, int y) {
16. this.x = x;
17. this.y = y;
18. }
19. }
Which two classes use the Shape class correctly? (Choose two.)
Correct Answer(s)
B. Public abstract class Circle extends Shape {
private int radius;
}
E. Public class Circle extends Shape {
private int radius;
public void draw() {/* code here */}
Explanation
The first class uses the Shape class correctly because it extends the Shape class and implements the abstract methods. The second class also uses the Shape class correctly because it extends the Shape class and provides an implementation for the draw() method.
7.
Given:
11. public class Barn {
12. public static void main(String[] args) {
13. new Barn().go("hi", 1);
14. new Barn().go("hi", "world", 2);
15. }
16. public void go(String... y, int x) {
17. System.out.print(y[y.length - 1] + " ");
18. }
19. }
What is the result?
Correct Answer
D. Compilation fails.
Explanation
The code will fail to compile because the method go() has a parameter of type int (x) after the varargs parameter (y). According to the rules of varargs, the varargs parameter must be the last parameter in the method signature. Therefore, having an int parameter after the varargs parameter is not allowed and will result in a compilation error.
8.
Given:
10. class Nav{
11. public enum Direction { NORTH, SOUTH, EAST, WEST }
12. }
13. public class Sprite{
14. // insert code here
15. }
Which code, inserted at line 14, allows the Sprite class to compile?
Correct Answer
D. Nav.Direction d = Nav.Direction.NORTH;
Explanation
The code "Nav.Direction d = Nav.Direction.NORTH;" allows the Sprite class to compile because it correctly specifies the fully qualified name of the Direction enum. This ensures that the compiler can identify the enum and its values without any ambiguity.
9.
Given:
11. public class Rainbow {
12. public enum MyColor {
13. RED(0xff0000), GREEN(0x00ff00), BLUE(0x0000ff);
14. private final int rgb;
15. MyColor(int rgb) { this.rgb = rgb; }
16. public int getRGB() { return rgb; }
17. };
18. public static void main(String[] args) {
19. // insert code here
20. }
21. }
Which code fragment, inserted at line 19, allows the Rainbow class to compile?
Correct Answer
B. MyColor treeColor = MyColor.GREEN;
Explanation
The code fragment "MyColor treeColor = MyColor.GREEN;" allows the Rainbow class to compile because it creates a new variable "treeColor" of type MyColor and assigns it the value MyColor.GREEN. This is a valid operation as MyColor is an enum and GREEN is one of its defined values.
10.
Given:
11. class Mud {
12. // insert code here
13. System.out.println("hi");
14. }
15. }
And the following five fragments:
public static void main(String...a) {
public static void main(String.* a) {
public static void main(String... a) {
public static void main(String[]... a) {
public static void main(String...[] a) {
How many of the code fragments, inserted independently at line 12, compile?
Correct Answer
D. 3
Explanation
Three of the code fragments, "public static void main(String...a)", "public static void main(String... a)", and "public static void main(String...[] a)", can be inserted independently at line 12 and will compile. These fragments define the main method with a variable-length argument parameter, which is a valid syntax in Java.
11.
Given:
5. class Atom {
6. Atom() { System.out.print("atom "); }
7. }
8. class Rock extends Atom {
9. Rock(String type) { System.out.print(type); }
10. }
11. public class Mountain extends Rock {
12. Mountain() {
13. super("granite ");
14. new Rock("granite ");
15. }
16. public static void main(String[] a) { new Mountain(); }
17. }
What is the result?
Correct Answer
F. Atom granite atom granite
Explanation
The correct answer is "atom granite atom granite" because when the Mountain class is instantiated, it calls the constructor of the Rock class with the argument "granite". This constructor then prints "granite". Then, a new instance of the Rock class is created with the argument "granite", which also prints "granite". Finally, the constructor of the Mountain class calls the constructor of the Atom class, which prints "atom". Therefore, the output is "atom granite atom granite".
12.
Given:
1. interface TestA { String toString(); }
2. public class Test {
3. public static void main(String[] args) {
4. System.out.println(new TestA() {
5. public String toString() { return "test"; }
6. });
7. }
8. }
What is the result?
Correct Answer
A. Test
Explanation
The code creates an anonymous inner class that implements the TestA interface and overrides the toString() method to return "test". The anonymous inner class is then instantiated and its toString() method is called when printing to the console. Therefore, the result is "test".
13.
Given:
11. public static void parse(String str) {
12. try {
13. float f = Float.parseFloat(str);
14. } catch (NumberFormatException nfe) {
15. f = 0;
16. } finally {
17. System.out.println(f);
18. }
19. }
20. public static void main(String[] args) {
21. parse("invalid");
22. }
What is the result?
Correct Answer
B. Compilation fails.
Explanation
The compilation fails because the variable "f" is declared inside the try block and is not accessible outside of it. Therefore, when trying to print the value of "f" in the finally block, a compilation error occurs.
14.
Given:
1. public class Blip {
2. protected int blipvert(int x) { return 0; }
3. }
4. class Vert extends Blip {
310-065
10
http://www.testkiller.com
http://www.troytec.com
5. // insert code here
6. }
Which five methods, inserted independently at line 5, will compile? (Choose five.)
Correct Answer(s)
A. Public int blipvert(int x) { return 0; }
C. Private int blipvert(long x) { return 0; }
E. Protected int blipvert(long x) { return 0; }
F. Protected long blipvert(long x) { return 0; }
G. Protected long blipvert(int x, int y) { return 0; }
Explanation
The correct answer includes five methods that will compile at line 5. These methods have different parameter types and access modifiers, but they all have the same name "blipvert" and return type. This is allowed because they are considered overloaded methods, meaning they have the same name but different parameters. The access modifiers in the correct answer are public, private, and protected, which are all valid for methods in a subclass. The parameter types include int and long, which are also valid. Overall, the correct answer provides a variety of valid methods that can be inserted at line 5.
15.
Given:
1. class Super {
2. private int a;
3. protected Super(int a) { this.a = a; }
4. }
...
11. class Sub extends Super {
12. public Sub(int a) { super(a); }
13. public Sub() { this.a = 5; }
14. }
Which two, independently, will allow Sub to compile? (Choose two.)
Correct Answer(s)
C. Change line 13 to:
public Sub() { this(5); }
D. Change line 13 to:
public Sub() { super(5); }
Explanation
Changing line 13 to either "public Sub() { this(5); }" or "public Sub() { super(5); }" will allow the Sub class to compile. In the first case, "this(5);" calls the constructor of the Sub class with the argument 5. In the second case, "super(5);" calls the constructor of the Super class with the argument 5. Both of these changes ensure that the Sub class has a valid constructor that can be used to create objects.
16.
Which Man class properly represents the relationship "Man has a best friend who is a
Dog"?
Correct Answer
D. Class Man { private Dog bestFriend; }
Explanation
The correct answer is "class Man { private Dog bestFriend; }". This answer properly represents the relationship "Man has a best friend who is a Dog" by declaring a private instance variable "bestFriend" of type Dog within the Man class. This allows each instance of the Man class to have a specific Dog object as their best friend.
17.
Given:
1. package test;
2.
3. class Target {
4. public String name = "hello";
5. }
What can directly access and change the value of the variable name?
Correct Answer
C. Any class in the test package
Explanation
Any class in the test package can directly access and change the value of the variable "name". This is because the variable "name" has default access modifier, which means it is accessible within the same package. Therefore, any class within the test package can access and modify the value of the variable "name".
18.
Given:
11. abstract class Vehicle { public int speed() { return 0; }
12. class Car extends Vehicle { public int speed() { return 60; }
13. class RaceCar extends Car { public int speed() { return 150; }
...
21. RaceCar racer = new RaceCar();
22. Car car = new RaceCar();
23. Vehicle vehicle = new RaceCar();
24. System.out.println(racer.speed() + ", " + car.speed()
25. + ", " + vehicle.speed());
What is the result?
Correct Answer
D. 150, 150, 150
Explanation
The result is "150, 150, 150" because the speed() method is overridden in each class. When the speed() method is called on the RaceCar object, it returns 150. Similarly, when the speed() method is called on the Car object and the Vehicle object, they both refer to the RaceCar object and return 150 as well. Therefore, the result is 150, 150, 150.
19.
Given:
5. class Building { }
6. public class Barn extends Building {
7. public static void main(String[] args) {
8. Building build1 = new Building();
9. Barn barn1 = new Barn();
10. Barn barn2 = (Barn) build1;
11. Object obj1 = (Object) build1;
12. String str1 = (String) build1;
13. Building build2 = (Building) barn1;
14. }
15. }
Which is true?
Correct Answer
C. If line 12 is removed, the compilation succeeds.
Explanation
Line 12 is attempting to cast the object "build1" of type Building to a String. Since Building is not a subclass of String, this cast is not valid and will result in a compilation error. Therefore, if line 12 is removed, the compilation will succeed.
20.
A team of programmers is reviewing a proposed API for a new utility class. After some
discussion, they realize that they can reduce the number of methods in the API without
losing any functionality. If they implement the new design, which two OO principles will
they be promoting?
Correct Answer
A. Looser coupling
Explanation
If the team of programmers decides to reduce the number of methods in the API without losing any functionality, they will be promoting two OO principles: looser coupling and higher cohesion. Looser coupling means that the classes or components in the system are less dependent on each other, making it easier to make changes or updates without affecting other parts of the system. Higher cohesion means that the methods and functionality within a class or component are closely related and focused, leading to a more organized and maintainable codebase.
21.
Given:
21. class Money {
22. private String country = "Canada";
23. public String getC() { return country; }
24. }
25. class Yen extends Money {
26. public String getC() { return super.country; }
27. }
28. public class Euro extends Money {
29. public String getC(int x) { return super.getC(); }
30. public static void main(String[] args) {
31. System.out.print(new Yen().getC() + " " + new Euro().getC());
32. }
33. }
What is the result?
Correct Answer
E. Compilation fails due to an error on line 26.
Explanation
The correct answer is "Compilation fails due to an error on line 26." This is because the method getC() in the Yen class is trying to access the private variable "country" from the superclass Money using the "super" keyword. However, since "country" is a private variable, it is not accessible from the subclass Yen, resulting in a compilation error.
22.
Assuming that the serializeBanana() and the deserializeBanana() methods will correctly
use Java serialization and given:
13. import java.io.*;
14. class Food implements Serializable {int good = 3;}
15. class Fruit extends Food {int juice = 5;}
16. public class Banana extends Fruit {
17. int yellow = 4;
18. public static void main(String [] args) {
19. Banana b = new Banana(); Banana b2 = new Banana();
20. b.serializeBanana(b); // assume correct serialization
21. b2 = b.deserializeBanana(); // assume correct
22. System.out.println("restore "+b2.yellow+ b2.juice+b2.good);
24. }
25. // more Banana methods go here
50. }
What is the result?
Correct Answer
C. Restore 453
Explanation
The code defines a class hierarchy of Food, Fruit, and Banana, with Banana being the most derived class. The Banana class has an instance variable "yellow" with a value of 4. In the main method, a Banana object "b" is created and serialized using the serializeBanana() method (which is assumed to be correct). Then, another Banana object "b2" is created and deserialized using the deserializeBanana() method (also assumed to be correct). Finally, the yellow, juice, and good instance variables of "b2" are printed. Since "b2" is deserialized from "b", it will have the same values for all the instance variables, resulting in "restore 453" being printed.
23.
Given a valid DateFormat object named df, and
16. Date d = new Date(0L);
17. String ds = "December 15, 2004";
18. // insert code here
What updates d's value with the date represented by ds?
Correct Answer
C. 18. try {
19. d = df.parse(ds);
20. } catch(ParseException e) { };
Explanation
The correct answer is 18. try {
19. d = df.parse(ds);
20. } catch(ParseException e) { };
This code block tries to parse the string representation of a date, "December 15, 2004", using the DateFormat object df. If the parsing is successful, the value of d will be updated to the date represented by ds. If there is a ParseException, the catch block will handle the exception.
24.
Given:
11. double input = 314159.26;
12. NumberFormat nf = NumberFormat.getInstance(Locale.ITALIAN);
13. String b;
14. //insert code here
Which code, inserted at line 14, sets the value of b to 314.159,26?
Correct Answer
B. B = nf.format( input );
Explanation
The code "b = nf.format( input );" sets the value of b to 314.159,26. This is because the format() method of the NumberFormat class formats the given number according to the specific locale, in this case, the Italian locale. The formatted number is then assigned to the variable b.
25.
Given:
1. public class TestString1 {
2. public static void main(String[] args) {
3. String str = "420";
4. str += 42;
5. System.out.print(str);
6. }
7. }
What is the output?
Correct Answer
D. 42042
Explanation
The output of this code is "42042". The code starts with a string "420" on line 3. On line 4, the "+=" operator is used to concatenate the number 42 to the string, resulting in "42042". Finally, on line 5, the string is printed to the console.
26.
Which capability exists only in java.io.FileWriter?
Correct Answer
D. Writing a line separator to an open stream.
Explanation
The capability of writing a line separator to an open stream exists only in java.io.FileWriter. This means that FileWriter specifically allows for the writing of a line separator, which is a special character or sequence of characters used to indicate the end of a line in a text file. The other options mentioned, such as closing an open stream, flushing an open stream, and writing to an open stream, are capabilities that are generally available in various I/O classes in Java, not exclusive to FileWriter.
27.
Given that the current directory is empty, and that the user has read and write
permissions, and the following:
11. import java.io.*;
12. public class DOS {
13. public static void main(String[] args) {
14. File dir = new File("dir");
15. dir.mkdir();
16. File f1 = new File(dir, "f1.txt");
17. try {
18. f1.createNewFile();
19. } catch (IOException e) { ; }
20. File newDir = new File("newDir");
21. dir.renameTo(newDir);
22. }
23. }
Which statement is true?
Correct Answer
E. The file system has a directory named newDir, containing a file f1.txt.
Explanation
The code creates a new directory named "dir" and a new file named "f1.txt" inside that directory. Then, it renames the "dir" directory to "newDir". Therefore, the file system has a directory named "newDir", containing a file "f1.txt".
28.
Given:
22. StringBuilder sb1 = new StringBuilder("123");
23. String s1 = "123";
24. // insert code here
25. System.out.println(sb1 + " " + s1);
Which code fragment, inserted at line 24, outputs "123abc 123abc"?
Correct Answer
E. Sb1.append("abc"); s1 = s1.concat("abc");
Explanation
The code fragment "sb1.append("abc"); s1 = s1.concat("abc");" is the correct answer because it appends "abc" to the StringBuilder object sb1 using the append() method and concatenates "abc" to the String object s1 using the concat() method. This ensures that both sb1 and s1 have "abc" added to their original values, resulting in the desired output "123abc 123abc".
29.
Given:
1. public class LineUp {
2. public static void main(String[] args) {
3. double d = 12.345;
4. // insert code here
5. }
6. }
Which code fragment, inserted at line 4, produces the output | 12.345|?
Correct Answer
F. System.out.printf("|%7.3f| \n", d);
Explanation
The code fragment "System.out.printf("|%7.3f| ", d);" produces the output "| 12.345|". The "%7.3f" format specifier is used to print a floating-point number with a total width of 7 characters, including the decimal point and any leading spaces. The ".3" precision specifier is used to display 3 digits after the decimal point. Therefore, the output will have a total width of 7 characters, with the number "12.345" centered within it.
30.
Given:
11. public class Test {
12. public static void main(String [] args) {
13. int x = 5;
14. boolean b1 = true;
15. boolean b2 = false;
16.
17. if ((x == 4) && !b2 )
18. System.out.print("1 ");
19. System.out.print("2 ");
20. if ((b2 = true) && b1 )
21. System.out.print("3 ");
22. }
23. }
What is the result?
Correct Answer
D. 2 3
Explanation
The result is "2 3" because the first if statement on line 17 evaluates to false since x is not equal to 4 and b2 is false. Therefore, the code inside the if statement is not executed. The second if statement on line 20 evaluates to true since b2 is assigned the value true and b1 is true. Therefore, the code inside the if statement is executed and "3" is printed. Finally, the program reaches the end of the main method and terminates, resulting in the output "2 3".
31.
10. interface Foo {}
11. class Alpha implements Foo {}
12. class Beta extends Alpha {}
13. class Delta extends Beta {
14. public static void main( String[] args ) {
15. Beta x = new Beta();
16. // insert code here
17. }
18. }
Which code, inserted at line 16, will cause a java.lang.ClassCastException?
Correct Answer
B. Foo f = (Delta)x;
Explanation
The code "Foo f = (Delta)x;" will cause a java.lang.ClassCastException. This is because the object "x" is of type Beta, and cannot be casted to type Delta, which is a subclass of Beta.
32.
Given:
22. public void go() {
23. String o = "";
24. z:
25. for(int x = 0; x < 3; x++) {
26. for(int y = 0; y < 2; y++) {
27. if(x==1) break;
28. if(x==2 && y==1) break z;
29. o = o + x + y;
30. }
31. }
32. System.out.println(o);
33. }
What is the result when the go() method is invoked?
Correct Answer
C. 000120
Explanation
The go() method contains nested for loops. The outer loop iterates from 0 to 2, while the inner loop iterates from 0 to 1.
At line 27, if x equals 1, the inner loop is terminated using the "break" statement. This means that when x is 1, the inner loop will not execute and move to the next iteration of the outer loop.
At line 28, if x equals 2 and y equals 1, the outer loop is terminated using the "break z" statement. This means that when x is 2 and y is 1, both the inner and outer loops will be terminated.
The variable "o" stores the concatenation of x and y at each iteration of the inner loop. Therefore, the final value of "o" will be "000120".
Hence, the result when the go() method is invoked is "000120".
33.
Given:
11. static void test() throws RuntimeException {
12. try {
13. System.out.print("test ");
14. throw new RuntimeException();
15. }
16. catch (Exception ex) { System.out.print("exception "); }
17. }
18. public static void main(String[] args) {
19. try { test(); }
20. catch (RuntimeException ex) { System.out.print("runtime "); }
21. System.out.print("end ");
22. }
What is the result?
Correct Answer
D. Test exception end
Explanation
The code defines a method called "test" that throws a RuntimeException. In the main method, the "test" method is called within a try-catch block. Since the "test" method throws a RuntimeException, it is caught by the catch block in the main method. Therefore, the code will print "test exception end".
34.
Given:
33. try {
34. // some code here
35. } catch (NullPointerException e1) {
36. System.out.print("a");
37. } catch (Exception e2) {
38. System.out.print("b");
39. } finally {
40. System.out.print("c");
41. }
If some sort of exception is thrown at line 34, which output is possible?
Correct Answer
D. Ac
Explanation
If an exception is thrown at line 34, the catch block at line 35 will catch the exception since it is specifically catching NullPointerException. It will then print "a". After the catch block, the finally block at line 40 will always execute and print "c". Therefore, the possible output in this scenario is "ac".
35.
Given:
31. // some code here
32. try {
33. // some code here
34. } catch (SomeException se) {
35. // some code here
36. } finally {
37. // some code here
38. }
Under which three circumstances will the code on line 37 be executed? (Choose three.)
Correct Answer(s)
B. The code on line 33 throws an exception.
C. The code on line 35 throws an exception.
E. The code on line 33 executes successfully.
Explanation
The code on line 37 will be executed under the following three circumstances:
1) When the code on line 33 throws an exception, the catch block on line 34 will handle the exception and then the code on line 37 will be executed in the finally block.
2) When the code on line 35 throws an exception, the catch block on line 34 will handle the exception and then the code on line 37 will be executed in the finally block.
3) When the code on line 33 executes successfully without throwing any exception, the code on line 37 will still be executed in the finally block.
36.
Given:
10. int x = 0;
11. int y = 10;
12. do {
13. y--;
14. ++x;
15. } while (x < 5);
16. System.out.print(x + "," + y);
What is the result?
Correct Answer
B. 5,5
Explanation
The code snippet is using a do-while loop to decrement the value of y by 1 and increment the value of x by 1 until x is less than 5. Since the initial value of x is 0, the loop will run 5 times (from x = 0 to x = 4). Therefore, the final values of x and y will be 5 and 5 respectively.
37.
Given:
1. public class Donkey2 {
2. public static void main(String[] args) {
3. boolean assertsOn = true;
4. assert (assertsOn) : assertsOn = true;
5. if(assertsOn) {
6. System.out.println("assert is on");
7. }
8. }
9. }
If class Donkey is invoked twice, the first time without assertions enabled, and the second
time with assertions enabled, what are the results?
Correct Answer
C. Assert is on
Explanation
When the class Donkey is invoked for the first time without assertions enabled, the code on line 4 does not execute because the condition (assertsOn) is false. Therefore, the if statement on line 5 is not executed, and there is no output.
When the class Donkey is invoked for the second time with assertions enabled, the code on line 4 executes because the condition (assertsOn) is true. This causes the value of assertsOn to be set to true. Therefore, the if statement on line 5 is executed, and the message "assert is on" is printed as output.
38.
Given:
11. Float pi = new Float(3.14f);
12. if (pi > 3) {
13. System.out.print("pi is bigger than 3. ");
14. }
15. else {
16. System.out.print("pi is not bigger than 3. ");
17. }
18. finally {
19. System.out.println("Have a nice day.");
20. }
What is the result?
Correct Answer
A. Compilation fails.
Explanation
The given code will result in a compilation error. This is because the "finally" block is placed after the "if-else" statements, which is not allowed in Java. The "finally" block should always come after the "try" and "catch" blocks. Therefore, the code will not compile and an error will occur.
39.
Given:
1. public class Boxer1{
2. Integer i;
3. int x;
4. public Boxer1(int y) {
5. x = i+y;
6. System.out.println(x);
7. }
8. public static void main(String[] args) {
9. new Boxer1(new Integer(4));
10. }
11. }
What is the result?
Correct Answer
D. A NullPointerException occurs at runtime.
Explanation
The code is attempting to add the value of variable "y" to the value of variable "i", but variable "i" has not been assigned a value. This results in a NullPointerException at runtime because the code is trying to perform an operation on a null object.
40.
Given:
1. public class Person {
2. private String name;
3. public Person(String name) { this.name = name; }
4. public boolean equals(Person p) {
5. return p.name.equals(this.name);
6. }
7. }
Which statement is true?
Correct Answer
A. The equals method does NOT properly override the Object.equals method.
Explanation
The equals method does not properly override the Object.equals method because it takes a parameter of type Person instead of Object. In order to properly override the equals method, it should have the signature "public boolean equals(Object obj)".
41.
Which two statements are true about the hashCode method? (Choose two.)
Correct Answer(s)
C. The hashCode method for a given class can be used to test for object inequality, but NOT object equality, for that class.
E. The hashCode method is used by the java.util.HashSet collection class to group the elements within that set into hash buckets for swift retrieval.
Explanation
The first statement is true because the hashCode method can be used to check if two objects are not equal. The second statement is true because the hashCode method is used by the java.util.HashSet collection class to group elements into hash buckets for efficient retrieval.
42.
1. public class Score implements Comparable<Score> {
2. private int wins, losses;
3. public Score(int w, int l) { wins = w; losses = l; }
4. public int getWins() { return wins; }
5. public int getLosses() { return losses; }
6. public String toString() {
7. return "<" + wins + "," + losses + ">";
8. }
9. // insert code here
10. }
Which method will complete this class?
Correct Answer
B. Public int compareTo(Score other){/*more code here*/}
Explanation
The correct method to complete the class is "public int compareTo(Score other){/*more code here*/}". This is because the class implements the Comparable interface, which requires the implementation of the compareTo method. The compareTo method is used to compare two objects of the same class and determine their order. In this case, the compareTo method will compare two Score objects based on their wins and losses, allowing for sorting or ordering of Score objects based on their performance.
43.
Given a pre-generics implementation of a method:
11. public static int sum(List list) {
12. int sum = 0;
13. for ( Iterator iter = list.iterator(); iter.hasNext(); ) {
14. int i = ((Integer)iter.next()).intValue();
15. sum += i;
16. }
17. return sum;
18. }
What three changes allow the class to be used with generics and avoid an unchecked
warning? (Choose three.)
Correct Answer(s)
A. Remove line 14.
C. Replace line 13 with "for (int i : intList) {".
F. Replace the method declaration with "sum(List intList)".
Explanation
The first change, removing line 14, allows the class to be used with generics because it eliminates the need to cast the object returned by the iterator to an Integer.
The second change, replacing line 13 with "for (int i : intList) {", allows the class to be used with generics because it uses the enhanced for loop syntax for iterating over the list, which automatically handles the casting of the objects to the specified type.
The third change, replacing the method declaration with "sum(List intList)", allows the class to be used with generics because it specifies the type parameter for the List, ensuring type safety and avoiding an unchecked warning.
44.
Given:
23. Object [] myObjects = {
24. new Integer(12),
25. new String("foo"),
26. new Integer(5),
27. new Boolean(true)
28. };
29. Arrays.sort(myObjects);
30. for(int i=0; i<myObjects.length; i++) {
31. System.out.print(myObjects[i].toString());
32. System.out.print(" ");
33. }
What is the result?
Correct Answer
C. A ClassCastException occurs in line 29
Explanation
The line 29 is attempting to sort the array "myObjects" using the Arrays.sort() method. However, the array contains objects of different types (Integer, String, and Boolean), which cannot be directly compared. This results in a ClassCastException, as the sort method cannot determine the correct order of the objects.
45.
Given a class Repetition:
1. package utils;
2.
3. public class Repetition {
4. public static String twice(String s) { return s + s; }
5. }
and given another class Demo:
1. // insert code here
2.
3. public class Demo {
4. public static void main(String[] args) {
5. System.out.println(twice("pizza"));
6. }
7. }
Which code should be inserted at line 1 of Demo.java to compile and run Demo to print
"pizzapizza"?
Correct Answer
F. Import static utils.Repetition.twice;
Explanation
The correct answer is "import static utils.Repetition.twice;". This is because the method "twice" is a static method in the class "Repetition", and in order to directly access the method without specifying the class name, we need to use the "import static" statement.
46.
A UNIX user named Bob wants to replace his chess program with a new one, but he is
not sure where the old one is installed. Bob is currently able to run a Java chess program
starting from his home directory /home/bob using the command:
java -classpath /test:/home/bob/downloads/*.jar games.Chess
Bob's CLASSPATH is set (at login time) to:
/usr/lib:/home/bob/classes:/opt/java/lib:/opt/java/lib/*.jar
What is a possible location for the Chess.class file?
Correct Answer
C. /test/games/Chess.class
Explanation
A possible location for the Chess.class file is /test/games/Chess.class. This is because the command to run the Java chess program includes the classpath argument "-classpath /test:/home/bob/downloads/*.jar", which means that the program will look for the Chess.class file in the /test directory. Additionally, the package structure of the chess program is specified as "games.Chess", indicating that the Chess.class file should be located in a "games" directory within the classpath. Therefore, /test/games/Chess.class is a possible location for the file.
47.
Given the following directory structure:
bigProject
|--source
| |--Utils.java
|
|--classes
|--
And the following command line invocation:
javac -d classes source/Utils.java
Assume the current directory is bigProject, what is the result?
Correct Answer
C. If the compile is successful, Utils.class is added to the classes directory.
Explanation
The given command line invocation "javac -d classes source/Utils.java" compiles the Utils.java file in the source directory and specifies the output directory as classes using the -d flag. Therefore, if the compilation is successful, the resulting Utils.class file will be added to the classes directory.
48.
Given:
1. package com.company.application;
2.
3. public class MainClass {
4. public static void main(String[] args) {}
5. }
And MainClass exists in the /apps/com/company/application directory. Assume the
CLASSPATH environment variable is set to "." (current directory).Which two java
commands entered at the command line will run MainClass? (Choose two.)
Correct Answer(s)
B. Java com.company.application.MainClass if run from the /apps directory
C. Java -classpath /apps com.company.application.MainClass if run from any directory
49.
Which statement is true?
Correct Answer
C. The finalize() method for a given object is called no more than once by the garbage
collector.
Explanation
The finalize() method for a given object is called no more than once by the garbage collector. This means that even if the garbage collector runs multiple times, the finalize() method will only be called once for a specific object.
50.
Given:
3. public class Batman {
4. int squares = 81;
5. public static void main(String[] args) {
6. new Batman().go();
7. }
8. void go() {
9. incr(++squares);
10. System.out.println(squares);
11. }
12. void incr(int squares) { squares += 10; }
13. }
What is the result?
Correct Answer
B. 82
Explanation
The result is 82 because the variable "squares" is incremented by 10 inside the "incr" method, which is called in the "go" method. The "++" operator before "squares" in the line "incr(++squares)" increments the value of "squares" before passing it to the "incr" method. Therefore, the original value of 81 is incremented by 10 to become 91, and then it is printed in the line "System.out.println(squares)" in the "go" method.