Self Test


1. 

Given:

 import java.util.regex.*; class Regex2 {   public static void main(String[] args) {     Pattern p = Pattern.compile(args[o]);     Matcher m = p.matcher(args[1]);     boolean b = false;     while(b = m.find()) {       System.out.print(m.start() + m.group());     }   } } 

And the command line:

 java Regex2 "\d*" ab34ef 

What is the result?

  1. 234

  2. 334

  3. 2334

  4. 0123456

  5. 01234456

  6. 12334567

  7. Compilation fails.

image from book

2. 

Given:

 import java.io.*; class Player {   Player() { System.out.print("p"); } } class CardPlayer extends Player implements Serializable {   CardPlayer() { System.out.print("c"); }   public static void main(String[] args){     CardPlayer cl = new CardPlayer();     try {       FileOutputStream fos = new FileOutputStream("play.txt");       ObjectOutputStream os = new ObjectOutputStream(fos);       os.writeObject(c1);       os.close() ;       FileInputStream fis = new FileInputStream("play.txt");       ObjectInputStream is = new ObjectInputStream(fis);       CardPlayer c2 = (CardPlayer) is.readObject();       is.close();     } catch (Exception x ) { }   } } 

What is the result?

  1. pc

  2. pcc

  3. pcp

  4. pcpc

  5. Compilation fails.

  6. An exception is thrown at runtime.

image from book

3. 

Given that bw is a reference to a valid BufferedWriter

And the snippet:

 15.  BufferedWriter b1 = new BufferedWriter(new File("f")); 16.  BufferedWriter b2 = new BufferedWriter(new FileWriter("f1")); 17.  BufferedWriter b3 = new BufferedWriter(new PrintWriter("f2")); 18.  BufferedWriter b4 = new BufferedWriter(new BufferedWriter(bw)); 

What is the result?

  1. Compilation succeeds.

  2. Compilation fails due only to an error on line 15.

  3. Compilation fails due only to an error on line 16.

  4. Compilation fails due only to an error on line 17.

  5. Compilation fails due only to an error on line 18.

  6. Compilation fails due to errors on multiple lines.

image from book

4. 

Given:

 Class TKO {   public static void main(String[] args) {     String s = "-";     Integer x = 343;     long L343 = 343L;     if(x.equals(L343)) s += ".e1 ";     if(x.equals(343)) s += ".e2 ";     Short s1 = (short)((new Short((short)343)) / (new Short((short)49)));     if (s1 == 7)       s += "=s ";     if(sl < new Integer(7+1)) s += "fly ";     System.out.println(s);   } } 

Which of the following will be included in the output String s? (Choose all that apply.)

  1. .e1

  2. .e2

  3. =s

  4. fly

  5. None of the above.

  6. Compilation fails.

  7. An exception is thrown at runtime.

image from book

5. 

Given:

 1. import java.text.*; 2. class DateOne { 3.   public static void main(String[] args) { 4.     Date d = new Date(1123631685981L); 5.     DateFormat df = new DateFormat(); 6.     System.out.println(df.format(d)); 7.   } 8. } 

And given that 1123631685981L is the number of milliseconds between Jan. 1, 1970, and sometime on Aug. 9, 2005, what is the result? (Note: the time of day in option A may vary.)

  1. 8/9/05 5:54 PM

  2. 1123631685981L,

  3. An exception is thrown at runtime.

  4. Compilation fails due to a single error in the code.

  5. Compilation fails due to multiple errors in the code.

image from book

6. 

Given:

 import java.io.*; class Keyboard { } public class Computer implements Serializable {   private Keyboard k = new Keyboard();   public static void main(String[] args)     Computer c = new Computer();     c.storeIt(c) ;   }   void storeIt(Computer c) {     try {       ObjectOutputStream os = new ObjectOutputStream(          new FileOutputStream("myFile"));       os.writeObject(c);       os.close() ;       System.out.println("done");     } catch (Exception x) {System.out.println("exc"); } }   } } 

What is the result? (Choose all that apply.)

  1. exc

  2. done

  3. Compilation fails.

  4. Exactly one object is serialized.

  5. Exactly two objects are serialized.

image from book

7. 

Using the fewest fragments possible (and filling the fewest slots possible), complete the code below so that the class builds a directory named "dir3" and creates a file named "file3" inside "dir3". Note you can use each fragment either zero or one times.

Code:

 import java.io.________________ class Maker {   public static void main(String [] args) {     ___________  ___________  ___________     ___________  ___________  ___________     ___________  ___________  ___________     ___________  ___________  ___________     ___________  ___________  ___________     ___________  ___________  ___________     ___________  ___________  ___________   } } 

Fragments:

 File;     FileDescriptor;     FileWriter;    Directory; try {     .createNewDir();    File dir       File { }       (Exception x)       ("dir3");      file file      .createNewFile();   = new File     = new File dir       (dir, "file3");     (dir, file);   .createFile() ; } catch   ("dir3", "file3");  .mkdir();      File file 

image from book

8. 

Which are true? (Choose all that apply.)

  1. The DateFormat.getDate() is used to convert a String to a Date instance.

  2. Both DateFormat and NumberFormat objects can be constructed to be Locale specific.

  3. Both Currency and NumberFormat objects must be constructed using static methods.

  4. If a NumberFormat instance's Locale is to be different than the current Locale, it must be specified at creation time.

  5. A single instance of NumberFormat can be used to create Number objects from Strings and to create formatted numbers from numbers.

image from book

9. 

Which will compile and run without exception? (Choose all that apply.)

  1. System.out.format("%b", 123);

  2. System.out.format("%c", "x");

  3. System.out.printf("%d", 123);

  4. System.out.printf("%f", 123);

  5. System.out.printf("%d", 123.45);

  6. System out. printf ("%f", 123.45);

  7. System.out.format("%s", new Long("123"));

image from book

10. 

Which about the three java.lang classes String, StringBuilder, and StringBuffer are true? (Choose all that apply.)

  1. All three classes have a length() method.

  2. Objects of type StringBuffer are thread-safe.

  3. All three classes have overloaded append() methods.

  4. The "+" is an overloaded operator for all three classes.

  5. According to the API, StringBuffer will be faster than StringBuilder under most implementations.

  6. The value of an instance of any of these three types can be modified through various methods in the API.

image from book

11. 

Given that 1119280000000L is roughly the number of milliseconds from Jan. 1, 1970, to June 20, 2005, and that you want to print that date in German, using the LONG style such that "June" will be displayed as "juni", complete the code using the fragments below. Note: you can use each fragment either zero or one times, and you might not need to fill all of the slots.

Code:

 import Java.___________ import Java.___________ class DateTwo {   public static void main(String[] args) {     Date d = new Date(1119280000000L);     DateFormat df =__________________________                    _____________ , ______________ ) ;     System.out.println(_____________   } } 

Fragments:

 io.*;     new DateFormat(                Locale.LONG nio.*;    DateFormat.getlnstance(        Locale.GERMANY util.*;   DateFormat.getDatelnstance(    DateFormat.LONG text.*;   util.regex;                    DateFormat.GERMANY date.*;   df.format(d));                 d.format(df)); 

image from book

12. 

Given:

 import java.io.*; class Directories {   static String [] dirs = {"dirl", "dir2"};   public static void main(String [] args){     for (String d : dirs) {       // insert code 1 here       File file = new File(path, args[0]) ;       // insert code 2 here     }   } } 

and that the invocation

 java Directories file2.txt 

is issued from a directory that has two subdirectories "dir1" and "dir1", and that "dir1" has a file "file1.txt" and "dir2" has a file "file2.txt", and the output is "false true"; which set(s) of code fragments must be inserted? (Choose all that apply.)

  1. String path = d;

    System.out.print (file.exists() + " ");

  2. String path = d;

    System.out .print (file . isFile() + " ");

  3. String path = File.separator + d;

    System.out .print (file . exists() + " ");

  4. String path = File.separator + d;

    System.out.print(file.isFile() +

image from book

13. 

Given:

 class Polish {   public static void main(String[] args) {     int x = 4 ;     StringBuffer sb = new StringBuffer("..fedcba");     sb.delete(3,6);     sb.insert(3, "az");     if(sb.length() > 6) x = sb.indexOf("b");     sb.delete((x-3), (x-2));     System.out.println(sb); } } 

What is the result?

  1. .faza

  2. .fzba

  3. ..azba

  4. .fazba

  5. ..fezba

  6. Compilation fails.

  7. An exception is thrown at runtime.

image from book

14. 

Given:

 1. import java.util.*; 2. class Brain { 3.   public static void main(String[] args) { 4.     // insert code block here 5.   } 6. } 

Which, inserted independently at line 4, compile and produce the output "123 82"? (Choose all that apply.)

  1. Scanner sc = new Scanner("123 A 3b c,45, x5x,76 82 L");

    while(sc.hasNextInt()) System.out.print(sc.nextlnt() + " ");

  2. Scanner sc = new Scanner("123 A 3b c,45, x5x,76 82 L").

    useDelimiter(" ");

    while(sc.hasNextlnt()) System.out.print(sc.nextlnt() + " ");

  3. Scanner sc = new Scanner("123 A 3b c,45, x5x,76 82 L");

    useDelimiter(" ");

    while(sc.hasNext()) {

    if (sc.hasNextlnt()) System.out.print(sc.nextlnt() + " ") ;

    else sc.next(); }

  4. Scanner sc = new Scanner("123 A 3b c,45, x5x,76 82 L").

    useDelimiter(" ");

    while(sc.hasNext()) }

    if (sc.hasNextlnt()) System.out.print(sc.nextlnt() + " ") ;

    else sc.next(); }

  5. Scanner sc = new Scanner ("123 A 3b c,45, x5x, 76 82 L");

    do {

    if (sc.hasNextInt()) System.out.print (sc.nextInt() + "");

    } while (sc.hasNext());

  6. Scanner sc = new Scanner("12,3 A 3b c,45, x5x, 76 82 L").

    useDelimiter(" ");

    do {

    if(sc.hasNextlnt()) System.out.print(sc.nextInt() + " ");

    } while ( sc.hasNext() );

image from book

15. 

Given:

 import java.io.*; public class TestSer {   public static void main(String[] args) {     SpecialSerial s = new SpecialSerial() ;     try {       ObjectOutputStream os = new ObjectOutputStream(          new FileOutputStream("myFile"));       os.writeObject(s);  os. close();       System.out.print( + + s.z + " ");       ObjectlnputStream is = new ObjectlnputStream(          new FileInputStream("myFile"));       SpecialSerial s2 = (SpecialSerial)is.readObject();       is.close();       System.out.println(s2.y + " " + s2.z);     } catch (Exception x) {System.out.println("exc"); }   } } class SpecialSerial implements Serializable {   transient int y = 7;   static int z = 9; } 

Which are true? (Choose all that apply.)

  1. Compilation fails.

  2. The output is 10 0 9

  3. The output is 10 0 10

  4. The Output is 10 7 9

  5. The output is 10 7 10

  6. In order to alter the standard deserialization process you would override the readobject() method in SpecialSerial.

  7. In order to alter the standard deserialization process you would override the defaultReadObject() method in SpecialSerial.

image from book

Answers

1. 

þ  

E is correct. The \d is looking for digits. The * is a quantifier that looks for 0 to many occurrences of the pattern that precedes it. Because we specified *, the group() method returns empty Strings until consecutive digits are found, so the only time group() returns a value is when it returns 34 when the matcher finds digits starting in position 2. The start() method returns the starting position of the previous match because, again, we said find 0 to many occurrences.

ý  

A, B, C, D, E, F, and G are incorrect based on the above. (Objective 3 5)

2. 

þ  

C is correct. It's okay for a class to implement Serializable even if its superelass doesn't. However, when you deserialize such an object, the non-serializable superelass must run its constructor. Remember, constructors don't run on deserialized classes that implement Serializable.

ý  

A, B, D, E, and F are incorrect based on the above. (Objective .3.3)

3. 

þ  

B is correct. Buffered Writers can be constructed only by wrapping a-Writer. Lines 16, 17, and 18 are correct because BufferedWriter, FileWriter, and PrintWriter all extend Writer. (Note: Buff eredWriter is a decorator class. Decorator classes are used extensively in the java.io package to allow you to extend the functionality of other classes.)

ý  

A, C, D, E, and F are incorrect based on the above. (Objective 3.2)

4. 

þ  

B, C, and D are correct. Remember, that the equals() method for the integer wrappers will only return true if the two primitive types and the two values are equal, With C, it's okay to unbox and use ==, For D, it's okay to create a wrapper object with an expression, and unbox it for comparison with a primitive.

ý  

A, E, F, and G are incorrect based on the above. (Remember that A is using the equals() method to try to compare two different types.) (Objective 3,1)

5. 

þ  

E is correct. The Date class is located in the java.util package so it needs an import, and DateFormat objects must be created using a static method such as DateFormat.getInstance() or DateFormat.getDateInstance().

ý  

A, B, C, and D are incorrect based on the above. (Objective 3.4)

6. 

þ  

A is correct. An instance of type Computer Has-a Keyboard, Because Keyboard doesn't implement Serializable, any attempt to serialize an instance of Computer will cause an exception to be thrown.

ý  

B, C, D, and E are incorrect based on the above. If Keyboard did implement Serializable then two objects would have been serialized. (Objective 3.3)

7. 

 import java.io.File; class Maker   public static void main(String[] args) {     try {       File dir = new File("dir3");       dir,mkdir();       File file = new File(dir, "file3");       file.createNewFile();     } catch (Exception x) {} } } 

Notes: The new File statements don't make actual files or directories, just objects. You need the mkdir() and createNewFile() methods to actually create the directory and the file. (Objective 3.2)

8. 

þ  

B, C, D, and E are correct.

ý  

A is incorrect, DateFormat.parse() is used to convert a String to a Date, (Objective 3,4)

9. 

þ  

A, C, F, and G are correct. The %b (boolean) conversion character returns true for any non-null or non-boolean argument.

ý  

B is incorrect, the %c (character) conversion character expects a character, not a String, ,D is incorrect, the %f (floating-point) conversion character won't automatically promote an integer type. E is incorrect, the %d (integral) conversion character won't take a floating point number. (Note; The format() and printf() methods behave identically.) (Objective 3.5)

10. 

þ  

A and B are correct.

ý  

C is incorrect because String does not have an "append" method. D is incorrect because only String objects can be operated on using the overloaded "+" operator. E is backwards; StringBuilder is typically faster because it's not thread-safe. F is incorrect because String objects are immutable. A String reference can be altered to refer to a different String object, but the objects themselves are immutable. (Objective 3,1)

11. 

 import java.util.*; import java.text.*; class DateTwo {   public static void main(String[] args) {     Date d = new Date(1119280000000L);   DateFormat df = DateFormat.getDateInstance(                     DateFormat.LONG, Locale.GERMANY);     System.out,println(df.format(d));   } } 

Notes: Remember that you must build DateFormat objects using static methods. Also remember that you must specify a Locale for a DateFormat object at the time of instantiation. The getInstance() method does not take a Locale. (Objective 3.4)

12. 

þ  

A and B are correct. Because you are invoking the program from the directory whose direct subdirectories are to be searched, you don't start your path with a File.separator character. The exists()method tests for either files or directories; the isfile() method tests only for files. Since we're looking for a file, both methods work.

ý  

C and D are incorrect based On the above. (Objective 3,2)

13. 

þ  

C is correct, Remember that StringBuffer methods use zero-based indexes, and that ending indexes are typically exclusive.

ý  

A, B, D, E, F, and G are incorrect based on the above, (Objective 3,1)

14. 

þ  

C and D are correct. Whitespace is the default delimiter, and the while loop advances through the String using nextInt() or next().

ý  

A and B are incorrect because the while loop won't progress past the first non-int. E and F are incorrect. The do loop will loop endlessly once the first non-int is found because hasNext() does not advance through data. (Objective 3.5)

15. 

þ  

C and F are correct. C is correct because static and transient variables are not serialized when an object is serialized. F is a valid statement.

ý  

A, B, D, and E are incorrect based on the above. G is incorrect because you don't Override the de£aultReadobject() method, you call it from within the overridden readobject() method, along with any custom read operations your class needs. (Objective 3.3)




SCJP Sun Certified Programmer for Java 5 Study Guide Exam 310-055
SCJP Sun Certified Programmer for Java 5 Study Guide (Exam 310-055) (Certification Press)
ISBN: 0072253606
EAN: 2147483647
Year: 2006
Pages: 131

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net