Showing posts with label self assement. Show all posts
Showing posts with label self assement. Show all posts

Friday, April 29, 2011

Self Test: Chapters 47 to 50

Questions:

Question 1:

Which two statements apply to the following code snippet? (Choose two.)
< servlet >
< servlet-name >
testServlet
< /servlet-name >
< servlet-class >
myPackage.MyTestServlet
< /servlet-class >
< /servlet >

A. It is a mapping between a servlet name and the fully-qualified name of the servlet class.
B. It is a map between a URL and a servlet.
C. This code belongs in the WebApp deployment descriptor.
D. It tells the container where to install the servlet.

Question 2:

Which two of the following statements most closely relate to HTTPS Client Authentication?
A. It uses a Status-Code element (three-digit integer).
B. It uses predefined form fields.
C. It is the most secure form of authentication.
D. It uses SSL.

Question 3:

Which directory is the location for myApp.jar?
A. /WEB-INF/
B. /WEB-INF/classes/
C. /WEB-INF/lib/D. /

Question 4:

In which two elements can you define initialization parameters?
A. servlet
B. context-param
C. welcome-file
D. login-config

Question 5:

Which three of the following are elements of the Web Application Descriptor?
A. servlet
B. context-param
C. listener
D. error

Question 6:

What is the configuration that the deployment descriptor uses to handle each exception?
A. error-page
B. exception
C. error
D. exception-page

Question 7:

What is the deployment descriptor file named?
A. server.conf
B. server.xml
C. web.xml
D. web.conf

Question 8:

Which directory is the location for Web application class files?
A. /WEB-INF/
B. /WEB-INF/classes/
C. /WEB-INF/classpath/
D. /META-INF/classes

Question 9:

What does the security-role element do?
A. It configures the authentication method that should be used by the form login mechanism.
B. It defines the status codes for security breaches.
C. It contains a mapping between an error code or exception type to the path of a resource in the Web application.
D. It describes and names the security role.

Question 10:

Which directory is the location for the deployment descriptor?
A. /WEB-INF/
B. /WEB-INF/classes/
C. /WEB-INF/lib/D. /

Question 11:

Which of the following best defines authentication?
A. The means used to prove that information has not been modified by a third party while in transit.
B. This is access control where interactions with resources are limited to collections of users or programs for the purpose of enforcing integrity, confidentiality, or availability constraints.
C. You have permission to use a given page.
D. The means by which communicating entities prove to one another that they are acting on behalf of specific identities.

Question 12:

What is the best definition for auditing?
A. This is access control where it defines who can interact with what resources.
B. Maintaining a record of Web application activity.
C. This is a check of the Web application when it is used for commercial transactions.
D. This prevents Web site attacks.

Answers:

Question 1:

A and C. The servlet element establishes a mapping between a servlet name and the fully-qualified name of the servlet class. You would place this code in the WebApp deployment descriptor.

Question 2:
C and D. This is end user authentication using HTTPS (HTTP over SSL). This mechanism uses public key encryption that requires the user to possess a Public Key Certificate (PKC). This is the highest level security of the four here.

Question 3:

C. The jar files go in the /WEB-INF/lib/ directory.

Question 4:

A and B. The initialization parameters are defined in both the context-param and the servlet elements of the Web deployment descriptor.

Question 5:

A, B, and C. All of these are elements except there is no error element. It should have been error-page.

Question 6:

A. The error-page element, which defines what resource the container should use for a given exception.
< web-app >
< error-page >
< error-code >404< / error-code >
< location > /404.html < /location >
< /error-page >
< /web-app >


Question 7:

C. web.xml is the deployment descriptor file.

Question 8:

B. You place your servlets and utility classes in /WEB-INF/classes/.

Question 9:

D. The security-role element contains the definition of a security role. The definition consists of an optional description of the security role, and the security role name.

Question 10:

A. web.xml is the deployment descriptor file in /WEB-INF/web.xml.

Question 11:

D. Authentication is the means by which communicating entities prove to one another that they are acting on behalf of specific identities. In other words, it is the attempt to prove that you are really you.

Question 12:

B. Maintain a record of Web application activity. For example, you can log resource accesses including times and requester IP and ID. This usually involves a log somewhere.

Previous Chapter: Quick Recap - Chapters 47 to 50

Next Chapter: Chapter 51 - Introduction to Design Patterns

Wednesday, March 23, 2011

Self Test: Chapters 6 to 19

Questions:

Question 1: Which of the following methods are defined in the Servlet interface?
A. init()
B. service()
C. finalize()
D. destroy()

Question 2: Which of the following objects are passed to a servlet's service() method?
A. ServletRequest
B. HttpServletRequest
C. ServletResponse
D. HttpServletResponse

Question 3: By default, how many instances of a servlet are created by a Servlet Container?
A. One
B. One per request
C. One per session
D. None of the above

Question 4: Which of the following exceptions are defined by the Servlet API?
A. ServletException
B. InitializationException
C. UnavailableException
D. ServletContextException

Question 5: Which of the following are used by Servlet Containers to maintain session information?
A. cookies
B. hidden form fields
C. HTTPS protocol information
D. URL rewriting

Question 6: Which of the following event listeners are defined by the Servlet API?
A. HttpSessionBindingListener
B. HttpSessionEventListener
C. HttpSessionParameterListener
D. HttpSessionAttributeListener

Question 7: Which of the following methods are defined by the RequestDispatcher interface?
A. dispatch()
B. include()
C. redirect()
D. forward()

Question 8: Which of the following is the name of the cookie used by Servlet Containers to maintain session information?
A. SESSIONID
B. SERVLETID
C. JSESSIONID
D. CONTAINERID


Answers:

Answer 1: C. The finalize() method is not defined by the Servlet interface.

Answer 2: A, C. ServletRequest and ServletResponse methods are passed to the service() method.

Answer 3: A. By default, only one instance of a servlet is created by a Servlet Container.
Answer 4: A, C. The Servlet API defines ServletException and UnavailableException.

Answer 5: A, C, D. Hidden form fields are not used by Servlet Containers to maintain session information..”
Answer 6: A. Only HttpSessionBindingListener is defined by the Servlet API.

Answer 7: B, D. The RequestDispatcher interface defines the include() and forward() methods.
Answer 8: C. The JSESSIONID cookie is used by Servlet Containers to maintain session information.

Previous Chapter: Quick Recap - Chapters 6 to 19

Next Chapter: Chapter 20 - Introduction to Session Management

Saturday, February 26, 2011

Self Test: Chapters 55 to 61

This is going to be the last self test chapter in our SCJP Exam series. The following questions will help you judge your expertise about threads that you learnt just now.

Questions:

Question 1

The following block of code creates a Thread using a Runnable target:
Runnable r = new MyRunnable();
Thread SimpleThreadExample = new Thread(r);

Which of the following classes can be used to create the target, so that the preceding code compiles correctly?
A. public class MyRunnable extends Runnable{public void run(){}}
B. public class MyRunnable extends Object{public void run(){}}
C. public class MyRunnable implements Runnable{public void run(){}}
D. public class MyRunnable implements Runnable{void run(){}}
E. public class MyRunnable implements Runnable{public void start(){}}

Question 2

Given:

3. class SimpleThreadExample extends Thread {

4. public static void main(String [] args) {

5. SimpleThreadExample t = new SimpleThreadExample();

6. Thread x = new Thread(t);

7. x.start();

8. }

9. public void run() {

10. for(int i=0;i<3;++i) {

11. System.out.print(i + "..");

12. }

13. }

14. }



What is the result of this code?

A. Compilation fails

B. 1..2..3..

C. 0..1..2..3..

D. 0..1..2..

E. An exception occurs at runtime





Question 3



Given:

3. class Test {

4. public static void main(String [] args) {

5. printStuff(args);

6. }

7. public static void printStuff(String[] lines) {

8. for(int i=0;i < lines.length;i++){

9. System.out.println(lines[i]);

10. Thread.currentThread().sleep(1000);

11. }

12. }

13. }



The static method Thread.currentThread() returns a reference to the currently executing Thread object. What is the result of this code?

A. Each String in the array lines will output, with a 1-second pause between lines

B. Each String in the array lines will output, with no pause in between because this method is not executed in a Thread

C. Each String in the array lines will output, and there is no guarantee there will be a pause because currentThread() may not retrieve this thread

D. This code will not compile

E. Each String in the lines array will print, with at least a one-second pause between lines



Question 4

Assume you have a class that holds two private variables: x and y. Which of the following pairs can prevent concurrent access problems in that class? (Choose all that apply.)
A. public int read(){return x+y;}
B. public void set(int x, int y){this.x=x;this.y=y;}
C. public synchronized int read(){return x+y;}
D. public synchronized void set(int x, int y){this.x=x;this.y=y;}
E. public int read(){synchronized(x){return x+y;}}
F. public void set(int x, int y){synchronized(x){this.x=x;this.y=y;}}
G. public int read(){synchronized(x){return x+y;}}
H. public void set(int x, int y){synchronized(y){this.x=x;this.y=y;}}
I. public synchronized(this) int read(){return x+y;}
J. public synchronized(this) void set(int x, int y){this.x=x;this.y=y;}
K. public int read(){synchronized(this){return x+y;}}
L. public void set(int x, int y){synchronized(this){this.x=x;this.y=y;}}

Question 5

Given:
1. public class TestWaitMethod {
2. public static void main(String [] args) {
3. System.out.print("1 ");
4. synchronized(args){
5. System.out.print("2 ");
6. try {
7. args.wait();
8. }
9. catch(InterruptedException e){}
10. }
11. System.out.print("3 ");
12. }
13. }

What is the result of trying to compile and run this program?
A. It fails to compile because the IllegalMonitorStateException of wait() is not dealt with in line 7
B. 1 2 3
C. 1 3
D. 1 2
E. At runtime, it throws an IllegalMonitorStateException when trying to wait
F. It will fail to compile because it has to be synchronized on the this object

Question 6

Assume the following method is properly synchronized and called from a thread A on an object B:
wait(2000);

After calling this method, when will the thread A become a candidate to get another turn at the CPU?
A. After object B is notified, or after two seconds
B. After the lock on B is released, or after two seconds
C. Two seconds after object B is notified
D. Two seconds after lock B is released

Question 7

Which are true? (Choose all that apply.)
A. The notifyAll() method must be called from a synchronized context
B. To call wait(), an object must own the lock on the thread
C. The notify() method is defined in class java.lang.Thread
D. When a thread is waiting as a result of wait(), it releases its lock
E. The notify() method causes a thread to immediately release its lock
F. The difference between notify() and notifyAll() is that notifyAll() notifies all waiting threads, regardless of the object they’re waiting on

Question 8

Given the scenario: This class is intended to allow users to write a series of messages, so that each message is identified with a timestamp and the name of the thread that wrote the message:
public class MyErrorLoggingUtilClass {
private StringBuilder contents = new StringBuilder();
public void log(String message) {
contents.append(System.currentTimeMillis());
contents.append(": ");
contents.append(Thread.currentThread().getName());
contents.append(message);
contents.append("\n");
}
public String getLogMessages() { return contents.toString(); }
}

How can we ensure that instances of this class can be safely used by multiple threads?
A. This class is already thread-safe
B. Replacing StringBuilder with StringBuffer will make this class thread-safe
C. Synchronize the log() method only
D. Synchronize the getLogMessages() method only
E. Synchronize both log() and getLogMessages()
F. This class cannot be made thread-safe

Question 9

Given:
public static synchronized void main(String[] args) throws
InterruptedException {
Thread t = new Thread();
t.start();
System.out.print("X");
t.wait(10000);
System.out.print("Y");
}

What is the result of this code?
A. It prints X and exits
B. It prints X and never exits
C. It prints XY and exits almost immeditately
D. It prints XY with a 10-second delay between X and Y
E. It prints XY with a 10000-second delay between X and Y
F. The code does not compile
G. An exception is thrown at runtime

Question 10

Given:
class SimpleThreadExample extends Thread {
SimpleThreadExample() {
System.out.print(" SimpleThreadExample");
}
public void run() {
System.out.print(" aaa");
}
public void run(String s) {
System.out.print(" bbb");
}
}
public class TestThreads {
public static void main (String [] args) {
Thread t = new SimpleThreadExample() {
public void run() {
System.out.print(" ccc");
}
};
t.start();
} }

What is the result?
A. ccc
B. SimpleThreadExample ccc
C. SimpleThreadExample aaa
D. ccc aaa
E. ccc aaa bbb
F. aaa ccc
G. Compilation fails
H. An exception is thrown at runtime

Question 11

Given:
public class ExampleThread {
synchronized void a() { doSomething(); }
static synchronized void b() { doSomething(); }
static void doSomething() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
public static void main(String[] args) {
final ExampleThread x = new ExampleThread();
final ExampleThread y = new ExampleThread();
Runnable runnable = new Runnable() {
public void run() {
int option = (int) (Math.random() * 4);
switch (option) {
case 0: x.a(); break;
case 1: x.b(); break;
case 2: y.a(); break;
case 3: y.b(); break;
}
}
};
Thread thread1 = new Thread(runnable);
Thread thread2 = new Thread(runnable);
thread1.start();
thread2.start();
}
}



Which of the following pairs of method invocations could NEVER be executing at the same time? (Choose all that apply.)
A. x.a() in thread1, and x.a() in thread2
B. x.a() in thread1, and x.b() in thread2
C. x.a() in thread1, and y.a() in thread2
D. x.a() in thread1, and y.b() in thread2
E. x.b() in thread1, and x.a() in thread2
F. x.b() in thread1, and x.b() in thread2
G. x.b() in thread1, and y.a() in thread2
H. x.b() in thread1, and y.b() in thread2

Question 12

Given:
public class MultipleThreadExample {
static Thread cena, orton;
public static void main(String[] args) {
cena = new Thread() {
public void run() {
System.out.println("A");
try {
orton.sleep(1000);
} catch (Exception e) {
System.out.println("B");
}
System.out.println("C");
}
};
orton = new Thread() {
public void run() {
System.out.println("D");
try {
cena.wait();
} catch (Exception e) {
System.out.println("E");
}
System.out.println("F");
}
};
cena.start();
orton.start();
}
}


Which letters will eventually appear somewhere in the output? (Choose all that apply.)
A. A
B. B
C. C
D. D
E. E
F. F
G. The answer cannot be reliably determined
H. The code does not compile

Question 13

Given:
3. public class Runner implements Runnable {
4. void go(long id) {
5. System.out.println(id);
6. }
7. public static void main(String[] args) {
8. System.out.print(Thread.currentThread().getId() + " ");
9. // insert code here
10. }
11. public void run() { go(Thread.currentThread().getId()); }
12. }

And given the following five fragments:
I. new Runner().run();
II. new Runner().start();
III. new Thread(new Runner());
IV. new Thread(new Runner()).run();
V. new Thread(new Runner()).start();

When the five fragments are inserted, one at a time at line 9, which are true? (Choose all that apply.)
A. All five will compile
B. Only one might produce the output 4 4
C. Only one might produce the output 4 2
D. Exactly two might produce the output 4 4
E. Exactly two might produce the output 4 2
F. Exactly three might produce the output 4 4
G. Exactly three might produce the output 4 2

Question 14

Given:
3. public class Awesome implements Runnable {
4. public static void main(String[] args) {
5. Thread t = new Thread(new Awesome());
6. t.start();
7. System.out.print("a1 ");
8. t.join();
9. System.out.print("a2 ");
10. }
11. public void run() {
12. System.out.print("b1 ");
13. System.out.print("b2 ");
14. }
15. }

Which are true? (Choose all that apply.)
A. Compilation fails
B. The output could be b1 b2 a1 a2
C. The output could be a1 a2 b1 b2
D. The output could be a1 b1 b2 a2
E. The output could be a1 b1 a2 b2
F. An exception is thrown at runtime

Question 15

Given:

3. class Friends {

4. static long flag = 0;

5. // insert code here

6. if(flag == 0) flag = id;

7. for(int x = 1; x < 3; x++) {

8. if(flag == id) System.out.print("yo ");

9. else System.out.print("Friend ");

10. }

11. }

12. }

13. public class FriendsHangOut implements Runnable {

14. static Friends d;

15. public static void main(String[] args) {

16. new FriendsHangOut().go();

17. }

18. void go() {

19. d = new Friends();

20. new Thread(new FriendsHangOut()).start();

21. new Thread(new FriendsHangOut()).start();

22. }

23. public void run() {

24. d.chat(Thread.currentThread().getId());

25. }

26. }






And given these two fragments:

I. synchronized void chat(long id) {

II. void chat(long id) {



When fragment I or fragment II is inserted at line 5, which are true? (Choose all that apply.)

A. An exception is thrown at runtime

B. With fragment I, compilation fails

C. With fragment II, compilation fails

D. With fragment I, the output could be yo Friend Friend yo

E. With fragment I, the output could be Friend Friend yo yo

F. With fragment II, the output could be yo Friend Friend yo





Answers:

Answer 1
C is correct. The class implements the Runnable interface with a legal run() method.

A is incorrect because interfaces are implemented, not extended. B is incorrect because even though the class has a valid public void run() method, it does not implement the Runnable interface. D is incorrect because the run() method must be public. E is incorrect because the method to implement is run(), not start().

Answer 2
D is correct. The thread SimpleThreadExample will start and loop three times (from 0 to 2).

A is incorrect because the Thread class implements the Runnable interface; therefore, in line 5, Thread can take an object of type Thread as an argument in the constructor (this is NOT recommended). B and C are incorrect because the variable i in the for loop starts with a value of 0 and ends with a value of 2.

Answer 3
D is correct. The sleep() method must be enclosed in a try/catch block, or the method printStuff() must declare it throws the InterruptedException.

E is incorrect, but it would be correct if the InterruptedException was dealt with (A is too precise). B is incorrect (even if the InterruptedException was dealt with) because all Java code, including the main() method, runs in threads. C is incorrect. The sleep() method is static, it always affects the currently executing thread.

Answer 4
B and F are correct. By marking the methods as synchronized, the threads will get the lock of the this object before proceeding. Only one thread will be setting or reading at any given moment, thereby assuring that read() always returns the addition of a valid pair.

A is incorrect because it is not synchronized; therefore, there is no guarantee that the values added by the read() method belong to the same pair. C and D are incorrect; only objects can be used to synchronize on. E fails—it is not possible to select other objects (even this) to synchronize on when declaring a method as synchronized.

Answer 5
D is correct. 1 and 2 will be printed, but there will be no return from the wait call because no other thread will notify the main thread, so 3 will never be printed. It’s frozen at line 7.

A is incorrect; IllegalMonitorStateException is an unchecked exception. B and C are incorrect; 3 will never be printed, since this program will wait forever. E is incorrect because IllegalMonitorStateException will never be thrown because the wait() is done on args within a block of code synchronized on args. F is incorrect because any object can be used to synchronize on and this and static don’t mix.

Answer 6
A is correct. Either of the two events will make the thread a candidate for running again.

B is incorrect because a waiting thread will not return to runnable when the lock is released, unless a notification occurs. C is incorrect because the thread will become a candidate immediately after notification. D is also incorrect because a thread will not come out of a waiting pool just because a lock has been released.

Answer 7
A is correct because notifyAll() (and wait() and notify()) must be called from within a synchronized context. D is a correct statement.

B is incorrect because to call wait(), the thread must own the lock on the object that wait() is being invoked on, not the other way around. C is wrong because notify() is defined in java.lang.Object. E is wrong because notify() will not cause a thread to release its locks. The thread can only release its locks by exiting the synchronized code. F is wrong because notifyAll() notifies all the threads waiting on a particular locked object, not all threads waiting on any object.

Answer 8
E is correct. Synchronizing the public methods is sufficient to make this safe, so F is false. This class is not thread-safe unless some sort of synchronization protects the changing data.

B is not correct because although a StringBuffer is synchonized internally, we call append() multiple times, and nothing would prevent two simultaneous log() calls from mixing up their messages. C and D are not correct because if one method remains unsynchronized, it can run while the other is executing, which could result in reading the contents while one of the messages is incomplete, or worse.

Answer 9
G is correct. The code does not acquire a lock on t before calling t.wait(), so it throws an IllegalMonitorStateException. The method is synchronized, but it’s not synchronized on t so the exception will be thrown. If the wait were placed inside a synchronized(t) block, then the answer would have been D.

Answer 10
B is correct. The first line of main we’re constructing an instance of an anonymous inner class extending from SimpleThreadExample. So the SimpleThreadExample constructor runs and prints SimpleThreadExample. Next, main() invokes start() on the new thread instance, which causes the overridden run() method (the run() method in the anonymous inner class) to be invoked.

Answer 11

A, F, and H. A is a right answer because when synchronized instance methods are called on the same instance, they block each other. F and H can’t happen because synchronized static methods in the same class block each other, regardless of which instance was used to call the methods. (An instance is not required to call static methods; only the class.)

C could happen because synchronized instance methods called on different instances do not block each other. B, D, E, and G could all happen because instance methods and static methods lock on different objects, and do not block each other.

Answer 12
A, C, D, E, and F are correct. This may look like cena and orton are battling to cause the other to sleep() or wait()—but that’s not the case. Since sleep() is a static method, it affects the current thread, which is cena (even though the method is invoked using a reference to orton). That’s misleading but perfectly legal, and the Thread cena is able to sleep with no exception, printing A and C (after at least a 1-second delay). Meanwhile orton tries to call cena.wait()—but orton has not synchronized on cena, so calling cena.wait() immediately causes an IllegalMonitorStateException, and so orton prints D, E, and F. Although the order of the output is somewhat indeterminate (we have no way of knowing whether A is printed before D, for example) it is guaranteed that A, C, D, E, and F will all be printed in some order, eventually—so G is incorrect.

Answer 13
C and D are correct. Fragment I doesn’t start a new thread. Fragment II doesn’t compile. Fragment III creates a new thread but doesn’t start it. Fragment IV creates a new thread and invokes run() directly, but it doesn’t start the new thread. Fragment V creates and starts a new thread.

Answer 14
A is correct. The join() must be placed in a try/catch block. If it were, answers B and D would be correct. The join() causes the main thread to pause and join the end of the other thread, meaning "a2" must come last.

Answer 15
F is correct. With fragment I, the chat method is synchronized, so the two threads can’t swap back and forth. With either fragment, the first output must be yo.

Previous Chapter: Quick Review - Threads

Next Chapter: Other Topics of Importance

Friday, February 25, 2011

Self Test: Chapters 52 to 55

In this chapter, we are going to take a look at some questions on the Inner class topics we had seen in the past few chapters.

All the best!!!

Questions:

Question 1.

Which are true about a static nested class? (Choose all that apply.)
A. You must have a reference to an instance of the enclosing class in order to instantiate it
B. It does not have access to non-static members of the enclosing class
C. Its variables and methods must be static
D. If the outer class is named MyOuter, and the nested class is named MyInner, it can be instantiated using new MyOuter.MyInner();
E. It must extend the enclosing class

Question 2.

Given:
class Parent {
Parent(String s) { }
Parent() { }
}
class Child extends Parent {
Child() { }
Child(String s) {super(s);}
void dooo() {
// insert code here
}
}

Which create an anonymous inner class from within class Child? (Choose all that apply.)
A. Parent f = new Parent(24) { };
B. Parent f = new Child() { };
C. Parent f = new Parent() {String s; };
D. Child f = new Parent(String s) { };
E. Parent f = new Parent.Child(String s) { };

Question 3.

Which are true about a method-local inner class? (Choose all that apply.)
A. It must be marked final
B. It can be marked abstract
C. It can be marked public
D. It can be marked static
E. It can access private members of the enclosing class

Question 4.

Given:
1. public class TestClass {
2. public static void main(String[] args) {
3. Object o = new Object() {
4. public boolean equals(Object obj) {
5. return true;
6. }
7. }
8. System.out.println(o.equals("Rocky"));
9. }
10. }

What is the result?
A. An exception occurs at runtime
B. true
C. Rocky
D. Compilation fails because of an error on line 3
E. Compilation fails because of an error on line 4
F. Compilation fails because of an error on line 8
G. Compilation fails because of an error on a line other than 3, 4, or 8

Question 5.

Given:
1. public class CarTest {
2. public static void main(String[] args) {
3. class Car {
4. public String name;
5. public Car(String s) {
6. name = s;
7. }
8. }
9. Object obj = new Car("Ferrari");
10. System.out.println(obj.name);
11. }
12. }

What is the result?
A. An exception occurs at runtime at line 10
B. Ferrari
C. Compilation fails because of an error on line 3
D. Compilation fails because of an error on line 9
E. Compilation fails because of an error on line 10

Question 6.

Given:
public abstract class TestAbstractEx {
public int getNum() {
return 45;
}
public abstract class Child {
public int getNum() {
return 38;
}
}
public static void main(String[] args) {
TestAbstractEx t = new TestAbstractEx() {
public int getNum() {
return 22;
}
};
TestAbstractEx.Child f = t.new Child() {
public int getNum() {
return 57;
}
};
System.out.println(f.getNum() + " " + t.getNum());
}
}



What is the result?
A. 57 22
B. 45 38
C. 45 57
D. An exception occurs at runtime
E. Compilation fails

Question 7.

Given:
3. public class Test {
4. public static void main(String[] args) {
5. Outer c = new Outer();
6. // insert code here
7. s.go();
8. }
9. }
10. class Outer {
11. class Inner {
12. void go() { System.out.println("hiii"); }
13. }
14. }

Which, inserted independently at line 6, compile and produce the output “hiii”? (Choose all that apply.)
A. Inner s = c.new Inner();
B. c.Inner s = c.new Inner();
C. c.Inner s = Outer.new Inner();
D. Outer.Inner s = c.new Inner();
E. Outer.Inner s = Outer.new Inner();

Question 8.

Given:
5. class A { void m() { System.out.println("outer"); } }
6.
7. public class TestInnerClass {
8. public static void main(String[] args) {
9. new TestInnerClass().go();
10. }
11. void go() {
12. new A().m();
13. class A { void m() { System.out.println("inner"); } }
14. }
15. class A { void m() { System.out.println("middle"); } }
16. }

What is the result?
A. inner
B. outer
C. middle
D. Compilation fails
E. An exception is thrown at runtime

Question 9.

Given:
3. public class Car {
4. class Engine {
5. // insert code here
6. }
7. public static void main(String[] args) {
8. new Car().go();
9. }
10. void go() {
11. new Engine();
12. }
13. void drive() { System.out.println("hi"); }
14. }

Which, inserted independently at line 5, produce the output “hi”? (Choose all that apply.)
A. { Car.drive(); }
B. { this.drive(); }
C. { Car.this.drive(); }
D. { this.Car.this.drive(); }
E. Engine() { Car.drive(); }
F. Engine() { this.drive(); }
G. Engine() { Car.this.drive(); }

Question 10.

Given:
3. public class City {
4. class Chennai {
5. void doSomething() throws Exception { System.out.print("x "); }
6. }
7. class MarinaBeach extends Chennai {
8. void doSomething() throws Exception { }
9. }
10. public static void main(String[] args) throws Exception {
11. new City().go();
12. }
13. void go() throws Exception { new MarinaBeach().doSomething(); }
14. }

What is the result?
A. x
B. x x
C. No output is produced
D. Compilation fails due to multiple errors
E. Compilation fails due only to an error on line 4
F. Compilation fails due only to an error on line 7
G. Compilation fails due only to an error on line 10
H. Compilation fails due only to an error on line 13


Self Test Answers:

Answer 1.

B and D. B is correct because a static nested class is not tied to an instance of the enclosing class, and thus can’t access the non-static members of the class (just as a static method can’t access non-static members of a class). D uses the correct syntax for instantiating a static nested class.

A is incorrect because static nested classes do not need (and can’t use) a reference to an instance of the enclosing class. C is incorrect because static nested classes can declare and define non-static members. E is wrong because...it just is. There’s no rule that says an inner or nested class has to extend anything.

Answer 2.

B and C. B is correct because anonymous inner classes are no different from any other class when it comes to polymorphism. That means you are always allowed to declare a reference variable of the superclass type and have that reference variable refer to an instance of a subclass type, which in this case is an anonymous subclass of Child. Since Child is a subclass of Parent, it all works. C uses correct syntax for creating an instance of Parent.

A is incorrect because it passes an int to the Parent constructor, and there is no matching constructor in the Parent class. D is incorrect because it violates the rules of polymorphism; you cannot refer to a superclass type using a reference variable declared as the subclass type. The superclass doesn’t have everything the subclass has. E uses incorrect syntax.

Answer 3.

B and E. B is correct because a method-local inner class can be abstract, although it means a subclass of the inner class must be created if the abstract class is to be used (so an abstract method-local inner class is probably not useful). E is correct because a method-local inner class works like any other inner class—it has a special relationship to an instance of the enclosing class, thus it can access all members of the enclosing class.

A is incorrect because a method-local inner class does not have to be declared final (although it is legal to do so). C and D are incorrect because a method-local inner class cannot be made public (remember—local variables can’t be public) or static.

Answer 4.

G. This code would be legal if line 7 ended with a semicolon. Remember that line 3 is a statement that doesn’t end until line 7, and a statement needs a closing semicolon!

A, B, C, D, E, and F are incorrect based on the program logic described above. If the semicolon were added at line 7, then answer B would be correct—the program would print true, the return from the equals() method overridden by the anonymous subclass of Object.

Answer 5.

E. If you use a reference variable of type Object, you can access only those members defined in class Object.

Answer 6.

A. You can define an inner class as abstract, which means you can instantiate only concrete subclasses of the abstract inner class. The object referenced by the variable t is an instance of an anonymous subclass of TestAbstractEx, and the anonymous class overrides the getNum() method to return 22. The variable referenced by f is an instance of an anonymous subclass of Child, and the anonymous Child subclass also overrides the getNum() method (to return 57). Remember that to create a Child instance, we need an instance of the enclosing TestAbstractEx class to tie to the new Child inner class instance. TestAbstractEx can’t be instantiated because it’s abstract, so we created an anonymous subclass (non-abstract) and then used the instance of that anonymous subclass to tie to the new Child subclass instance.

Answer 7.

D is correct. It is the only code that uses the correct inner class instantiation syntax.

A, B, C, and E are incorrect based on the above. (Objective 1.1)

Answer 8.

C is correct. The "inner" version of class A isn’t used because its declaration comes after the instance of class A is created in the go() method.

Answer 9.

C and G are correct. C is the correct syntax to access an inner class’s outer instance method from an initialization block, and G is the correct syntax to access it from a constructor.

Answer 10.

C is correct. The inner classes are valid, and all the methods (including main()), correctly throw an Exception, given that doSomething() throws an Exception. The doSomething() in class MarinaBeach overrides class Chennai’s doSomething() and produces no output.

Previous Chapter: Quick Review - Inner classes

Next Chapter: Chapter 56 - Threads & Multithreading

Self Test: Chapters 38 to 51

Below are some questions from the previous chapters that would help you practice for the SCJP examination.

All the best !!!

Questions:

Question 1.

Given:
public static void main(String[] args) {

// CODE HERE
for (int i = 0; i <= 10; i++) {

List < Integer > row = new ArrayList < Integer > ();

for (int j = 0; j <= 10; j++)

row.add(i * j);

table.add(row);

}

for (List < Integer > row : table)

System.out.println(row);

}

Which statements could be inserted at // CODE HERE to allow this code to compile and run? (Choose all that apply.)
A. List < List< Integer > > table = new List < List < Integer > >();
B. List < List< Integer > > table = new ArrayList < List < Integer > >();
C. List < List< Integer > > table = new ArrayList < ArrayList < Integer > >();
D. List < List, Integer > table = new List < List, Integer >();
E. List < List, Integer > table = new ArrayList < List, Integer >();
F. List < List, Integer > table = new ArrayList < ArrayList, Integer >();
G. None of the above

Question 2.

Which statements are true about comparing two instances of the same class, given that the equals() and hashCode() methods have been properly overridden? (Choose all that apply.)
A. If the equals() method returns true, the hashCode() comparison == might return false
B. If the equals() method returns false, the hashCode() comparison == might return true
C. If the hashCode() comparison == returns true, the equals() method must return true
D. If the hashCode() comparison == returns true, the equals() method might return true
E. If the hashCode() comparison != returns true, the equals() method might return true

Question 3.

Given:
public static void doSomething() {
Set set = new TreeSet();
set.add("2");
set.add(3);
set.add("1");
Iterator it = set.iterator();
while (it.hasNext())
System.out.print(it.next() + " ");
}

Which statements are true?
A. The doSomething() method will print 1 2
B. The doSomething() method will print 1 2 3
C. The doSomething() method will print three numbers, but the order cannot be determined
D. The doSomething() method will not compile
E. The doSomething() method will throw an exception at runtime

Question 4.

Given:
import java.util.*;
class TestMaps {
public static void main(String[] args) {
Map m = new HashMap();
Day t1 = new Day("Monday");
Day t2 = new Day("Monday");
Day t3 = new Day("Tuesday");
m.put(t1, "goToGym");
m.put(t2, "visitMom");
m.put(t3, "goShopping");
System.out.println(m.size());
}
}
class Day{
String day;
Day(String d) { day = d; }
public boolean equals(Object o) {
return ((Day)o).day == this.day;
}
// public int hashCode() { return 9; }
}

Which is correct? (Choose all that apply.)
A. As the code stands it will not compile
B. As the code stands the output will be 2
C. As the code stands the output will be 3
D. If the hashCode() method is uncommented the output will be 2
E. If the hashCode() method is uncommented the output will be 3
F. If the hashCode() method is uncommented the code will not compile

Question 5.

Given:
12. public class BankAppManager {
13. private Map allBalances = new HashMap();
14. private int corpus;
15.
16. public int calcAccBalance(String custName) {
17. Integer total = (Integer) allBalances.get(custName);
18. if (total == null)
19. total = Integer.valueOf(0);
20. return total.intValue();
21. }
23. public void updateAccBalance(String custName, int amount) {
24. allBalances.put(custName, Integer.valueOf(amount));
25. }
26. }

This class is to be updated to make use of appropriate generic types, with no changes in behavior (for better or worse). Which of these steps could be performed? (Choose three.)
A. Replace line 13 with
private Map < String, int > allBalances = new HashMap < String, int >();
B. Replace line 13 with
private Map < String, Integer > allBalances = new HashMap < String, Integer >();
C. Replace line 13 with
private Map < String< Integer > > allBalances = new HashMap < String< Integer > >();
D. Replace lines 17–20 with
int total = allBalances.get(custName);
if (total == null)
total = 0;
return total;
E. Replace lines 17–20 with
Integer total = allBalances.get(custName);
if (total == null)
total = 0;
return total;
F. Replace lines 17–20 with
return allBalances.get(custName);
G. Replace line 24 with
allBalances.put(custName, amount);
H. Replace line 24 with
allBalances.put(custName, amount.intValue());

Question 6.

Given:
interface Drivable< E > { void driveee(E x); }
interface Car extends Drivable< E > {}
interface Van extends Drivable< E > {}
abstract class SomethingElse {}
class Xxxxxx extends SomethingElse {}
abstract class Something {}
class SuzukiSwift extends Something implements Van {
public void driveee(SuzukiSwift x) {}
}
class VwJetta extends Something implements Car {
public void driveee(SuzukiSwift x) {}
}

Which of the following changes (taken separately) would allow this code to compile? (Choose all that apply.)
A. Change the Car interface to
interface Car extends Drivable< E > {}
B. Change the Van interface to
interface Van extends Drivable< E > {}
C. Change the SuzukiSwift class to
class SuzukiSwift extends Something implements Van {
public void driveee(Xxxxxx x) {}
}
D. Change the SuzukiSwift class to
class SuzukiSwift extends SomethingElse implements Car {
public void driveee(VwJetta x) {}

E. Change the VwJetta class to
class VwJetta extends Something implements Van {
public void driveee(Xxxxxx x) {}
}
F. No changes are necessary

Question 7.

Which collection class(es) allows you to grow or shrink its size and provides indexed access to its elements, but whose methods are not synchronized? (Choose all that apply.)
A. java.util.HashSet
B. java.util.LinkedHashSet
C. java.util.List
D. java.util.ArrayList
E. java.util.Vector
F. java.util.PriorityQueue

Question 8.

Given a method declared as
public static < e extends Number > List < E > process(List < E > nums)

A programmer wants to use this method like this
// PUT CODE HERE

output = process(input);

Which pairs of declarations could be placed at // PUT CODE HERE to allow the code to compile? (Choose all that apply.)
A. ArrayList < Integer > input = null;
B. ArrayList < Integer > output = null;
C. ArrayList < Integer > input = null;
D. List < Integer > output = null;
E. ArrayList < Integer > input = null;
F. List < Number > output = null;
G. List < Number > input = null;
H. ArrayList < Integer > output = null;
I. List < Number > input = null;
J. List < Number > output = null;
K. List < Integer > input = null;
L. List < Integer > output = null;
M. None of the above

Question 9.

Given the proper import statement(s), and
13. PriorityQueue < String > pq = new PriorityQueue < String >();
14. pq.add("2");
15. pq.add("4");
16. System.out.print(pq.peek() + " ");
17. pq.offer("1");
18. pq.add("3");
19. pq.remove("1");
20. System.out.print(pq.poll() + " ");
21. if(pq.remove("2")) System.out.print(pq.poll() + " ");
22. System.out.println(pq.poll() + " " + pq.peek());

What is the result?
A. 2 2 3 3
B. 2 2 3 4
C. 4 3 3 4
D. 2 2 3 3 3
E. 4 3 3 3 3
F. 2 2 3 3 4
G. Compilation fails
H. An exception is thrown at runtime

Question 10.

Given:
3. import java.util.*;
4. public class ConfuseMe {
5. public static void main(String[] args) {
6. Object o = new Object();
7. // insert code here
8. s.add("o");
9. s.add(o);
10. }
11. }

And these three fragments:
I. Set s = new HashSet();
II. TreeSet s = new TreeSet();
III. LinkedHashSet s = new LinkedHashSet();

When fragments I, II, or III are inserted, independently, at line 7, which are true? (Choose all that apply.)
A. Fragment I compiles
B. Fragment II compiles
C. Fragment III compiles
D. Fragment I executes without exception
E. Fragment II executes without exception
F. Fragment III executes without exception

Question 11.

Given:
3. import java.util.*;
4. class Dog {
5. int size;
6. public Dog(int s) { size = s; }
7. public boolean equals(Object o) { return (this.size == ((Dog)o).size); }
8. // insert code here
9. }
10. public class DogTest {
11. public static void main(String[] args) {
12. LinkedHashSet< Dog > t = new LinkedHashSet< Dog >();
13. t.add(new Dog(1)); t.add(new Dog(2)); t.add(new Dog(1));
14. System.out.println(t.size());
15. }
16. }



And these two fragments:
I. public int hashCode() { return size/5; }
II. // no hashCode method declared

If fragment I or II is inserted, independently, at line 8, which are true? (Choose all that apply.)
A. If fragment I is inserted, the output is 2
B. If fragment I is inserted, the output is 3
C. If fragment II is inserted, the output is 2
D. If fragment II is inserted, the output is 3
E. If fragment I is inserted, compilation fails
F. If fragment II is inserted, compilation fails

Question 12.

Given the proper import statement(s), and:
13. TreeSet< String > s = new TreeSet< String >();
14. TreeSet< String > subs = new TreeSet< String >();
15. s.add("a"); s.add("b"); s.add("c"); s.add("d"); s.add("e");
16.
17. subs = (TreeSet)s.subSet("b", true, "d", true);
18. s.add("g");
19. s.pollFirst();
20. s.pollFirst();
21. s.add("c2");
22. System.out.println(s.size() +" "+ subs.size());

Which are true? (Choose all that apply.)
A. The size of s is 4
B. The size of s is 5
C. The size of s is 7
D. The size of subs is 1
E. The size of subs is 2
F. The size of subs is 3
G. The size of subs is 4
H. An exception is thrown at runtime

Question 13.

Given:
3. import java.util.*;
4. public class TestMe {
5. public static void main(String[] args) {
6. TreeMap myMap = new TreeMap();
7. myMap.put("a", "apple"); myMap.put("d", "date");
8. myMap.put("f", "fig"); myMap.put("p", "pear");
9. System.out.println("1st after mango: " + // sop 1
10. myMap.higherKey("f"));
11. System.out.println("1st after mango: " + // sop 2
12. myMap.ceilingKey("f"));
13. System.out.println("1st after mango: " + // sop 3
14. myMap.floorKey("f"));
15. SortedMap sub = new TreeMap();
16. sub = myMap.tailMap("f");
17. System.out.println("1st after mango: " + // sop 4
18. sub.firstKey());
19. }
20. }

Which of the System.out.println statements will produce the output 1st after mango: p? (Choose all that apply.)
A. sop 1
B. sop 2
C. sop 3
D. sop 4
E. None; compilation fails
F. None; an exception is thrown at runtime

Question 14.

Given:
3. import java.util.*;
4. class Car { }
5. class Ferrari extends Car { }
6. class F550Barchetta extends Ferrari { }
7. public class DriveAround {
8. ArrayList< Ferrari > go() {
9. // insert code here
10. }
11. }

Which, inserted independently at line 9, will compile? (Choose all that apply.)
A. return new ArrayList < F550Barchetta >();
B. return new ArrayList < Ferrari >();
C. return new ArrayList < Object >();
D. return new ArrayList < Car >();

Question 15.

Given:
3. import java.util.*;
4. class Shoe { int size; Shoe(int s) { size = s; } }
5. public class FirstGrade {
6. public static void main(String[] args) {
7. TreeSet < Integer > i = new TreeSet < Integer >();
8. TreeSet < Shoe > d = new TreeSet < Shoe >();
9.
10. d.add(new Shoe(1)); d.add(new Shoe(2)); d.add(new Shoe(1));
11. i.add(1); i.add(2); i.add(1);
12. System.out.println(d.size() + " " + i.size());
13. }
14. }

What is the result?
A. 1 2
B. 2 2
C. 2 3
D. 3 2
E. 3 3
F. Compilation fails
G. An exception is thrown at runtime

Answers:

Answer 1.

B is correct.

A is incorrect because List is an interface, so you can’t say new List() regardless of any generic types. D, E, and F are incorrect because List only takes one type parameter (a Map would take two, not a List). C is tempting, but incorrect. The type argument < List< Integer >> must be the same for both sides of the assignment, even though the constructor new ArrayList() on the right side is a subtype of the declared type List on the left.

Answer 2.

B and D. B is true because often two dissimilar objects can return the same hashcode value. D is true because if the hashCode() comparison returns ==, the two objects might or might not be equal.

A, C, and E are incorrect. C is incorrect because the hashCode() method is very flexible in its return values, and often two dissimilar objects can return the same hash code value. A and E are a negation of the hashCode() and equals() contract.

Answer 3.

E is correct. You can’t put both Strings and ints into the same TreeSet. Without generics, the compiler has no way of knowing what type is appropriate for this TreeSet, so it allows everything to compile. At runtime, the TreeSet will try to sort the elements as they’re added, and when it tries to compare an Integer with a String it will throw a ClassCastException. Note that although the doSomething() method does not use generics, it does use autoboxing. Watch out for code that uses some new features and some old features mixed together.

Answer 4.

C and D are correct. If hashCode() is not overridden then every entry will go into its own bucket, and the overridden equals() method will have no effect on determining equivalency. If hashCode() is overridden, then the overridden equals() method will view t1 and t2 as duplicates.

Answer 5.

B, E, and G are correct.

A is wrong because you can’t use a primitive type as a type parameter. C is wrong because a Map takes two type parameters separated by a comma. D is wrong because an int can’t autobox to a null, and F is wrong because a null can’t unbox to 0. H is wrong because you can’t autobox a primitive just by trying to invoke a method with it.

Answer 6.

B is correct. The problem with the original code is that SuzukiSwift tries to implement Van and Van declares that its type parameter E can be any type that extends SomethingElse. Since a SuzukiSwift is not a SomethingElse, Van makes no sense—the type SuzukiSwift is outside the allowed range of Van’s parameter E. Only solutions that either alter the definition of a SuzukiSwift or alter the definition of Van will be able to fix this. So A, E, and F are eliminated. B works, changing the definition of an Van to allow it to eat SuzukiSwift solves the problem. C doesn’t work because an Van must have a driveee(SomethingElse) method, not driveee(Xxxxxx).
And D doesn’t work, because in D we made SuzukiSwift extend SomethingElse, now the VwJetta class breaks because its driveee(SuzukiSwift) method no longer fulfills the contract of Car.

Answer 7.

D is correct. All of the collection classes allow you to grow or shrink the size of your collection. ArrayList provides an index to its elements. The newer collection classes tend not to have synchronized methods. Vector is an older implementation of ArrayList functionality and has synchronized methods; it is slower than ArrayList.

A, B, C, E, and F are incorrect based on the logic described above; Notes: C, List is an interface, and F, PriorityQueue does not offer access by index.

Answer 8.

B, E, and F are correct.

The return type of process is definitely declared as a List, not an ArrayList, so A and D are wrong. C is wrong because the return type evaluates to List< Integer >, and that can’t be assigned to a variable of type List< Number >. Of course all these would probably cause a NullPointerException since the variables are still null—but the question only asked us to get the code to compile.

Answer 9.

B is correct. For the sake of the exam, add() and offer() both add to (in this case), naturally sorted queues. The calls to poll() both return and then remove the first item from the queue, so the if test fails.

Answer 10.

A, B, C, D, and F are all correct.

Only E is incorrect. Elements of a TreeSet must in some way implement Comparable.

Answer 11.

A and D are correct. While fragment II wouldn’t fulfill the hashCode() contract (as you can see by the results), it is legal Java. For the purpose of the exam, if you don’t override hashCode(), every object will have a unique hashcode.

Answer 12.

B and F are correct. After "g" is added, TreeSet s contains six elements and TreeSet subs contains three (b, c, d), because "g" is out of the range of subs. The first pollFirst() finds and removes only the "a". The second pollFirst() finds and removes the "b" from both TreeSets (remember they are backed). The final add() is in range of both TreeSets. The final contents are [c,c2,d,e,g] and [c,c2,d].


Answer 13.

A is correct. The ceilingKey() method’s argument is inclusive. The floorKey() method would be used to find keys before the specified key. The firstKey() method’s argument is also inclusive.

Answer 14.

B is correct.

A is incorrect because polymorphic assignments don’t apply to generic type parameters. C and D are incorrect because they don’t follow basic polymorphism rules.

Answer 15.

G is correct. Class Shoe needs to implement Comparable in order for a TreeSet (which keeps its elements sorted) to be able to contain Shoe objects.

Previous Chapter: Quick Review - Chapters 38 to 51

Next Chapter: Chapter 52 - Inner Classes

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

Monday, February 14, 2011

Self test – Chapters 27 to 31

Questions:


Question 1:


Given two files:

1. class One {

2. public static void main(String[] args) {

3. int assert = 0;

4. }

5. }


1. class Two {

2. public static void main(String[] args) {

3. assert(false);

4. }

5. }


And the four command-line invocations:


javac -source 1.3 One.java

javac -source 1.4 One.java

javac -source 1.3 Two.java

javac -source 1.4 Two.java


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


A. Only one compilation will succeed

B. Exactly two compilations will succeed

C. Exactly three compilations will succeed

D. All four compilations will succeed

E. No compiler warnings will be produced

F. At least one compiler warning will be produced


Question 2:


Given:

class Plane {

static String s = "-";

public static void main(String[] args) {

new Plane().s1();

System.out.println(s);

}

void s1() {

try { s2(); }

catch (Exception e) { s += "c"; }

}

void s2() throws Exception {

s3(); s += "2";

s3(); s += "2b";

}
void s3() throws Exception {

throw new Exception();

}

}


What is the result?


A. -

B. -c

C. -c2

D. -2c

E. -c22b

F. -2c2b

G. -2c2bc

H. Compilation fails


Question 3:


Given:

try { int x = Integer.parseInt("two"); }


Which could be used to create an appropriate catch block? (Choose all that apply.)

A. ClassCastException

B. IllegalStateException

C. NumberFormatException

D. IllegalArgumentException

E. ExceptionInInitializerError

F. ArrayIndexOutOfBoundsException


Question 4:


Which are true? (Choose all that apply.)

A. It is appropriate to use assertions to validate arguments to methods marked public

B. It is appropriate to catch and handle assertion errors

C. It is NOT appropriate to use assertions to validate command-line arguments

D. It is appropriate to use assertions to generate alerts when you reach code that should not be reachable

E. It is NOT appropriate for assertions to change a program’s state


Question 5:


Given:

1. class TestLoops {

2. public static void main(String[] args) {

3. int[] x = {7,6,5,4,3,2,1};

4. // insert code here

5. System.out.print(y + " ");

6. }

7. }

8. }


Which, inserted independently at line 4, compiles? (Choose all that apply.)


A. for(int y : x) {

B. for(x : int y) {

C. int y = 0; for(y : x) {

D. for(int y=0, z=0; z < x.length; z++) { y = x[z];

E. for(int y=0, int z=0; z < x.length; z++) { y = x[z];

F. int y = 0; for(int z=0; z < x.length; z++) { y = x[z];


Question 6:


Given:

class Ostrich {

static String s = "-";

public static void main(String[] args) {

try {

throw new Exception();

} catch (Exception e) {

try {

try { throw new Exception();

} catch (Exception ex) { s += "ic "; }

throw new Exception(); }

catch (Exception x) { s += "mc "; }

finally { s += "mf "; }

} finally { s += "of "; }

System.out.println(s);

} }


What is the result?


A. -ic of

B. -mf of

C. -mc mf

D. -ic mf of

E. -ic mc mf of

F. -ic mc of mf

G. Compilation fails


Question 7:


Given:


3. class SubException extends Exception { }

4. class SubSubException extends SubException { }

5.

6. public class CC { void doStuff() throws SubException { } }

7.

8. class CC2 extends CC { void doStuff() throws SubSubException { } }

9.

10. class CC3 extends CC { void doStuff() throws Exception { } }

11.

12. class CC4 extends CC { void doStuff(int x) throws Exception { } }

13.

14. class CC5 extends CC { void doStuff() { } }


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


A. Compilation succeeds

B. Compilation fails due to an error on line 8

C. Compilation fails due to an error on line 10

D. Compilation fails due to an error on line 12

E. Compilation fails due to an error on line 14


Question 8:


Given:


3. public class TestLoops {

4. static int x = 7;

5. public static void main(String[] args) {

6. String s = "";

7. for(int y = 0; y < 3; y++) {

8. x++;

9. switch(x) {

10. case 8: s += "8 ";

11. case 9: s += "9 ";

12. case 10: { s+= "10 "; break; }

13. default: s += "d ";

14. case 13: s+= "13 ";

15. }

16. }

17. System.out.println(s);

18. }

19. static { x++; }

20. }


What is the result?


A. 9 10 d

B. 8 9 10 d

C. 9 10 10 d

D. 9 10 10 d 13

E. 8 9 10 10 d 13

F. 8 9 10 9 10 10 d 13

G. Compilation fails


Question 9:


Given:

3. class Limitless { }

4. public class Beyond extends Limitless {

5. static Integer i;

6. public static void main(String[] args) {

7. int sw = (int)(Math.random() * 3);

8. switch(sw) {

9. case 0: { for(int x = 10; x > 5; x++)

10. if(x > 10000000) x = 10;

11. break; }

12. case 1: { int y = 7 * i; break; }

13. case 2: { Limitless inf = new Beyond();

14. Beyond b = (Beyond)inf; }

15. }

16. }

17. }


And given that line 7 will assign the value 0, 1, or 2 to sw, which are true? (Choose all that apply.)


A. Compilation fails

B. A ClassCastException might be thrown

C. A StackOverflowError might be thrown

D. A NullPointerException might be thrown

E. An IllegalStateException might be thrown

F. The program might hang without ever completing

G. The program will always complete without exception


Question 10:


Given:


3. public class Spears {

4. public static void main(String[] args) {

5. int[] ia = {1,3,5,7,9};

6. for(int x : ia) {

7. for(int j = 0; j < 3; j++) {

8. if(x > 4 && x < 8) continue;

9. System.out.print(" " + x);

10. if(j == 1) break;

11. continue;

12. }

13. continue;

14. }

15. }

16. }


What is the result?


A. 1 3 9

B. 5 5 7 7

C. 1 3 3 9 9

D. 1 1 3 3 9 9

E. 1 1 1 3 3 3 9 9 9

F. Compilation fails


Question 11:


Given:

3. public class OverAndOut {

4. static String s = "";

5. public static void main(String[] args) {

6. try {

7. s += "1";

8. throw new Exception();

9. } catch (Exception e) { s += "2";

10. } finally { s += "3"; doStuff(); s += "4";

11. }

12. System.out.println(s);

13. }

14. static void doStuff() { int x = 0; int y = 7/x; }

15. }


What is the result?

A. 12

B. 13

C. 123

D. 1234

E. Compilation fails

F. 123 followed by an exception

G. 1234 followed by an exception

H. An exception is thrown with no other output


Question 12:



Given:


3. public class Breeze {

4. public static void main(String[] args) {

5. foreach:

6. for(int j=0; j<5; j++) {

7. for(int k=0; k< 3; k++) {

8. System.out.print(" " + j);

9. if(j==3 && k==1) break foreach;

10. if(j==0 || j==2) break;

11. }

12. }

13. }

14. }


What is the result?


A. 0 1 2 3

B. 1 1 1 3 3

C. 0 1 1 1 2 3 3

D. 1 1 1 3 3 4 4 4

E. 0 1 1 1 2 3 3 4 4 4

F. Compilation fails


Question 13:


Given:

3. public class GotYa {

4. public static void main(String[] args) {

5. // insert code here

6.

7. }

8. void go() {

9. go();

10. }

11. }


And given the following three code fragments:

I. new GotYa().go();

II. try { new GotYa().go(); }

catch (Error e) { System.out.println("ouch"); }


III. try { new GotYa().go(); }

catch (Exception e) { System.out.println("ouch"); }


When fragments I - III are added, independently, at line 5, which are true? (Choose all that apply.)

A. Some will not compile

B. They will all compile

C. All will complete normally

D. None will complete normally

E. Only one will complete normally

F. Two of them will complete normally


Question 14:


Given:

3. public class Funny {

4. public static void main(String[] args) {

5. int j = 7;

6. assert(++j > 7);

7. assert(++j > 8): "hi";

8. assert(j > 10): j=12;

9. assert(j==12): doStuff();

10. assert(j==12): new Funny();

11. }

12. static void doStuff() { }

13. }


Which are true? (Choose all that apply.)

A. Compilation succeeds

B. Compilation fails due to an error on line 6

C. Compilation fails due to an error on line 7

D. Compilation fails due to an error on line 8

E. Compilation fails due to an error on line 9

F. Compilation fails due to an error on line 10


Question 15:


Given:

1. public class ThrowMe {

2. // insert code here

3. int x = 0;

4. System.out.println(7/x);

5. }

6. }


And given the following four code fragments:

I. public static void main(String[] args) {

II. public static void main(String[] args) throws Exception {

III. public static void main(String[] args) throws IOException {

IV. public static void main(String[] args) throws RuntimeException {


If the four fragments are inserted independently at line 4, which are true? (Choose all that apply.)

A. All four will compile and execute without exception

B. All four will compile and execute and throw an exception

C. Some, but not all, will compile and execute without exception

D. Some, but not all, will compile and execute and throw an exception

E. When considering fragments II, III, and IV, of those that will compile, adding a try/catch block around line 6 will cause compilation to fail


Answers:

Answer 1:

B and F are correct. Class One will compile (and issue a warning) using the 1.3 flag, and class Two will compile using the 1.4 flag.
A, C, D, and E are incorrect based on the above.

Answer 2:

B is correct. Once s3() throws the exception to s2(), s2() throws it to s1(), and no more of s2()’s code will be executed.
A, C, D, E, F, G, and H are incorrect based on the above.

Answer 3:

C and D are correct. Integer.parseInt can throw a NumberFormatException, and IllegalArgumentException is its superclass (i.e., a broader exception).
A, B, E, and F are not in NumberFormatException’s class hierarchy

Answer 4:

C, D, and E are correct statements.
A is incorrect. It is acceptable to use assertions to test the arguments of private methods. B is incorrect. While assertion errors can be caught, Sun discourages you from doing so.

Answer 5:

A, D, and F are correct. A is an example of the enhanced for loop. D and F are examples of the basic for loop.
B is incorrect because its operands are swapped. C is incorrect because the enhanced for must declare its first operand. E is incorrect syntax to declare two variables in a for statement.

Answer 6:

E is correct. There is no problem nesting try / catch blocks. As is normal, when an exception is thrown, the code in the catch block runs, then the code in the finally block runs.
A, B, C, D, and F are incorrect based on the above.

Answer 7:

C is correct. An overriding method cannot throw a broader exception than the method it’s overriding. Class CC4’s method is an overload, not an override.
A, B, D, and E are incorrect based on the above.

Answer 8:

D is correct. Did you catch the static initializer block? Remember that switches work on “fall-thru” logic, and that fall-thru logic also applies to the default case, which is used when no other case matches.
A, B, C, E, F, and G are incorrect based on the above.

Answer 9:

D and F are correct. Because i was not initialized, case 1 will throw an NPE. Case 0 will initiate an endless loop, not a stack overflow. Case 2’s downcast will not cause an exception.
A, B, C, E, and G are incorrect based on the above.

Answer 10:

D is correct. The basic rule for unlabeled continue statements is that the current iteration stops early and execution jumps to the next iteration. The last two continue statements are redundant!
A, B, C, E, and F are incorrect based on the above.

Answer 11:

H is correct. It’s true that the value of String s is 123 at the time that the divide-by-zero exception is thrown, but finally() is not guaranteed to complete, and in this case finally() never completes, so the System.out.println (S.O.P.) never executes.
A, B, C, D, E, F, and G are incorrect based on the above.

Answer 12:

C is correct. A break breaks out of the current innermost loop and continues. A labeled break breaks out of and terminates the current loops.
A, B, D, E, and F are incorrect based on the above.

Answer 13:

B and E are correct. First off, go() is a badly designed recursive method, guaranteed to cause a StackOverflowError. Since Exception is not a superclass of Error, catching an Exception will not help handle an Error, so fragment III will not complete normally. Only fragment II will catch the Error.
A, C, D, and F are incorrect based on the above.

Answer 14:

E is correct. When an assert statement has two expressions, the second expression must return a value. The only two-expression assert statement that doesn’t return a value is on line 9.
A, B, C, D, and F are incorrect based on the above

Answer 15:

D is correct. This is kind of sneaky, but remember that we’re trying to toughen you up for the real exam. If you’re going to throw an IOException, you have to import the java.io package or declare the exception with a fully qualified name.
E is incorrect because it’s okay to both handle and declare an exception. A, B, and C are incorrect based on the above.


Previous Chapter: Quick Review - Chapters 27 to 31

Next Chapter: Chapter 32 - String Class

Monday, January 3, 2011

Self Test – Chapters 1 to 5

We have successfully completed 5 chapters that have covered the basics of the java programming language (Of course, there is still a lot more basic stuff to come) Let us now try to assess how much knowledge we have gained in these chapters.

The following is a quick self-assessment (test). All questions are multiple choice (Like the original SCJP exam). Try to answer them based on what you have learnt in these previous 5 chapters. Don’t worry, I have given the answers to the questions too at the end of the chapter to let you judge how well you have learnt these topics.

Questions:

Question 1:

Which is true? (Choose all that apply.)
A. “X extends Y” is correct if and only if X is a class and Y is an interface
B. “X extends Y” is correct if and only if X is an interface and Y is a class
C. “X extends Y” is correct if X and Y are either both classes or both interfaces
D. “X extends Y” is correct for all combinations of X and Y being classes and/or interfaces

Question 2:

Which method names follow the JavaBeans standard? (Choose all that apply.)
A. addSize
B. getCust
C. deleteRep
D. isTrue
E. putDimensions

Question 3:

Which of the following are valid method declarations? Choose all that apply.
A. public abstract final String getName();
B. public final getName() { return “Anand”; }
C. public static void doSomething() {…}
D. public abstract String getName() { return “Anand” };

Question 4:

Given:
1. enum Animals {
2. DOG("woof"), CAT("meow"), FISH("burble");
3. String sound;
4. Animals(String s) { sound = s; }
5. }
6. class TestEnum {
7. static Animals a;
8. public static void main(String[] args) {
9. System.out.println(a.DOG.sound + " " + a.FISH.sound);
10. }
11. }

What is the result?

A. woof burble
B. Multiple compilation errors
C. Compilation fails due to an error on line 2
D. Compilation fails due to an error on line 3
E. Compilation fails due to an error on line 4
F. Compilation fails due to an error on line 9

Question 5:

Given:

1. public class Electronic implements Device
{ public void doIt() { } }
2.
3. abstract class Phone1 extends Electronic { }
4.
5. abstract class Phone2 extends Electronic
{ public void doIt(int x) { } }
6.
7. class Phone3 extends Electronic implements Device
{ public void doStuff() { } }
8.
9. interface Device { public void doIt(); }

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

A. Compilation succeeds
B. Compilation fails with an error on line 1
C. Compilation fails with an error on line 3
D. Compilation fails with an error on line 5
E. Compilation fails with an error on line 7
F. Compilation fails with an error on line 9

Question 6:

Given:

4. class Announce {
5. public static void main(String[] args) {
6. for(int __x = 0; __x < 3; __x++) ; 7. int #lb = 7; 8. long [] x [5]; 9. Boolean []ba[]; 10. enum Traffic { RED, YELLOW, GREEN }; 11. } 12. } What is the result? (Choose all that apply.) A. Compilation succeeds B. Compilation fails with an error on line 6 C. Compilation fails with an error on line 7 D. Compilation fails with an error on line 8 E. Compilation fails with an error on line 9 F. Compilation fails with an error on line 10 Question 7:

Given:

3. public class TestDays {
4. public enum Days { MON, TUE, WED };
5. public static void main(String[] args) {
6. for(Days d : Days.values() )
7. ;
8. Days [] d2 = Days.values();
9. System.out.println(d2[2]);
10. }
11. }

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

A. TUE
B. WED
C. The output is unpredictable
D. Compilation fails due to an error on line 4
E. Compilation fails due to an error on line 6
F. Compilation fails due to an error on line 8
G. Compilation fails due to an error on line 9

Question 8:

Given:

4. public class Frodo extends Hobbit {
5. public static void main(String[] args) {
6. Short myGold = 7;
7. System.out.println(countGold(myGold, 6));
8. }
9. }
10. class Hobbit {
11. int countGold(int x, int y) { return x + y; }
12. }

What is the result?

A. 13
B. Compilation fails due to multiple errors
C. Compilation fails due to an error on line 6
D. Compilation fails due to an error on line 7
E. Compilation fails due to an error on line 11

Question 9:

Which of the following statements are true? Choose all that apply

A. An abstract class can have final methods
B. A Final class can have abstract methods
C. A static method can access instance variables
D. An abstract class can have one or more methods that contain implementations

Question 10:

Given the code below, Guess the output:

1. public class test {
2. public String name = “Anand”;
3. public String getName() {
4. return this.name;
5. }
6. public static void main(String[] args) {
7. System.out.print (“Name is:” + name);
8. System.out.print(“Name is:” + getName());
9. }
10. }

A. Output Anand Anand gets printed in the console
B. Compilation error at line 7
C. Compilation error at line 8
D. Program compiles fine but fails at runtime

Answers:

Answer 1:

C is correct

A is incorrect because classes implement interfaces, they don’t extend them. B is incorrect because interfaces only “inherit from” other interfaces. D is incorrect based on the preceding rules.

Answer 2:

B and D use the valid prefixes ‘get’ and ‘is’. And hence they are correct

A is incorrect because ‘add’ can be used only with Listener methods. C and E are incorrect because ‘delete’ and ‘put’ are not standard JavaBeans name prefixes.

Answer 3:

C is a valid method declaration and hence is correct.

A is incorrect because a method cannot be both abstract and final. B is incorrect because the method’s return type “String” is missing. D is incorrect because an abstract method cannot have any code inside it.

Answer 4:

A is correct; enums can have constructors and variables.

B, C, D, E, and F are incorrect; these lines all use correct syntax

Answer 5:

A is correct; all of these are legal declarations.

B, C, D, E, and F are incorrect based on the above information

Answer 6:

C, D, and F are correct. Variable names cannot begin with a #, an array declaration can’t include a size without an instantiation, and enums can’t be declared within a method.

A, B, and E are incorrect based on the above information

Answer 7:

B is correct. Every enum comes with a static values() method that returns an array of the enum’s values, in the order in which they are declared in the enum

A, C, D, E, F, and G are incorrect based on the above information

Answer 8:

D is correct. The Short myGold is autoboxed correctly, but the countGold() method cannot be invoked from a static context

A, B, C, and E are incorrect based on the above information

Answer 9:

D is correct because an abstract class can have one or more methods that contain implementations (code)
A is correct because an abstract class can have final methods

B is incorrect because a final class cannot have abstract methods C is incorrect because a static method cannot access instance variables

Answer 10:

B & C are correct because the main method is static and it cannot access instance methods or variables.

A & D are incorrect because of the above mentioned reasons.

Previous Chapter - Quick Recap - Chapters 1 to 5

Next Chapter - Chapter 6: Object Oriented Concepts - Encapsulation
© 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