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

Friday, April 29, 2011

Self Test: Chapters 51 to 58

Questions

Question 1

Which design pattern has as its primary responsibility to decouple presentation and service tiers, and a central director?
A. Value Object
B. Composite View
C. Business Delegate
D. Model-View-Controller

Question 2

Which design pattern has as its primary responsibility to exchange data between tiers?
A. Value Object
B. Composite View
C. Business Delegate
D. Model-View-Controller

Question 3

Which design pattern has as its primary responsibility to abstract data sources and provide transparent access to the data in these sources?
A. Value Object
B. Data Access Object
C. Business Delegate
D. Model-View-Controller
E. None of the above

Question 4

Which design pattern has as its primary responsibility to isolate the presentation and the business tiers from each other by adding a director between the two, making it is easier to manage changes on either side?
A. Session Facade
B. Data Access Object
C. Business Delegate
D. Model-View-Controller
E. Aggregate Entity

Question 5

Which one of the following is most likely used for cache?
A. Value Object
B. Data Access Object
C. Business Delegate
D. Cache Object
E. Aggregate Entity

Question 6

Which design pattern acts as a switchboard, dispatching incoming requests to the correct resource?
A. Value Object
B. Data Access Object
C. Business Delegate
D. Front Controller

Question 7

Which design pattern is most likely to care about RDBMS, OODBMS, and flat files?
A. Value Object
B. Data Access Object
C. Business Delegate
D. Cache Object
E. Aggregate Entity

Question 8

Which design pattern does the following force most affect?
Persistent storage APIs vary between vendors, which causes a lack of uniform APIs to address the requirements for accessing storages.
A. Value Object
B. Data Access Object
C. Business Delegate
D. Cache Object
E. Aggregate Entity

Question 9

Which design pattern has as its primary role to provide control and protection for the business service?
A. Value Object
B. Data Access Object
C. Business Delegate
D. Cache Object
E. Aggregate Entity

Question 10

Which design pattern is most likely to be used as a proxy?
A. Business Delegate
B. Data Access Object
C. Model-View-Controller
D. Value Object

Question 11

Which design pattern reduces the number of remote network method calls required to obtain the attribute values from the entity beans?
A. Business Delegate
B. Data Access Object
C. Model-View-Controller
D. Value Object

Question 12

Which design pattern that usually is a good candidate to work with entity beans becomes less useful when a cache is used to persist data?
A. Business Delegate
B. Data Access Object
C. Model-View-Controller
D. Value Object

Answers

Question 1

D. The Model-View-Controller pattern has as its primary responsibility to decouple presentation and data/business logic tiers, by using a director or switchboard between them.

Question 2

A. The Value Object pattern has as its primary responsibility to exchange data between tiers. Although the Business Delegate and Model-View-Controller also do this, it isn't their primary responsibility.

Question 3

B. The Data Access Object pattern has as its primary responsibility to abstract data sources and provide transparent access to the data in these sources. The Business Delegate and Model-View-Controller may do so, but the Data Access Object always does this.

Question 4

D. The Model-View-Controller pattern has as its primary responsibility to minimize the impact of changing the client or business tier. Remember that this is a very high-level pattern, so it often uses other patterns.

Question 5

A. The Value Object pattern is most likely used for cache. Notice that its whole purpose is to collect data from somewhere far and bring it close in a neat package. The Data Access Object and Business Delegate often actually use a Value Object underneath. The Cache Object is fiction and the Aggregate Entity is not one of the four that you might see on the exam.

Question 6

D. The front controller pattern acts as a switch board, dispatching incoming requests to the correct resource.

Question 7

B. The Data Access Object design pattern is one that deals with RDBMS, OODBMS, excel, flat files, and more. This is pattern you use to isolate the access API from the actual data repository implementation. Value Object and Business Delegate don't do this. The other two patterns mentioned are distracters.

Question 8

B. The Data Access Object design pattern is affected most by varying persistent storage APIs due to different vendors and non-uniform APIs to address the requirements to access storages. Whenever you see the word persistent, think Data Access Object design pattern.

Question 9

C. The Business Delegate design pattern has as its primary role to provide control and protection for the business service. Although you can't just ignore the rest of the Question, normally when a Question focuses on the business service, think Business Delegate design pattern.

Question 10

A. The Business Delegate design pattern is most likely to be used as a proxy. Its whole purpose is being the mediator between a business service and the rest of the world, especially, but not limited to, clients. This is what proxies do, too.

Question 11

D. The Value Object design pattern reduces the number of remote network method calls required to obtain the attribute values from the entity beans. Although the four patterns in the answers do this, it's the main reason for using a Value Object.

Question 12

B. The Data Access Object design pattern is usually a good candidate to work with data that is remote or and costly to query often, but becomes a bad choice with container-managed persistence. This is tricky because the container often, but not always, will persist data as a primary function.

Previous Chapter: Quick Recap - Chapters 51 to 58

Next Chapter: Chapter 59 - Exam Preparation Tips

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

Thursday, April 28, 2011

Self Test: Chapters 44 & 45

Questions

Question 1:

Which three of the following is part of the Tag Library Descriptor element?
A. namespace
B. name
C. tag handler class
D. tag attributes

Question 2:

Which two of the following attributes are not part of the taglib directive?
A. url
B. uri
C. prefix
D. name

Question 3:

Which file does the following DTD element definition apply to: ?
A. web.init
B. YourTagHandler.java
C. YourTagLibraryDefinition.tld
D. web.xml

Question 4:

Which of the following is the Web Deployment Descriptor, the purpose of which is to configure a Web application?
A. web.xml
B. web.init
C. YourTagLibraryDefinition.tld
D. YourTagHandler.java

Question 5:

Which three of the following files is part of a simple tag library?
A. web.xml
B. web.init
C. YourTagLibraryDefinition.tld
D. YourTagHandler.java

Question 6:

How do you declare a tag library within a JSP page?
A. You use a declare scriptlet.
B. You use a taglib directive.
C. You use a unique variable.
D. You use the path to the tag handler.

Question 7:

Which two of the following options apply to an empty custom tag?
A. Specified in the web.xml Web component descriptor.
B. Specified in the tag library handler.
C. < libraryPrefix : handlerName / >
D. A custom tag with no body.

Question 8:

What does the container use to validate a custom tag in a JSP page?
A. web.xml
B. Xerces
C. Xmlspy
D. Tag Library Descriptor

Question 9:

Which interface does the doStartTag() belong to?
A. TagSupport
B. TagProcess
C. Tag
D. TagStart

Question 10:

What does the container do during translation when it encounters a custom tag in a JSP page?
A. It converts the XML notation into Java calls, inserted into the Java that resulted from the page translation.
B. It passes it to the tag handler.
C. It converts it to scriptlets.
D. It adds the code to the output stream.

Answers:

Question 1:

B, C, and D. All of these are part of the Tag Library Descriptor element except option A. Also, you need a JSP file such as yourJSP.jsp.

Question 2:

A and D. The taglib directive only takes two attributes, uri and prefix.

Question 3:

D. The taglib element is used to describe a JSP tag library. The syntax for the taglib element in the web.xml file is < ! ELEMENT taglib (taglib-uri, taglib-location) >. The required taglib-location element contains the location and the taglib-uri element describes a URI identifying a Tag Library used in the Web application. You use the URI to give a tag library a unique address or namespace.

Question 4:

A. The web.xml file is used as the deployment descriptor. The deployment descriptor defines the elements and configuration information of a Web application. In it you define elements to support the Web application within a servlet container, including ServletContext init parameters, session configuration, and servlet declarations..”
Note: We will be covering Deployment & Deployment Descriptions shortly. So for now, just know this about the web.xml file.

Question 5:

A, C, and D. All of these files could be used as part of your tag library except option B because web.init is not a file defined by the specification. Also, you need a JSP file such as yourJSP.jsp.

Question 6:

B. The taglib directive creates a reference to the prefix. The prefix tells the container which library you want. Once that is done, you can use a custom tag, so called because it is your tag, not a standard one that came shipped with the container.

Question 7:

C and D. C uses correct XML notation to refer to an empty tag. By convention, we call a custom tag in a JSP page without a body an empty custom tag.

Question 8:

D. The Tag Library Descriptor (TLD) is used by a Web container to validate the tags in a JSP page.

Question 9:

A. Your tag handler is a class that extends the TagSupport abstract class if it has doStartTag() and doEndTag() methods.

Question 10:

A. The container will combine the JSP code and tag library into one Java source file. The container converts your custom tags into Java calls during the JSP page translation.

Previous Chapter: Quick Recap - Chapters 44 & 45

Next chapter: chapter 46 - JSP API

Tuesday, April 12, 2011

Self Test: Chapters 31 to 37

Questions:

Question 1:

Assume the custom tag is GLOOP and the prefix is TWONG. Which of the following is the syntax for an empty custom tag?
A. < TWONG : GLOOP / >
B. < GLOOP : TWONG / >
C. < GLOOP : TWONG > < / GLOOP : TWONG >
D. < TWONG : GLOOP > < / TWONG : GLOOP >

Question 2:

Which design pattern did the designers of JSP use to provide centralized dispatching of requests via a controller servlet?
A. Model-View-Controller
B. Facade
C. Server-Client
D. Publish-Subscribe

Question 3:

Which of the following options is a valid declaration?
A. < % ! String name="Rocky" % >
B. < % ! String name="Rocky"; % >
C. < % String name="Anand" % >
D. < % public String name="Anand"; % >

Question 4:

The following are the contents of comment.jsp:
1 < html >
2 < head > < title >Two Comments< / title > < / head >
3 < body >
4 < % - - JSP Comment - - % >
5 < ! - - HTML Comment - - >
6 < / body >
7 < / html >

Which option best describes what happens upon executing index.jsp?
A. A fatal error occurs because the body is empty.
B. Line 5 (but not 4) gets added to the output stream.
C. 4 (but not 5) gets added to the output stream.
D. All seven lines get added to the output stream.

Question 5:

The following are the contents of request_parameter.jsp:
< html >
< head >
< title >Retrieve Request Parameter< / title >
< / head >
< body >
< % String customerName = request.getParameter("customer"); % >
< p >
The customer is < % = customerName % >
< / body >
< / html >

Assuming the www.que.com server is responding correctly and the page path is valid, what displays in the browser if the user types http://www.quepublishing.com/customer/request_parameter.jsp?customer=Anand?
A. The customer is
B. A blank page.
C. The customer is Anand
D. An error page.

Question 6:

The following are the contents of welcomeHeader.inc:
< h1 >Welcome to our drive through

Java coding service!< / h1 >

The following are the contents of index.jsp:
< html >
< head > < title >Java Quick Code< / title > < / head >
< body >
< % String file="welcomeHeader.inc"; % >
< %@ include file="file" % > < p >
We are the best J2EE Programmers.
< / body >
< / html >

Which option best describes what happens upon executing comment.jsp?
A. An error occurs.
B. The page displays including the welcome header.
C. The page displays excluding the welcome header.
D. The page displays, but replaces the welcome header with the words welcomeHeader.inc.

Question 7:

Which of the following options is a JSP implicit object?
A. objRequest
B. Request.send
C. request
D. servlet

Question 8:

Which of the following options is not a JSP implicit object?
A. out
B. in
C. response
D. page

Question 9:

Which of the following will not compile (assume < x : tag > is a valid custom tag that is declared for the current JSP file)?
A. < % String employees = "Rocky"+"Anand"; % >
B. < x : tag value='< % = "5" % > ' />
C. < x : tag value="< % = "hi!" % > " />
D. < x : tag value='< % = "Joe said \\"" +statement+ "\\"." % > '/ >

Question 10:

Which among the following objects is the best choice to share information between users?
A. application
B. page
C. request
D. session

Question 11:

Which among the following objects is the best choice to share information between pages for a single user?
A. application
B. page
C. request
D. session

Question 12:

Which of the following objects is used to share information between pages using the setAttribute and getAttribute methods?
A. application
B. page
C. request
D. session

Question 13:

Which option is a valid page directive?
A. < % @ page language="java" import="com.myco.*" buffer="16kb" % >
B. < % @ page import="com.myco.class" buffer="16" % >
C. < % @ page language="javaScript" buffer="16" % >
D. < % @ page import='com.myco.*' buffer='16' % >

Question 14:

Which option indicates whether the current JSP page is intended to be the URL target of another JSP page's error page?
A. < % @ page isErrorPage="true" % >
B. < % @ page isErrorPage="/messages/errorPage.jsp" % >
C. < % @ page errorPage="true" % >
D. < % @ page errorPage="/messages/errorPage.jsp" % >

Question 15:

Which option defines a URL to a resource to which any Java programming language Throwable object(s) thrown but not caught by the page implementation are forwarded for error processing?
A. < % @ page isErrorPage="true" % >
B. < % @ page isErrorPage="/messages/errorPage.jsp" % >
C. < % @ page errorPage="true" % >
D. < % @ page errorPage="/messages/errorPage.jsp" % >

Answers:

Answer 1:

A, D. These use the correct syntax for an empty custom tag of GLOOP having the prefix TWONG.

Answer 2:

A. The Model-View-Controller design pattern is the one the designers of JSP use to provide centralized dispatching of requests via a controller servlet.

Answer 3:

B. This is a valid declaration. Be careful about the semicolon, which is required in a declaration.

Answer 4:

B. Remember that the JSP Comment is ignored by the compiler. However, the HTML Comment is passed through. Even though the browser doesn't display content in response to it, the JSP container does add it to the output stream.

Answer 5:

C. The declaration is correct. The customer is < % = customerName % > fragment becomes The customer is Anand.

Answer 6:

A. The following is wrong: < % @ include file="file" % >. It should have been < % @ include file="welcomeHeader.inc" % >. Note that "file" in quotes literally means you were asking the system to include a file whose filename is “file.”

Answer 7:

C. Option C is correct if the request is the only implicit object.

Answer 8:

B. All of these are JSP implicit objects except the fictitious in.

Answer 9:

C. All of these will compile except C, because there are quotes within quotes. It should have been < x : tag value="<%= \"hi!\" %>" / >.

Answer 10:

A. The same application object is accessible by all users.

Answer 11:

D. The session object is the best choice for sharing information between pages for a single user. Users can see their own session object, but can't see others' session objects.

Answer 12:

A, C, and D. Both the application and the session objects can be used to share information between pages with the setAttribute and setAttribute methods. Either A or D is correct. Option C is also valid because you can share attributes from a “master” page to an “included” page.

Answer 13:

A. Only A is correct. All the others are syntactically wrong. Notice the kb requirement on the buffer attribute.

Answer 14:

A. This is the isErrorPage attribute of the page directive. Another page can now, but doesn't have to, use this page as an error page.

Answer 15:

D. The errorPage attribute of the page directive defines a URL to a resource to which any Java programming language Throwable object(s) thrown but not caught by the page implementation are forwarded for error processing.

Previous Chapter: Quick Recap - Chapters 31 to 37

Next Chapter: Chapter 38 - Introduction to JavaBeans

Thursday, March 24, 2011

Self Test: Chapters 20 to 24

Questions

Question 1:
Which of the following two methods are used to track or store the session ID?
A. encodeURL()
B. sessionTrack()
C. sessionUpdate()
D. encodeRedirectURL()

Question 2:
How do you create a session?
A. createSession()
B. makeSession()
C. callSession()
D. getSession()

Question 3:
How do you retrieve a session object across multiple requests to the same or different servlets within the same WebApp?
A. retrieveSession()
B. findSession()
C. getSession()
D. callSession()

Question 4:
How do you store objects into a session object?
A. put(String, Object)
B. setAttribute(String, Object)
C. addObject(Object)
D. putObject(String, Object)

Question 5:
How do you know if a session is alive?
A. Look in the cookies.
B. getSession(false)
C. isSessionAlive()
D. Exception thrown if you try to create one when one already exists.

Question 6:
How do you destroy or expunge a session?
A. Session.isAlive = false;
B. Session.isNew(false)
C. invalidate()
D. removeSession()

Question 7:
How do you know when a particular object is added to a session?
A. getCreationTime()
B. getAttribute(Date)
C. Session.attributeDate(index)
D. attributeAdded(HttpSessionBindingEvent)

Question 8:
How do you know when a session is created?
A. sessionDidActivate(HttpSessionEvent)
B. You check with sessionIsAlive().
C. You only know when it is killed.
D. When the SESSIONID becomes null.


Question 9:
How do you know when a session is destroyed?
A. sessionBound(HttpSessionEvent)
B. sessionFinalize(HttpSessionEvent)
C. sessionWillPassivate(HttpSessionEvent)
D. valueBound(HttpSessionEvent)

Question 10:
Given that URL-rewriting must be used for session management, identify the query string attribute used when URL-rewriting.
A. sessionid
B. servletid
C. jsessionid
D. containerid

Question 11:
Where are cookies stored?
A. On the server.
B. In web.xml.
C. On the client.
D. In HTML.


Question 12:
Where are session IDs stored?
A. In cookies.
B. In HTML form fields.
C. In query strings.
D. Session IDs are not stored.

Question 13:
Which two technique can be used by a Web container to manage session IDs?
A. deleteAttribute(String)
B. attributeRemove(String)
C. removeAttribute(String)
D. setAttribute(null)

Question 14:
How do you get the date stamp of the session's creation?
A. getCreationTime()
B. sessionDate()
C. getSession(Date)
D. From the response object.

Answers:

Answer 1: A and D. You append the session ID in URLs by calling the response's encodeURL(URL) (or encodeRedirectURL()) method on all URLs returned by a servlet. This method includes the session ID in the URL only if cookies are disabled; otherwise, it returns the URL unchanged.

Answer 2: D. To get the current session in a servlet, you call the getSession() method of HttpServletRequest. You have one parameter to think about. If you don't provide a boolean, this method will create a session if one doesn't exist. The same behavior occurs when you provide a true boolean. However, the container will not create a new session if it doesn't already exist when you use a false argument.

Answer 3: C. This is the same question as #2, but stated differently. You call the getSession() method of HttpServletRequest to create a session.

Answer 4: B. You use the setAttribute(java.lang.String name, java.lang.Object value) method to add objects to a session. The other methods listed are incorrect.

Answer 5: B. This is somewhat difficult. You use getSession(false) method and test for a null result.
HttpSession session = request.getSession(false);
if (session = null) {
//do something about lacking a session
}

If you get a null then the session is alive. You can also check for the session ID with getId(), which returns the id of the session as a String representing the unique identifier assigned to this session. If the session is dead, it will return a null.

Answer 6: C. Only the invalidate() method can destroy a session. Notice that the session can't be referenced after this method has been called. A and D are incorrect and B isn't used properly.

Answer 7: D. The attributeAdded(HttpSessionBindingEvent se) method gets called as the notification that an attribute has been added to a session. The other options are incorrect.

Answer 8: A. The sessionDidActivate(HttpSessionEvent) method is called when the session has just been activated. The other options are incorrect.

Answer 9: C. The sessionWillPassivate(HttpSessionEvent) method is called as the notification that the session is about to be passivated. This is strange language so don't feel bad. They should have used another term such as alive or destroy. A and B are incorrect. D (valueBound(HttpSessionBindingEvent)) is the notification to the object that it is being bound to a session, but doesn't tell you about the session being destroyed.

Answer 10: C. The jsessionid is the parameter that is appended to URLs by the encodeURL() method when cookies are not available to maintain state. The other options are incorrect.

Answer 11: C. Cookies are stored on the client only.

Answer 12: A and C. Session IDs are stored in cookies on the client machine. If cookies are turned off, session IDs can be stored in query strings.

Answer 13: C. The removeAttribute(java.lang.String name) method removes an attribute. It deletes it from the session object. The other options are incorrect.

Answer 14: A. The getCreationTime() method returns a long containing the date stamp of creation. The other options are incorrect.

Previous Chapter: Quick Recap - Chapters 20 to 24

Next Chapter: Chapter 25 - Introduction to Servlet Exception Handling

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

Tuesday, March 1, 2011

Self Test: Chapters 1 to 5

Let us now test what we have learnt so far in our SCWCD exam preparation series.

Questions:

Question 1: What language is used to write servlets and JSP?

Question 2: What is the servlet life cycle and who manages it?

Question 3: What protocol do servlets and JSP use to communicate with clients?

Question 4: What is the relationship between servlets and JSP?

Question 5: What is the benefit of using a Servlet instead of CGI?

Answers:

Answer 1: Servlets are written in the Java language. JSPs on the other hand use a combination of HTML and Java. Eventually JSPs are converted into a pure Java servlet.

Answer 2: The servlet life cycle refers to the loading, initialization, invoking, and killing of a servlet. The container manages this life cycle

Answer 3: Servlets use the HTTP protocol

Answer 4: JSPs are converted to servlets. First, the JSP source is parsed and a Java source file is generated. Then this source is compiled into a Servlet

Answer 5: A CGI spawns a heavyweight process for every request it receives. It is both resource intensive and not scalable. Whereas, a Servlet spawns only a lightweight thread for every request it receives. Hence it is faster than CGI as well as much more scalable when compared to CGI.

Previous Chapters: Quick Recap - Chapters 1 to 5

Next Chapter: Chapter 6 - Servlet Handling of Http Requests

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

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
© 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