Saturday, February 19, 2011

Self Test: Chapters 32 to 37

Questions:

Question 1:
Given:
import java.util.regex.*;
class TestRegex {
public static void main(String[] args) {
Pattern p = Pattern.compile(args[0]);
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 TestRegex "\d*" ab34ef
What is the result?
A. 234
B. 334
C. 2334
D. 0123456
E. 01234456
F. 12334567
G. Compilation fails

Question 2:
Given:
import java.io.*;
class Player {
Player() { System.out.print("p"); }
}
class MusicPlayer extends Player implements Serializable {
MusicPlayer() { System.out.print("c"); }
public static void main(String[] args) {
MusicPlayer c1 = new MusicPlayer();
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);
MusicPlayer c2 = (MusicPlayer) is.readObject();
is.close();
} catch (Exception x ) { }
}
}
What is the result?
A. pc
B. pcc
C. pcp
D. pcpc
E. Compilation fails
F. An exception is thrown at runtime

Question 3:
Given:

class Test {

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(s1 < 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.) A. .e1 B. .e2 C. =s D. fly E. None of the above F. Compilation fails G. An exception is thrown at runtime Question 4:
Given:
import java.io.*;

class Engine { }
public class Ferrari implements Serializable {
private Engine k = new Engine();
public static void main(String[] args) {
Ferrari c = new Ferrari();
c.serializeIt(c);
}
void serializeIt(Ferrari c) {
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream("myTestFile"));
os.writeObject(c);
os.close();
System.out.println("done");
} catch (Exception x) {System.out.println("exc"); }
}
}
What is the result? (Choose all that apply.)
A. exc
B. done
C. Compilation fails
D. Exactly one object is serialized
E. Exactly two objects are serialized

Question 5:
Given:
import java.io.*;

public class SerializeTest {
public static void main(String[] args) {
SplSerialTest s = new SplSerialTest();
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream("myTestFile"));
os.writeObject(s); os.close();
System.out.print(++s.z + " ");

ObjectInputStream is = new ObjectInputStream(
new FileInputStream("myTestFile"));
SplSerialTest s2 = (SplSerialTest)is.readObject();
is.close();
System.out.println(s2.y + " " + s2.z);
} catch (Exception x) {System.out.println("exc"); }
}
}
class SplSerialTest implements Serializable {
transient int y = 7;
static int z = 9;
}
Which are true? (Choose all that apply.)
A. Compilation fails
B. The output is 10 0 9
C. The output is 10 0 10
D. The output is 10 7 9
E. The output is 10 7 10
F. In order to alter the standard deserialization process you would implement the readObject() method in SplSerialTest
G. In order to alter the standard deserialization process you would implement the defaultReadObject() method in SplSerialTest

Question 6:
Given:
3. public class TestStrings {
4. public static void main(String[] args) {
5. String s1 = "abc";
6. String s2 = s1;
7. s1 += "d";
8. System.out.println(s1 + " " + s2 + " " + (s1==s2));
9.
10. StringBuffer sb1 = new StringBuffer("abc");
11. StringBuffer sb2 = sb1;
12. sb1.append("d");
13. System.out.println(sb1 + " " + sb2 + " " + (sb1==sb2));
14. }
15. }

Which are true? (Choose all that apply.)
A. Compilation fails
B. The first line of output is abc abc true
C. The first line of output is abc abc false
D. The first line of output is abcd abc false
E. The second line of output is abcd abc false
F. The second line of output is abcd abcd true
G. The second line of output is abcd abcd false

Question 7:
Given:
3. import java.io.*;
4. public class TestReader {
5. public static void main(String[] args) {
6. String s;
7. try {
8. FileReader fr = new FileReader("myTestFile.txt");
9. BufferedReader br = new BufferedReader(fr);
10. while((s = br.readLine()) != null)
11. System.out.println(s);
12. br.flush();
13. } catch (IOException e) { System.out.println("io error"); }
16. }
17. }
And given that myTestFile.txt contains the following two lines of data:
ab
cd
What is the result?
A. ab
B. abcd
C. ab
D. cd
E. a
F. b
G. c
H. d
I. Compilation fails

Question 8:
Given:
3. import java.io.*;
4. public class TestConsole {
5. public static void main(String[] args) {
6. Console c = System.console();
7. String u = c.readLine("%s", "username: ");
8. System.out.println("hello " + u);
9. String pw;
10. if(c != null && (pw = c.readPassword("%s", "password: ")) != null)
11. // check for valid password
12. }
13. }
If line 6 creates a valid Console object, and if the user enters rocky as a username and 1234 as a password, what is the result? (Choose all that apply.)
A. username:
B. password:
C. username: rocky
D. password:
E. username: rocky
F. password: 1234
G. Compilation fails
H. An exception is thrown at runtime

Question 9:
Given:
3. import java.io.*;
4. class Automobile { }
5. class Engine { }
6. class Car extends Automobile implements Serializable { }
7. class Ferrari extends Car { }
8. class Lamborghini extends Car {
9. Engine w = new Engine();
10. }

Instances of which class(es) can be serialized? (Choose all that apply.)
A. Car
B. Ferrari
C. Lamborghini
D. Engine
E. Automobile

Question 10:
Given:
3. import java.text.*;
4. public class TestNumbers {
5. public static void main(String[] args) {
6. String s = "987.123456";
7. double d = 987.123456d;
8. NumberFormat nf = NumberFormat.getInstance();
9. nf.setMaximumFractionDigits(5);
10. System.out.println(nf.format(d) + " ");
11. try {
12. System.out.println(nf.parse(s));
13. } catch (Exception e) { System.out.println("got exc"); }
14. }
15. }

Which are true? (Choose all that apply.)
A. The output is 987.12345 987.12345
B. The output is 987.12346 987.12345
C. The output is 987.12345 987.123456
D. The output is 987.12346 987.123456
E. The try/catch block is unnecessary
F. The code compiles and runs without exception
G. The invocation of parse() must be placed within a try/catch block

Question 11:
Given:
3. import java.util.*;
4. public class TestScanner {
5. public static void main(String[] args) {
6. String input = "1 2 a 3 45 6";
7. Scanner sc = new Scanner(input);
8. int x = 0;
9. do {
10. x = sc.nextInt();
11. System.out.print(x + " ");
12. } while (x!=0);
13. }
14. }

What is the result?
A. 1 2
B. 1 2 3 45 6
C. 1 2 3 4 5 6
D. 1 2 a 3 45 6
E. Compilation fails
F. 1 2 followed by an exception

Question 12:
Given:
3. import java.util.regex.*;
4. public class TestPatterns {
5. public static void main(String[] args) {
6. Pattern p = Pattern.compile(args[0]);
7. Matcher m = p.matcher(args[1]);
8. int count = 0;
9. while(m.find())
10. count++;
11. System.out.print(count);
12. }
13. }

And given the command line invocation:
java TestPatterns "\d+" ab2c4d67

What is the result?
A. 0
B. 3
C. 4
D. 8
E. 9
F. Compilation fails

Answers:

Answer 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.

Answer 2:

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

Answer 3:

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.

Remember that A is using the equals() method to try to compare two different types.

Answer 4:

A is correct. An instance of type Ferrari Has-a Engine. Because Engine doesn’t implement Serializable, any attempt to serialize an instance of Ferrari will cause an exception to be thrown.
If Engine did implement Serializable then two objects would have been serialized.

Answer 5:

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.

G is incorrect because you don’t implement the defaultReadObject() method, you call it from within the readObject() method, along with any custom read operations your class needs.

Answer 6:

D and F are correct. While String objects are immutable, references to Strings are mutable. The code s1 += "d"; creates a new String object. StringBuffer objects are mutable, so the append() is changing the single StringBuffer object to which both StringBuffer references refer

Answer 7:

I is correct. Readers don’t have flush() methods. So, compilation would fail

Answer 8:

G is correct. The code compilation fails because the readPassword method returns a character array while the pw variable is a String

Answer 9:

A and B are correct. Lamborghini instances cannot be serialized because they “have” an instance of Engine, which is not serializable. Automobile instances cannot be serialized even though the subclass Car can be.

Answer 10:

D, F, and G are correct. The setMaximumFractionDigits() applies to the formatting but not the parsing. The try/catch block is placed appropriately. This one might scare you into thinking that you’ll need to memorize more than you really do. If you can remember that you’re formatting the number and parsing the string you should be fine for the exam.

Answer 11:

F is correct. The nextXxx() methods are typically invoked after a call to a hasNextXxx(), which determines whether the next token is of the correct type.

Answer 12:

B is correct. The “\d” metacharacter looks for digits, and the + quantifier says look for “one or more” occurrences. The find() method will find three sets of one or more consecutive digits: 2, 4, and 67.

Previous Chapter: Quick Review - Chapters 32 to 37

Next Chapter: Chapter 38 - Overriding toString(), hashCode() and equals() Methods

2 comments:

  1. Hi Anand

    I have a doubt with the answers to the questions 7 and 8, both says the answer should be E and D respectively, but i think both codes get a compilation error (Answers I and G respectively), as you said in the answer of the question 7("Readers don’t have flush() methods"), and the code of the question 8, at the line 10, the method readPassword() returns a char array and it's assigned to the String variable "pw". Can you help me these questions.

    Thanks in advance, and by the way, keep up the good work, your blog is really interesting and helpfull.

    ReplyDelete
    Replies
    1. Hi Ricardo,
      Thanks for spotting and pointing out. It was a typo error. In both cases there will be a compilation error as you have pointed out. The answers have been corrected.

      Thanks again...

      Anand

      Delete

© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers