Certif. Java - SCJP - Introduction
What is the output of the following program? 1. public class Worker extends Thread { 2. public void run() { 3. System.out.print("N"); 4. } 5. 6. public static void main(String [] args) { 7. Thread worker = new Worker(); 8. worker.run(); 9. System.out.print("O"); 10. } 11. } A. The output is always NO . B. The output is always ON . C. The output varies and is either NO or ON . D. The code does not compile.
A . The code compiles fi ne and runs fi ne, so D is incorrect. On line 8, the run method of the new Worker thread is invoked. However, the run method does not start a new thread in the process. (Only a call to start starts a new thread.) In other words, this program is not multithreaded and the call to run occurs within the main thread. The output of this program is always NO and therefore the answer is A. For more information, see Chapter 5.
Which of the following statements are true? (Select two.) A. All string literals are automatically instantiated into a String object. B. The StringBuilder and StringBuffer classes define the exact same public methods. C. In a multithreaded environment, use StringBuilder instead of StringBuffer . D. A StringBuilder object is immutable. E. A StringBuffer object cannot change its length once it is instantiated
A and B. String literals are automatically instantiated into String objects, so A is true. B is also true; the two classes contain the same methods. The only difference between String- Builder and StringBuffer is that StringBuffer is thread-safe, which is why C is false. You should use StringBuffer if using mutable strings in a multithreaded application. D is false; the StringBuilder and StringBuffer classes represent mutable character sequences. E is false; a StringBuffer and StringBuilder can grow and shrink to match the number of characters in the sequence. For more information, see Chapter 4.
Given the following statements: 30. Set < Object > objects = new HashSet < Object > (); 31. String one = "hello"; 32. int two = 2; 33. Boolean three = new Boolean(true); 34. objects.add(one); 35. objects.add(two); 36. objects.add(three); 37. objects.add(three); 38. for(Object object : objects) { 39. System.out.print(object); 40. } which of the following statements are true? (Select two.) A. The code compiles successfully. B. The output is hello , 2 and true in an indeterminate order. C. The output is hello , 2 , true and true in an indeterminate order. D. Line 35 generates a compiler error. E. Line 37 throws an exception at runtime.
A and B. The code compiles and runs fi ne, so D and E are incorrect and A is true. Line 37 attempts to add the same object to the set, which does not alter the set. Therefore, C is incorrect. The for loop on line 38 outputs the objects in an indeterminate order, so the other correct answer is B. For more information, see Chapter 7.
Suppose you need to write data that consists of char values and String objects to a file that maintains the format of the original data. The data needs to be buffered to improve performance. Which two java.io classes can be chained together to best achieve this result? A. FileWriter B. FileOutputStream C. BufferedOutputStream D. BufferedWriter E. PrintWriter F. PipedOutputStream
A and D. The data to be output consists of strings and characters, so writer classes are the best choice. FileWriter is needed to write to the fi le, and BufferedWriter is needed to buffer the data, so the best choices are A and D. For more information, see Chapter 4.
Suppose a class named com.mypackage.MyProgram contains the main method of a stand - alone Java application, and MyProgram.class is in the following directory: \my\classes\com\mypackage Which of the following commands successfully executes MyProgram ? (Select two answers.) A. java - classpath \my\classes com.mypackage.MyProgram B. java - classpath \my\classes\com\mypackage MyProgram C. java - classpath=\my\classes com.mypackage.MyProgram D. java - classpath \my\classes\com mypackage.MyProgram E. java - cp \my\classes com.mypackage.MyProgram
A and E. A assigns the -classpath fl ag to the appropriate directory. E also sets the class path correctly except -cp is used. C uses an equals sign, =, with the -classpath fl ag, which is not the correct syntax. B and D set the class path to the wrong directory and also incorrectly refer to the MyProgram class without its fully qualifi ed name. Therefore, the answers are A and E. For more information, see Chapter 1.
Given the following class definition: 1. public class PrintStrings { 2. public static void print(String... values) { 3. for(String value : values) { 4. System.out.print(value); 5. } 6. } 7. } which of the following statements are valid method calls to print ? A. PrintStrings.print(); B. PrintStrings.print( " abc " ); C. PrintStrings.print('a', ' b', ' c'); D. PrintStrings.print( " a " , " b " , " c " ); E. PrintStrings.print(new java.util.Date());
A, B, and D. The print method can take in any number of String objects, including zero, so A, B, and D are valid statements. C attempts to pass in chars, which is not valid and generates a compiler error. D also generates a compiler error attempting to pass in a Date object. For more information, see Chapter 2.
Given the following class definitions: 1. public class Student implements java.io.Serializable { 2. private String name; 3. 4. public static void main(String [] args) { 5. ___________________ s = new Senior(); 6. } 7. } 8. 9. class Senior extends Student {} 10. 11. class Junior extends Student {} which of the following answers can fi ll in the blank on line 5 and have the code compile successfully? (Select three.) xxx Assessment Test A. Object B. Junior C. Student D. String E. java.io.Serializable
A, C, and E. A and C are valid because Object and Student are both parent classes of Senior. B and D are not valid because Junior and String are not compatible with Senior. E is valid because Senior is of type Serializable—a type inherited from Student. For more information, see Chapter 6
What is the result of the following code? 1. public class Beverage { 2. private void drink() { 3. System.out.println("Beverage"); 4. } 5. 6. public static void main(String [] args) { 7. Beverage b = new Coffee(); Assessment Test xxxvii 8. b.drink(); 9. } 10. } 11. 12. class Coffee extends Beverage { 13. public void drink() { 14. System.out.println("Coffee"); 15. } 16. } A. Beverage B. Coffee C. Compiler error on line 2 D. Compiler error on line 8 E. Compiler error on line 13
A. The code compiles fi ne, so C, D and E are incorrect. A private method cannot be overridden, so drink in Coffee is not overriding drink in Beverage . The method call to drink on line 8 is referring to the private method on line 2, and that is also the method that gets invoked at runtime because it is not overridden. Therefore, the output is Beverage and the correct answer is A. For more information, see Chapter 6.
Given the following TV class: 1. public class TV { 2. private String make; 3. private String model; 4. 5. public TV(String make, String model) { 6. this.make = make; 7. this.model = model; 8. } 9. 10. public boolean equals(TV other) { 11. return make.equals(other.make) & & 12. model.equals(other.model); 13. } 14. 15. public int hashCode() { 16. return make.length() * 10 + model.length(); 17. } 18. } what is the result of the following statements? TV a = new TV("Philips", "42PFL5603D"); TV b = new TV("Philips", "42PFL5603D"); if(a.equals(b)) { System.out.println("equal"); } else { System.out.println("not equal"); } A. equal B. not equal C. Line 10 causes a compiler error. D. Line 11 causes a compiler error. E. Line 15 causes a runtime exception to occur.
A. The code compiles fi ne, so C, D, and E are incorrect. Based on the defi nition of the equals method, two TV objects are equal if they have the same make and model fi elds, so the line a.equals(b) evaluates to true and equal is output, so the answer is A. For more information, see Chapter 1.
What is the result of the following code? 6. byte x = 23, y = 4; 7. int z = 23 % 4; 8. System.out.println(z); A. 3 B. 4 C. 4.75 Assessment Test xxv D. Compiler error on line 6 E. Compiler error on line 7
A. The code compiles fi ne, so D and E are incorrect. The value of z is the remainder of 23 divided by 4, which is 3. Therefore, the answer is A. For more information, see Chapter 1.
Given the following variable declaration: Set < ? extends RuntimeException > set = ___________________; which of the following statements can appear in the blank line so that the statement compiles successfully? (Select all that apply.) A. new HashSet < ? extends RuntimeException () B. new TreeSet < RuntimeException > () C. new TreeSet < NullPointerException > () D. new LinkedHashSet < Exception > () E. None of the above
B and C . The reference set declares an upper bound of RuntimeException on the generic, D is not valid because Exception is a parent class of RuntimeException . A is not valid because a new statement cannot declare a wildcard in the generic type. B is valid because TreeSet implements Set . C is valid because TreeSet implements Set and NullPointerException is a subclass of RuntimeException . Therefore, the answers are B and C. For more information, see Chapter 7.
Given the following code: 3. Pattern p = Pattern.compile(".+es"); 4. String [] words = {"unless", "guesses", 5. "boxes", "guest"}; 6. for(String word : words) { 7. if(p.matcher(word).matches()) { 8. System.out.println(word); 9. } 10. } which of the following strings is output? (Select all that apply.) A. unless B. guesses C. boxes D. guest E. None of the above
B and C. The regular expression .+es matches character streams that start with any number of characters and end in es . Two of the strings in the array match this pattern: guesses and boxes . Therefore, the answers are B and C. For more information, see Chapter 4.
Given the following Parent class definition: 1. public class Parent { 2. Object doSomething(int x) { 3. return null; 4. } 5. } Assessment Test xxxi which of the following methods could appear in a child class of Parent ? (Select three answers.) A. public void doSomething(int x) B. protected String doSomething(int x) C. private Thread doSomething(int x) D. private Thread doSomething(short x) E. public double doSomething(int y)
B and D. A is incorrect because void is an incompatible return type with Object. (If the return type is changed, it must be a subclass of the return type in the parent class.) B is a valid overriding of doSomething in Parent because it is more accessible and String is a subclass of Object. C is incorrect because it assigns a weaker access, which is not allowed. D is valid because it is not overriding doSomething in Parent—it is overloading the method instead. E is not valid because double is not a subclass of Object. Therefore, the answers are B and D. For more information, see Chapter 6.
What state can a NEW thread transition into? (Select all that apply.) A. WAITING B. RUNNABLE C. BLOCKED D. TIMED_WAITING E. TERMINATED
B. A NEW thread can only transition into the RUNNABLE state, so the answer is B. For more information, see Chapter 5.
When does the String object " hi " instantiated on line 2 become eligible for garbage collection? 1. public class Hello { 2. String greeting = "hi"; 3. 4. public static void main(String [] args) { 5. Hello h = new Hello(); 6. h.greeting = null; 7. System.gc(); 8. return; 9. } 10. } A. Immediately after line 5 B. Immediately after line 6 C. Immediately after line 7 D. Immediately after line 8 E. Immediately after line 9
B. The String on line 2 is created in memory after line 5 executes, and the greeting reference points to it. After line 6, no references point to "hi" anymore and it immediately becomes eligible for garbage collection then, so the answer is B. For more information, see Chapter 1.
Given the following enum declaration: 1. public enum Toppings { 2. PEPPERONI, SAUSAGE, ONION, OLIVES, CHEESE; 3. } what is the result of the following statements? 8. Toppings [] choices = Toppings.values(); 9. System.out.println(choices[1]); A. PEPPERONI B. SAUSAGE C. The code compiles but the output is indeterminate. D. Line 8 generates a compiler error. E. Line 9 generates a compiler error.
B. The code compiles fi ne, so D and E are incorrect. The values method of an enum returns an array containing the elements in the enum, in the order they are declared in the enum. The element at index 1 is SAUSAGE , which is printed at line 9. Therefore, the answer is B. For more information, see Chapter 2.
What is the result of the following program? 1. public class MathFunctions { 2. public static void addToInt(int x, int amountToAdd) 3. { 4. x = x + amountToAdd; 5. } 6. 7. public static void main(String [] args) { 8. int a = 15; 9. int b = 10; 10. MathFunctions.addToInt(a, b); 11. System.out.println(a); 12. } 13. } A. 25 B. 15 C. 10 D. A compiler error occurs on line 4. E. A compiler error occurs on line 10.
B. The code compiles successfully, so D and E are incorrect. The value of a cannot be changed by the addToInt method, no matter what the method does, because only a copy of a is passed into the parameter x. Therefore, a does not change and the output on line 11 is 15, so the answer is B. For more information, see Chapter 1.
What is the result of the following statements? 4. Thread t = new Thread() { 5. public void run() { 6. System.out.println( 7. Thread.currentThread().getState()); 8. } 9. }; 10. t.start(); A. NEW B. RUNNABLE C. BLOCKED D. TERMINATED E. The state of the thread is indeterminate.
B. The state of the currently running thread must be RUNNABLE, so the answer is B. For more information, see Chapter 5.
What is the result of the following statements? 28. Integer i = 5; 29. switch(i) { 30. case 1: System.out.print(1); break; 31. case 3: System.out.print(3); 32. case 5: System.out.print(5); 33. case 7: System.out.print(7); break; 34. default: System.out.print("default"); 35. } A. 5 B. 57 C. 57default D. Compiler error on line 28 E. Compiler error on line 29
B. You cannot switch on an Integer, but because of Java's autoboxing, i is converted to an int, so lines 28 and 29 are valid, which means D and E are incorrect. The value of i is 5, so the case on line 32 executes and prints 5. Because there is no break, 7 is printed. The break on line 33 causes control to break out of the switch, so the output is 57 and the answer is B. For more information, see Chapter 3
What is the result of the following code? 3. Boolean m = true; 4. int n = 14; 5. do { 6. n = n > > 1; 7. if(n < 4) { 8. m = new Boolean(false); 9. } 10. }while(m); 11. System.out.println(n); A. 0 B. 2 C. 3 D. An infinite loop E. Line 10 generates a compiler error.
C. Line 10 compiles fine, so E is incorrect. Line 6 right shifts n by 1, which is equivalent to integer division by 2. The first time through the loop, n becomes 14/2 = 7; the second time through n becomes 7/2 = 3. Because 3 < 4 is true, m is set to false and the loop terminates. The value of n is 3, which is printed on line 11, so the answer is C. For more information, see Chapter 3.
The following code appears in a file named Book.java . What is the result of compiling this source file? (Select one answer.) 1. public class Book { 2. private int pageNumber; 3. 4. private class BookReader { 5. public int getPage() { 6. return pageNumber; 7. } 8. } 9. } A. The code compiles successfully and one bytecode file is generated: Book.class . B. The code compiles successfully and two bytecode files are generated: Book.class and BookReader.class . C. The code compiles successfully and two bytecode files are generated: Book.class and Book$BookReader.class . D. A compiler error occurs on line 4. E. A compiler error occurs on line 6.
C. The code compiles fi ne, so D and E are incorrect. The bytecode fi le for the outer class Book is Book.class, and the bytecode fi le for the inner class BookReader is Book$BookReader.class, so the answer is C. For more information, see Chapter 2.
Given the following class definition: 1. public class EchoInput { 2. public static void main(String [] args) { 3. if(args.length < = 3) { 4. assert false; 5. } Assessment Test xxxv 6. System.out.println(args[0] + args[1] 7. + args[2]); 8. } 9. } what is the result of the following command line? java EchoInput hi there A. hithere B. The assert statement on line 4 throws an AssertionError . C. Line 7 throws an ArrayIndexOutOfBoundsException . D. The code compiles and runs successfully, but there is no output. E. The code does not compile.
C. The code compiles fi ne, so E is incorrect. The command line has only two arguments, so args.length is 2 and line 3 is true . However, because assertions are not enabled, line 4 does not throw an AssertionError , so B is incorrect. Line 7 attempts to print args[2] , which generates an ArrayIndexOutOfBoundsException , so the answer is C. For more information, see Chapter 3.
Given the following Football class definition: 1. package my.sports; 2. 3. public class Football { 4. public static final int teamSize = 11; 5. } and also the following FootballGame class: 1. package my.apps; 2. 3. 4. 5. public class FootballGame { 6. public int getTeamSize() { 7. return teamSize; 8. } 9. } which of the following statements can appear on line 3 so that the FootballGame class compiles successfully? A. import static my.sports.Football; B. import my.sports.Football; C. import static my.sports.Football.*; D. import static my.sports.*; E. No import statement is necessary.
C. The code does not compile without a proper import for the teamSize variable on line 7, so E is incorrect. A is not a valid statement. B is a valid statement but does not import teamSize, so B is incorrect. D causes a compiler error because sports is not a class or interface name. C is valid and imports all static members of the Football class, so C is the correct answer. For more information, see Chapter 2.
What is the result of the following code? 46. NumberFormat nf = 47. NumberFormat.getCurrencyInstance(Locale.US); 48. double value = 123.456; 49. System.out.println(nf.format(value)); A. $123.456 B. $123.45 C. $123.46 D. 123.45 E. 123.46
C. The currency format rounds decimals up to two decimal places, so 123.456 is rounded up to 123.46 and printed in the U.S. locale. The output is $123.46 , and therefore the answer is C. For more information, see Chapter 4.
What is the result of the following code? 14. DecimalFormat df = new DecimalFormat("#,000.0#"); 15. double pi = 3.141592653; 16. System.out.println(df.format(pi)); A. 3.141592653 B. 0,003.14 C. ,003.1 D. 003.14 E. 00.04
D. The DecimalFormat object calls for at least three digits before the decimal point, so two leading 0s appears before the 3. The format also calls for at least one digit past the decimal but no more than two. Therefore, the output is 003.14 and the answer is D. For more information, see Chapter 4.
What is the result of the following code? 21. final byte b = 1; 22. int value = 2; 23. switch(value) { 24. case b : System.out.print("A"); 25. break; 26. case 2 : System.out.print("B"); 27. case 3 : System.out.print("C"); 28. default : System.out.print("D"); 29. break; 30. } A. Compiler error on line 24 B. B C. BC D. BCD E. Compiler error on line 29
D. The code compiles fi ne, so A and E are incorrect. The case on line 26 is satisfi ed, so B is printed. There is no break , so line 27 executes and C is printed. Because there is no break , the default block executes and D is printed on line 28. Therefore, the output is BCD and the answer is D. For more information, see Chapter 3.
What is the result of the following program? 1. public class PrintX implements Runnable { 2. private int count; 3. 4. public PrintX(int count) { 5. this.count = count; 6. } 7. 8. public void run() { 9. for(int i = 1; i < = count; i++) { 10. System.out.print("x"); 11. } 12. } 13. 14. public static void main(String [] args) { 15. Thread t = new Thread(new PrintX(3)); 16. t.start(); 17. System.out.print("y"); 18. t.start(); 19. } 20. } A. xxxyxxx B. yxxxxxx C. Six x s and one y printed in an indeterminate order D. The code throws an exception at runtime. E. The code does not compile.
D. The code compiles fi ne, so E is incorrect. However, a Thread object cannot be started twice, so line 18 throws an IllegalThreadStateException and D is the correct answer. For more information, see Chapter 5.
Given the following class definition: 1. public class AssertDemo { 2. public static void main(String [] args) { 3. Integer x = 10; 4. assert x == null & & x > = 0; 5. System.out.println(x); 6. } 7. } and given the following command line, which one of the following statements is true? java AssertDemo A. Line 3 generates a compiler error. B. Line 4 generates a compiler error. C. Line 4 throws an AssertionError at runtime. D. The output is 10 .
D. The code compiles, so A and B are incorrect. The command line does not enable assertions, so C cannot happen. Line 5 executes and prints out 10, so the answer is D. For more information, see Chapter 3.
What is the result of the following program? 1. public abstract class Message { 2. public String recipient; 3. 4. public abstract final void sendMessage(); 5. 6. public static void main(String [] args) { 7. Message m = new TextMessage(); 8. m.recipient = "6055551212"; 9. m.sendMessage(); 10. } 11. } 12. 13. class TextMessage extends Message { 14. public final void sendMessage() { 15. System.out.println("TextMessage to " 16. + recipient); 17. } 18. } A. TextMessage to 6055551212 B. TextMessage to null C. Compiler error on line 1 D. Compiler error on line 4 E. Compiler error on line 9
D. The code does not compile, so A and B are incorrect. The problem with this code is the Message declares the sendMessage method as both abstract and final, which does not make sense. An abstract method must be overridden, and a final method cannot be overridden. Using abstract and final on the same method results in a compiler error, so the answer is D. For more information, see Chapter 6.
What is the result of the following statements? 23. List < Number > data = new Vector < Number > (); 24. data.add(10); 25. data.add("4.5F"); 26. data.add(new Double(56.7)); 27. for(Number number : data) { 28. System.out.print(number); 29. } A. 104.556.7 B. 104.5F56.7 C. 10 followed by a ClassCastException D. Compiler error on line 25 E. Compiler error on line 27
D. The code does not compile, so A, B, and C are incorrect. E is also incorrect; line 27 compiles fi ne because data contains Number objects. Line 25 does not compile because data is instantiated using generics; only Number objects can be added to data and "4.5F" is a String. Therefore, the answer is D. For more information, see Chapter 7.
Given the following Box class definition: 1. public class Box < T > { 2. T value; 3. 4. public Box(T value) { 5. this.value = value; 6. } 7. 8. public T getValue() { 9. return value; 10. } 11. } what is the result of the following statements? 15. Box < String > one = new Box < String > ("a string"); 16. Box < Integer > two = new Box < Integer > (123); 17. System.out.print(one.getValue()); 18. System.out.print(two.getValue()); xxxii Assessment Test A. Compiler error on line 1 B. Compiler error on line 2 C. Compiler error on line 16 D. a string123 E. The code compiles but throws an exception at runtime.
D. The compiles and runs fi ne, so A, B, C, and E are incorrect. The Box class uses a generic type named T. For one, the generic type is a String. For two, the generic type is an Integer. The two value fi elds are printed out on lines 17 and 18, which print a string123, so the answer is D. For more information, see Chapter 7.
Given the following interface and class definitions: 1. //Readable.java 2. public interface Readable { 3. public void read(); 4. public int MAX_LENGTH = 10; 5. } 1. //MyReader.java 2. public class MyReader implements Readable { 3. public void read() { 4. Readable.MAX_LENGTH = 25; 5. System.out.println(Readable.MAX_LENGTH); 6. } 7. } what is the result of the following statement? new MyReader().read(); A. 25 B. 10 C. Compiler error on line 3 of Readable.java xxxiv Assessment Test D. Compiler error on line 4 of Readable.java E. Compiler error on line 4 of MyReader.java
E . The Readable interface compiles fi ne, so C and D are incorrect. However, the MyReader class does not compile, so A and B are incorrect. Fields in an interface are implicitly final , so attempting to set MAX_LENGTH to 25 on line 4 of MyReader is not allowed and generates a compiler error. Therefore, the answer is E. For more information, see Chapter 2.
Fill in the blank: When an object performs a collection of closely related tasks, this is referred to as . A. The is - a relationship B. The has - a relationship C. Tight encapsulation D. Loose coupling E. High cohesion
E . The defi nition of high cohesion is when an object performs a collection of closely related tasks, so the answer is E. For more information, see Chapter 6.
What is the result of the following program? 1. public class Vehicle { 2. public boolean used; 3. public String make; 4. 5. public static void main(String [] args) { 6. Vehicle v = new Vehicle(); 7. if(v.used) { 8. System.out.println(v.make); 9. } else { 10. System.out.println(v.make.length()); 11. } 12. } 13. } A. null B. 0 C. Line 7 generates a compiler error. D. Line 8 generates an exception at runtime. E. Line 10 generates an exception at runtime.
E. The code compiles fi ne, so C is incorrect. The used fi eld initializes to false and the make fi eld initializes to null for the new Vehicle v. Therefore, line 7 is false and line 10 executes. Because v.make is a null reference, attempting to invoke its length method results in a NullPointerException at runtime. Therefore, the answer is E. For more information, see Chapter 2.