Você está na página 1de 53

# What is a output comment?

Answer: A comment that is sent to the client in the viewable page source.The JSP
engine handles an output comment as uninterpreted HTML text, returning the comm
ent in the HTML output sent to the client.You can see the comment by viewing the
page source from your Web browser.
JSP Syntax:
!-- comment [ %= expression % ] --
# What is a Hidden Comment?
Answer: A comments that documents the JSP page but is not sent to the client.The
JSP engine ignores a hidden comment, and does not process any code within hidde
n comment tags.A hidden comment is not sent to the client, either in the display
ed JSP page or the HTML page source.
The hidden comment is useful when you want to hide or "comment out" part of your
JSP page.You can use any characters in the body of the comment except the closi
ng --% combination.If you need to use --% in your comment, you can escape it by ty
ping --%\
JSP Syntax:
%-- comment --%
Examples:
%@ page language="java" %
html
head
title A Hidden Comment /title
/head
body
%-- This comment will not be visible to the colent in the page source --%
/body
/html
# What is a Expression?
Answer: An expression tag contains a scripting language expression that is evalu
ated, converted to a String, and inserted where the expression appears in the JS
P file.Because the value of an expression is converted to a String, you can use
an expression within text in a JSP file.Like
%= someexpression % %= (new java.util.Date()).toLocaleString() %
You cannot use a semicolon to end an expression
# What is a Declaration?
Answer: A declaration declares one or more variables or methods for use later in
the JSP source file.A declaration must contain at least one complete declarativ
e statement.You can declare any number of variables or methods within one declar
ation tag, as long as they are separated by semicolons.The declaration must be v
alid in the scripting language used in the JSP file.
%! somedeclarations %
%! int i = 0; %
%! int a, b, c; %
# What is a Scriptlet?
Answer: A scriptlet can contain any number of language statements, variable or m
ethod declarations, or expressions that are valid in the page scripting language
.Within scriptlet tags, you can:
* Declare variables or methods to use later in the file.
* Write expressions valid in the page scripting language.
* Use any of the JSP implicit objects or any object declared with a jsp:useBe
an tag.You must write plain text, HTML-encoded text, or other JSP tags outside th
e scriptlet.Scriptlets are executed at request time, when the JSP engine process
es the client request.If the scriptlet produces output, the output is stored in
the out object, from which you can display it.
# What are implicit objects? List them?
Answer: Certain objects that are available for the use in JSP documents without
being declared first.These objects are parsed by the JSP engine and inserted int
o the generated servlet.
The implicit objects are listed below:
* Request
* Response
* PageContext
* Session
* Application
* Out
* Config
* Page
* Exception
# Difference between forward and sendRedirect?
Answer: When you invoke a forward request, the request is sent to another resour
ce on the server, without the client being informed that a different resource is
going to process the request.This process occurs completly with in the web cont
ainer.When a sendRedirtect method is invoked, it causes the web container to ret
urn to the browser indicating that a new URL should be requested.Because the bro
wser issues a completly new request any object that are stored as request attrib
utes before the redirect occurs will be lost.This extra round trip a redirect is
slower than forward.
# What are the different scope valiues for the jsp:useBean ?
Answer: The different scope values for jsp:useBean are:
* Page
* Request
* Session
* Application
# Explain the life-cycle mehtods in JSP?
Answer: The generated servlet class for a JSP page implements the HttpJspPage in
terface of the javax.servlet.jsp package.Hte HttpJspPage interface extends the J
spPage interface which inturn extends the Servlet interface of the javax.servlet
package.the generated servlet class thus implements all the methods of the thes
e three interfaces.
The JspPage interface declares only two mehtods:
* jspInit()
* jspDestroy()
However the JSP specification has provided the HttpJspPage interfaec specificall
y for the JSp pages serving HTTP requests.This interface declares one method _js
pService().The jspInit()- The container calls the jspInit() to initialize te ser
vlet instance.It is called before any other method, and is called only once for
a servlet instance.The _jspservice()- The container calls the _jspservice() for
each request, passing it the request and the response objects.The jspDestroy()-
The container calls this when it decides take the instance out of service.It is
the last method called n the servlet instance.
# How do I prevent the output of my JSP or Servlet pages from being cached by th
e browser?
Answer: You will need to set the appropriate HTTP header attributes to prevent t
he dynamic content output by the JSP page from being cached by the browser.Just
execute the following scriptlet at the beginning of your JSP pages to prevent th
em from being cached at the browser.
You need both the statements to take care of some of the older browser versions.
%response.setHeader("Cache-Control","no-store"); //HTTP 1.1response.setHeader("Pr
agma\","no-cache"); //HTTP 1.0response.setDateHeader ("Expires", 0); //prevents
caching at the proxy server%

# How does JSP handle run-time exceptions?


Answer: You can use the errorPage attribute of the page directive to have uncaug
ht run-time exceptions automatically forwarded to an error processing page.
# How can I implement a thread-safe JSP page? What are the advantages and Disadv
antages of using it?
Answer: You can make your JSPs thread-safe by having them implement the SingleTh
readModel interface.This is done by adding the directive %@ page isThreadSafe="fa
lse" % within your JSP page.With this, instead of a single instance of the servle
t generated for your JSP page loaded in memory, you will have N instances of the
servlet loaded and initialized, with the service method of each instance effect
ively synchronized.You can typically control the number of instances (N) that ar
e instantiated for all servlets implementing SingleThreadModel through the admin
screen for your JSP engine.More importantly, avoid using the tag for variables.
If you do use this tag, then you should set isThreadSafe to true, as mentioned a
bove.Otherwise, all requests to that page will access those variables, causing a
nasty race condition.SingleThreadModel is not recommended for normal use.There
are many pitfalls, including the example above of not being able to use %! % .You s
hould try really hard to make them thread-safe the old fashioned way: by making
them thread-safe.
# How do I use a scriptlet to initialize a newly instantiated bean?
Answer: A jsp:useBean action may optionally have a body.If the body is specified
, its contents will be automatically invoked when the specified bean is instanti
ated.Typically, the body will contain scriptlets or jsp:setProperty tags to init
ialize the newly instantiated bean, although you are not restricted to using tho
se alone.
# How can I prevent the word "null" from appearing in my HTML input text fields
when I populate them with a resultset that has null values?
Answer: You could make a simple wrapper function, like
%!String blanknull(String s) {return (s == null) ? \"\" : s;}%
then use it inside your JSP form, like
input type="text" name="lastName" value=" %=blanknull(lastName)% "
# What's a better approach for enabling thread-safe servlets and JSPs? SingleThr
eadModel Interface or Synchronization?
Answer: Although the SingleThreadModel technique is easy to use, and works well
for low volume sites, it does not scale well.If you anticipate your users to inc
rease in the future, you may be better off implementing explicit synchronization
for your shared data.The key however, is to effectively minimize the amount of
code that is synchronzied so that you take maximum advantage of multithreading.A
lso, note that SingleThreadModel is pretty resource intensive from the server\'s
perspective.The most serious issue however is when the number of concurrent req
uests exhaust the servlet instance pool.In that case, all the unserviced request
s are queued until something becomes free - which results in poor performance.Si
nce the usage is non-deterministic, it may not help much even if you did add mor
e memory and increased the size of the instance pool.
# What makes J2EE suitable for distributed multitiered Applications?
Answer: The J2EE platform uses a multitiered distributed application model.Appli
cation logic is divided into components according to function, and the various a
pplication components that make up a J2EE application are installed on different
machines depending on the tier in the multitiered J2EE environment to which the
application component belongs.
The J2EE application parts are:
* Client-tier components run on the client machine.
* Web-tier components run on the J2EE server.
* Business-tier components run on the J2EE server.
* Enterprise information system (EIS)-tier software runs on the EIS server.
# What is J2EE?
Answer: J2EE is an environment for developing and deploying enterprise applicati
ons.The J2EE platform consists of a set of services, application programming int
erfaces (APIs), and protocols that provide the functionality for developing mult
itiered, web-based applications.
# What are the components of J2EE application?
Answer: A J2EE component is a self-contained functional software unit that is as
sembled into a J2EE application with its related classes and files and communica
tes with other components.
The J2EE specification defines the following J2EE components:
* Application clients and applets are client components.
* Java Servlet and JavaServer Pages technology components are web components
.
* Enterprise JavaBeans components (enterprise beans) are business components
.
* Resource adapter components provided by EIS and tool vendors.
# What do Enterprise JavaBeans components contain?
Answer: Enterprise JavaBeans components contains Business code, which is logic t
hat solves or meets the needs of a particular business domain such as banking, r
etail, or finance, is handled by enterprise beans running in the business tier.A
ll the business code is contained inside an Enterprise Bean which receives data
from client programs, processes it (if necessary), and sends it to the enterpris
e information system tier for storage.An enterprise bean also retrieves data fro
m storage, processes it (if necessary), and sends it back to the client program.
# Is J2EE application only a web-based?
Answer: No, It depends on type of application that client wants.A J2EE applicati
on can be web-based or non-web-based.if an application client executes on the cl
ient machine, it is a non-web-based J2EE application.The J2EE application can pr
ovide a way for users to handle tasks such as J2EE system or application adminis
tration.It typically has a graphical user interface created from Swing or AWT AP
Is, or a command-line interface.When user request, it can open an HTTP connectio
n to establish communication with a servlet running in the web tier.
# Are JavaBeans J2EE components?
Answer: No.JavaBeans components are not considered J2EE components by the J2EE s
pecification.They are written to manage the data flow between an application cli
ent or applet and components running on the J2EE server or between server compon
ents and a database.JavaBeans components written for the J2EE platform have inst
ance variables and get and set methods for accessing the data in the instance va
riables.JavaBeans components used in this way are typically simple in design and
implementation, but should conform to the naming and design conventions outline
d in the JavaBeans component architecture.
# Is HTML page a web component?
Answer: No.Static HTML pages and applets are bundled with web components during
application assembly, but are not considered web components by the J2EE specific
ation.Even the server-side utility classes are not considered web components, ei
ther.
# What can be considered as a web component?
Answer: J2EE Web components can be either servlets or JSP pages.Servlets are Jav
a programming language classes that dynamically process requests and construct r
esponses.JSP pages are text-based documents that execute as servlets but allow a
more natural approach to creating static content.
# What is the container?
Answer: Containers are the interface between a component and the low-level platf
orm specific functionality that supports the component.Before a Web, enterprise
bean, or application client component can be executed, it must be assembled into
a J2EE application and deployed into its container.
# What are container services?
Answer: A container is a runtime support of a system-level entity.Containers pro
vide components with services such as:
* lifecycle management
* security
* deployment
* threading
# What is the web container?
Answer: Servlet and JSP containers are collectively referred to as Web container
s.It manages the execution of JSP page and servlet components forJ2EE applicatio
ns.Web components and their container run on the J2EE server.
# What is Enterprise JavaBeans (EJB) container?
Answer: It manages the execution of enterprise beans for J2EE applications. Ente
rprise beans and their container run on the J2EE server.
# What is Applet container?
Answer: IManages the execution of applets.Consists of a Web browser and Java Plu
gin running on the client together.
# How do we package J2EE components?
Answer: J2EE components are packaged separately and bundled into a J2EE applicat
ion for deployment.Each component, its related files such as GIF and HTML files
or server-side utility classes, and a deployment descriptor are assembled into a
module and added to theJ2EE application.A J2EE application is composed of one o
r more enterprise bean,Web, or application client component modules.The final en
terprise solution can use oneJ2EE application or be made up of two or more J2EE
applications, depending on design requirements.A J2EE application and each of it
s modules has its own deployment descriptor.A deployment descriptor is an XML do
cument with an.xml extension that describes a components deployment settings.
# What is a thin client?
Answer: A thin client is a lightweight interface to the application that does no
t have such operations like query databases, execute complex business rules, or
connect to legacy applications.
# What are types of J2EE clients?
Answer: Following are the types of J2EE clients:
* Applets
* Application clients
* Java Web Start-enabled rich clients, powered by Java Web Start technology.
* Wireless clients, based on Mobile Information Device Profile (MIDP) techno
logy.
# What is deployment descriptor?
Answer: A deployment descriptor is an Extensible Markup Language (XML) text-base
d file with an.xml extension that describes a components deploymentsettings.A J2
EE application and each of its modules has its own deployment descriptor.For exa
mple, an enterprise bean module deployment descriptor declares transaction attri
butes and security authorizations for an enterprise bean.Because deployment desc
riptor information is declarative, it can be changed without modifying the bean
source code.At run time, the J2EE server reads the deployment descriptor and act
s upon the component accordingly.
# What is the EAR file?
Answer: An EAR file is a standard JAR file with an.ear extension, named from Ent
erprise ARchive file.A J2EE application with all of its modules is delivered in
EAR file.
# What is JTA and JTS?
Answer: JTA is the abbreviation for the Java Transaction API.JTS is the abbrevia
tion for the Jave Transaction Service.JTA provides a standard interface and allo
ws you to demarcate transactions in a manner that is independent of the transact
ion manager implementation.TheJ2EE SDK implements the transaction manager with J
TS.But your code doesnt call the JTS methods directly.Instead, it invokes the JT
A methods, which then call the lower-level JTS routines.Therefore, JTA is a high
level transaction interface that your application uses to control transaction.a
nd JTS is a low level transaction interface and ejb uses behind the scenes (clie
nt code doesnt directly interact with JTS.It is based on object transaction serv
ice(OTS) which is part of CORBA.
# What is JAXP?
Answer: JAXP stands for Java API for XML.XML is a language for representing and
describing text-based data which can be read and handled by any program or tool
that uses XML APIs.It provides standard services to determine the type of an arb
itrary piece of data, encapsulate access to it, discover the operations availabl
e on it, and create the appropriate JavaBeans component to perform those operati
ons.
# What is J2EE Connector?
Answer: The J2EE Connector API is used by J2EE tools vendors and system integrat
ors to create resource adapters that support access to enterprise information sy
stems that can be plugged into any J2EE product.Each type of database or EIS has
a different resource adapter.Note: A resource adapter is a software component t
hat allows J2EE application components to access and interact with the underlyin
g resource manager.Because a resource adapter is specific to its resource manage
r, there is typically a different resource adapter for each type of database or
enterprise information system.
# What is JAAP?< p>Ans:The Java Authentication and Authorization Service (JAAS)
provides a way for a J2EE application to authenticate and authorize a specific u
ser or group of users to run it.It is a standard Pluggable Authentication Module
(PAM) framework that extends the Java 2 platform security architecture to suppo
rt user-based authorization.
# What is Java Naming and Directory Service?
Answer: The JNDI provides naming and directory functionality.It provides applica
tions with methods for performing standard directory operations, such as associa
ting attributes with objects and searching for objects using their attributes.Us
ing JNDI, a J2EE application can store and retrieve any type of named Java objec
t.Because JNDI is independent of any specific implementations, applications can
use JNDI to access multiple naming and directory services, including existing na
ming and directory services such as LDAP, NDS, DNS, and NIS.
# What is Struts?
Answer: A Web page development framework.Struts combines Java Servlets, Java Ser
ver Pages, custom tags, and message resources into a unified framework.It is a c
ooperative, synergistic platform, suitable for development teams, independent de
velopers, and everyone between.
# How is the MVC design pattern used in Struts framework?
Answer: In the MVC design pattern, application flow is mediated by a central Con
troller.The Controller delegates requests to an appropriate handler.The handlers
are tied to a Model, and each handler acts as an adapter between the request an
d the Model.The Model represents, or encapsulates, an applications business logi
c or state.Control is usually then forwarded back through the Controller to the
appropriate View.The forwarding can be determined by consulting a set of mapping
s, usually loaded from a database or configuration file.This provides a loose co
upling between the View and Model, which can make an application significantly e
asier to create and maintain.Controller: Servlet controller which supplied by St
ruts itself; View: what you can see on the screen, a JSP page and presentation c
omponents; Model: System state and a business logic JavaBeans.
# What is the Java 2 Platform, Enterprise Edition (J2EE)?
Answer: The Java 2 Platform, Enterprise Edition (J2EE) is a set of coordinated s
pecifications and practices that together enable solutions for developing, deplo
ying, and managing multi-tier server-centric applications.Building on the Java 2
Platform, Standard Edition (J2SE), the J2EE platform adds the capabilities nece
ssary to provide a complete, stable, secure, and fast Java platform to theenterp
rise level.It provides value by significantly reducing the cost and complexity o
f developing and deploying multi-tier solutions, resulting in services that can
be rapidly deployed and easily enhanced.
# What are the main benefits of the J2EE platform?
Answer: The J2EE platform provides the following:
* Complete Web services support:The J2EE platform provides a framework for d
eveloping and deploying web services on the Java platform.The Java API for XML-b
ased RPC (JAX-RPC) enables Java technology developers to develop SOAP based inte
roperable and portable web services.Developers use the standard JAX-RPC programm
ing model to develop SOAP based web service clients and endpoints.A web service
endpoint is described using a Web Services Description Language (WSDL) document.
JAX-RPC enables JAX-RPC clients to invoke web services developed across heteroge
neous platforms.In a similar manner, JAX-RPC web service endpoints can be invoke
d by heterogeneous clients.For more info, see http://java.sun.com/webservices/.
* Faster solutions delivery time to market:The J2EE platform uses "container
s" to simplify development.J2EE containers provide for the separation of busines
s logic from resource and lifecycle management, which means that developers can
focus on writing business logic -- their value add -- rather than writingenterpr
ise infrastructure.For example, the Enterprise JavaBeans (EJB) container (implem
ented by J2EE technology vendors) handles distributed communication, threading,
scaling, transaction management, etc.Similarly, Java Servlets simplify web devel
opment by providing infrastructure for component, communication, and session man
agement in a web container that is integrated with a web server.
* Freedom of choice:J2EE technology is a set of standards that many vendors
can implement.The vendors are free to compete on implementations but not on stan
dards or APIs.Sun supplies a comprehensive J2EE Compatibility Test Suite (CTS) t
o J2EE licensees.The J2EE CTS helps ensure compatibility among the application v
endors which helps ensure portability for the applications and components writte
n for the J2EE platform.The J2EE platform brings Write Once, Run Anywhere (WORA)
to the server.
* Simplified connectivity:J2EE technology makes it easier to connect the app
lications and systems you already have and bring those capabilities to the web,
to cell phones, and to devices.J2EE offers Java Message Service for integrating
diverse applications in a loosely coupled, asynchronous way.The J2EE platform al
so offers CORBA support for tightly linking systems through remote method calls.
In addition, the J2EE platform has J2EE Connectors for linking toenterprise info
rmation systems such as ERP systems, packaged financial applications, and CRM ap
plications.
* By offering one platform with faster solution delivery time to market, fre
edom of choice, and simplified connectivity, the J2EE platform helps IT by reduc
ing TCO and simultaneously avoiding single-source for theirenterprise software n
eeds.
# Can the J2EE platform interoperate with other WS-I implementations?
Answer: Yes, if the other implementations are WS-I compliant.
# What technologies are included in the J2EE platform?
Answer: The primary technologies in the J2EE platform are: Java API for XML-Base
d RPC (JAX-RPC), JavaServer Pages, Java Servlets, Enterprise JavaBeans component
s, J2EE Connector Architecture, J2EE Management Model, J2EE Deployment API, Java
Management Extensions (JMX), J2EE Authorization Contract for Containers, Java A
PI for XML Registries (JAXR), Java Message Service (JMS), Java Naming and Direct
ory Interface (JNDI), Java Transaction API (JTA), CORBA, and JDBC data access AP
I.
# What is the relationship of the Apache Tomcat open-source application server t
o the J2EE SDK?
Answer: Tomcat is based on the original implementation of the JavaServer Pages (
JSP) and Java Servlet specifications, which was donated by Sun to the Apache Sof
tware Foundation in 1999.Sun continues to participate in development of Tomcat a
t Apache, focusing on keeping Tomcat current with new versions of the specificat
ions coming out of the Java Community Source ProcessSM.Sun adapts and integrates
the then-current Tomcat source code into new releases of the J2EE SDK.However,
since Tomcat evolves rapidly at Apache, there are additional differences between
the JSP and Servlet implementations in the J2EE SDK and in Tomcat between J2EE
SDK releases.Tomcat source and binary code is governed by the ASF license, which
freely allowsdeployment and redistribution.

# What is the J2EE 1.4 SDK?


Answer: The Java 2 SDK, Enterprise Edition 1.4 (J2EE 1.4 SDK) is a complete pack
age for developing and deploying J2EE 1.4 applications.The J2EE 1.4 SDK contains
the Sun Java System Application Server Platform Edition 8, the J2SE 1.4.2 SDK,
J2EE 1.4 platform API documentation, and a slew of samples to help developers le
arn about the J2EE platform and technologies and prototype J2EE applications.The
J2EE 1.4 SDK is free for both development and deployment.
# Which version of the platform should I use now -- 1.4 or 1.3?
Answer: The J2EE 1.4 specification is final and you can use the J2EE 1.4 SDK to
deploy applications today.However, for improved reliability,scability, and perfo
rmance, it is recommended that you deploy your applications on J2EE 1.4 commerci
al implementations that will be available early in 2004.If you want to deploy yo
ur application before 2004, and reliability,scability, and performance are criti
cal, you should consider using a high performance application server that suppor
ts J2EE v1.3 such as theSun Java System Application Server 7.Many application se
rver vendors are expected to release J2EE platform v1.4 versions of their produc
t before the spring.
# Can applications written for the J2EE platform v1.3 run in a J2EE platform v1.
4 implementation?
Answer: J2EE applications that are written to the J2EE 1.3 specification will ru
n in a J2EE 1.4 implementation.Backwards compatibility is a requirement of the s
pecification.
# How is the J2EE architecture and the Sun Java Enterprise System related?
Answer: The J2EE architecture is the foundation of the Sun Java System Applicati
on Server, a component of the Sun Java Enterprise System.The Sun Java System App
lication Server in the current Sun Java Enterprise System is based on the J2EE p
latform v1.3, with additional support for Web services.Developers familiar with
J2EE technology can easily apply their skills to building applications, includin
g Web services applications, using the Sun Java Enterprise System.For more infor
mation, see the Sun Java Enterprise System Web site.
# Can I get the source for the Sun Java System Application Server?
Answer: You can get the source for the J2EE 1.4.1 Reference Implementation from
the Sun Community Source Licensing site.The J2EE 1.4.1 Reference Implementation
is theSun Java System Application Server Platform Edition 8 minus the following
components:
* The installer
* The Web-based administration GUI
* JavaServer Faces 1.0 and JSTL 1.1
* Solaris specific enhancements for security and logging
* Higher performance message queue implementation
# Who needs the J2EE platform?
Answer: ISVs need the J2EE platform because it gives them a blueprint for provid
ing a complete enterprise computing solution on the Java platform.Enterprisedeve
lopers need J2EE because writing distributed business applications is hard, and
they need a high-productivity solution that allows them to focus only on writing
their business logic and having a full range of enterprise-class services to re
ly on, like transactional distributed objects, message oriented middleware, and
naming and directory services.
# Are there compatibility tests for the J2EE platform?
Answer: Yes.The J2EE Compatibility Test Suite (CTS) is available for the J2EE pl
atform.The J2EE CTS contains over 5,000 tests for J2EE 1.4 and will contain more
for later versions.This test suite tests compatibility by performing specific a
pplication functions and checking results.For example, to test the JDBC call to
insert a row in a database, an EJB component makes a call to insert a row and th
en a call is made to check that the row was inserted.
# What is the difference between being a J2EE licensee and being J2EE compatible
?
Answer: A J2EE licensee has signed a commercial distribution license for J2EE.Th
at means the licensee has the compatibility tests and has made a commitment to c
ompatibility.It does not mean the licensees products are necessarily compatible
yet.Look for the J2EE brand which signifies that the specific branded product ha
s passed the Compatibility Test Suite (CTS) and is compatible.
# What is the web container?
Answer: Servlet and JSP containers are collectively referred to as Web container
s. It manages the execution of JSP page and servlet components for J2EE applicat
ions. Web components and their container run on the J2EE server.
# What is Enterprise JavaBeans (EJB) container?
Answer: It manages the execution of enterprise beans for J2EE applications. Ente
rprise beans and their container run on the J2EE server.

# What makes J2EE suitable for distributed multitiered Applications?


Answer: The J2EE platform uses a multitiered distributed application model. Appl
ication logic is divided into components according to function, and the various
application components that make up a J2EE application are installed on differen
t machines depending on the tier in the multitiered J2EE environment to which th
e application component belongs.
The J2EE application parts are:
* Client-tier components run on the client machine.
* Web-tier components run on the J2EE server.
* Business-tier components run on the J2EE server.
* Enterprise information system (EIS)-tier software runs on the EIS server.
# What is J2EE?
Answer: J2EE is an environment for developing and deploying enterprise applicati
ons. The J2EE platform consists of a set of services, application programming in
terfaces (APIs), and protocols that provide the functionality for developing mul
titiered, web-based applications.
# What are the components of J2EE application?
Answer: - A J2EE component is a self-contained functional software unit that is
assembled into a J2EE application with its related classes and files and communi
cates with other components. The J2EE specification defines the following J2EE c
omponents: Application clients and applets are client components. Java Servlet a
nd JavaServer Pages technology components are web components. Enterprise JavaBea
ns components (enterprise beans) are business components. Resource adapter compo
nents provided by EIS and tool vendors.
# What do Enterprise JavaBeans components contain?
Answer: Enterprise JavaBeans components contains Business code, which is logic t
hat solves or meets the needs of a particular business domain such as banking, r
etail, or finance, is handled by enterprise beans running in the business tier.
All the business code is contained inside an Enterprise Bean which receives data
from client programs, processes it (if necessary), and sends it to the enterpri
se information system tier for storage. An enterprise bean also retrieves data f
rom storage, processes it (if necessary), and sends it back to the client progra
m.
# Is J2EE application only a web-based?
Answer: No, It depends on type of application that client wants. A J2EE applicat
ion can be web-based or non-web-based. if an application client executes on the
client machine, it is a non-web-based J2EE application. The J2EE application can
provide a way for users to handle tasks such as J2EE system or application admi
nistration. It typically has a graphical user interface created from Swing or AW
T APIs, or a command-line interface. When user request, it can open an HTTP conn
ection to establish communication with a servlet running in the web tier.
# Are JavaBeans J2EE components?
Answer: No. JavaBeans components are not considered J2EE components by the J2EE
specification. They are written to manage the data flow between an application c
lient or applet and components running on the J2EE server or between server comp
onents and a database. JavaBeans components written for the J2EE platform have i
nstance variables and get and set methods for accessing the data in the instance
variables. JavaBeans components used in this way are typically simple in design
and implementation, but should conform to the naming and design conventions out
lined in the JavaBeans component architecture.
# Is HTML page a web component?
Answer: No. Static HTML pages and applets are bundled with web components during
application assembly, but are not considered web components by the J2EE specifi
cation. Even the server-side utility classes are not considered web components,
either.
# What can be considered as a web component?
Answer: J2EE Web components can be either servlets or JSP pages. Servlets are Ja
va programming language classes that dynamically process requests and construct
responses. JSP pages are text-based documents that execute as servlets but allow
a more natural approach to creating static content.
# What is the container?
Answer: Containers are the interface between a component and the low-level platf
orm specific functionality that supports the component. Before a Web, enterprise
bean, or application client component can be executed, it must be assembled int
o a J2EE application and deployed into its container.
# What are container services?
Answer: A container is a runtime support of a system-level entity. Containers pr
ovide components with services such as lifecycle management, security, deploymen
t, and threading.

# What is Applet container?


Answer: IManages the execution of applets. Consists of a Web browser and Java Pl
ugin running on the client together.
# How do we package J2EE components?
Answer: J2EE components are packaged separately and bundled into a J2EE applicat
ion for deployment. Each component, its related files such as GIF and HTML files
or server-side utility classes, and a deployment descriptor are assembled into
a module and added to the J2EE application. A J2EE application is composed of on
e or more enterprise bean,Web, or application client component modules. The fina
l enterprise solution can use one J2EE application or be made up of two or more
J2EE applications, depending on design requirements. A J2EE application and each
of its modules has its own deployment descriptor. A deployment descriptor is an
XML document with an .xml extension that describes a component's deployment set
tings.
# What is a thin client?
Answer: A thin client is a lightweight interface to the application that does no
t have such operations like query databases, execute complex business rules, or
connect to legacy applications.
# What are types of J2EE clients?
Answer: Following are the types of J2EE clients:
* Applets
* Application clients
* Java Web Start-enabled rich clients, powered by Java Web Start technology.
* Wireless clients, based on Mobile Information Device Profile (MIDP) techno
logy.
# What is deployment descriptor?
Answer: A deployment descriptor is an Extensible Markup Language (XML) text-base
d file with an .xml extension that describes a component's deployment settings.
A J2EE application and each of its modules has its own deployment descriptor. Fo
r example, an enterprise bean module deployment descriptor declares transaction
attributes and security authorizations for an enterprise bean. Because deploymen
t descriptor information is declarative, it can be changed without modifying the
bean source code. At run time, the J2EE server reads the deployment descriptor
and acts upon the component accordingly.
# What is the EAR file?
Answer: An EAR file is a standard JAR file with an .ear extension, named from En
terprise ARchive file. A J2EE application with all of its modules is delivered i
n EAR file.
# What is JTA and JTS?
Answer: JTA is the abbreviation for the Java Transaction API. JTS is the abbrevi
ation for the Jave Transaction Service. JTA provides a standard interface and al
lows you to demarcate transactions in a manner that is independent of the transa
ction manager implementation. The J2EE SDK implements the transaction manager wi
th JTS. But your code doesn't call the JTS methods directly. Instead, it invokes
the JTA methods, which then call the lower-level JTS routines. Therefore, JTA i
s a high level transaction interface that your application uses to control trans
action. and JTS is a low level transaction interface and ejb uses behind the sce
nes (client code doesn't directly interact with JTS. It is based on object trans
action service(OTS) which is part of CORBA. 20.
# What is JAXP?
Answer: JAXP stands for Java API for XML. XML is a language for representing and
describing text-based data which can be read and handled by any program or tool
that uses XML APIs. It provides standard services to determine the type of an a
rbitrary piece of data, encapsulate access to it, discover the operations availa
ble on it, and create the appropriate JavaBeans component to perform those opera
tions. 2
# What is J2EE Connector?
Answer: The J2EE Connector API is used by J2EE tools vendors and system integrat
ors to create resource adapters that support access to enterprise information sy
stems that can be plugged into any J2EE product. Each type of database or EIS ha
s a different resource adapter. Note: A resource adapter is a software component
that allows J2EE application components to access and interact with the underly
ing resource manager. Because a resource adapter is specific to its resource man
ager, there is typically a different resource adapter for each type of database
or enterprise information system. 2
# What is JAAP?
Answer: The Java Authentication and Authorization Service (JAAS) provides a way
for a J2EE application to authenticate and authorize a specific user or group of
users to run it. It is a standard Pluggable Authentication Module (PAM) framewo
rk that extends the Java 2 platform security architecture to support user-based
authorization.
# What is Java Naming and Directory Service?
Answer: The JNDI provides naming and directory functionality. It provides applic
ations with methods for performing standard directory operations, such as associ
ating attributes with objects and searching for objects using their attributes.
Using JNDI, aJ2EE application can store and retrieve any type of named Java obje
ct. Because JNDI is independent of any specific implementations, applications ca
n use JNDI to access multiple naming and directory services, including existing
naming and directory services such as LDAP, NDS, DNS, and NIS.
# What is Struts?
Answer: A Web page development framework. Struts combines Java Servlets, Java Se
rver Pages, custom tags, and message resources into a unified framework. It is a
cooperative, synergistic platform, suitable for development teams, independent
developers, and everyone between.
# How is the MVC design pattern used in Struts framework?
Answer: In the MVC design pattern, application flow is mediated by a central Con
troller. The Controller delegates requests to an appropriate handler. The handle
rs are tied to a Model, and each handler acts as an adapter between the request
and the Model. The Model represents, or encapsulates, an application's business
logic or state. Control is usually then forwarded back through the Controller to
the appropriate View. The forwarding can be determined by consulting a set of m
appings, usually loaded from a database or configuration file. This provides a l
oose coupling between the View and Model, which can make an application signific
antly easier to create and maintain. Controller: Servlet controller which suppli
ed by Struts itself; View: what you can see on the screen, a JSP page and presen
tation components; Model: System state and a business logic JavaBeans.

# Can a abstract method have the static qualifier?


Answer: No
# What are the different types of qualifier and What is the default qualifier?
Answer: public, protected, private, package (default)
# What is the super class of Hashtable?
Answer: Dictionary
# What is a lightweight component?
Answer: Lightweight components are the one which doesn't go with the native call
to obtain the graphical units.They share their parent component graphical units
to render them.Example, Swing components
# What is a heavyweight component?
Answer: For every paint call, there will be a native call to get the graphical u
nits.Example, AWT.
# What is an applet?
Answer: Applet is a program which can get downloaded into a client environment a
nd start executing there.
# What do you mean by a Classloader?
Answer: Classloader is the one which loads the classes into the JVM.
# What are the implicit packages that need not get imported into a class file?
Answer: java.lang
# What is the difference between lightweight and heavyweight component?
Answer: Lightweight components reuses its parents graphical units.Heavyweight co
mponents go with the native graphical unit for every component.Lightweight compo
nents are faster than the heavyweight components.
# What are the ways in which you can instantiate a thread?
Answer: Using Thread class By implementing the Runnable interface and giving tha
t handle to the Thread class.

# What is a Marker Interface?


Answer: An interface with no methods.Example: Serializable, Remote, Cloneable
# What interface do you implement to do the sorting?
Answer: Comparable
# What is the eligibility for a object to get cloned?
Answer: It must implement the Cloneable interface.
# What is the purpose of abstract class?
Answer: It is not an instantiable class.It provides the concrete implementation
for some/all the methods.So that they can reuse the concrete functionality by in
heriting the abstract class.
# What is the difference between interface and abstract class?
Answer: Abstract class defined with methods.Interface will declare only the meth
ods.Abstract classes are very much useful when there is some functionality acros
s various classes.Interfaces are well suited for the class, which varies in func
tionality but with the same method signatures.
# What do you mean by RMI and How it is useful?
Answer: RMI is a remote method invocation.Using RMI, you can work with remote ob
ject.The function calls are as though you are invoking a local variable.So it gi
ves you a impression that you are working really with a object that resides with
in your own JVM though it is somewhere.
# What is the protocol used by RMI?
Answer: RMI-IIOP
# What is a hashCode?
Answer: hash code value for this object which is unique for every object.
# What is a thread?
Answer: Thread is a block of code which can execute concurrently with other thre
ads in the JVM.
# What is the algorithm used in Thread scheduling?
Answer: Fixed priority scheduling.
# What is hash-collision in Hashtable and How it is handled in Java?
Answer: Two different keys with the same hash value.Two different entries will b
e kept in a single hash bucket to avoid the collision.
# What are the different driver types available in JDBC?
Answer: The driver types available in JDBC are:
* A JDBC-ODBC bridge
* A native-API partly Java technology-enabled driver
* A net-protocol fully Java technology-enabled driver
* A native-protocol fully Java technology-enabled driver
# Is JDBC-ODBC bridge multi-threaded?
Answer: No
# Does the JDBC-ODBC Bridge support multiple concurrent open statements per conn
ection?
Answer: No
# What is the use of serializable?
Answer: To persist the state of an object into any perminant storage device.
# What is the use of transient?
Answer: It is an indicator to the JVM that those variables should not be persist
ed.It is the users responsibility to initialize the value when read back from th
e storage.
# What are the different level lockings using the synchronization keyword?
Answer: Class level lock Object level lock Method level lock Block level lock
# What is the use of preparedstatement?
Answer: Preparedstatements are precompiled statements.It is mainly used to speed
up the process of inserting/updating/deleting especially when there is a bulk p
rocessing.
# What is callable statement? Tell me the way to get the callable statement?
Answer: Callable statements are used to invoke the stored procedures.You can obt
ain the callable statement from Connection using the following methods:
* prepareCall(String sql)
* prepareCall(String sql, int resultSetType, int resultSetConcurrency)
# In a statement, I am executing a batch.What is the result of the execution?
Answer: It returns the int array.The array contains the affected row count in th
e corresponding index of the SQL.

# What are the states of a thread?


Answer: There are four states of thread:
* New Runnable
* Not runnable
* Dead
# What is a socket?
Answer: A socket is an endpoint for communication between two machines.
# How will you establish the connection between the servlet and an applet?
Answer: Using the URL, I will create the connection URL.Then by openConnection m
ethod of the URL, I will establish the connection, through which I can be able t
o exchange data.
# What are the threads will start, when you start the java program?
Answer: Finalizer, Main, Reference Handler, Signal Dispatcher.
# Is it necessary that each try block must be followed by a catch block?
Answer: It is not necessary that each try block must be followed by a catch bloc
k.It should be followed by either a catch block OR a finally block.And whatever
exceptions are likely to be thrown should be declared in the throws clause of th
e method.
# If I write return at the end of the try block, will the finally block still ex
ecute?
Answer: Yes even if you write return as the last statement in the try block and
no exception occurs, the finally block will execute.The finally block will execu
te and then the control return.
# If I write System.exit (0); at the end of the try block, will the finally bloc
k still execute?
Answer: No in this case the finally block will not execute because when you say
System.exit (0); the control immediately goes out of the program, and thus final
ly never executes.
# How are Observer and Observable used?
Answer: Objects that subclass the Observable class maintain a list of observers.
When an Observable object is updated it invokes the update() method of each of i
ts observers to notify the observers that it has changed state.The Observer inte
rface is implemented by objects that observe Observable objects.
# What is synchronization and why is it important?
Answer: With respect to multithreading, synchronization is the capability to con
trolthe access of multiple threads to shared resources.Without synchronization,
it is possible for one thread to modify a shared object while another thread is
in the process of using or updating that object's value.This often leads tosigni
ficant errors.
# Why do we need wrapper classes?
Answer: It is sometimes easier to deal with primitives as objects.Moreover most
of the collection classes store objects and not primitive data types.And also th
e wrapper classes provide many utility methods also.Because of these resons we n
eed wrapper classes.And since we create instances of these classes we can store
them in any of the collection classes and pass them around as a collection.Also
we can pass them around as method parameters where a method expects an object.

# What is the difference between preemptive scheduling and time slicing?


Answer: Under preemptive scheduling, the highest priority task executes until it
entersthe waiting or dead states or a higher priority task comes into existence
.Under time slicing, a task executes for a predefined slice of time and then ree
nters the pool of ready tasks.The scheduler then determines which task should ex
ecute next, based on priority and other factors.
# When a thread is created and started, what is its initial state?
Answer: A thread is in the ready state after it has been created and started.
# What is the purpose of finalization?
Answer: The purpose of finalization is to give an unreachable object the opportu
nity to perform any cleanup processing before the object is garbage collected.
# What is the Locale class?
Answer: The Locale class is used to tailor program output to the conventions of
aparticular geographic, political, or cultural region.
# What is the difference between a while statement and a do statement?
Answer: A while statement checks at the beginning of a loop to see whether the n
extloop iteration should occur.A do statement checks at the end of a loop to see
whether the next iteration of a loop should occur.The do statement will always
execute the body of a loop at least once.
# What is the difference between static and non-static variables?
Answer: A static variable is associated with the class as a whole rather than wi
th specific instances of a class.Non-static variables take on unique values with
each object instance.
# How are this() and super() used with constructors?
Answer: Othis() is used to invoke a constructor of the same class.super() is use
d toinvoke a superclass constructor.
# What are synchronized methods and synchronized statements?
Answer: Synchronized methods are methods that are used to control access to an o
bject.A thread only executes a synchronized method after it has acquired the loc
k for the method's object or class.Synchronized statements are similar to synchr
onized methods.A synchronized statement can only be executed after a thread has
acquiredthe lock for the object or class referenced in the synchronized statemen
t.
# How does Java handle integer overflows and underflows?
Answer: It uses those low order bytes of the result that can fit into the size o
f the type allowed by the operation.
# Does garbage collection guarantee that a program will not run out of memory?
Answer: Garbage collection does not guarantee that a program will not run out of
memory.It is possible for programs to use up memory resources faster than they a
re garbage collected.It is also possible for programs to create objects that are
not subject togarbage collection.

# What is the difference between an Interface and an Abstract class?


Answer: An Abstract class declares have at least one instance method that is dec
lared abstract which will be implemented by the subclasses.An abstract class can
have instance methods that implement a default behavior.An Interface can only d
eclare constants and instance methods, but cannot implement default behavior.
# What is the purpose of garbage collection in Java, and when is it used?
Answer: The purpose of garbage collection is to identify and discard objects tha
t are no longer needed by a program so that their resources can be reclaimed and
reused.A Java object is subject to garbage collection when it becomes unreachab
le to the program in which it is used.
# Describe synchronization in respect to multithreading.
Answer: With respect to multithreading, synchronization is the capability to con
trol the access of multiple threads to shared resources.Without synchonization,
it is possible for one thread to modify a shared variable while another thread i
s in the process of using or updating same shared variable.This usually leads to
significant errors.
# Explain different way of using thread?
Answer: The thread could be implemented by using runnable interface or by inheri
ting from the Thread class.The former is more advantageous, 'cause when you are
going for multiple inheritance..the only interface can help.
# What are pass by reference and passby value?
Answer: Pass By Reference means the passing the address itself rather than passi
ng the value.Passby Value means passing a copy of the value to be passed.
# What is HashMap and Map?
Answer: Map is Interface and Hashmap is class that implements that.
# Difference between HashMap and HashTable?
Answer: The HashMap class is roughly equivalent to Hashtable, except that it is
unsynchronized and permits nulls.(HashMap allows null values as key and value wh
ereas Hashtable doesnt allow).HashMap does not guarantee that the order of the m
ap will remain constant over time.HashMap is non synchronized and Hashtable is s
ynchronized.
# Difference between Vector and ArrayList?
Answer: Vector is synchronized whereas arraylist is not.
# Difference between Swing and Awt?
Answer: AWT are heavy-weight componenets.Swings are light-weight components.Henc
e swing works faster than AWT.
# What is the difference between a constructor and a method?
Answer: A constructor is a member function of a class that is used to create obj
ects of that class.It has the same name as the class itself, has no return type,
and is invoked using the new operator.A method is an ordinary member function o
f a class.It has its own name, a return type (which may be void), and is invoked
using the dot operator.
# What is an Iterators?
Answer: Some of the collection classes provide traversal of their contents via a
java.util.Iterator interface.This interface allows you to walk a collection of
objects, operating on each object in turn.Remember when using Iterators that the
y contain a snapshot of the collection at the time the Iterator was obtained; ge
nerally it is not advisable to modify the collection itself while traversing an
Iterator.
# State the significance of public, private, protected, default modifiers both s
ingly and in combination and state the effect of package relationships on declar
ed items qualified by these modifiers.
Answer: public : Public class is visible in other packages, field is visible eve
rywhere (class must be public too)private : Private variables or methods may be
used only by an instance of the same class that declares the variable or method,
A private feature may only be accessed by the class that owns the feature.prote
cted : Is available to all classes in the same package and also available to all
subclasses of the class that owns the protected feature.This access is provided
even to subclasses that reside in a different package from the class that owns
the protected feature.default :What you get by default ie, without any access mo
difier (ie, public private or protected).It means that it is visible to all with
in a particular package.
# What is an abstract class?
Answer: Abstract class must be extended/subclassed (to be useful).It serves as a
template.A class that is abstract may not be instantiated (ie, you may not call
its constructor), abstract class may contain static data.Any class with an abst
ract method is automatically abstract itself, and must be declared as such.A cla
ss may be declared abstract even if it has no abstract methods.This prevents it
from being instantiated.
# What is static in java?
Answer: Static means one per class, not one for each object no matter how many i
nstance of a class might exist.This means that you can use them without creating
an instance of a class.Static methods are implicitly final, because overriding
is done based on the type of the object, and static methods are attached to a cl
ass, not an object.A static method in a superclass can be shadowed by another st
atic method in a subclass, as long as the original method was not declared final
.However, you can't override a static method with a nonstatic method.In other wo
rds, you can't change a static method into aninstance method in a subclass.
# What is final?
Answer: A final class can't be extended ie., final class may not be subclassed.A
final method can't be overridden when its class is inherited.You can't change v
alue of a final variable (is a constant).
# What if the main method is declared as private?
Answer: The program compiles properly but at runtime it will give "Main method n
ot public." message.
# What if the static modifier is removed from the signature of the main method?
Answer: Program compiles.But at runtime throws an error "NoSuchMethodError".
# What if I write static public void instead of public static void?
Answer: Program compiles and runs properly.
# What if I do not provide the String array as the argument to the method?
Answer: Program compiles but throws a runtime error "NoSuchMethodError".
# What is the first argument of the String array in main method?
Answer: The String array is empty.It does not have any element.This is unlike C/
C++ where the first element by default is the program name.

# One of the components of a computer is its CPU.What is a CPU and what role doe
s it play in a computer?
Answer: The CPU, or Central Processing Unit, is the active part of the computer.
Its function is to execute programs that are coded in machine language and store
d in the main memory (RAM) of the computer.It does this by repeating the fetchan
dexecute cycle over and over; that is, it repeatedly fetches a machine language
instruction from memory and executes it.
# Explain what is meant by an "asynchronous event." Give some examples.
Answer: An asynchronous event is one that occurs at an unpredictable time outsid
e the control of the program that the CPU is running.It is not "synchronized" wi
th the program.An example would be when the user presses a key on the keyboard o
r clicks the mouse button.(These events generate "interrupts" that cause the CPU
to interrupt what it is doing and to take some action to handle the asynchronou
s event.After handling the event, the CPU returns to what it was doing before it
was interrupted.)
# What is the difference between a "compiler" and an "interpreter"?
Answer: Compilers and interpreters have similar functions: They take a program w
ritten in some programming language and translate it into machine language.A com
piler does the translation all at once.It produces a complete machine languagepr
ogram that can then be executed.An interpreter, on the other hand, just translat
es one instruction at a time, and then executes that instruction immediately.(Ja
va uses a compiler to translate java programs into Java Bytecode, which is a mac
hine language for the imaginary Java Virtual Machine.Java Bytecode programs are
then executed by an interpreter.)
# Explain the difference between highlevel languages and machine language.
Answer: Programs written in the machine language of a given type of computer can
be directly executed by the CPU of that type of computer.Highlevel languageprog
rams must be translated into machine language before they can be executed.(Machi
ne language instructions are encoded as binary numbers that are meant to be used
by a machine, not read or written by people.Highlevel languages use a syntax th
at is closer to human language.)
# If you have the source code for a Java program, and you want to run that progr
am, you will need both a compiler and an interpreter.What does the Java compiler
do, and what does the Java interpreter do?
Answer: The Java compiler translates Java programs into a language called Java b
ytecode.Although bytecode is similar to machine language, it is not the machine
language of any actual computer.A Java interpreter is used to run the compiled J
ava bytecode program.(Each type of computer needs its own Java bytecode interpre
ter, but all these interpreters interpret the same bytecode language.)
# What is a subroutine?
Answer: A subroutine is a set of instructions for performing some task that have
been grouped together and given a name.Later, when that task needs to be perfor
med, it is only necessary to call the subroutine by giving its name, rather than
repeating the whole sequence of instructions.
# Java is an objectoriented programming language.What is an object?
Answer: An object consists of some data together with a set of subroutines that
manipulate that data.(An object is a kind of "module," or selfcontained entity t
hat communicates with the rest of the world through a welldefined interface.An o
bject should represent some coherent concept or realworld object.)
# What is a variable?
Answer: A variable is a memory location that has been given a name so that it ca
n easily be referred to in a program.The variable holds a value, which must be o
f some specified type.The value can be changed during the course of the executio
n of theprogram.
# Java is a "platformindependent language." What does this mean?
Answer: A Java program can be compiled once into a Java Bytecode program.The com
piled program can then be run on any computer that has an interpreter for the Ja
va virtual machine.Other languages have to be recompiled for each platform on wh
ich they are going to run.The point about Java is that it can be executed on man
y different types of computers without being recompiled.
# What is the "Internet"? Give some examples of how it is used.
Answer: The Internet is a network connecting millions of computers around the wo
rld.Computers connected to the Internet can communicate with each other.The Inte
rnet can be used for:
* Telnet:which lets a user of one computer log onto another computer remotel
y.
* FTP:which is used to copy files between computers.
* World Wide Web:which lets a user view "pages" of information published on
computers around the world.

# What is garbage collection? What is the process that is responsible for doing
that in java?
Answer: Reclaiming the unused memory by the invalid objects.Garbage collector is
responsible for this process
# What kind of thread is the Garbage collector thread?
Answer: It is a daemon thread.
# What is a daemon thread?
Answer: These are the threads which can run without user intervention.The JVM ca
n exit when there are daemon thread by killing them abruptly.
# How will you invoke any external process in Java?
Answer: Runtime.getRuntime().exec(.)
# What is the finalize method do?
Answer: Before the invalid objects get garbage collected, the JVM give the user
a chance to clean up some resources before it got garbage collected.
# What is mutable object and immutable object?
Answer: If a object value is changeable then we can call it as Mutable object.(E
x., StringBuffer, ) If you are not allowed to change the value of an object, it
is immutable object.(Ex., String, Integer, Float,)
# What is the basic difference between string and stringbuffer object?
Answer: String is an immutable object.StringBuffer is a mutable object.
# What is the purpose of Void class?
Answer: The Void class is an uninstantiable placeholder class to hold a referenc
e to the Class object representing the primitive Java type void.
# What is reflection?
Answer: Reflection allows programmatic access to information about the fields, m
ethods and constructors of loaded classes, and the use reflected fields, methods
, and constructors to operate on their underlying counterparts on objects, withi
n security restrictions.
# What is Class.forName() does and how it is useful?
Answer: It loads the class into the ClassLoader.It returns the Class.Using that
you can get the instance ( class-instance.newInstance() ).

# What is the base class for Error and Exception?


Answer: Throwable
# What is the byte range??
Answer: 128 to 127
# What is the implementation of destroy method in java..is it native or java cod
e?
Answer: This method is not implemented.
# What is a package?
Answer: To group set of classes into a single unit is known as packaging.Package
s provides wide namespace ability.
# What are the approaches that you will follow for making a program very efficie
nt?
Answer: By avoiding too much of static methods avoiding the excessive and unnece
ssary use of synchronized methods Selection of related classes based on the appl
ication (meaning synchronized classes for multiuser and non-synchronized classes
for single user) Usage of appropriate design patterns Using cache methodologies
for remote invocations Avoiding creation of variables within a loop and lot mor
e.
# What is a DatabaseMetaData?
Answer: Comprehensive information about the database as a whole.
# What is Locale?
Answer: A Locale object represents a specific geographical, political, or cultur
al region
# How will you load a specific locale?
Answer: Using ResourceBundle.getBundle();
# What is JIT and its use?
Answer: Really, just a very fast compiler In this incarnation, pretty much a one
-pass compiler no offline computations.So you cant look at the whole method, ran
k the expressions according to which ones are re-used the most, and then generat
e code.In theory terms, its an on-line problem.
# Is JVM a compiler or an interpreter?
Answer: Interpreter

# When you think about optimization, what is the best way to findout the time/me
mory consuming process?
Answer: Using profiler
# What is the purpose of assert keyword used in JDK1.4.x?
Answer: In order to validate certain expressions.It effectively replaces the if
block and automatically throws the AssertionError on failure.This keyword should
be used for the critical arguments.Meaning, without that the method does nothin
g.
# How will you get the platform dependent values like line separator, path separ
ator, etc., ?
Answer: Using Sytem.getProperty() (line.separator, path.separator, )
# What is skeleton and stub? what is the purpose of those?
Answer: Stub is a client side representation of the server, which takes care of
communicating with the remote server.Skeleton is the server side representation.
But that is no more in use it is deprecated long before in JDK.
# What is the final keyword denotes?
Answer: final keyword denotes that it is the final implementation for that metho
d or variable or class.You cant override that method/variable/class any more.
# What is the significance of ListIterator?
Answer: You can iterate back and forth.
# What is the major difference between LinkedList and ArrayList?
Answer: LinkedList are meant for sequential accessing.ArrayList are meant for ra
ndom accessing.
# What is nested class?
Answer: If all the methods of a inner class is static then it is a nested class.
# What is inner class?
Answer: If the methods of the inner class can only be accessed via the instance
of the inner class, then it is called inner class.
# What is composition?
Answer: Holding the reference of the other class within some other class is know
n as composition.

# What is aggregation?
Answer: It is a special type of composition.If you expose all the methods of a c
omposite class and route the method call to the composite method through its ref
erence, then it is called aggregation.
# Can you instantiate the Math class?
Answer: You cant instantiate the math class.All the methods in this class are st
atic.And the constructor is not public.
# What is singleton?
Answer: It is one of the design pattern.This falls in the creational pattern of
the design pattern.There will be only one instance for that entire JVM.You can a
chieve this by having the private constructor in the class.For eg., public class
Singleton { private static final Singleton s = new Singleton(); private Singlet
on() { } public static Singleton getInstance() { return s; } // all non static m
ethods }
# What is DriverManager?
Answer: The basic service to manage set of JDBC drivers.
# Suppose that temperature measurements were made on each day of 1999 in each of
100 cities.The measurements have been stored in an array
int[][]temps=newint[100][365];
where temps[c][d] holds the measurement for city number c on the dth day of the
year.Write a code segment that will print out the average temperature, over the
course of the whole year, for each city.The average temperature for a city can b
e obtained by adding up all 365 measurements for that city and dividing the answ
er by 365.0.
Answer: A pseudocode outline of the answer is
For each city {
Add up all the temperatures for that city
Divide the total by 365 and print the answer
}
Adding up all the temperatures for a given city itself requires a for loop, so t
he code segment looks like this:
for (int city = 0; city < 100; city++) {
int total = 0;
for (int day = 0; day < 365; day++)
total = total + temps[city][day];
double avg = total / 365.0;
System.out.println("Average temp for city number " + city + " is " + avg);
}
# Suppose that a class, Employee, is defined as follows: class Employee {
String lastName;
String firstName;
double hourlyWage;
int yearsWithCompany;
}
Suppose that data about 100 employees is already stored in an array:
Employee[] employeeData = new
Employee[100];
Write a code segment that will output the first name, last name, and hourly wage
of each employee who has been with the company for 20 years or more.
Answer: The code segment is as follows:
for (int i=0; i < 100; i++) {
if ( employeeData[i].yearsWithCompany >= 20 )
System.out.println(employeeData[i].firstName + " " + employeeData[i].lastName +
": " + employeeData[i].hourlyWage);
}
# Suppose that A has been declared and initialized with the statement
double[] A = new double[20];
And suppose that A has already been filled with 20 values.Write a program segmen
t that will find the average of all the non-zero numbers in the array.(The avera
ge is the sum of the numbers, divided by the number of numbers.Note that you wil
l have to count the number of non-zero entries in the array.) Declare any variab
les that you use.
Answer: int nonzeroCt = 0;
double total = 0;
double average;
for (int i = 0; i < 20; i++) {
if (A[i] != 0) {
total += A[i];
nonzeroCt++;
}
}
if (nonzeroCt > 0)
average = total / nonzeroCt;
else
average = 0;
# What does it mean to say that a program is robust?
Answer: A robust program is one that can handle errors and other unexpected cond
itions in some reasonable way.This means that the program must anticipate possib
le errors and respond to them if they occur.
# Why do programming languages require that variables be declared before they ar
e used? What does this have to do with correctness and robustness?
Answer: It's a little inconvenient to have to declare every variable before it i
s used, but its much safer.If the compiler would accept undeclared variables, th
en it would also accept misspelled names and treat them as valid variables.This
can easily lead to incorrect programs.When variables must be declared, the unint
entional creation of a variable is simply impossible, and a whole class of possi
ble bugs is avoided.
# What is "Double.NaN"?
Answer: Double.NaN is a special value of type double.(It is defined as a public
static member variable of the standard class, Double.) It is used to represent t
he result of an undefined operation on real numbers.For example, if you divide a
number of type double by zero, the result will be Double.NaN.

# What does it mean to use a null layout manager, and why would you want to do s
o?
Answer: If the layout manager for a container is set to null, then the programme
r takes full responsibility for setting the sizes and positions of all of the co
mponents in thatcontainer.This gives the programmer more control over the layout
, but the programmer has to do more work.For simple layouts in a container that
does not change size, the setBounds() method of each component can be called whe
n it is added to the container.If the container can change size, then the sizes
and positions should be recomputed when a size change occurs.This is done automa
tically by a layout manager, and this is one good reason to use a layout manager
for acontainer that can change size.
# What is a JCheckBox and how is it used?
Answer: A JCheckBox is a component that has two possible states, "checked" and "
unchecked".The user can change the state by clicking on the JCheckBox.If box is
a variable of type JCheckBox, then a program can check the box by calling box.se
tSelected(true) and can uncheck the box by calling box.setSelected(false).The cu
rrent state can be determined by calling box.isSelected(), which is a boolean-va
lued function.A JCheckBox generates an event of type ActionEvent when it changes
state.A program can listen for these events if it wants to take some action at
the time the state changes.Often, however, it's enough for a program simply to l
ook at the state of the JCheckBox when it needs it.
# What is a thread ?
Answer: A thread, like a program, executes a sequence of instructions from begin
ning to end.Several threads can execute "in parallel" at the same time.In Java,
a thread is represented by an object of type Thread.A Thread object has a run()
method to execute (usually the run() method of a Runnable object that is provide
d when the Thread is constructed).The thread begins executing the run() routine
when its start() method is called.At the same time, the rest of the program cont
inues to execute in parallel with the thread.
# Explain how Timers are used to do animation?
Answer: Displaying an animation requires showing a sequence of frames.The frames
are shown one after the other, with a short delay between each frame and the ne
xt.A Timer can generate a sequence of ActionEvents.When a timer is used to do an
imation, each event triggers the display of another frame.The ActionListener tha
t processes events from the timer just needs to be programmed to display a frame
when its actionPerformed() method is called.
# Menus can contain sub-menus.What does this mean, and how are sub-menus handled
in Java?
Answer: Menus can be "hierarchical." A menu can contain other menus, which are c
alled sub-menus.A sub-menu is represented as a single item in the menu that cont
ains it.When the user selects this item, the full sub-menu appears, and the user
can select an item from the sub-menu.In Java, a sub-menu is no different from a
ny other menu.A menu can be added to a menu bar, or it can be added to another m
enu.In the latter case, it becomes a sub-menu.
# What is the purpose of the JFrame class?
Answer: An object belonging to the class JFrame is an independent window on the
screen.You don't need a Web browser to create a JFrame like you do for an JApple
t.A JFrame can be used as a user interface for a stand-alone program.It is also
possible for an applet to open a JFrame.
# What does the computer do when it executes the following statement? Try to giv
e as complete an answer as possible.
Color[]pallette=newColor[12];
Answer: This is a declaration statement, that declares and initializes a variabl
e named pallette of type Color[].The initial value of this variable is a newly c
reated array that has space for 12 items.To be specific about what the computer
does: It creates a new 12-element array object on the heap, and it fills each sp
ace in that array with null.It allocates a memory space for the variable, pallet
te.And it stores a pointer to the new array object in that memory space.
# What is meant by the basetype of an array?
Answer: The base type of an array refers to the type of the items that can be st
ored in that array.For example, the base type of the array in the previous probl
em is Color.
# What does it mean to sort an array?
Answer: To sort an array means to rearrange the items in the array so that they
are in increasing or decreasing order.
# What is meant by a dynamic array? What is the advantage of a dynamic array ove
r a regular array?
Answer: A dynamic array is like an array in that it is a data structure that sto
res a sequence of items, all of the same type, in numbered locations.It is diffe
rent from an array in that there is no preset upper limit on the number of items
that it can contain.This is an advantage in situations where a reasonable value
for the size of the array is not known at the time it is created.

# Briefly explain what is meant by the syntax and the semantics of a programming
language.Give an example to illustrate the difference between a syntax error an
d a semantics error?
Answer: The syntax of a language is its grammar, and the semantics is its meanin
g.A program with a syntax error cannot be compiled.A program with a semantic err
or can be compiled and run, but gives an incorrect result.A missing semicolon in
a program is an example of a syntax error, because the compiler will find the e
rror and report it.If N is an integer variable, then the statement "frac = 1/N;"
is probably an error of semantics.The value of 1/N will be 0 for any N greater
than 1.It's likely that the programmer meant to say 1.0/N.
# What does the computer do when it executes a variable declaration statement.Gi
ve an example.
Answer: A variable is a "box", or location, in the computer's memory that has a
name.The box holds a value of some specified type.A variable declaration stateme
nt is a statement such as
int x;
which creates the variable x.When the computer executes a variable declaration,
it creates the box in memory and associates a name (in this case, x) with that b
ox.Later in the program, that variable can be referred to by name.
# What is a type, as this term relates to programming?
Answer: A "type" represents a set of possible values.When you specify that a var
iable has a certain type, you are saying what values it can hold.When you say th
at an expression is of a certain type, you are saying what values the expression
can have.For example, to say that a variable is of type int says that integer v
alues in a certain range can be stored in that variable.
# One of the primitive types in Java is boolean.What is the boolean type? Where
are boolean values used? What are its possible values?
Answer: The only values of type boolean are true and false.Expressions of type b
oolean are used in places where true/false values are expected, such as the cond
itions in while loops and if statements.
# Give the meaning of each of the following Java operators - ++, &&, !=
Answer: The Operators are Explained as follows:
* ++:The operator ++ is used to add 1 to the value of a variable.For example
, "count++" has the same effect as "count = count + 1".
* &&:The operator && represents the word and.It can be used to combine two b
oolean values, as in "(x > 0 && y > 0)", which means, "x is greater than 0 and y
is greater than 0."
* !=:The operation != means "is not equal to", as in "if (x != 0)", meaning
"if x is not equal to zero.".
# Explain what is meant by an assignment statement, and give an example.What are
assignment statements used for?
Answer: An assignment statement computes a value and stores that value in a vari
able.
Examples include:
x = 17;
newRow = row;
ans = 17*x + 42;
An assignment statement is used to change the value of a variable as the program
is running.Since the value assigned to the variable can be another variable or
an expression, assignments statements can be used to copy data from one place to
another in the computer, and to do complex computations.
# What is meant by precedence of operators?
Answer: If two or more operators are used in an expression, and if there are no
parentheses to indicate the order in which the operators are to be evaluated, th
en the computer needs some way of deciding which operator to evaluate first.The
order is determined by the precedence of the operators.For example, * has higher
precedence than +, so the expression 3+5*7 is evaluated as if it were written 3
+(5*7).
# What is a literal?
Answer: A literal is a sequence of characters used in a program to represent a c
onstant value.For example, 'A' is a literal that represents the value A, of type
char, and 17L is a literal that represents the number 17 as a value of type lon
g.A literal is a way of writing a value, and should not be confused with the val
ue itself.
# In Java, classes have two fundamentally different purposes.What are they?
Answer: A class can be used to group together variables and subroutines that are
contained in the class.These are called the static members of the class.For exa
mple, the subroutine Math.sqrt is a static member of the class called Math.Also,
the main routine in any program is a static member of a class.The second possib
le purpose of a class is to describe and create objects.The class specifies what
variables and subroutines are contained in those objects.In this role, classes
are used in object-oriented programming (which we haven't studied yet in any det
ail.)
# What is the difference between the statement "x = TextIO.getDouble();" and the
statement "x = TextIO.getlnDouble();"
Answer: Either statements will read a real number input by the user, and store t
hat number in the variable, x.They would both read and return exactly the same v
alue.The difference is that in the second statement, using getlnDouble, after re
ading the value, the computer will continue reading characters from input up to
and including the next carriage return.These extra characters are discarded.

# Explain briefly what is meant by "pseudocode" and how is it useful in the deve
lopment of algorithms.
Answer: Pseudocode refers to informal descriptions of algorithms, written in a l
anguage that imitates the structure of a programming language, but without the s
trict syntax.Pseudocode can be used in the process of developing an algorithm wi
th stepwise refinement.You can start with a brief pseudocode description of the
algorithm and then add detail to the description through a series of refinements
until you have something that can be translated easily into a program written i
n an actual programming language.
# What is a block statement? How are block statements used in Java programs?
Answer: A block statement is just a sequence of Java statements enclosed between
braces, { and }.The body of a subroutine is a block statement.Block statements
are often used in control structures.A block statement is generally used to grou
p together several statements so that they can be used in a situation that only
calls for a single statement.For example, the syntax of a while loop calls for a
single statement: "while (condition) do statement".However, the statement can b
e a block statement, giving the structure: "while (condition) { statement; state
ment;...}".
# What is the main difference between a while loop and a do..while loop?
Answer: Both types of loop repeat a block of statements until some condition bec
omes false.The main difference is that in a while loop, the condition is tested
at the beginning of the loop, and in a do..while loop, the condition is tested a
t the end of the loop.It is possible that the body of a while loop might not be
executed at all.However, the body of a do..while loop is executed at least once
since the condition for ending the loop is not tested until the body of the loop
has been executed.
# What does it mean to prime a loop?
Answer: The condition at the beginning of a while loop has to make sense even th
e first time it is tested, before the body of the loop is executed.To prime the
loop is to set things up before the loop starts so that the test makes sense (th
at is, the variables that it contains have reasonable values).For example, if th
e test in the loop is "while the user's response is yes," then you will have to
prime the loop by getting a response from the user (or making one up) before the
loop.
# Explain what is meant by an animation and how a computer displays an animation
?
Answer: An animation consists of a series of "frames." Each frame is a still ima
ge, but there are slight differences from one frame to the next.When the images
are displayed rapidly one frame after another, the eye perceives motion.A comput
er displays an animation by showing one image on the screen, then replacing it w
ith the next image, then the next, and so on.
# Write a for loop that will print out all the multiples of 3 from 3 to 36, that
is: 3 6 9 12 15 18 21 24 27 30 33 36.
Answer: Here are two possible answers.Assume that N has been declared to be a va
riable of type int:
for ( N = 3;N <= 36;N = N + 3 )
{
System.out.println( N );
}
or
for ( N = 3;N <= 36;N++ )
{
if ( N % 3 == 0 )
System.out.println( N );
}
# Fill in the following main() routine so that it will ask the user to enter an
integer, read the user's response, and tell the user whether the number entered
is even or odd.(You can use TextIO.getInt() to read the integer.Recall that an i
nteger n is even if n % 2 == 0.)
public static void main(String[] args) {
}
Answer: The problem already gives an outline of the program.The last step, telli
ng the user whether the number is even or odd, requires an if statement to decid
e between the two possibilities.
public static void main (String[] args)
{
int n;
TextIO.put("Type an integer: ");
n = TextIO.getInt();
if (n % 2 == 0)
System.out.println("That's an even number.");
Else
System.out.println("That's an odd number.");
}
# Show the exact output that would be produced by the following main() routine:
public static void main(String[] args) {
int N;
N = 1;
while (N <= 32)
{
N = 2 * N;
System.out.println(N);
}
}
Answer: The exact output printed by this program is:
2
4
8
16
32
64
# What output is produced by the following program segment? Why?
String name;
int i;
boolean startWord;
name = "Richard M.Nixon";
startWord = true;
for (i = 0; i < name.length(); i++) {
if (startWord)
System.out.println(name.charAt(i));
if (name.charAt(i) == ' ')
startWord = true;
else
startWord = false;
}
Answer: This is a tough one! The output from this program consists of the three
lines:
R
M
N
As the for loop in this code segment is executed, name.charAt(i) represents each
of the characters in the string "Richard M.Nixon" in succession.The statement S
ystem.out.println(name.charAt(i)) outputs the single character name.charAt(i) on
a line by itself.However, this output statement occurs inside an if statement,
so only some of the characters are output.The character is output if startWord i
s true.This variable is initialized to true, so when i is 0, startWord is true,
and the first character in the string, 'R', is output.Then, since 'R' does not e
qual ' ', startWorld becomes false, so no more characters are output until start
Word becomes true again.This happens when name.charAt(i) is a space, that is, ju
st before the 'M' is processed and again just before the 'N' is processed.In fac
t whatever the value of name, this for statement would print the first character
in name and every character in name that follows a space
# A "black box" has an interface and an implementation.Explain what is meant by
the terms interface and implementation.
Answer: The interface of a black box is its connection with the rest of the worl
d, such as the name and parameters of a subroutine or the dial for setting the t
emperature on a thermostat.The implementation refers to internal workings of the
black box.To use the black box, you need to understand its interface, but you d
on't need to know anything about the implementation.

# Explain what is meant by the client / server model of network communication.


Answer: In the client/server model, a server program runs on a computer somewher
e on the Internet and "listens" for connection requests from client programs.The
server makes some service available.A client program connects to the server to
access that service.For example, a Web server has a collection of Web pages.A We
b browser acts as a client for the Web server.It makes a connection tothe server
and sends a request for one of its pages.The server responds by transmitting a
copy of the requested page back to the client.
# What is a socket?
Answer: A socket represents one endpoint of a network connection.A program uses
a socket to communicate with another program over the network.Data written by a
program to the socket at one end of the connection is transmitted to the socket
on the other end of the connection, where it can be read by the program at that
end.
# What is a ServerSocket and how is it used?
Answer: A SeverSocket is used by a server program to listen for connection reque
sts from client programs.If listener refers to an object that belongs to Java's
ServerSocket class, then calling the function listener.accept() will wait for a
connection request and will return a Socket object that can be used to communica
te with the client that made the request.
# Network server programs are often multithreaded.Explain what this means and wh
y it is true?
Answer: A multi-threaded server creates a new thread to handle each client conne
ction that it accepts.A server program is generally designed to process connecti
on requests from many clients.It runs in an infinite loop in which it accepts a
connection request and processes it.If the processing takes a significant amount
of time, it's not a good idea to make the other clients wait while the current
client is processed.The solution is forthe server to make a new thread to handle
each client connection.The server can continue to accept other client connectio
ns even while the first client is being serviced.
# Explain what is meant by a recursive subroutine.
Answer: A recursive subroutine is simply one that calls itself either directly o
r through a chain of calls involving other subroutines.
# What are the three operations on a stack?
Answer: The three stack operations are push, pop, and isEmpty.The definitions of
these operations are: push(item) adds the specified item to the top of the stac
k; pop() removes the top item of the stack and returns it; and isEmpty() is a bo
olean-valued function that returns true if there are no items on the stack.
# What is the basic difference between a stack and a queue?
Answer: In a stack, items are added to the stack and removed from the stack on t
he same end (called the "top" of the stack).In a queue, items are added at one e
nd (the "back") and removed at the other end (the "front").Because of this diffe
rence, a queue is a FIFO structure (items are removed in the same order in which
they were added), and a stack is a LIFO structure (the item that is popped from
a stack is the one that was added most recently).
# What is an activation record? What role does a stack of activation records pla
y in a computer?
Answer: When a subroutine is called, an activation record is created to hold the
information that is needed for the execution of the subroutine, such as the val
ues of the parameters and local variables.Thisactivation record is stored on a s
tack of activation records.A stack is used since one subroutine can call another
, which can then call a third, and so on.Because of this, many activation record
s can be in use at the same time.The data structure is a stack because an activa
tion record has to continue to exist while all the subroutines that are called b
y the subroutine are executed.While they are being executed, the stack ofactivat
ion records can grow and shrink as subroutines are called and return.
# What is a postorder traversal of a binary tree?
Answer: In a traversal of a binary tree, all the nodes are processed in some way
.(For example, they might be printed.) In a postorder traversal, the order of pr
ocessing is defined by the rule: For each node, the nodes in the left subtree of
that node are processed first.Then the nodes in the right subtree are processed
.Finally, the node itself is processed.
# Explaining what is meant by parsing a computer program.
Answer: To parse a computer program means to determine its syntactic structure,
that is, to figure out how it can be constructed using the rules of a grammar (s
uch as a BNF grammar).

211. A subroutine is said to have a contract.What is meant by the contract of a


subroutine? When you want to use a subroutine, why is it important to understan
d its contract? The contract has both "syntactic" and "semantic" aspects.What is
the syntactic aspect? What is the semantic aspect?
Answer: The contract of a subroutine says what must be done to call the su
broutine correctly and what it will do when it is called.It is, in short, everyt
hing a programmer needs to know about the subroutine in order to use it correctl
y.(It does not include the "insides," or implementation, of the subroutine.)
The syntactic component of a subroutine's contract includes the name of th
e subroutine, the number of parameters, and the type of each parameter.This is t
he information needed to write a subroutine call statement that can be successfu
lly compiled.The semantic component of the contract specifies the meaning of the
subroutine, that is, the task that the subroutine performs.It might also specif
y limitations on what parameter values the subroutine can process correctly.The
semantic component is not part of the program.It is generally expressed in comme
nts.
212. Briefly explain how subroutines can be a useful tool in the top-down desig
n of programs.
Answer: Top-down refers to starting from the overall problem to be solved,
and breaking it up into smaller problems that can be solved separately.When des
igning a program to solve the problem, you can simply make up a subroutine to so
lve each of the smaller problems.Then you can separately design and test each su
broutine.
213. Discuss the concept of parameters.What are parameters for? What is the dif
ference between formal parameters and actual parameters?
Answer: Parameters are used for communication between a subroutine and the
part of the program that calls the subroutine.If a subroutine is thought of as
a black box, then parameters are part of the interface to that black box.Formal
parameters are found in the subroutine definition.Actual parameters are found in
subroutine call statements.When the subroutine is called, the values of the act
ual parameters are assigned to the formal parameters before the body of the subr
outine is executed.
214. Give two different reasons for using named constants
Answer: A constant has a meaningful name, which makes the program easier t
o read.It's easier to understand what a name like INTEREST_RATE is for than it i
s to figure out how a literal number like 0.07 is being used.
A second reason for using named constants is that it's easy to modify the
value of the constant if that becomes necessary.If a literal value is used throu
ghout the program, the programmer has to track down each occurrence of the value
and change it.When a constant is used correctly, it is only necessary to change
the value assigned to the constant at one point in the program.
A third reason is that using the final modifier protects the value of a va
riable from being changed.This is especially important for member variables that
are accessible from outside the class where they are declared.
215. What is an API? Give an example.
Answer: An API is an Applications Programming Interface.It is the interfac
e to a "toolbox" of subroutines that someone has written.It tells you what routi
nes are available, how to call them, and what they do, but it does not tell you
how the subroutines are implemented.An example is the standard Java API which de
scribes the interfaces of all the subroutines in all the classes that are availa
ble in such packages as java.lang and java.awt.
216. Write a subroutine named "stars" that will output a line of stars to stand
ard output.(A star is the character "*".) The number of stars should be given as
a parameter to the subroutine.Use a for loop.For example, the command "stars(20
)" would output
********************
Answer: The subroutine could be written as follows.
static void stars(int numberOfStars) {
for (int i = 0; i < numberOfStars; i++) {
System.out.print('*');
}
System.out.println();
}
217. Write a main() routine that uses the subroutine that you wrote for Questio
n 7 to output 10 lines of stars with 1 star in the first line, 2 stars in the se
cond line, and so on, as shown below. *
**
***
****
*****
******
*******
********
*********
**********
Answer: The main() routine can use a for loop that calls the stars() subro
utine ten times, once to produce each line of output.(An occasional beginner's m
istake in this problem is to rewrite the body of the subroutine inside the main(
) routine, instead of just calling it by name.) Here is the main routine -- whic
h would, of course, have to be put together with the subroutine in a class in or
der to be used.
public static void main(String[] args) {
int line;
for ( line = 1;line <= 10;line++ ) {
stars( line );
}
}
218. Write a function named countChars that has a String and a char as paramete
rs.The function should count the number of times the character occurs in the str
ing, and it should return the result as the value of the function.
Answer: The returned value will be of type int.The function simply uses a
for loop to look at each character in the string.When the character in the strin
g matches the parameter value, it is counted.
static int countChars( String str, char searchChar ) {
int i;
char ch;
int count;
count = 0;
for ( i = 0;i < str.length();i++ ) {
ch = str.charAt(i);
if ( ch == searchChar )
count++;
}
return count;
}
219. Write a subroutine with three parameters of type int.The subroutine should
determine which of its parameters is smallest.The value of the smallest paramet
er should be returned as the value of the subroutine.
Answer: I'll call the subroutine smallest and the three parameters x, y, a
nd z.The value returned by the subroutine has to be either x or y or z.The answe
r will be x if x is less than or equal to both y and z.The correct syntax for ch
ecking this is "if (x <= y && x <= z).Similarly for y.The only other remaining p
ossibility is z, so there is no necessity for making any further test before ret
urning z.
static int smallest(int x, int y, int z) {
if (x <= y && x <= z) {
return x;
}
else if (y <= x && y <= z) {
return y;
}
else
return z;
}
Note: Since a return statement causes the computer to terminate the execut
ion of a subroutine anyway, this could also be written as follows, without the e
lses:
static int smallest(int x, int y, int z) {
if (x <= y && x <= z) {
return x;
}
if (y <= x && y <= z) {
return y;
}
return z;
}
220. Object-oriented programming uses classes and objects.What are classes and
what are objects? What is the relationship between classes and objects?
Answer: When used in object-oriented programming, a class is a factory for
creating objects.(We are talking here about the non-static part of the class.)
An object is a collection of data and behaviors that represent some entity (real
or abstract).A class defines the structure and behaviors of all entities of a g
iven type.An object is one particular "instance" of that type of entity.For exam
ple, if Dog is a class, than Lassie would be an object of type Dog.

221. Explain carefully what null means in Java, and why this special value is n
ecessary.
Answer: When a variable is of object type (that is, declared with a class
as its type rather than one of Java's primitive types), the value stored in the
variable is not an object.Objects exist in a part of memory called the heap, and
the variable holds a pointer or reference to the object.Null is a special value
that can be stored in a variable to indicate that it does not actually point to
any object.
222. What is a constructor? What is the purpose of a constructor in a class?
Answer: A constructor is a special kind of subroutine in a class.It has th
e same name as the name of the class, and it has no return type, not even void.A
constructor is called with the new operator in order to create a new object.Its
main purpose is to initialize the newly created object, but in fact, it can do
anything that the programmer wants it to do.
223. Suppose that Kumquat is the name of a class and that fruit is a variable o
f type Kumquat.What is the meaning of the statement "fruit = new Kumquat();"? Th
at is, what does the computer do when it executes this statement? (Try to give a
complete answer.The computer does several things.)
Answer: This statement creates a new object belonging to the class Kumquat
, and it stores a reference to that object in the variable fruit.More specifical
ly, when the computer executes this statement, it allocates memory to hold a new
object of type Kumquat.It calls a constructor, which can initialize the instanc
e variables of the object as well as perform other tasks.A reference to the new
object is returned as the value of the expression "new Kumquat()".Finally, the a
ssignment statement stores the reference in the variable, fruit.So, fruit can no
w be used to access the new object.
224. What is meant by the terms instance variable and instance method?
Answer: Instance variables and instance methods are non-static variables a
nd methods in a class.This means that they do not belong to the class itself.Ins
tead, they specify what variables and methods are in an object that belongs to t
hat class.That is, the class contains the source code that defines instance vari
ables and instance methods, but actual instance variables and instance methods a
re contained in object.
225. Explain what is meant by the terms subclass and superclass.
Answer: In object oriented programming, one class can inherit all the prop
erties and behaviors from another class.It can then add to and modify what it in
herits.The class that inherits is called a subclass, and the class that it inher
its from is said to be its superclass.InJava, the fact that ClassA is a subclass
of ClassB is indicated in the definition of ClassA as follows:
class ClassA extends ClassB {...}
226. Explain the term polymorphism.
Answer: Polymorphism refers to the fact that different objects can respond
to the same method in different ways, depending on the actual type of the objec
t.This can occur because a method can be overridden in a subclass.In that case,
objects belonging to the subclass will respond to the method differently from ob
jects belonging to the superclass.
227. Java uses "garbage collection" for memory management.Explain what is meant
here by garbage collection.What is the alternative to garbage collection?
Answer: The purpose of garbage collection is to identify objects that can
no longer be used, and to dispose of such objects and reclaim the memory space t
hat they occupy.If garbage collection is not used, then the programmer must be r
esponsible for keeping track of which objects are still in use and disposing of
objects when they are no longer needed.If the programmer makes a mistake, then t
here is a "memory leak," which might gradually fill up memory with useless objec
ts until the program crashes for lack of memory.
228. For this problem, you should write a very simple but complete class.The cl
ass represents a counter that counts 0, 1, 2, 3, 4,....The name of the class sho
uld be Counter.It has one private instance variable representing the value of th
e counter.It has two instance methods: increment() adds one to the counter value
, and getValue() returns the current counter value.Write a complete definition f
or the class, Counter.
Answer: Here is a possible answer.
public class Counter {
private int value = 0;
public void increment() {
value++;
}
public int getValue() {
return value;
}
}
229. This problem uses the Counter class from Question 9.The following program
segment is meant to simulate tossing a coin 100 times.It should use two Counter
objects, headCount and tailCount, to count the number of heads and the number of
tails.Fill in the blanks so that it will do so.
Counter headCount, tailCount;
tailCount = new Counter();
headCount = new Counter();
for ( int flip = 0;flip < 100;flip++ ) {
if (Math.random() < 0.5)
______________________;
else
______________________;
}
System.out.println("There were " + ___________________ + " heads.");
System.out.println("There were " + ___________________ + " tails.");
Answer: The variable headCount is a variable of type Counter, so the only
thing that you can do with it is call the instance methods headCount.increment()
and headCount.getValue().Call headCount.increment() to add one to the counter.C
all headCount.getValue() to discover the current value of the counter.Note that
you can't get at the value of the counter directly, since the variable that hold
s the value is a private instance variables in the Counter object.Similarly for
tailCount.Here is the program with calls to these instance methods filled in:
Counter headCount, tailCount;
tailCount = new Counter();
headCount = new Counter();
for ( int flip = 0;flip < 100;flip++ ) {
if (Math.random() < 0.5)
headCount.increment();
else
tailCount.increment();
}
System.out.println(("There were " + headCount.getValue() + " heads.");
System.out.println(("There were " + tailCount.getValue() + " tails.");
230. Programs written for a graphical user interface have to deal with "events.
" Explain what is meant by the term event.Give at least two different examples o
f events, and discuss how a program might respond to those events.
Answer: An event is anything that can occur asynchronously, not under the
control of the program, to which the program might want to respond.GUI programs
are said to be "event-driven" because for the most part, such programs simply wa
it for events and respond to them when they occur.In many (but not all) cases, a
n event is the result of a user action, such as when the user clicks the mouse b
utton, types a character, or clicks a button.The program might respond to a mous
e-click on a canvas by drawing a shape, to a typed character by adding the chara
cter to an input box, or to a click on a button by clearing a drawing.More gener
ally, a programmer can set up any desired response to an event by writing an eve
nt-handling routine for that event.

# What is an event loop?


Answer: An event-driven program doesn't have a main() routine that says what wil
l happen from beginning to end, in a step-by-step fashion.Instead, the program r
uns in a loop that says:
while the program is still running:
Wait for the next event
Process the event
This is called an event loop.In Java, the event loop is executed by the system.T
he system waits for events to happen.When an event occurs, the system calls a ro
utine that has been designated to handle events of that type.
# Explain carefully what the repaint() method does.
Answer: The repaint() method is called to notify the system that the applet (or
other component for which it is called) needs to be redrawn.It does not itself d
o any drawing (neither directly nor by calling a paint() or paintComponent() rou
tine).You should call repaint() when you have made some change to the state of t
he applet that requires its appearance to change.Sometime shortly after you call
it, the system will call the applet's paint() routine or the component's paintC
omponent() routine.
# Suppose that you are writing an applet, and you want the applet to respond in
some way when the user clicks the mouse on the applet.What are the four things y
ou need to remember to put into the source code of your applet?
Answer: The four things are as follows:
* Since the event and listener classes are defined in the java.awt.event pac
kage, you have to put "import java.awt.event.*;" at the beginning of the source
code, before the class definition.
* The applet class must be declared to implement the MouseListener interface
, by adding the words "implements MouseListener" to the heading.For example: "pu
blic class MyApplet extends JApplet implements MouseListener".(It is also possib
le for another object besides the applet to listen for the mouse events.)
* The class must include definitions for each of the five methods specified
in the MouseListener interface.Even if a method is not going to do anything, it
has to be defined, with an empty body.
* The applet (or other listening object) must be registered to listen for mo
use events by calling addMouseListener().This is usually done in the init() meth
od of the applet.
# Java has a standard class called MouseEvent.What is the purpose of this class?
What does an object of type MouseEvent do?
Answer: When an event occurs, the system packages information about the event in
to an object.That object is passed as a parameter to the event-handling routine.
Different classes of objects represent different types of events.An object of ty
pe MouseEvent represents a mouse or mouse motion event.It contains information a
bout the location of the mouse cursor and any modifier keys that the user is hol
ding down.This information can be obtained by calling the instance methods of th
e object.For example, if evt is a MouseEvent object, then evt.getX() is the x-co
ordinate of themouse cursor, and evt.isShiftDown() is a boolean value that tells
you whether the user was holding down the Shift key.
# Explain what is meant by input focus.How is the input focus managed in a Java
GUI program?
Answer: When the user uses the keyboard, the events that are generated are direc
ted to some component.At a given time, there is just one component that can get
keyboard events.That component is said to have the input focus.Usually, the appe
arance of a component changes if it has the input focus and wants to receive use
r input from the keyboard.For example, there might be a blinking text cursor in
the component, or the component might be hilited with a colored border.In order
to change its appearance in this way, the component needs to be notified when it
gains or loses the focus.InJava, a component gets this notification by listenin
g for focus events.
Some components, including applets and canvasses, do not get the input focus unl
ess they request it by calling requestFocus().If one of these components needs t
o process keyboard events, it should also listen formouse events and call reques
tFocus() when the user clicks on the component.(Unfortunately, this rule is not
enforced uniformly on all platforms.)
# Java has a standard class called JPanel.Discuss two ways in which JPanels can
be used.
Answer: A JPanel is a type of component.That is, it is a visible element of a GU
I.By itself, a JPanel is simply a blank rectangular region on the screen.However
, a JPanel is a "container", which means that other components can be added to i
t and will then appear on the screen inside the JPanel.A JPanel can also be used
as a drawing surface.
The two ways are as follows:
* paintComponent()An object belonging to that subclass can then be added to
an applet or other component.The
* paintComponent()This method defines how that object will draw itself on th
e screen.
# What is the FontMetrics class used for?
Answer: An object that belongs to the class FontMetrics can be used to obtain in
formation about the sizes of characters and strings that are drawn in a specific
font.The font is specified when the FontMetrics object is created.If fm is a va
riable of type FontMetrics, then, for example, fm.stringWidth(str) gives the wid
th of the string str and fm.getHeight() is the usual amount of vertical space al
lowed for one line of text.This information could be used, for example, for posi
tioning the string is a component.
# What are off-screen images? How are they used? Why are they important? What do
es this have to do with animation?
Answer: In Java, an off-screen image is an object belonging to the class Image a
nd created with the createImage() function.An off-screen image is a segment of t
he computer's memory that can be used as a drawing surface.What is drawn to the
off-screen image is not visible on the screen, but the Image can be quickly copi
ed onto the screen with a drawImage() command.It is important to use an off-scre
en image in a situation where the user should not see the process of drawing the
image.This is true, for example, in animation.Each frame of the animation can b
e composed in an off-screen Image and then copied to the screen when it is compl
ete.The alternative would be to erase the screen and draw the next frame directl
y on the screen.This causes unacceptable flickering of the image.By default, Swi
ng already uses an off-screen image for double-buffering an applet or frame, so
you don't have to program it yourself just to do simple animation.
# One of the main classes in Swing is the JComponent class.What is meant by a co
mponent? What are some examples?
Answer: A JComponent represents a visual component of the computer's graphical u
ser interface.A JComponent is not completely independent.It must be added to a "
container," such as an applet or a frame.Examples of JComponents are JButtons, J
TextFields, and JPanels.
# What is the function of a LayoutManager in Java?
Answer: A LayoutManager implements some policy for laying out all the visual com
ponents that have been added to a container, such as a JPanel or the content pan
e of a JApplet.That is, it sets the sizes and positions of the components.Differ
ent types of layout managers have different rules about how components are to be
arranged.Some standard layout manager classes are BorderLayout and GridLayout.

# Explain how preconditions can be used as an aid in writing correct programs.


Answer: Suppose that a programmer recognizes a precondition at some point in a p
rogram.This is a signal to the programmer that an error might occur if the preco
ndtion is not met.In order to have a correct and robustprogram , the programmer
must deal with the possible error.There are several approaches that the programm
er can take.One approach is to use an if statement to test whether the precondit
ion is satisfied.If not, the programmer can take some other action such as print
ing an error message and terminating theprogram .Another approach is to use a tr
y statement to catch and respond to the error.This is really just a cleaner way
of accomplishing the same thing as the first approach.The best approach, when it
is possible, is to ensure that the precondition is satisfied as a result of wha
t has already been done in the program.For example, if the precondition is that
x >= 0, and the preceding statement is "x = Math.abs(y);", then we know that the
precondition is satisfied, since the absolute value of any number is greater th
an or equal to zero.
# Java has a predefined class called Throwable.What does this class represent? W
hy does it exist?
Answer: The class Throwable represents all possible objects that can be thrown b
y a throw statement and caught by a catch clause in a try...catch statement.That
is, the thrown object must belong to the class Throwable or to one of its (many
) subclasses such as Exception and RuntimeException.The object carries informati
on about an exception from the point where the exception occurs to the point whe
re it is caught and handled.
# Some classes of exceptions require mandatory exception handling.Explain what t
his means.
Answer: Subclasses of the class Exception which are not subclasses of RuntimeExc
eption require mandatory exception handling.This has two consequences: First, if
a subroutine can throw such an exception, then it must declare this fact by add
ing a throws clause to the subroutine heading.Second, if a routine includes any
code that can generate such anexception, then the routine must deal with the exc
eption.It can do this by including the code in a try statement that has a catch
clause to handle the exception.Or it can use a throws clause to declare that cal
ling the subroutine might throw the exception.
# Consider a subroutine processData that has the header
static void processData() throws IOException
Write a try...catch statement that calls this subroutine and prints an error mes
sage if an IOException occurs.
Answer: try {
processData();
}
catch (IOException e) {
System.out.println( "An IOException occurred while precessing the data.");
}
# Why should a subroutine throw an exception when it encounters an error? Why no
t just terminate the program?
Answer: Terminating the program is too drastic, and this tactic certainly doesn'
t lead to robust programs! It's likely that the subroutine doesn't know what to
do with the error, but that doesn't mean that it should abort the whole program.
When the subroutine throws an exception, the subroutine is terminated, but the p
rogram that called the subroutine still has a chance to catch the exception and
handle it.In effect, the subroutine is saying "Alright, I'm giving up.Let's hope
someone else can deal with the problem."
# In Java, input/output is done using streams.Streams are an abstraction.Explain
what this means and why it is important.
Answer: A stream represents a source from which data can be read or a destinatio
n to which data can be written.A stream is an abstraction because it represents
the abstract idea of a source or destination of data, as opposed to specific, co
ncrete sources and destinations such as a particular file or network connection.
The stream abstraction is important because it allows programmers to do input/ou
tput using the same methods for a wide variety of data sources and destinations.
It hides the details of working with files, networks, and the screen and keyboar
d.
# Java has two types of streams: character streams and byte streams.Why? What is
the difference between the two types of streams?
Answer: Character streams are for working with data in human-readable format, th
at is, data expressed as sequences of characters.Byte streams are for data expre
ssed in the machine-readable format that is used internally in the computer to r
epresent the data while aprogram is running.It is very efficient for a computer
to read and write data in machine format, since no translation of the data is ne
cessary.However, if a person must deal directly with the data, then character st
reams should be used so that the data is presented in human-readable form.
# What is a file? Why are files necessary?
Answer: A file is a collection of data that has been given a name and stored on
some permanent storage device such as a hard disk or floppy disk.Files are neces
sary because data stored in the computer's RAM is lost whenever the computer is
turned off.Data that is to be saved permanently must be stored in a file.
# What is the point of the following statement?
out = new PrintWriter( new FileWriter("data.dat") );
Why would you need a statement that involves two different stream classes, Print
Writer and FileWriter?
Answer: The PrintWriter class is being used as a "wrapper" for the FileWriter cl
ass.A FileWriter is a stream object that knows how to send individual characters
to a file.By wrapping this in a PrintWriter, you get the ability to write other
data types such as ints, doubles, and Strings to the file using the PrintWriter
's print() and println() methods.Wrapping the FileWriter in a PrintWriter adds c
apabilities to the file output stream but still sends the data to the same desti
nation.
# The package java.io includes a class named URL.What does an object of type URL
represent, and how is it used?
Answer: A url is an address for a web page (or other information) on the Interne
t.For example, "http://math.hws.edu/javanotes/index.html" is a url that refers t
o the main page of the current edition of this on-line textbook.A URL object rep
resents such an address.Once you have a URL object, you can call its openConnect
ion() method to access the information at the url address that it represents.

# What is the purpose of the following subroutine? What is the meaning of the va
lue that it returns, in terms of the value of its parameter?
static String concat( String[] str ) {
if (str == null)
return "";
String ans = "";
for (int i = 0; i < str.length; i++) {
ans = ans + str[i];
return ans;
}
Answer: The purpose of the subroutine is to chain all the strings in an array of
strings into one long string.If the array parameter is null, then there are no
strings, and the empty string is returned.Otherwise, the value returned is the s
tring made up of all the strings from the array.For example, if stringList is an
array declared as String[] stringList = { "Put 'em ", "all", " together" };
then the value of concat(stringList) is "Put 'em all together".
# Show the exact output produced by the following code segment.
char[][] pic = new char[6][6];
for (int i = 0; i < 6; i++)
for (int j = 0; j < 6; j++) {
if ( i == j || i == 0 || i == 5 )
pic[i][j] = '*';
else
pic[i][j] = '.';
}
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
System.out.print(pic[i][j]);
System.out.println();
}
Answer: The output consists of six lines, with each line containing six characte
rs.In the first line, i is 0, so all the characters are *'s.In the last line, i
is 5, so all the characters are *'s.In each of the four lines in the middle, one
of the characters is a * and the rest are periods.The output is
******
.*....
..*...
...*..
....*.
******
It might help to look at the array items that are printed on each line.Note that
pic[row][col] is '*' if row is 0 or if row is 5 or if row and col are equal.
pic[0][0] pic[0][1] pic[0][2] pic[0][3] pic[0][4] pic[0][5]
pic[1][0] pic[1][1] pic[1][2] pic[1][3] pic[1][4] pic[1][5]
pic[2][0] pic[2][1] pic[2][2] pic[2][3] pic[2][4] pic[2][5]
pic[3][0] pic[3][1] pic[3][2] pic[3][3] pic[3][4] pic[3][5]
pic[4][0] pic[4][1] pic[4][2] pic[4][3] pic[4][4] pic[4][5]
pic[5][0] pic[5][1] pic[5][2] pic[5][3] pic[5][4] pic[5][5]
# Write a complete subroutine that finds the largest value in an array of ints.T
he subroutine should have one parameter, which is an array of type int[].The lar
gest number in the array should be returned as the value of the subroutine.
Answer: public static int getMax(int[] list) {
int max = list[0];
for (int i = 1; i < list.length; i++) {
if (list[i] > max)
max = list[i];
}
return max;
}
# What is a precondition? Give an example.
Answer: A precondition is a condition that has to hold at given point in the exe
cution of a program, if the execution of the program is to continue correctly.Fo
r example, the statement "x = A[i];" has two preconditions: that A is not null a
nd that 0 <= i < A.length.If either of these preconditions is violated, then the
execution of the statement will generate an error.
Also, a precondition of a subroutine is a condition that has to be true when the
subroutine is called in order for the subroutine to work correctly.
# Is "abc" a primitive value?
Answer: The String literal "abc" is not a primitive value. It is a String object
.
# What restrictions are placed on the values of each case of a switch statement?
Answer: During compilation, the values of each case of a switch statement must e
valuate to a value that can be promoted to an int value.
# What modifiers may be used with an interface declaration?
Answer: An interface may be declared as public or abstract.
# Is a class a subclass of itself?
Answer: A class is a subclass of itself.
# What is the difference between a while statement and a do statement?
Answer: A while statement checks at the beginning of a loop to see whether the n
ext loop iteration should occur. A do statement checks at the end of a loop to s
ee whether the next iteration of a loop should occur. The do statement will alwa
ys execute the body of a loop at least once.
# What modifiers can be used with a local inner class?
Answer: A local inner class may be final or abstract.

# What is the purpose of the File class?


Answer: The File class is used to create objects that provide access to the file
s and directories of a local file system.
# Can an exception be rethrown?
Answer: Yes, an exception can be rethrown.
# When does the compiler supply a default constructor for a class?
Answer: The compiler supplies a default constructor for a class if no other cons
tructors are provided.
# If a method is declared as protected, where may the method be accessed?
Answer: Classes or interfaces of the same package or may only access a protected
method by subclasses of the class in which it is declared.
# Which non-Unicode letter characters may be used as the first character of an i
dentifier?
Answer: The non-Unicode letter characters $ and _ may appear as the first charac
ter of an identifier.
# What restrictions are placed on method overloading?
Answer: Two methods may not have the same name and argument list but different r
eturn types.
# What is casting?
Answer: There are two types of casting, casting between primitive numeric types
and casting between object references. Casting between numeric types is used to
convert larger values, such as double values, to smaller values, such as byte va
lues. Casting between object references is used to refer to an object by a compa
tible class, interface, or array type reference.
# What is the return type of a program's main() method?
Answer: A program's main() method has a void return type.
# What class of exceptions are generated by the Java run-time system?
Answer: The Java runtime system generates RuntimeException and Error exceptions.
# What class allows you to read objects directly from a stream?
Answer: The ObjectInputStream class supports the reading of objects from input s
treams.

# Is "abc" a primitive value?


Answer: The String literal "abc" is not a primitive value. It is a String object
.
# What restrictions are placed on the values of each case of a switch statement?
Answer: During compilation, the values of each case of a switch statement must e
valuate to a value that can be promoted to an int value.
# What modifiers may be used with an interface declaration?
Answer: An interface may be declared as public or abstract.
# Is a class a subclass of itself?
Answer: A class is a subclass of itself.
# What is the difference between a while statement and a do statement?
Answer: A while statement checks at the beginning of a loop to see whether the n
ext loop iteration should occur. A do statement checks at the end of a loop to s
ee whether the next iteration of a loop should occur. The do statement will alwa
ys execute the body of a loop at least once.
# What modifiers can be used with a local inner class?
Answer: A local inner class may be final or abstract.
# What is the purpose of the File class?
Answer: The File class is used to create objects that provide access to the file
s and directories of a local file system.
# Can an exception be rethrown?
Answer: Yes, an exception can be rethrown.
# When does the compiler supply a default constructor for a class?
Answer: The compiler supplies a default constructor for a class if no other cons
tructors are provided.
# If a method is declared as protected, where may the method be accessed?
Answer: Classes or interfaces of the same package or may only access a protected
method by subclasses of the class in which it is declared.

# Which non-Unicode letter characters may be used as the first character of an i


dentifier?
Answer: The non-Unicode letter characters $ and _ may appear as the first charac
ter of an identifier.
# What restrictions are placed on method overloading?
Answer: Two methods may not have the same name and argument list but different r
eturn types.
# What is casting?
Answer: There are two types of casting, casting between primitive numeric types
and casting between object references. Casting between numeric types is used to
convert larger values, such as double values, to smaller values, such as byte va
lues. Casting between object references is used to refer to an object by a compa
tible class, interface, or array type reference.
# What is the return type of a program's main() method?
Answer: A program's main() method has a void return type.
# What class of exceptions are generated by the Java run-time system?
Answer: The Java runtime system generates RuntimeException and Error exceptions.
# What class allows you to read objects directly from a stream?
Answer: The ObjectInputStream class supports the reading of objects from input s
treams.
# What is the difference between a field variable and a local variable?
Answer: A field variable is a variable that is declared as a member of a class.
A local variable is a variable that is declared local to a method.
# How are this() and super() used with constructors?
Answer: this() is used to invoke a constructor of the same class. super() is use
d to invoke a superclass constructor.
# What is the relationship between a method's throws clause and the exceptions t
hat can be thrown during the method's execution?
Answer: A method's throws clause must declare any checked exceptions that are no
t caught within the body of the method.
# Why are the methods of the Math class static?
Answer: So they can be invoked as if they are a mathematical code library.

# What are the legal operands of the instanceof operator?


Answer: The left operand is an object reference or null value and the right oper
and is a class, interface, or array type.
# What an I/O filter?
Answer: An I/O filter is an object that reads from one stream and writes to anot
her, usually altering the data in some way as it is passed from one stream to an
other.
# If an object is garbage collected, can it become reachable again?
Answer: Once an object is garbage collected, it ceases to exist. It can no longe
r become reachable again.
# What are E and PI?
Answer: E is the base of the natural logarithm and PI is mathematical value pi.
# Are true and false keywords?
Answer: The values true and false are not keywords.
# What is the difference between the File and RandomAccessFile classes?
Answer: The File class encapsulates the files and directories of the local file
system. The RandomAccessFile class provides the methods needed to directly acces
s data contained in any part of a file.
# What happens when you add a double value to a String?
Answer: The result is a String object.
# What is your platform's default character encoding?
Answer: If you are running Java on English Windows platforms, it is probably Cp1
252. If you are running Java on English Solaris platforms, it is most likely 885
9_1.
# Which package is always imported by default?
Answer: The java.lang package is always imported by default.
# What interface must an object implement before it can be written to a stream a
s an object?
Answer: An object must implement the Serializable or Externalizable interface be
fore it can be written to a stream as an object.
# How can my application get to know when a HttpSession is removed?
Answer: Define a Class HttpSessionNotifier which implements HttpSessionBindingLi
stener and implement the functionality what you need in valueUnbound() method. C
reate an instance of that class and put that instance in HttpSession.
# Whats the difference between notify() and notifyAll()?
Answer: notify() is used to unblock one waiting thread; notifyAll() is used to u
nblock all of them. Using notify() is preferable (for efficiency) when only one
blocked thread can benefit from the change (for example, when freeing a buffer b
ack into a pool). notifyAll() is necessary (for correctness) if multiple threads
should resume.
# Why can't I say just abs() or sin() instead of Math.abs() and Math.sin()?
Answer: The import statement does not bring methods into your local name space.
It lets you abbreviate class names, but not get rid of them altogether. That's j
ust the way it works, you'll get used to it. It's really a lot safer this way. H
owever, there is actually a little trick you can use in some cases that gets you
what you want. If your top-level class doesn't need to inherit from anything el
se, make it inherit from java.lang.Math. That *does* bring all the methods into
your local name space. But you can't use this trick in an applet, because you ha
ve to inherit from java.awt.Applet. And actually, you can't use it on java.lang.
Math at all, because Math is a "final" class which means it can't be extended.
# Why are there no global variables in Java?
Answer: Global variables are considered bad form for a variety of reasons: Addin
g state variables breaks referential transparency (you no longer can understand
a statement or expression on its own: you need to understand it in the context o
f the settings of the globalvariables), State variables lessen the cohesion of a
program: you need to know more to understand how something works. A major point
of Object-Oriented programming is to break up global state into more easily und
erstood collections of local state, When you add one variable, you limit the use
of your program to one instance. What you thought was global, someone else migh
t think of as local: they may want to run two copies of your program at once. Fo
r these reasons, Java decided to ban globalvariables.
# What does it mean that a class or member is final?
Answer: A final class can no longer be subclassed. Mostly this is done for secur
ity reasons with basic classes like String and Integer. It also allows the compi
ler to make some optimizations, and makes thread safety a little easier to achie
ve. Methods may be declared final as well. This means they may not be overridden
in a subclass. Fields can be declared final, too. However, this has a completel
y different meaning. A final field cannot be changed after it's initialized, and
it must include an initializer statement where it's declared. For example, publ
ic final double c = 2.998; It's also possible to make a static field final to ge
t the effect of C++'s const statement or some uses of C's #define, e.g. public s
tatic final double c = 2.998;
# What does it mean that a method or class is abstract?
Answer: An abstract class cannot be instantiated. Only its subclasses can be ins
tantiated. You indicate that a class is abstract with the abstract keyword like
this: public abstract class Container extends Component {Abstract classes may co
ntain abstract methods. A method declared abstract is not actually implemented i
n the current class. It exists only to be overridden in subclasses. It has no bo
dy. For example, public abstract float price();Abstract methods may only be incl
uded in abstract classes. However, an abstract class is not required to have any
abstract methods, though most of them do. Each subclass of an abstract class mu
st override the abstract methods of its superclasses or itself be declared abstr
act.
# What is a transient variable?
Answer: transient variable is a variable that may not be serialized.
# How are Observer and Observable used?
Answer: Objects that subclass the Observable class maintain a list of observers.
When an Observable object is updated it invokes the update() method of each of
its observers to notify the observers that it has changed state. The Observer in
terface is implemented by objects that observe Observable objects.
# Can a lock be acquired on a class?
Answer: Yes, a lock can be acquired on a class. This lock is acquired on the cla
ss's Class object.
# What state does a thread enter when it terminates its processing?
Answer: When a thread terminates its processing, it enters the dead state.

# How does Java handle integer overflows and underflows?


Answer: It uses those low order bytes of the result that can fit into the size o
f the type allowed by the operation.
# What is the difference between the >> and >>> operators?
Answer: The >> operator carries the sign bit when shifting right. The >>> zero-f
ills bits that have been shifted out.
# Is sizeof a keyword?
Answer: The sizeof operator is not a keyword.
# Does garbage collection guarantee that a program will not run out of memory?
Answer: Garbage collection does not guarantee that a program will not run out of
memory. It is possible for programs to use up memory resources faster than they
are garbage collected. It is also possible for programs to create objects that
are not subject to garbage collection.
# Can an object's finalize() method be invoked while it is reachable?
Answer: An object's finalize() method cannot be invoked by the garbage collector
while the object is still reachable. However, an object's finalize() method may
be invoked by other objects.
# What value does readLine() return when it has reached the end of a file?
Answer: The readLine() method returns null when it has reached the end of a file
.
# Can a for statement loop indefinitely?
Answer: Yes, a for statement can loop indefinitely. For example, consider the fo
llowing: for(;;);
# To what value is a variable of the String type automatically initialized?
Answer: The default value of an String type is null.
# What is a task's priority and how is it used in scheduling?
Answer: A task's priority is an integer value that identifies the relative order
in which it should be executed with respect to other tasks. The scheduler attem
pts to schedule higher priority tasks before lower priority tasks.
# What is the range of the short type?
Answer: The range of the short type is (215) to 215 - 1.
# What is the purpose of garbage collection?
Answer: The purpose of garbage collection is to identify and discard objects tha
t are no longer needed by a program so that their resources may be reclaimed and
reused.
# What do you understand by private, protected and public?
Answer: These are accessibility modifiers. Private is the most restrictive, whil
e public is the least restrictive. There is no real difference between protected
and the default type (also known as package protected) within the context of th
e same package, however the protected keyword allows visibility to a derived cla
ss in a different package.
# What is Downcasting ?
Answer: Downcasting is the casting from a general to a more specific type, i.e.
casting down the hierarchy.
# Can a method be overloaded based on different return type but same argument ty
pe?
Answer: No, because the methods can be called without using their return type in
which case there is ambiquity for the compiler.
# What happens to a static var that is defined within a method of a class?
Answer: Can't do it. You'll get a compilation error.
# How many static init can you have?
Answer: As many as you want, but the static initializers and class variable init
ializers are executed in textual order and may not refer to class variables decl
ared in the class whose declarations appear textually after the use, even though
these class variables are in scope.
# What is the difference amongst JVM Spec, JVM Implementation, JVM Runtime?
Answer: The JVM spec is the blueprint for the JVM generated and owned by Sun. Th
e JVM implementation is the actual implementation of the spec by a vendor and th
e JVM runtime is the actual running instance of a JVM implementation.
# What does the "final" keyword mean in front of a variable? A method? A class?
Answer: FINAL for a variable: value is constant. FINAL for a method: cannot be o
verridden. FINAL for a class: cannot be derived.
# What is the difference between instanceof and isInstance?
Answer: instanceof is used to check to see if an object can be cast into a speci
fied type without throwing a cast class exception. isInstance() Determines if th
e specified Object is assignment-compatible with the object represented by this
Class. This method is the dynamic equivalent of the Java language instanceof ope
rator. The method returns true if the specified Object argument is non-null and
can be cast to the reference type represented by this Class object without raisi
ng a ClassCastException. It returns false otherwise.
# Why does it take so much time to access an Applet having Swing Components the
first time?
Answer: Because behind every swing component are many Java objects and resources
. This takes time to create them in memory. JDK 1.3 from Sun has some improvemen
ts which may lead to faster execution of Swing applications.

Você também pode gostar