Download Java Job Interview Questions

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java Job Interview Questions & Answers
Special Tips
The rule is that not the best qualified candidates get job. Your on-site performance plays a big
role. Here are some easily forgettable points.
90% interviewing questions raised based on your own resume.
eye-to-eye contact, smiling all the way. don't miss anyone in the corner.
asking easier and relevant questions back to the interviewers occasionally.
be honest to answer technical questions, you are not expert to know everything.
don't let your boss feel you might be a threat to take his position.
don't be critical, focus on what you can do.
try to be humor to show your smartness.
don't act in a superior way.
find right time to raise questions AND answer those questions to show your
strength.
aggressively to get candidacy info back after interviewing.
For more tips, go to this special tips page
<http://www.javacamp.org/misc/specialtips.html>
Tell me about yourself?
The first is focusing on the needs of the organization. The second is focusing on
the needs of the people within that organization. Don't talk so much about strong
points about yourself because your resume has already brought you at the
interview site.
How to deal with a question that is inappropriate?
Briefly answer the question and move to a new topic.
Ignore the question and redirect the discussion toward a different
topic.
If the question is blatant and offensive, you have every right to
terminate the interview and walk out.
Don't answer the question, but answer the intent behind the
question.
For instance, if the interviewer asks, "Who is going to take care of your children
when you have to travel?" You might answer, "I can meet the travel and work
schedule that this job requires." Or if he/she asks, "Are you planning a family in
the future?" You might say, "Right now I am focused on my career and as a
family is always an option, it is not a priority right now."
What lessons have you learnt from "Apprentice" show?
At least 8 lessons:
Have a Strategy
Find Out What the Boss/Client Wants and Give it to Them
Deal With the Person in Charge
Be Positive
Have the Courage to Speak Your Mind
Stand Up For Yourself
Be Flexible
There's Life After Being Fired
Return to top <http://www.javacamp.org/jobinterview.html>
Java Language
Note: only the most important questions are listed below and they are not categorized, since your
interviewing questions will not be categorized either.
More Java related interview questions.
<http://www.javacamp.org/scjp/interview.html>
Can a private method of a superclass be declared within a subclass?
Sure. A private field or method or inner class belongs to its declared class and
hides from its subclasses. There is no way for private stuff to have a runtime
overloading or overriding (polymorphism) features.
Why Java does not support multiple inheritence ?
Java DOES support multiple inheritance via interface implementation.
What is the difference between final, finally and finalize?
final - declare constant
finally - handles exception
finalize - helps in garbage collection
Where and how can you use a private constuctor.
Private constructor can be used if you do not want any other class to instanstiate
the object , the instantiation is done from a static public method, this method is
used when dealing with the factory method pattern when the designer wants only
one controller (fatory method ) to create the object .
In System.out.println(),what is System,out and println,pls explain?
System is a predefined final class,out is a PrintStream object and println is a builtin overloaded method in the out object.
What is meant by "Abstract Interface"?
First, an interface is abstract. That means you cannot have any implementation in
an interface. All the methods declared in an interface are abstract methods or
signatures of the methods.
Can you make an instance of an abstract class? For example - java.util.Calender is
an abstract class with a method getInstance() which returns an instance of the
Calender class.
No! You cannot make an instance of an abstract class. An abstract class has to be
sub-classed. If you have an abstract class and you want to use a method which has
been implemented, you may need to subclass that abstract class, instantiate your
subclass and then call that method.
What is the output of x<y? a:b = p*q when x=1,y=2,p=3,q=4?
When this kind of question has been asked, find the problems you think is
necessary to ask before you give an answer. Ask if variables a and b have been
declared or initialized. If the answer is yes. You can say that the syntax is wrong.
If the statement is rewritten as: x<y? a:(b=p*q); the return value would be
variable a because the x is 1 and less than y = 2; the x < y statement return true
and variable a is returned.
What is the difference between Swing and AWT components?
AWT components are heavy-weight, whereas Swing components are lightweight.
Heavy weight components depend on the local windowing toolkit. For example,
java.awt.Button is a heavy weight component, when it is running on the Java
platform for Unix platform, it maps to a real Motif button.
Why Java does not support pointers?
Because pointers are unsafe. Java uses reference types to hide pointers and
programmers feel easier to deal with reference types without pointers. This is why
Java and C# shine.
Parsers? DOM vs SAX parser
parsers are fundamental xml components, a bridge between XML documents and
applications that process that XML. The parser is responsible for handling xml
syntax, checking the contents of the document against constraints established in a
DTD or Schema.
DOM SAX
---------------------------------------------------------------1. Tree of nodes 1.Sequence of events
2.Memory: Occupies more memory, 2.does'nt use any memory
preffered for small XML documents preferred for large documents
3.Slower at runtime 3. Faster at runtime
4.stored as objects 4. objects are to be created
5.Programmatically easy, since objects 5.Need to write code for
creating objects
are to reffered
6.Ease of navigation 6.backward navigation is not possible as it
sequentially processes the document
Return to top <http://www.javacamp.org/jobinterview.html>
Networking
More networking questions
<http://www.javacamp.org/j2ee/network/network.html>
What two protocols are used in Java RMI technology?
Java Object Serialization and HTTP. The Object Serialization protocol is used to
marshal call and return data. The HTTP protocol is used to "POST" a remote
method invocation and obtain return data when circumstances warrant.
What is difference between Swing and JSF?
The key difference is that JSF runs on the server in a standard Java servlet
container like Tomcat or WebLogic and display HTML or some other markup to
the client.
What is JSF?
JSF stands for JavaServer Faces, or simply Faces. It is a framework for building
Web-based user interfaces in Java. Like Swing, it provides a set of standard
widgets such as buttons, hyperlinks, checkboxes, ans so on.
Return to top <http://www.javacamp.org/jobinterview.html>
XML
More XML questions <http://www.javacamp.org/j2ee/xml/xmlfaqs.html>
Return to top <http://www.javacamp.org/jobinterview.html>
JDBC
More JDBC questions
<http://www.javacamp.org/moreclasses/jdbc/jdbcfaqs.html>
Return to top <http://www.javacamp.org/jobinterview.html>
JSP
More JSP questions <http://www.javacamp.org/j2ee/jsp/jspfaqs.html>
What is a JSP and what is it used for?
Java Server Pages (JSP) is a platform independent presentation layer technology
that comes with SUN’s J2EE platform. JSPs are normal HTML pages with Java
code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler
is used in the background to generate a Servlet from the JSP page.
What is difference between custom JSP tags and beans?
Custom JSP tag is a tag you defined. You define how a tag, its attributes and its
body are interpreted, and then group your tags into collections called tag libraries
that can be used in any number of JSP files. To use custom JSP tags, you need to
define three separate components:
the tag handler class that defines the tag's behavior
the tag library descriptor file that maps the XML element names to
the tag implementations
the JSP file that uses the tag library
When the first two components are done, you can use the tag by using taglib
directive:
<%@ taglib uri="xxx.tld" prefix="..." %>
Then you are ready to use the tags you defined. Let's say the tag prefix is test:
<test:tag1>MyJSPTag</test:tag1> or <test:tag1 />
JavaBeans are Java utility classes you defined. Beans have a standard format for
Java classes. You use tags
<jsp:useBean id="identifier" class="packageName.className"/>
to declare a bean and use
<jsp:setProperty name="identifier" property="classField"
value="someValue" />
to set value of the bean class and use
<jsp:getProperty name="identifier" property="classField" />
<%=identifier.getclassField() %>
to get value of the bean class.
Custom tags and beans accomplish the same goals -- encapsulating complex
behavior into simple and accessible forms. There are several differences:
Custom tags can manipulate JSP content; beans cannot.
Complex operations can be reduced to a significantly simpler form
with custom tags than with beans.
Custom tags require quite a bit more work to set up than do beans.
Custom tags usually define relatively self-contained behavior,
whereas beans are often defined in one servlet and used in a
different servlet or JSP page.
Custom tags are available only in JSP 1.1 and later, but beans can
be used in all JSP 1.x versions.
what are the two kinds of comments in JSP and whats the difference between
them
<%-- JSP Comment --%>
<!-- HTML Comment -->
Return to top <http://www.javacamp.org/jobinterview.html>
Servlet
More Servlet questions <http://www.javacamp.org/j2ee/servlet/servletfaqs.html>
What mechanisms are used by a Servlet Container to maintain session
information?
Cookies, URL rewriting, and HTTPS protocol information are used to maintain
session information
Difference between GET and POST
In GET, your entire form submission can be encapsulated in one URL, like a
hyperlink. query length is limited to 260 characters, not secure, faster, quick and
easy.
In POST, your name/value pairs inside the body of the HTTP request, which
makes for a cleaner URL and imposes no size limitations on the form's output. It
is used to send a chunk of data to the server to be processed, more versatile, most
secure.
What is session?
The session is an object used by a servlet to track a user's interaction with a Web
application across multiple HTTP requests.
What is servlet mapping?
The servlet mapping defines an association between a URL pattern and a servlet.
The mapping is used to map requests to servlets.
What is servlet context ?
The servlet context is an object that contains a servlet's view of the Web
application within which the servlet is running. Using the context, a servlet can
log events, obtain URL references to resources, and set and store attributes that
other servlets in the context can use. (answer supplied by Sun's tutorial).
Which interface must be implemented by all servlets?
Servlet interface.
Return to top <http://www.javacamp.org/jobinterview.html>
EJB
More EJB questions <http://www.javacamp.org/j2ee/ejb/ejbfaqs.html>
What is session Facade
Session Facade is a design pattern to access the Entity bean through local
interface than acessing directly. It increases the performance over the network. In
this case we call session bean which on turn call entity bean
what is the difference between session and entity bean?
Session beans are business data and have not any persistance. Entity beans are
Data Objects and have more persistance.
Return to top <http://www.javacamp.org/jobinterview.html>
J2EE
More J2EE questions <http://www.javacamp.org/j2ee/j2ee/j2eefaqs.html>
What is difference between J2EE 1.3 and J2EE 1.4?
J2EE 1.4 is an enhancement version of J2EE 1.3. It is the most complete Web
services platform ever.
J2EE 1.4 includes:
Java API for XML-Based RPC (JAX-RPC 1.1)
SOAP with Attachments API for Java (SAAJ),
Web Services for J2EE(JSR 921)
J2EE Management Model(1.0)
J2EE Deployment API(1.1)
Java Management Extensions (JMX),
Java Authorization Contract for Containers(JavaACC)
Java API for XML Registries (JAXR)
Servlet 2.4
JSP 2.0
EJB 2.1
JMS 1.1
J2EE Connector 1.5
The J2EE 1.4 features complete Web services support through the new JAX-RPC
1.1 API, which supports service endpoints based on servlets and enterprise beans.
JAX-RPC 1.1 provides interoperability with Web services based on the WSDL
and SOAP protocols.
The J2EE 1.4 platform also supports the Web Services for J2EE specification
(JSR 921), which defines deployment requirements for Web services and utilizes
the JAX-RPC programming model.
In addition to numerous Web services APIs, J2EE 1.4 platform also features
support for the WS-I Basic Profile 1.0. This means that in addition to platform
independence and complete Web services support, J2EE 1.4 offers platform Web
services interoperability.
The J2EE 1.4 platform also introduces the J2EE Management 1.0 API, which
defines the information model for J2EE management, including the standard
Management EJB (MEJB). The J2EE Management 1.0 API uses the Java
Management Extensions API (JMX).
The J2EE 1.4 platform also introduces the J2EE Deployment 1.1 API, which
provides a standard API for deployment of J2EE applications.
The J2EE 1.4 platform includes security enhancements via the introduction of the
Java Authorization Contract for Containers (JavaACC). The JavaACC API
improves security by standardizing how authentication mechanisms are integrated
into J2EE containers.
The J2EE platform now makes it easier to develop web front ends with
enhancements to Java Servlet and JavaServer Pages (JSP) technologies. Servlets
now support request listeners and enhanced filters. JSP technology has simplified
the page and extension development models with the introduction of a simple
expression language, tag files, and a simpler tag extension API, among other
features. This makes it easier than ever for developers to build JSP-enabled pages,
especially those who are familiar with scripting languages.
Other enhancements to the J2EE platform include the J2EE Connector
Architecture, which provides incoming resource adapter and Java Message
Service (JMS) pluggability. New features in Enterprise JavaBeans (EJB)
technology include Web service endpoints, a timer service, and enhancements to
EJB QL and message-driven beans.
The J2EE 1.4 platform also includes enhancements to deployment descriptors.
They are now defined using XML Schema which can also be used by developers
to validate their XML structures.
Note: The above information comes from SUN released notes.
Do you have to use design pattern in J2EE project?
Yes. If I do it, I will use it. Learning design pattern will boost my coding skill.
Is J2EE a super set of J2SE?
Yes
Return to top <http://www.javacamp.org/jobinterview.html>
JMS
What is JMS?
Java Message Service is the new standard for interclient communication. It allows
J2EE application components to create, send, receive, and read messages. It
enables distributed communication that is loosely coupled, reliable, and
asynchronous.
what type messaging is provided by JMS
Both synchronous and asynschronous
How may messaging models do JMS provide for and what are they?
JMS provide for two messaging models, publish-and-subscribe and point-to-point
queuing
Return to top <http://www.javacamp.org/jobinterview.html>
Misc
What is WML?
Wireless Markup Language (WML) page is delivered over Wireless Application
Protocol (WAP) and the network configuration requires a gateway to translate
WAP to HTTP and back again. It can be generated by a JSP page or servlet
running on the J2EE server.
What software development methodologies are prevailing?
Rational Unified Process(RUP) <http://www.rational.com> -Model-driven architecture, design and development; customizable
framework for scalable processes; developed and marketed by
Rational company.
Enterprise Unified Process(EUP)
<http://www.enterpriseunifiedprocess.info> -- extension of
RUP(add: production, retirement, operations,support and enterprise
disciplines.)
Personal Software Process(PSP) -- Self-calibration.
Team Software Process(TSP) -- Extends PSP with specific roles.
Agile Modeling (AM)-- Feature-driven, test often.
Extreme Programming(XP) -- Effective pair-programming.
Reuse -- Across multiple providers.
Architecture-driven reuse -- domain component
Artifact reuse -- use cases, standards docu, models,
procesures, guidelines,etc.
Code reuse -- source code, across multiple
applications, etc.
Component reuse -- fully-encapsulated, well tested
components.
Framework reuse -- collections of classes with basic
funtionality of a common tech or business domain.
Inheritance reuse -- taking advantagle of behavior
implemented in existing classes.
Pattern reuse -- publicly documented approaches to
solve common problems.
Template reuse -- common set of layouts for key
development artifacts.
Note: They are all iterative development methodologies.
What are orthogonal dimensions in software development?
There are several popular orthogonal dimensions listed as follows
Top-down vs. bottom-up.
Waterfall vs. incremental.
Iterative vs. concurrent.
Planned vs. mining.
Same team vs. different team.
What is domain engineering(DE)?
Domain engineering(DE) is a process that produces reusable assets including
components, web services, generators, frameworks, models and documents, for
subsequent use in the development of applications or product line.
What is domain analysis(DA)?
Domain analysis(DA) is the front part of domain engineering(DE), which
analyzes the anticipated applications, technology trends, standards,and existing
assets to develop a model of commonality, variability and initial features into
reusable assets.
What are alpha, beta or gamma version of a software?
alpha -- the release contains some large section of new code that
hasn't been 100% tested.
beta -- all new code has been tested, no fatal bugs.
gamma -- a beta that has been around a while and seems to work
fine. Only minor fixes are added. The so-called a release.
What is the difference between component and class?
A component is a finished class, whereas a class is a design schema. A component
is ready to be used as a member of a class and a class may consist of many
components(classes). Component and class names may be exchangeble in
context. For example, a Button is a component and also a class. MyWindow class
may contain several buttons.
What is JUnit?
JUnit is a unit-testing framework. Unit-testing is a means of verifying the results
you expect from your classes. If you write your test before hand and focus your
code on passing the test you are more likely to end up with simple code that does
what it should and nothing more. Unit-testing also assists in the refactoring
process. If your code passes the unit-test after refactoring you will know that you
haven't introduced any bugs to it.
What is the difference between Java and PL/SQL?
Java is a general programming language. PL/SQL is a database query languague,
especially for Oracle database.
Return to top <http://www.javacamp.org/jobinterview.html>
Donate a Job Interview Question
Anyone is allowed to donate a job interview question here. The contents you put in will be
censored every three days by webmaster to ensure the quality. If you think your question is cool
and don't want others to see it before censoring, please send email to javacamp
<mailto:[email protected]?subject=donate a job interview question>. If your machine
doesn't have an email client to use, please contact us via this link.
<http://www.javacamp.org/contactus.html>
If you want to add a job interview question, please follow steps below:
Select a subject from the left drop down menu.
Enter the question.
Enter your answer. If you don't know how to answer, leave it blank or just type
some words in.
Click "Add a Job Interview Question" button.
If you want to clear it before clicking "Add a Job Interview Question" button,
click "Clear" button.
Your added question will be reviewed by javacamp webmaster.
If you add a job interview question to this page, your question will not be shown immediately as
you did before. We alter the rules because we find that some guys abuse such function and list
garbage or repeated questions. If you concern about this or really want to publish your question
quickly, please feel free to contact javacamp.org <http://www.javacamp.org/contactus.html>
=====================================================================
===============
Java Language Questions
What is a platform?
A platform is the hardware or software environment in which a program runs.
Most platforms can be described as a combination of the operating system and
hardware, like Windows 2000/XP, Linux, Solaris, and MacOS.
What is the main difference between Java platform and other platforms?
The Java platform differs from most other platforms in that it's a software-only
platform that runs on top of other hardware-based platforms.
The Java platform has two components:
The Java Virtual Machine (Java VM)
The Java Application Programming Interface (Java API)
What is the Java Virtual Machine?
The Java Virtual Machine is a software that can be ported onto various hardwarebased platforms.
What is the Java API?
The Java API is a large collection of ready-made software components that
provide many useful capabilities, such as graphical user interface (GUI) widgets.
What is the package?
The package is a Java namespace or part of Java libraries. The Java API is
grouped into libraries of related classes and interfaces; these libraries are known
as packages.
What is native code?
The native code is code that after you compile it, the compiled code runs on a
specific hardware platform.
Is Java code slower than native code?
Not really. As a platform-independent environment, the Java platform can be a bit
slower than native code. However, smart compilers, well-tuned interpreters, and
just-in-time bytecode compilers can bring performance close to that of native
code without threatening portability.
What is the serialization?
The serialization is a kind of mechanism that makes a class or a bean persistence
by having its properties or fields and state information saved and restored to and
from storage.
How to make a class or a bean serializable?
By implementing either the java.io.Serializable interface, or the
java.io.Externalizable interface. As long as one class in a class's inheritance
hierarchy implements Serializable or Externalizable, that class is serializable.
How many methods in the Serializable interface?
There is no method in the Serializable interface. The Serializable interface acts as
a marker, telling the object serialization tools that your class is serializable.
How many methods in the Externalizable interface?
There are two methods in the Externalizable interface. You have to implement
these two methods in order to make your class externalizable. These two methods
are readExternal() and writeExternal().
What is the difference between Serializalble and Externalizable interface?
When you use Serializable interface, your class is serialized automatically by
default. But you can override writeObject() and readObject() two methods to
control more complex object serailization process. When you use Externalizable
interface, you have a complete control over your class's serialization process.
What is a transient variable?
A transient variable is a variable that may not be serialized. If you don't want
some field to be serialized, you can mark that field transient or static.
Which containers use a border layout as their default layout?
The Window, Frame and Dialog classes use a border layout as their default
layout.
How are Observer and Observable used?
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 interface
is implemented by objects that observe Observable objects.
What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the
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 causes dirty data and
leads to significant errors.
What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to an object. A
thread only executes a synchronized method after it has acquired the lock for the
method's object or class. Synchronized statements are similar to synchronized
methods. A synchronized statement can only be executed after a thread has
acquired the lock for the object or class referenced in the synchronized statement.
What are three ways in which a thread can enter the waiting state?
A thread can enter the waiting state by invoking its sleep() method, by blocking
on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an
object's wait() method. It can also enter the waiting state by invoking its
(deprecated) suspend() method.
Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class
object.
What's new with the stop(), suspend() and resume() methods in JDK 1.2?
The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.
What is the preferred size of a component?
The preferred size of a component is the minimum component size that will allow
the component to display normally.
What method is used to specify a container's layout?
The setLayout() method is used to specify a container's layout.
Which containers use a FlowLayout as their default layout?
The Panel and Applet classes use the FlowLayout as their default layout.
What is thread?
A thread is an independent path of execution in a system.
What is multithreading?
Multithreading means various threads that run in a system.
How does multithreading take place on a computer with a single CPU?
The operating system's task scheduler allocates execution time to multiple tasks.
By quickly switching between executing tasks, it creates the impression that tasks
execute sequentially.
How to create multithread in a program?
You have two ways to do so. First, making your class "extends" Thread class.
Second, making your class "implements" Runnable interface. Put jobs in a run()
method and call start() method to start the thread.
Can Java object be locked down for exclusive use by a given thread?
Yes. You can lock an object by putting it in a "synchronized" block. The locked
object is inaccessible to any thread other than the one that explicitly claimed it.
Can each Java object keep track of all the threads that want to exclusively access
to it?
Yes.
What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.
What invokes a thread's run() method?
After a thread is started, via its start() method of the Thread class, the JVM
invokes the thread's run() method when the thread is initially executed.
What is the purpose of the wait(), notify(), and notifyAll() methods?
The wait(),notify(), and notifyAll() methods are used to provide an efficient way
for threads to communicate each other.
What are the high-level thread states?
The high-level thread states are ready, running, waiting, and dead.
What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on
collections of objects.
What is the List interface?
The List interface provides support for ordered collections of objects.
How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type
allowed by the operation.
What is the Vector class?
The Vector class provides the capability to implement a growable array of objects
What modifiers may be used with an inner class that is a member of an outer
class?
A (non-local) inner class may be declared as public, protected, private, static,
final, or abstract.
If a method is declared as protected, where may the method be accessed?
A protected method may only be accessed by classes or interfaces of the same
package or by subclasses of the class in which it is declared.
What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection.
How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8
characters?
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character
set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters
using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When a task
invokes its sleep() method, it returns to the waiting state.
Is sizeof a keyword?
The sizeof operator is not a keyword.
What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects.
Does garbage collection guarantee that a program will not run out of memory?
No, it doesn't. 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
What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the
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 reenters the pool of
ready tasks. The scheduler then determines which task should execute next, based
on priority and other factors.
Name Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.
What is a native method?
A native method is a method that is implemented in a language other than Java.
How can you write a loop indefinitely?
for(;;)--for loop; while(true)--always true, etc.
Can an anonymous class be declared as implementing an interface and extending
a class?
An anonymous class may implement an interface or extend a superclass, but may
not be declared to do both.
What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to
perform any cleanup processing before the object is garbage collected.
Which class is the superclass for every class.
Object
What is the difference between the Boolean & operator and the && operator?
If an expression involving the Boolean & operator is evaluated, both operands are
evaluated. Then the & operator is applied to the operand. When an expression
involving the && operator is evaluated, the first operand is evaluated. If the first
operand returns a value of true then the second operand is evaluated. The &&
operator is then applied to the first and second operands. If the first operand
evaluates to false, the evaluation of the second operand is skipped.
Operator & has no chance to skip both sides evaluation and && operator does. If
asked why, give details as above.
What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.
What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.
Which Container method is used to cause a container to be laid out and
redisplayed?
validate()
What is the Properties class?
The properties class is a subclass of Hashtable that can be read from or written to
a stream. It also provides the capability to specify a set of default values to be
used.
What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.
What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.
What is the purpose of the finally clause of a try-catch-finally statement?
The finally clause is used to provide the capability to execute code no matter
whether or not an exception is thrown or caught.
What is the Locale class?
The Locale class is used to tailor program output to the conventions of a particular
geographic, political, or cultural region.
What must a class do to implement an interface?
It must provide all of the methods in the interface and identify the interface in its
implements clause.
What is an abstract method?
An abstract method is a method whose implementation is deferred to a subclass.
Or, a method that has no implementation (an interface of a method).
What is a static method?
A static method is a method that belongs to the class rather than any object of the
class and doesn't apply to an object or even require that any objects of the class
have been instantiated.
What is a protected method?
A protected method is a method that can be accessed by any method in its
package and inherited by any subclass of its class.
What is the difference between a static and a non-static inner class?
A non-static inner class may have object instances that are associated with
instances of the class's outer class. A static inner class does not have any object
instances.
What is an object's lock and which object's have locks?
An object's lock is a mechanism that is used by multiple threads to obtain
synchronized access to the object. A thread may execute a synchronized method
of an object only after it has acquired the object's lock. All objects and classes
have locks. A class's lock is acquired on the class's Class object.
When can an object reference be cast to an interface reference?
An object reference be cast to an interface reference when the object implements
the referenced interface.
What is the difference between a Window and a Frame?
The Frame class extends Window to define a main application window that can
have a menu bar.
What do heavy weight components mean?
Heavy weight components like Abstract Window Toolkit (AWT), depend on the
local windowing toolkit. For example, java.awt.Button is a heavy weight
component, when it is running on the Java platform for Unix platform, it maps to
a real Motif button. In this relationship, the Motif button is called the peer to the
java.awt.Button. If you create two Buttons, two peers and hence two Motif
Buttons are also created. The Java platform communicates with the Motif Buttons
using the Java Native Interface. For each and every component added to the
application, there is an additional overhead tied to the local windowing system,
which is why these components are called heavy weight.
Which package has light weight components?
javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame
and JWindow are lightweight components.
What are peerless components?
The peerless components are called light weight components.
What is the difference between the Font and FontMetrics classes?
The FontMetrics class is used to define implementation-specific properties, such
as ascent and descent, of a Font object.
What happens when a thread cannot acquire a lock on an object?
If a thread attempts to execute a synchronized method or synchronized statement
and is unable to acquire an object's lock, it enters the waiting state until the lock
becomes available.
What is the difference between the Reader/Writer class hierarchy and the
InputStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the
InputStream/OutputStream class hierarchy is byte-oriented.
What classes of exceptions may be caught by a catch clause?
A catch clause can catch any exception that may be assigned to the Throwable
type. This includes the Error and Exception types.
What is the difference between throw and throws keywords?
The throw keyword denotes a statement that causes an exception to be initiated. It
takes the Exception object to be thrown as argument. The exception will be
caught by an immediately encompassing try-catch construction or propagated
further up the calling hierarchy.
The throws keyword is a modifier of a method that designates that exceptions
may come out of the mehtod, either by virtue of the method throwing the
exception itself or because it fails to catch such exceptions that a method it calls
may throw.
If a class is declared without any access modifiers, where may the class be
accessed?
A class that is declared without any access modifiers is said to have package or
friendly access. This means that the class can only be accessed by other classes
and interfaces that are defined within the same package.
What is the Map interface?
The Map interface replaces the JDK 1.1 Dictionary class and is used associate
keys with values.
Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its superclasses.
Name primitive Java types.
The primitive types are byte, char, short, int, long, float, double, and boolean.
Which class should you use to obtain design information about an object?
The Class class is used to obtain information about an object's design.
How can a GUI component handle its own events?
A component can handle its own events by implementing the required eventlistener interface and adding itself as its own event listener.
How are the elements of a GridBagLayout organized?
The elements of a GridBagLayout are organized according to a grid. However, the
elements are of different sizes and may occupy more than one row or column of
the grid. In addition, the rows and columns may have different sizes.
What advantage do Java's layout managers provide over traditional windowing
systems?
Java uses layout managers to lay out components in a consistent manner across all
windowing platforms. Since Java's layout managers aren't tied to absolute sizing
and positioning, they are able to accommodate platform-specific differences
among windowing systems.
What are the problems faced by Java programmers who don't use layout
managers?
Without layout managers, Java programmers are faced with determining how
their GUI will be displayed across multiple windowing systems and finding a
common sizing and positioning that will work within the constraints imposed by
each windowing system.
What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific
instances of a class. Non-static variables take on unique values with each object
instance.
What is the difference between the paint() and repaint() methods?
The paint() method supports painting via a Graphics object. The repaint() method
is used to cause paint() to be invoked by the AWT painting thread.
What is the purpose of the File class?
The File class is used to create objects that provide access to the files and
directories of a local file system.
What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different return
types.
What restrictions are placed on method overriding?
Overridden methods must have the same name, argument list, and return type.
The overriding method may not limit the access of the method it overrides. The
overriding method may not throw any exceptions that may not be thrown by the
overridden method.
What is casting?
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
values. Casting between object references is used to refer to an object by a
compatible class, interface, or array type reference.
Name Container classes.
Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane
What class allows you to read objects directly from a stream?
The ObjectInputStream class supports the reading of objects from input streams.
How are this() and super() used with constructors?
this() is used to invoke a constructor of the same class. super() is used to invoke a
superclass constructor.
How is it possible for two String objects with identical values not to be equal
under the == operator?
The == operator compares two objects to determine if they are the same object in
memory. It is possible for two String objects to have the same value, but located
indifferent areas of memory.
What an I/O filter?
An I/O filter is an object that reads from one stream and writes to another, usually
altering the data in some way as it is passed from one stream to another.
What is the Set interface?
The Set interface provides methods for accessing the elements of a finite
mathematical set. Sets do not allow duplicate elements.
What is the List interface?
The List interface provides support for ordered collections of objects.
What is the purpose of the enableEvents() method?
The enableEvents() method is used to enable an event for a particular object.
Normally, an event is enabled when a listener is added to an object for a particular
event. The enableEvents() method is used by objects that handle events by
overriding their event-dispatch methods.
What is the difference between the File and RandomAccessFile classes?
The File class encapsulates the files and directories of the local file system. The
RandomAccessFile class provides the methods needed to directly access data
contained in any part of a file.
What interface must an object implement before it can be written to a stream as an
object?
An object must implement the Serializable or Externalizable interface before it
can be written to a stream as an object.
What is the ResourceBundle class?
The ResourceBundle class is used to store locale-specific resources that can be
loaded by a program to tailor the program's appearance to the particular locale in
which it is being run.
What is the difference between a Scrollbar and a ScrollPane?
A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A
ScrollPane handles its own events and performs its own scrolling.
What is a Java package and how is it used?
A Java package is a naming context for classes and interfaces. A package is used
to create a separate name space for groups of classes and interfaces. Packages are
also used to organize related classes and interfaces into a single API unit and to
control accessibility to these classes and interfaces.
What are the Object and Class classes used for?
The Object class is the highest-level class in the Java class hierarchy. The Class
class is used to represent the classes and interfaces that are loaded by a Java
program.
What is Serialization and deserialization?
Serialization is the process of writing the state of an object to a byte stream.
Deserialization is the process of restoring these objects.
what is tunnelling?
Tunnelling is a route to somewhere. For example, RMI tunnelling is a way to
make RMI application get through firewall. In CS world, tunnelling means a way
to transfer data.
Does the code in finally block get executed if there is an exception and a return
statement in a catch block?
If an exception occurs and there is a return statement in catch block, the finally
block is still executed. The finally block will not be executed when the
System.exit(1) statement is executed earlier or the system shut down earlier or the
memory is used up earlier before the thread goes to finally block.
How you restrict a user to cut and paste from the html page?
Using javaScript to lock keyboard keys. It is one of solutions.
Is Java a super set of JavaScript?
No. They are completely different. Some syntax may be similar.
What is a Container in a GUI?
A Container contains and arranges other components (including other containers)
through the use of layout managers, which use specific layout policies to
determine where components should go as a function of the size of the container.
How the object oriented approach helps us keep complexity of software
development under control?
We can discuss such issue from the following aspects:
Objects allow procedures to be encapsulated with their data to
reduce potential interference.
Inheritance allows well-tested procedures to be reused and enables
changes to make once and have effect in all relevant places.
The well-defined separations of interface and implementation
allows constraints to be imposed on inheriting classes while still
allowing the flexibility of overriding and overloading.
What is polymorphism?
Polymorphism allows methods to be written that needn't be concerned about the
specifics of the objects they will be applied to. That is, the method can be
specified at a higher level of abstraction and can be counted on to work even on
objects of yet unconceived classes.
What is design by contract?
The design by contract specifies the obligations of a method to any other methods
that may use its services and also theirs to it. For example, the preconditions
specify what the method required to be true when the method is called. Hence
making sure that preconditions are. Similarly, postconditions specify what must
be true when the method is finished, thus the called method has the responsibility
of satisfying the post conditions.
In Java, the exception handling facilities support the use of design by contract,
especially in the case of checked exceptions. The assert keyword can be used to
make such contracts.
What are use cases?
A use case describes a situation that a program might encounter and what
behavior the program should exhibit in that circumstance. It is part of the analysis
of a program. The collection of use cases should, ideally, anticipate all the
standard circumstances and many of the extraordinary circumstances possible so
that the program will be robust.
What is the difference between interface and abstract class?
interface contains methods that must be abstract; abstract class
may contain concrete methods.
interface contains variables that must be static and final; abstract
class may contain non-final and final variables.
members in an interface are public by default, abstract class may
contain non-public members.
interface is used to "implements"; whereas abstract class is used to
"extends".
interface can be used to achieve multiple inheritance; abstract class
can be used as a single inheritance.
interface can "extends" another interface, abstract class can
"extends" another class and "implements" multiple interfaces.
interface is absolutely abstract; abstract class can be invoked if a
main() exists.
interface is more flexible than abstract class because one class can
only "extends" one super class, but "implements" multiple
interfaces.
If given a choice, use interface instead of abstract class.
=========================================================
Networking Questions
What is the difference between URL instance and URLConnection instance?
A URL instance represents the location of a resource, and a URLConnection
instance represents a link for accessing or communicating with the resource at the
location.
How do I make a connection to URL?
You obtain a URL instance and then invoke openConnection on it.
URLConnection is an abstract class, which means you can't directly create
instances of it using a constructor. We have to invoke openConnection method on
a URL instance, to get the right kind of connection for your URL. Eg. URL url;
URLConnection connection;
try{ url = new URL("...");
connection = url.openConnection();
}catch (MalFormedURLException e) { }
What Is a Socket?
A socket is one end-point of a two-way communication link between two
programs running on the network. A socket is bound to a port number so that the
TCP layer can identify the application that data is destined to be sent. Socket
classes are used to represent the connection between a client program and a server
program. The java.net package provides two classes--Socket and ServerSocket-which implement the client side of the connection and the server side of the
connection, respectively.
What information is needed to create a TCP Socket?
The Local System?s IP Address and Port Number. And the Remote System's
IPAddress and Port Number.
What are the two important TCP Socket classes?
Socket and ServerSocket. ServerSocket is used for normal two-way socket
communication. Socket class allows us to read and write through the sockets.
getInputStream() and getOutputStream() are the two methods available in Socket
class.
When MalformedURLException and UnknownHostException throws?
When the specified URL is not connected then the URL throw
MalformedURLException and If InetAddress? methods getByName and
getLocalHost are unable to resolve the host name they throw an
UnknownHostException.
What does RMI stand for?
It stands for Remote Method Invocation.
What is RMI?
RMI is a set of APIs that allows to build distributed applications. RMI uses
interfaces to define remote objects to turn local method invocations into remote
method invocations.
=======================================================================
XML FAQS
What Is XML?
XML stands for Extensible Markup Language. It is a text-based meta-markup
language defined by the World Wide Web Consortium <http://www.w3c.org>. It
has become the standard for data interchange on the Web.
Why do we need to learn XML?
Because XML is a meta-markup language, it lets you create your own markup
language.
It is easy for data exchange, customization, self-describing, structured and
integrated.
What does XML look like?
<?xml version="1.0" encoding="UTF-8"?>
<DOCUMENT>
<MESSAGE>
Hello guys!
</MESSAGE>
</DOCUMENT>
What is the difference between HTML and XML?
HTML and XML both are based on Standard Generalized Markup
Language(SGML), but
HTML uses predefined tags, whereas XML uses user-defined tags
which can be used to identify data relationships like hierarchical
structure(elements, subelements, subsubelements,and so on.)
HTML specifies its representation, whereas XML identifies the
content for the data.
Unlike HTML, XML tags are well-formed. XML data is
searchable, format-free and reusable.
What is XML attribute?
Attribute is an additional information attached to a tag. For example
<message to="[email protected]" from="[email protected]"
subject="Discuss XML issues">
<text>
here we go
</text>
</message>
The "to", "from" and "subject" are attributes of "message" tag.
How to deal with double quotes in attribute assignment?
Use a single quote to enclose a double quotes, for example,
<quote txt='he said, "hello guys" ' />
What is an empty tag?
Empty tag is a tag with ending "/>" and used to mark something in your wellformed tags. It doesn't contain any content, so it is called "empty tag". It has two
forms:
<info/>
Note: not </info>
or
<tg> </tg>
or
<Greeting text="hello guys" />
What comments should be used in XML?
Comments are ignored by XML parsers. A program will never see them in fact,
unless you activate special settings in the parser. XML comments are very much
like HTML comments.
<!-- this is a comment -->
It is worth noting that Comments must not come before an XML declaration or
inside markups. You cannot use "--" between your comments. You can use
comments to hide or remove parts of documents as long as the enclosed parts do
not themselves contain any comments.
How to deal with special characters in XML like < or &, etc.?
Like HTML, you should use entity reference to replace them, even if in embeded
JavaScript code.
What is XML Prolog?
Prologs come at the very beginning of XML documents. Like HTML's tag
<html>, XML prolog is a declaration that is used to indicate the start of XML file
like the following:
<?xml version="1.0"?>
or
<?xml version='1.0' encoding='utf-8'?>
or
<?xml version="1.0" encoding="ISO-8859-1" standalone="yes"?>
It contains some or all of three attributes:
version -- not optional
encoding -- default UTF-8
standalone -- "yes" or "no"
It is a good practice to include XML prolog whenever you create an XML file,
though it is optional.
Return to top <xmlfaqs.html>
What is Unicode?
Unicode uses 2 bytes to represent characters, extending from 0 to 65,535. ASCII(American Standard Code for Information
Interchange) code uses 1 byte to represent characters, extending from 0 to 255. The Unicodes 0 to 255 correspond to the ASCII 0 to
255 codes. Therefore, Unicode can include many of the symbols commonly used in worldwide character and ideograph sets.
UTF-8 means using a compressed version of Unicode that uses 8 bits to represent characters. UTF-16 is a special encoding that
represent UCS(Universal Character System) symbols using 2 bytes to represent characters.
How to write XML processing instructions?
The XML processing instructions give commands or information to an application that is processing the XML data; it is application
specific. It has the following format:
<?target instructions?>
where <? is the start and ?> is the end of procession instruction, the "target" is the name of the application that is expected to do the
processing, and "instructions" is a string of characters that embodies the information or commands for the application to process.
Note: there cannot be any space between the initial <? and the target identifier. The "instructions" begins after the first space. Fully
qualifying the target with the complete web-unique package prefix is recommended. For readability, use a (:) after the target name.
Like
<?my.subdirectory.myprograme: query="..."?>
An XML file may have multiple processing instructions to tell different applications to do similar things.
How XML treats with whitespace?
The spaces, carriage returns, line feeds and tabs are all treated as whitespace in XML. XML document uses the UNIX convention
for line endings, which means that lines are ended with a linefeed character only -- ASCII code 10(DOS file uses a pair of ASCII
codes 13 and 10). When parsed, that is treated simply as a single linefeed.
If you want to preserve whitespace, use a special attribute xml:space or set attribute to default to indicate it in a element
declaration.
Is XML tag case-sensitive?
Yes. XML tags are case-sensitive. The start and end tags should be matched exactly.
How to let browser to display XML file?
There are two ways to do so:
Use a style sheet to indicate to a browser how you want the content of the elements to be displayed, like
Cascading Style Sheet(CSS) or Extensible Style Sheet Language(XSL).
use a programming language to handle the XML document in programming code,like Java or JavaScript.
Which is better to store data using elements or using attributes?
There is no clear-cut to say which is better. It depends on the case. But it is worth noting that too many attributes make documents
hard to read and attribute names must be unique. If more than 4 attributes in a tag are used, think about breaking up the tag into a
number of enclosed tags.
Return to top <xmlfaqs.html>
How to use JavaScript to display XML document?
To illustrate it, we use a simple XML document hello.xml as follows:
<?xml version="1.0" encoding="UTF-8"?>
<DOCUMENT>
<MESSAGE>
Hello guys!
</MESSAGE>
</DOCUMENT>
In an HTML file called getxml.html:
<html>
<head>
<xml id="Myxml" src="hello.xml"></xml>
<script language="JavaScript">
function getData(){
xmldoc=document.all("Myxml").XMLDocument;
node=xmldoc.documentElement;
nodeMsg=node.firstChild;
output="From hello.xml file, you get -- " +
nodeMsg.firstChild.nodeValue;
message.innerHTML=output;
}
</script>
</head>
<body>
<h1 align=center>Get data from XML document</h1>
Here comes: <div id ="message"></div>
<input type="button" value="get data from xml"
onclick="getData()">
</body>
</html>
Here is the display in your browser. Click the button to see what happens? Press the "F5" button on your keyboard to refresh the
display.
Get data from XML document
Here comes:
What is DTD tag?
A DTD tag is a tag used in DTD definition file. It starts with <! and ends with >. It tells parser how to handle xml file.
What is CDATA?
A CDATA is a section mark which works like <pre>...</pre> in HTML, only more so--all whitespace in a CDATA section is
significant, and characters in it are not interpreted as XML. A CDATA section starts with <![CDATA[ and ends with ]]>. If you
have a section which contains many & or <, you can mark it, so the XML processor will not parse it.
What is the basic syntax for the document type declaration?
The basic syntax:
<!DOCTYPE root-name [DTD]>
where the <!DOCTYPE> is part of a document's prolog; the root-name is the name of root tag; the DTD is a document type
definition. It can be internal or external.
The document type declaration may have the following forms:
<!DOCTYPE root-name [DTD]>
<!DOCTYPE root-name SYSTEM URL>
<!DOCTYPE root-name SYSTEM URL [DTD]>
<!DOCTYPE root-name PUBLIC identifier URL>
<!DOCTYPE root-name PUBLIC identifier URL [DTD]>
How the internal DTD looks like?
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE DOCUMENT [
<!ELEMENT DOCUMENT (CUSTOMER) *>
]>
<DOCUMENT>
<CUSTOMER>
....
</DOCUMENT>
What is the syntax of element declaration?
<!ELEMENT NAME CONTENT_MODEL>
where name is the name of the element; CONTENT_MODEL can be set to EMPTY or ANY, or it can hold mixed content or child
elements.
What is the meaning of the following statement?
<!ELEMENT slideshow (slide+)>
This is a DTD tag definition. The notation says that a slideshow element consists of one or more slide elements. If there is no plus
sign after slide, it says that a slideshow has only one slide element. If the plus sign is replaced with question mark "?", it says there
may be zero or one slide. If the plus sign is replaced with asterisk "*", it say that there may be zero or more slide elements.
What syntax should be used to describe a more children elements?
For example, if a and b represent child elements:
a+ -- one or more occurences of a
a* -- zero or more occurences of a
a? -- a or nothing
a, b -- a followed by b
a | b -- a or b, but not both
(expression) -- a unit may have more of above expressions
What the following tells us in a dtd file?
1. <!ELEMENT slideshow (slide+)>
2. <!ELEMENT slide (title, item*)>
3. <!ELEMENT title (#PCDATA)>
4. <!ELEMENT item (#PCDATA | item)*>
5. <!ELEMENT %content; >
The first line says that a slideshow element contains one or more slide elements. The second line says that a slide element consists
of a title followed by zero or more item elements. The third line says that a title element consists entirely of parsed character
data(PCDATA). The "#" sign that precedes PCDATA indicates that what follows is a special word. The fourth line says the item
element is either PCDATA or an item. The asterisk at the end says that either one can occur zero or more times in succession. The
fifth line says that content is a parameter entity reference.
What is mixed-content model?
The content of a tag in the xml file can be #PCDATA or any number of item elements like the fourth line above.
Is DTD definition hierarchical?
No. The DTD definition is not hierarchical. But you can work around to make your xml tags hierarchical. For example, if you have
a title for slideshow and a title for each slide, you can use slide-title to represent the title in slide and make a definition for slidetitle. It is so called "hyphenation hierarchy. Otherwise, the title definition will work for every title in xml file.
What is special element value and how to use it?
There are two special values: ANY or EMPTY. The "ANY" notation says that the element may contain any other defined element,
or PCDATA. The "EMPTY" notation says that the element contains no contents. For example an empty tag contains no contents.
How to reference a DTD file?
If the DTD definition is in a separate file from the XML document, you have to write something to reference it from the XML
document. For example, if your slideshow.dtd is ready for use, then, in your xml document file, after the xml declaration, write:
<!DOCTYPE slideshow SYSTEM "slideshow.dtd">
The above statement says that the element slideshow tag will use definition in slideshow.dtd. The SYSTEM identifier specifies the
location of the DTD file and the path is relative to the location of the xml document. You may use http:// or file:/ to indicate the
path of the DTD file.
Or you can reference a definition within the XML document by using a square brackets like the following, rather than referring to
an external DTD file.
<!DOCTYPE slideshow SYSTEM "slideshow1.dtd" [
...local subset definitions here...
]>
How to declare a public DTD?
Replace SYSTEM to PUBLIC and give url to that dtd.
<!DOCTYPE slideshow PUBLIC "-//somewhere//customized XML Version
1.0//EN"
"http://www.somewhere.com/someones/slideshow1.dtd" >
What is the meaning of ATTLIST? What do the following statements tell us?
ATTLIST means attribute list. The name that follows ATTLIST specifies the element for which the attributes are being defined.
For example, you have a slideshow tag with title, date and author attributes, you may code as:
<!ELEMENT slideshow (slide+)>
<!ATTLIST slideshow
title CDATA #REQUIRED
date CDATA #IMPLIED
author CDATA "unknown"
>
<!ELEMENT slide (title, item*)>
The DTD tag ATTLIST begins the series of attribute definitions. The slideshow element has three attributes. The title, date and
author are the names of attributes of slideshow. CDATA is a type of the attribute; it means unparsed charater data or a text string.
The #REQUIRED means the attribute value must be specified in the document. The #IMPLIED means the value need not be
specified in the document.
What does the & sign mean in dtd file?
The & sign means an entity variable name. Note it should be ended with semicolon ";" sign. For example:
<!DOCTYPE slideshow SYSTEM "slideshow.dtd" [
<!ENTITY copyright "&#169" >
...
]>
...
&copyright; ...
Wherever the &copyright; is parsed, it will be replaced with entity copyright sign ©.
How to declare a parameter entity reference?
Use <!ENTITY> to declare it and use an & as start and ; as end to enclose the parameter entity reference. For example, TODAY is
a parameter entity reference.
<?xml version='1.0' standalone="yes"?>
<!DOCTYPE DOCUMENT [
<!ELEMENT GREETING (#PCDATA)>
<!ELEMENT MESSAGE (#PCDATA)>
<!ELEMENT DATE (#PCDATA)>
<!ENTITY TODAY "NOV 1, 2003">
]>
<DOCUMENT>
<GREETING>
HELLO FROM HTML
</GREETING>
<MESSAGE>
WELCOME TO THE WILD WORLD
</MESSAGE>
<DATE> &TODAY; </DATE>
</DOCUMENT>
Save above file as greeting.xml, use your browser to look at it. You may get a similar display, except that the <DATE> tag will
display "NOV 1, 2003".
Note: It is possible that your browser may not support XML. If you use MS IE 5.5 above, or NS 5.0 above, you may be able to see
it.
How to declare an image tag in a DTD file?
You can declare an image tag in the following form:
1. <!ELEMENT image EMPTY>
2. <!ATTLIST image
alt CDATA #IMPLIED
src CDATA #REQUIRED
type CDATA "image/gif"
>
3. <!NOTATION GIF SYSTEM "image/gif">
4. <!ENTITY some SYSTEM "image.gif" NDARA GIF>
The line one declares image as an optional element. The line 2 declares attributes of an image tag. For the moment, you can not
declare an image tag like type ("image/gif", "image/jpeg"). The line 3 declares a notation named GIF that stands for the image/gif
MIME type. The line 4 creates an external unparsed entity named some to refer to the external image file, image.gif.
What is conditional section?
Conditional section is a way to let XML document to choose which dtd should be "included" or "ignored". Use <![ as a start and
]]> as an end. For example, you want to use a different versions of a DTD for xml document or sgml document, you may code as
follows:
<![ INCLUDE [
... XML-only definitions
]]>
<![ IGNORE [
... SGML-only definitions
]]>
... common definitions
How many entities are catagorized in dtd?
Internal entity: An entity that is referenced in its own document content.
External entity: An entity that is referenced in another file.
General entity: including internal or external entity
Parameter entity: An entity that contains DTD specifications that are referenced from within the DTD.
Parsed entity: An entity that contains XML(text and markup) and is therefore parsed.
Unparsed entity: An entity that contains binary data(like images)
Return to top <xmlfaqs.html>
What is xmlns?
The xmlns stands for XML NameSpace. It is an attribute for a tag. It is used in DTD to prevent conflicts. For example, the
following tells us the title element will use designated DTD.
<!ELEMENT title (%inline;)*>
<!ATTLIST title
xmlns CDATA #FIXED "http://www.example.com/slideshow">
...
or
<title xmlns="http://www.example.com/slideshow">
Overview
</title>
or
<SL:slideshow xmlns:SL='http:/www.example.com/slideshow'
...>
...
</SL:slideshow>
or
<SL:slideshow xmlns:SL='http:/www.example.com/slideshow'
...>
...
<slide>
<SL:title>Overview</SL:title>
</slide>
...
</SL:slideshow>
or
<SL:slideshow xmlns:SL='http:/www.example.com/slideshow'
xmlns:xhtml='urn:...'>
...
</SL:slideshow>
Here we use "http:", you may use "urn:" instead.
What is xsi?
The "xsi" stands for XML Schema Instance like:
xsi:noNamespaceSchemaLocation='YourSchemaDefinition.xsd'
The line specifies the schema to use for elements in the document that do not have a namespace prefix.
Where to use XML?
XML can be used in many places:
Data representation in Web, especially for Java client/server web.
Data interchange in all sorts of transactions as long as both sides agree on.
Document-Driven Programming(DDP)
Binding
Archiving
How XML is related with other technologies?
There are many XML related technologies directly or non-directly:
SAX -- Simple API for XML: reads and writes XML data in a server.
DOM -- Document Object Model: converts an XML document into a collection of objects.
JDOM -- Java DOM: processes more data-oriented structures.
dom4j -- DOM for Java: a factory-based implementation, easier to modify for complex, special-purpose
apps.
DTD -- Document Type Definition: specifies the kinds of tags that can be included in XML document.
Namespace -- writes an XML document that uses two or more sets of XML tags in modular fashion.
XSL -- Extensible Stylesheet Language: specifies how to identify data, not how to display it.
XSLT -- Extensible Stylesheet Language for Transformations: specifies what to convert an XML tag into.
XSL-FO -- Extensible Stylesheet Language for Formatting Objects: specifies how to link multiple areas on
a page.
SAAJ -- SOAP with Attachments API for Java.
JAXR -- Java API for XML Registries, used to look and find web services.
etc.
What are major subcomponents of XSL?
The XML Stylesheet Language (XSL) has three major subcomponents:
XSL-FO -- The largest subcomponent. It describes font sizes, page layouts, and how information "flows"
from one page to another.
XSLT -- A transformation language that lets you define a transformation from XML into some other
format. Like producing HTML, a different XML structure, a plain text or other document format.
XPath -- A specification that lets you specify a path to an element.
What is transformation language in XSL?
Extensible Styles Language(XSL) has two parts:
a transformation language(XSLT) <http://www.w3.org/TR/xslt> and a formatting language.
The transformation language lets you transform documents into different forms, while the formatting language actually formats and
styles documents in various ways.
What is JAX-RPC?
JAX-RPC stands for Java API for XML-based RPC. It is an API for building Web services and clients that use RPC and XML.
In JAX-RPC, a remote procedure call is represented by an XML-based protocol such as SOAP. The SOAP specification defines the
envelope structure, encoding rules, and convention for representing remote procedure calls and responses. These calls and
responses are transmitted as SOAP messages (XML files) over HTTP.
With JAX-RPC, the developer does not generate or parse SOAP messages. It is the JAX-RPC runtime system that converts the API
calls and responses to and from SOAP messages.
What is value type?
A value type is a class whose state may be passed between a client and remote service as a method parameter or return value. For
example, an account class may have account number, account owner and amount field. These information may be passed between
client and server as a method deposit parameter and a return value of method account query.
What kind of rules do the value type must follow?
To be supported by JAX-RPC, a value type must conform to the following rules:
It must have a public default constructor.
It must not implement (either directly or indirectly) the java.rmi.Remote interface.
Its fields must be supported JAX-RPC types.
The value type may contain public, private, or protected fields. The field of a value type must meet these
requirements:
A public field cannot be final or transient.
A non-public field must have corresponding getter and setter methods.
Return to top <xmlfaqs.html>
What is SAAJ?
SAAJ stands for SOAP(Simple Object Access Protocal) with Attachments API for Java. SAAJ is used mainly for the SOAP
messaging that goes on behind the scenes in JAX-RPC and JAXR implementations.
Secondarily, it is an API that developers can use when they choose to write SOAP messaging applications directly rather than using
JAX-RPC.
What is XML Registry?
An XML registry is an infrastructure that enables the building, deployment, and discovery of Web services. It is a neutral third
party that facilitates dynamic and loosely coupled business-to-business (B2B) interactions. A registry is available to organizations
as a shared resource, often in the form of a Web-based service.
There are many kinds of specifications for XML registries, including ebXML Registry and Repository and The Universal
Description, Discovery, and Integration (UDDI).
What is JAXR?
JAXR stands for Java API for XML Registries. It enables Java software programmers to use an API to access a variety of XML
registries. The current version of the JAXR specification can be found at <http://java.sun.com/xml/downloads/jaxr.html>
What is XHTML?
XHTML is an application of XML that tries to make XML documents look and act like HTML documents. The XHTML
specification is a reformulation of HTML 4.0 into XML. The following is code of XHTML.
1. <?xml version="1.0"?>
2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
3. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4. <html xmlns="http://www.w3.org/2002/xhtml" xml:lang="en"
lang="en">
5. <head><title>Welcome to see xhtml</title></head>
6. <body>
7. <h1 align="center"> Welcome to XHTML!</h1>
8. </body>
9. </html>
The following is the display on your browser.
Welcome to XHTML!
It seems that we cannot see much difference between HTML and XTML except a few lines of code.
The line 1 starts with the XML declaration.
The line 2 indicates that the document element is HTML the DTDs that XHTML use are public DTDs and
created by W3C.
The line 3 gives the URI for the DTD which points to the W3 official site.
The line 4 defines an XML namespace for the document and language.
The line 5 to line 6 are standard HTML code.
Note that all tags are well-formed and written in lowercase except line 2, which is required by XHTML specification.
What is the advantage of XHTML?
XHTML is really XML, you can extend it with your own elements and you can display XHTML documents in today's browsers
without modification. XHTML provides a bridge between XML and HTML.
Are there some difference between XHTML and HTML?
Yes, at least, the differences are:
XHTML documents must be well-formed XML documents, but HTML are not.
XHTML elements and attributes must be in lowercase, but HTML are not required.
XHTML needs end tags for elements if they are not empty, but HTML can sometimes omit end tags.
XHTML attributes must always be quoted, but HTML are not required.
Some tags in XHTML have some special requirements. For example, <a> element cannot contain other
<a> element, so do <button>, <form>, <lable>, etc.
You must escape sensitive characters like & sign.
Return to top <xmlfaqs.html>
What is RDF?
RDF stands for Resource Description Framework. It defines what a particular data item is and how it can be used.
What is XTM?
XTM stands for XML Topic Maps. XTM is a usable knowledge-representation standard.
What is SMIL?
SMIL stands for Synchronized Multimedia Integration Language.
What is MathML?
MathML stands for Mathematical Markup Language.
What is SVG?
SVG stands for Scalable Vector Graplhics.
What is DrawML?
DrawML stands for Draw Meta Language.
What is ICE?
ICE stands for Information and Content Exchange.
What is ebXML?
ebXML stands for Electronic Business with XML.
What is cxml?
cxml stands for Commerce XML.
What is CBL?
CBL stands for Common Business Library.
What is UBL?
UBL stands for Universal Business Language.
What is OASIS?
OASIS stands for Organization for the Advancement of Structured Information System.
Where can I find free XML Validator?
There are some out there, try this one: <http://www.stg.brown.edu/service/xmlvalid/>
How to use Microsoft DSO to bind with XML file?
There are many DSO -- Data Source Objects in IE like MSHTML, TDC, XML DSO and XML data islands. A DSO is used to read
a document and convert data to a recordset. For more information, please visit <http://msdn.microsoft.com/workshop/>
Let's assume we have a customer.xml file like the following:
<?xml version="1.0"?>
<CUSTOMERS>
<CUSTOMER>
<NAME>Aaron</NAME>
<CUSTOMER_ID>12345</CUSTOMER_ID>
<PURCHASE_DATE>11/10/2003</PURCHASE_DATE>
<DEPARTMENT>Education</DEPARTMENT>
<PRODUCT_NAME>XML Book</PRODUCT_NAME>
</CUSTOMER>
<CUSTOMER>
<NAME>Betty</NAME>
<CUSTOMER_ID>23456</CUSTOMER_ID>
<PURCHASE_DATE>10/12/2003</PURCHASE_DATE>
<DEPARTMENT>Travel</DEPARTMENT>
<PRODUCT_NAME>Trip to Haiwaii</PRODUCT_NAME>
</CUSTOMER>
<CUSTOMER>
<NAME>Cathy</NAME>
<CUSTOMER_ID>34567</CUSTOMER_ID>
<PURCHASE_DATE>10/13/2003</PURCHASE_DATE>
<DEPARTMENT>Toys</DEPARTMENT>
<PRODUCT_NAME>Game II Machine</PRODUCT_NAME>
</CUSTOMER>
<CUSTOMER>
<NAME>Dan</NAME>
<CUSTOMER_ID>45678</CUSTOMER_ID>
<PURCHASE_DATE>10/14/2003</PURCHASE_DATE>
<DEPARTMENT>IT</DEPARTMENT>
<PRODUCT_NAME>DownloadWizard software</PRODUCT_NAME>
</CUSTOMER>
</CUSTOMERS>
We want to display the data from the XML file, follow the steps:
Use xml tag to destinate source of XML file and then assign an ID to point to the XML source.
Use datasrc to reference the source ID; use datafld to point to the specific element of the XML source.
Use properties of DSO to load data from XML source.
We will use a DSO to load customer.xml and navigate its data. The following file is customer.html
<html>
<head><title>Here we display data from XML</title></head>
<xml src="customer.xml" ID="customers"></xml>
<body>
<h1 align=center>Here we display data from XML</h1>
<center>
<p>Name: <input type="text" datasrc="#customers" datafld="NAME"
size=10>
<p>Customer ID: <input type="text" datasrc="#customers"
datafld="CUSTOMER_ID" size=5>
<p>Department: <select datasrc="#customers" datafld="DEPARTMENT"
size=1>
<option value="Education">Education
<option value="Travel">Travel
<option value="Toys">Toys
<option value="IT">DownloadWizard software
</select>
<p>Purchase Date: <span datasrc="#customers"
datafld="PURCHASE_DATE"></span>
<p>Product: <span datasrc="#customers"
datafld="PRODUCT_NAME"></span>
<p>
<button onclick="customers.recordset.moveFirst()"><<</button>
<button onclick="if(!customers.recordset.BOF)
customers.recordset.movePrevious()"><</button>
<button onclick="if(!customers.recordset.EOF)
customers.recordset.moveNext()">></button>
<button onclick="customers.recordset.moveLast()">>></button>
</center>
</body>
</html>
The following is the display of customer.html. Press "F5" to refresh your window. If you cannot see any or correct result from your
browser, please copy the code, save it to a separate file and see the result.
Here we display data from XML
Name:
Customer ID:
Department:
Purchase Date: 11/10/2003
Product: XML Book
<<<>>>
If the above example is not functional well in your browser, please check this independent html file <displayData.html> to see the
features.
How to display data from XML file in a tabular format?
Let's use the customer.xml above as a source file and use table tags to display it.
<html>
<head><title>Here we display data from XML</title></head>
<xml src="customer.xml" ID="customers"></xml>
<body>
<h1 align=center>Here we display data from XML</h1>
<center>
<table datasrc="#customers" cellspacing="15">
<thead>
<tr>
<th>Name</th>
<th>Customer ID</th>
<th>Purchase</th>
<th>Department</th>
<th>Product</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span datafld="NAME"></span>
</td>
<td>
<span datafld="CUSTOMER_ID"></span>
</td>
<td>
<span datafld="PURCHASE_DATE"></span>
</td>
<td>
<span datafld="DEPARTMENT"></span>
</td>
<td>
<span datafld="PRODUCT_NAME"></span>
</td>
</tr>
</tbody>
</table>
</center>
</body>
</html>
The following is the display of the above html file. If you cannot see the correct result from this page, it is probably that your
browser may not accept that, please copy the above code, save it to a separate file and see the result.
Here we display data from XML
Name
Customer ID
Purchase
Department
Product
Aaron
12345
11/10/2003
Education
XML Book
Betty
23456
10/12/2003
Travel
Trip to Haiwaii
Cathy
34567
10/13/2003
Toys
Game II Machine
Dan
45678
10/14/2003
IT
DownloadWizard software
If you cannot see the data in this display on your browser, please click this independent html file <customer2.html>
How to use XML DSO applet to connect XML file?
Use above customer.xml file as an example. Use applet tag to make a connection as follows:
replace xml tags
<xml src="customer.xml" ID="customers"></xml>
with
<applet
code="com.ms.xml.dso.XMLDSO.class"
id="customers"
width="0" height="0"
mayscript="true">
<param name="url" value="customer.xml">
</applet>
Make sure the com.ms.xml.dso.XMLDSO.class is available for loading.
Return to top <xmlfaqs.html>
===================
JDBC Questions
What is JDBC?
JDBC may stand for Java Database Connectivity. It is also a trade mark. JDBC is
a layer of abstraction that allows users to choose between databases. It allows you
to change to a different database engine and to write to a single API. JDBC allows
you to write database applications in Java without having to concern yourself with
the underlying details of a particular database.
What are the two major components of JDBC?
One implementation interface for database manufacturers, the other
implementation interface for application and applet writers.
What is JDBC Driver interface?
The JDBC Driver interface provides vendor-specific implementations of the
abstract classes provided by the JDBC API. Each vendors driver must provide
implementations of the java.sql.Connection,Statement,PreparedStatement,
CallableStatement, ResultSet and Driver.
What are the common tasks of JDBC?
Create an instance of a JDBC driver or load JDBC drivers through
jdbc.drivers
Register a driver
Specify a database
Open a database connection
Submit a query
Receive results
How to use JDBC to connect Microsoft Access?
Please see this page <jdbc.html> for detailed information.
What are four types of JDBC driver?
Type 1 Drivers
Bridge drivers such as the jdbc-odbc bridge. They rely on an
intermediary such as ODBC to transfer the SQL calls to the
database and also often rely on native code.
Type 2 Drivers
Use the existing database API to communicate with the database
on the client. Faster than Type 1, but need native code and require
additional permissions to work in an applet. Good for client-side
connection.
Type 3 Drivers
Call the database API on the server.Flexible. Pure Java and no
native code.
Type 4 Drivers
The hightest level of driver reimplements the database network
API in Java. No native code.
What packages are used by JDBC?
There are at least 8 packages:
java.sql.Driver
Connection
Statement
PreparedStatement
CallableStatement
ResultSet
ResultSetMetaData
DatabaseMetaData
There are three basic types of SQL statements, what are they?
Statement
callableStatement
PreparedStatement
What are the flow statements of JDBC?
A URL string -->getConnection-->DriverManager-->Driver-->Connection->Statement-->executeQuery-->ResultSet.
What are the steps involved in establishing a connection?
This involves two steps: (1) loading the driver and (2) making the connection.
How can you load the drivers?
Loading the driver or drivers you want to use is very simple and involves just one
line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the
following code will load it:
Eg.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your driver documentation will give you the class name to use. For instance, if
the class name is jdbc.DriverXYZ , you would load the driver with the following
line of code:
E.g.
Class.forName("jdbc.DriverXYZ");
What Class.forName will do while loading drivers?
It is used to create an instance of a driver and register it with the DriverManager.
When you have loaded a driver, it is available for making a connection with a
DBMS.
How can you make the connection?
In establishing a connection is to have the appropriate driver connect to the
DBMS. The following line of code illustrates the general idea:
E.g.
String url = "jdbc:odbc:Fred";
Connection con = DriverManager.getConnection(url, "Fernanda",
"J8");
How can you create JDBC statements?
A Statement object is what sends your SQL statement to the DBMS. You simply
create a Statement object and then execute it, supplying the appropriate execute
method with the SQL statement you want to send. For a SELECT statement, the
method to use is executeQuery. For statements that create or modify tables, the
method to use is executeUpdate. E.g. It takes an instance of an active connection
to create a Statement object. In the following example, we use our Connection
object con to create the Statement object stmt :
Statement stmt = con.createStatement();
How to make a query?
Create a Statement object and calls the Statement.executeQuery method to select
data from the database. The results of the query are returned in a ResultSet object.
Statement stmt = con.createStatement();
ResultSet results = stmt.executeQuery("SELECT data FROM aDatabase
");
How can you retrieve data from the ResultSet?
Use get methods to retrieve data from returned ResultSet object.
ResultSet rs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM
COFFEES");
String s = rs.getString("COF_NAME");
The method getString is invoked on the ResultSet object rs , so getString will
retrieve (get) the value stored in the column COF_NAME in the current row of rs
How to navigate the ResultSet?
By default the result set cursor points to the row before the first row of the result
set. A call to next() retrieves the first result set row. The cursor can also be moved
by calling one of the following ResultSet methods:
beforeFirst(): Default position. Puts cursor before the first row of
the result set.
first(): Puts cursor on the first row of the result set.
last(): Puts cursor before the last row of the result set.
afterLast() Puts cursor beyond last row of the result set. Calls to
previous moves backwards through the ResultSet.
absolute(pos): Puts cursor at the row number position where
absolute(1) is the first row and absolute(-1) is the last row.
relative(pos): Puts cursor at a row relative to its current position
where relative(1) moves row cursor one row forward.
What are the different types of Statements?
Statement (use createStatement method)
Prepared Statement (Use prepareStatement method)
Callable Statement (Use prepareCall)
If you want to use the percent sign (%) as the percent sign and not have it
interpreted as the SQL wildcard used in SQL LIKE queries, how to do that?
Use escape keyword. For example:
stmt.executeQuery("select tax from sales where tax like '10\%'
{escape '\'}");
How to escape ' symbol found in the input line?
You may use a method to do so:
static public String escapeLine(String s) {
String retvalue = s;
if (s.indexOf ("'") != -1 ) {
StringBuffer hold = new StringBuffer();
char c;
for(int i=0; i < s.length(); i++ ) {
if ((c=s.charAt(i)) == '\'' ) {
hold.append ("''");
}else {
hold.append(c);
}
}
retvalue = hold.toString();
}
return retvalue;
}
Note that such method can be extended to escape any other characters that the
database driver may interprete another way.
How to make an update?
Creates a Statement object and calls the Statement.executeUpdate method.
String updateString = "INSERT INTO aDatabase VALUES (some text)";
int count = stmt.executeUpdate(updateString);
How to update a ResultSet?
You can update a value in a result set by calling the ResultSet.update method on
the row where the cursor is positioned. The type value here is the same used when
retrieving a value from the result set, for example, updateString updates a String
value and updateDouble updates a double value in the result set.
rs.first();
updateDouble("balance", rs.getDouble("balance") - 5.00);
The update applies only to the result set until the call to rs.updateRow(), which
updates the underlying database.
To delete the current row, use rs.deleteRow().
To insert a new row, use rs.moveToInsertRow().
How can you use PreparedStatement?
This special type of statement is derived from the more general class, Statement.
If you want to execute a Statement object many times, it will normally reduce
execution time to use a PreparedStatement object instead. The advantage to this is
that in most cases, this SQL statement will be sent to the DBMS right away,
where it will be compiled. As a result, the PreparedStatement object contains not
just an SQL statement, but an SQL statement that has been precompiled. This
means that when the PreparedStatement is executed, the DBMS can just run the
PreparedStatement 's SQL statement without having to compile it first.
PreparedStatement updateSales = con.prepareStatement("UPDATE
COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
How to call a Stored Procedure from JDBC?
The first step is to create a CallableStatement object. As with Statement an and
PreparedStatement objects, this is done with an open Connection object. A
CallableStatement object contains a call to a stored procedure;
E.g.
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
How to Retrieve Warnings?
SQLWarning objects are a subclass of SQLException that deal with database
access warnings. Warnings do not stop the execution of an application, as
exceptions do; they simply alert the user that something did not happen as
planned. A warning can be reported on a Connection object, a Statement object
(including PreparedStatement and CallableStatement objects), or a ResultSet
object. Each of these classes has a getWarnings method, which you must invoke
in order to see the first warning reported on the calling object
SQLWarning warning = stmt.getWarnings();
if (warning != null) {
while (warning != null) {
System.out.println("Message: " + warning.getMessage());
System.out.println("SQLState: " + warning.getSQLState());
System.out.print("Vendor error code: ");
System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}
How to Make Updates to Update ResultSets?
Another new feature in the JDBC 2.0 API is the ability to update rows in a result
set using methods in the Java programming language rather than having to send
an SQL command. But before you can take advantage of this capability, you need
to create a ResultSet object that is updatable. In order to do this, you supply the
ResultSet constant CONCUR_UPDATABLE to the createStatement method.
Connection con =
DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = ("SELECT COF_NAME, PRICE FROM COFFEES");
How to set a scroll type?
Both Statements and PreparedStatements have an additional constructor that
accepts a scroll type and an update type parameter. The scroll type value can be
one of the following values:
ResultSet.TYPE_FORWARD_ONLY Default behavior in JDBC
1.0, application can only call next() on the result set.
ResultSet.SCROLL_SENSITIVE ResultSet is fully navigable and
updates are reflected in the result set as they occur.
ResultSet.SCROLL_INSENSITIVE Result set is fully navigable,
but updates are only visible after the result set is closed. You need
to create a new result set to see the results.
How to set update type parameter?
In the constructors of Statements and PreparedStatements, you may use
ResultSet.CONCUR_READ_ONLY The result set is read only.
ResultSet.CONCUR_UPDATABLE The result set can be updated.
You may verify that your database supports these types by calling
con.getMetaData().supportsResultSetConcurrency(ResultSet.SCROLL_INSENSI
TIVE, ResultSet.CONCUR_UPDATABLE);
How to do a batch job?
By default, every JDBC statement is sent to the database individually. To send
multiple statements at one time , use addBatch() method to append statements to
the original statement and call executeBatch() method to submit entire statement.
Statement stmt = con.createStatement();
stmt.addBatch("update registration set balance=balance-5.00 where
theuser="+theuser);
stmt.addBatch("insert into auctionitems(description, startprice)
values("+description+","+startprice+")");
...
int[] results = stmt.executeBatch();
The return result of the addBatch() method is an array of row counts affected for
each statement executed in the batch job. If a problem occurred, a
java.sql.BatchUpdateException is thrown. An incomplete array of row counts can
be obtained from BatchUpdateException by calling its getUpdateCounts()
method.
How to store and retrieve an image?
To store an image, you may use the code:
int itemnumber=400456;
File file = new File(itemnumber+".jpg");
FileInputStream fis = new FileInputStream(file);
PreparedStatement pstmt = con.prepareStatement("update
auctionitems set theimage=? where id= ?");
pstmt.setBinaryStream(1, fis, (int)file.length()):
pstmt.setInt(2, itemnumber);
pstmt.executeUpdate();
pstmt.close();
fis.close();
To retrieve an image:
int itemnumber=400456;
byte[] imageBytes;//hold an image bytes to pass to createImage().
PreparedStatement pstmt = con.prepareStatement("select theimage
from auctionitems where id= ?");
pstmt.setInt(1, itemnumber);
ResultSet rs=pstmt.executeQuery();
if(rs.next()) {
imageBytes = rs.getBytes(1);
}
pstmt.close();
rs.close();
Image auctionimage =
Toolkit.getDefaultToolkit().createImage(imageBytes);
How to store and retrive an object?
A class can be serialized to a binary database field in much the same way as the
image. You may use the code above to store and retrive an object.
How to use meta data to check a column type?
Use getMetaData().getColumnType() method to check data type. For example to
retrieve an Integer, you may check it first:
int count=0;
Connection con=getConnection();
Statement stmt= con.createStatement();
stmt.executeQuery("select counter from aTable");
ResultSet rs = stmt.getResultSet();
if(rs.next()) {
if(rs.getMetaData().getColumnType(1) == Types.INTEGER) {
Integer i=(Integer)rs.getObject(1);
count=i.intValue();
}
}
rs.close();
Why cannot java.util.Date match with java.sql.Date?
Because java.util.Date represents both date and time. SQL has three types to
represent date and time.
java.sql.Date -- (00/00/00)
java.sql.Time -- (00:00:00)
java.sql.Timestamp -- in nanoseconds
Note that they are subclasses of java.util.Date.
How to convert java.util.Date value to java.sql.Date?
Use the code below:
Calendar currenttime=Calendar.getInstance();
java.sql.Date startdate= new
java.sql.Date((currenttime.getTime()).getTime());
or
SimpleDateFormat template = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date enddate = new java.util.Date("10/31/99");
java.sql.Date sqlDate =
java.sql.Date.valueOf(template.format(enddate));
Note: Most of sample codes are cited from Sun's JDBC tutorials.
=================================================
JSP Questions
What is JSP technology?
Java Server Page is a standard Java extension that is defined on top of the servlet
Extensions. The goal of JSP is the simplified creation and management of
dynamic Web pages. JSPs are secure, platform-independent, and best of all, make
use of Java as a server-side scripting language.
What is JSP page?
A JSP page is a text-based document that contains two types of text: static
template data, which can be expressed in any text-based format such as HTML,
SVG, WML, and XML, and JSP elements, which construct dynamic content.
What are the implicit objects?
Implicit objects are objects that are created by the web container and contain
information related to a particular request, page, or application. They are:
request
response
pageContext
session
application
out
config
page
exception
How many JSP scripting elements and what are they?
There are three scripting language elements:
declarations
scriptlets
expressions
Why are JSP pages the preferred API for creating a web-based client program?
Because no plug-ins or security policy files are needed on the client
systems(applet does). Also, JSP pages enable cleaner and more module
application design because they provide a way to separate applications
programming from web page design. This means personnel involved in web page
design do not need to understand Java programming language syntax to do their
jobs.
Is JSP technology extensible?
YES. JSP technology is extensible through the development of custom actions, or
tags, which are encapsulated in tag libraries.
What are the two kinds of comments in JSP and what's the difference between
them?
<%-- JSP Comment --%>
<!-- HTML Comment -->
In the Servlet 2.4 specification SingleThreadModel has been deprecates, why?
Because it is not practical to have such model. Whether you set isThreadSafe to
true or false, you should take care of concurrent client requests to the JSP page by
synchronizing access to any shared objects defined at the page level.
What is difference between custom JSP tags and beans?
Custom JSP tag is a tag you defined. You define how a tag, its attributes and its
body are interpreted, and then group your tags into collections called tag libraries
that can be used in any number of JSP files. To use custom JSP tags, you need to
define three separate components:
the tag handler class that defines the tag's behavior
the tag library descriptor file that maps the XML element names to
the tag implementations
the JSP file that uses the tag library
When the first two components are done, you can use the tag by using taglib
directive:
<%@ taglib uri="xxx.tld" prefix="..." %>
Then you are ready to use the tags you defined. Let's say the tag prefix is test:
<test:tag1>MyJSPTag</test:tag1> or <test:tag1 />
JavaBeans are Java utility classes you defined. Beans have a standard format for
Java classes. You use tags
<jsp:useBean id="identifier" class="packageName.className"/>
to declare a bean and use
<jsp:setProperty name="identifier" property="classField"
value="someValue" />
to set value of the bean class and use
<jsp:getProperty name="identifier" property="classField" />
<%=identifier.getclassField() %>
to get value of the bean class.
Custom tags and beans accomplish the same goals -- encapsulating complex
behavior into simple and accessible forms. There are several differences:
Custom tags can manipulate JSP content; beans cannot.
Complex operations can be reduced to a significantly simpler form
with custom tags than with beans.
Custom tags require quite a bit more work to set up than do beans.
Custom tags usually define relatively self-contained behavior,
whereas beans are often defined in one servlet and used in a
different servlet or JSP page.
Custom tags are available only in JSP 1.1 and later, but beans can
be used in all JSP 1.x versions.
===========================
Servlet Questions
What is the servlet?
Servlets are modules that extend request/response-oriented servers, such as Javaenabled web servers. For example, a servlet may be responsible for taking data in
an HTML order-entry form and applying the business logic used to update a
company's order database.
What's the difference between servlets and applets?
Servlets are to servers; applets are to browsers. Unlike applets, however, servlets
have no graphical user interface.
What's the advantages using servlets than using CGI?
Servlets provide a way to generate dynamic documents that is both easier to write
and faster to run. It is efficient, convenient, powerful, portable, secure and
inexpensive. Servlets also address the problem of doing server-side programming
with platform-specific APIs: they are developed with Java Servlet API, a standard
Java extension.
What are the uses of Servlets?
A servlet can handle multiple requests concurrently, and can synchronize
requests. This allows servlets to support systems such as on-line conferencing.
Servlets can forward requests to other servers and servlets. Thus servlets can be
used to balance load among several servers that mirror the same content, and to
partition a single logical service over several servers, according to task type or
organizational boundaries.
What's the Servlet Interface?
The central abstraction in the Servlet API is the Servlet interface. All servlets
implement this interface, either directly or, more commonly, by extending a class
that implements it such as HttpServlet.
Servlets-->Generic Servlet-->HttpServlet-->MyServlet.
The Servlet interface declares, but does not implement, methods that manage the
servlet and its communications with clients. Servlet writers provide some or all of
these methods when developing a servlet.
When a servlet accepts a call from a client, it receives two objects. What are they?
ServeltRequest: which encapsulates the communication from the client to the
server.
ServletResponse: which encapsulates the communication from the servlet back to
the client.
ServletRequest and ServletResponse are interfaces defined by the javax.servlet
package.
What information that the ServletRequest interface allows the servlet access to?
Information such as the names of the parameters passed in by the client, the
protocol (scheme) being used by the client, and the names of the remote host that
made the request and the server that received it. The input stream,
ServletInputStream.Servlets use the input stream to get data from clients that use
application protocols such as the HTTP POST and PUT methods.
What information that the ServletResponse interface gives the servlet methods for
replying to the client?
It Allows the servlet to set the content length and MIME type of the reply.
Provides an output stream, ServletOutputStream and a Writer through which the
servlet can send the reply data.
If you want a servlet to take the same action for both GET and POST request,
what should you do?
Simply have doGet call doPost, or vice versa.
What is the servlet life cycle?
Each servlet has the same life cycle:
A server loads and initializes the servlet (init())
The servlet handles zero or more client requests (service())
The server removes the servlet (destroy()) (some servers do this step only when
they shut down)
Which code line must be set before any of the lines that use the PrintWriter?
setContentType() method must be set before transmitting the actual document.
How HTTP Servlet handles client requests?
An HTTP Servlet handles client requests through its service method. The service
method supports standard HTTP client requests by dispatching each request to a
method designed to handle that request.
When using servlets to build the HTML, you build a DOCTYPE line, why do you
do that?
I know all major browsers ignore it even though the HTML 3.2 and 4.0
specifications require it. But building a DOCTYPE line tells HTML validators
which version of HTML you are using so they know which specification to check
your document against. These validators are valuable debugging services, helping
you catch HTML syntax errors.
<http://validator.w3.org> and
<http://www.htmlhelp.com/tools/validator/>
are two major online validators.
=============================
EJB Questions
What is EJB?
EJB stands for Enterprise JavaBean and is the widely-adopted server side
component architecture for J2EE. it enables rapid development of mission-critical
application that are versatile, reusable and portable across middleware while
protecting IT investment and preventing vendor lock-in.
What is EJB role in J2EE?
EJB technology is the core of J2EE. It enables developers to write reusable and
portable server-side business logic for the J2EE platform.
What is the difference between EJB and Java beans?
EJB is a specification for J2EE server, not a product; Java beans may be a
graphical component in IDE.
What are the key features of the EJB technology?
EJB components are server-side components written entirely in the
Java programming language
EJB components contain business logic only - no system-level
programming & services, such as transactions, security, life-cycle,
threading, persistence, etc. are automatically managed for the EJB
component by the EJB server.
EJB architecture is inherently transactional, distributed, portable
multi-tier, scalable and secure.
EJB components are fully portable across any EJB server and any
OS.
EJB architecture is wire-protocol neutral--any protocol can be
utilized like IIOP,JRMP, HTTP, DCOM,etc.
What are the key benefits of the EJB technology?
Rapid application development
Broad industry adoption
Application portability
Protection of IT investment
How many enterprice beans?
There are three kinds of enterprise beans:
session beans,
entity beans, and
message-driven beans.
What is message-driven bean?
A message-driven bean combines features of a session bean and a Java Message
Service (JMS) message listener, allowing a business component to receive JMS.
A message-driven bean enables asynchronous clients to access the business logic
in the EJB tier.
What is Entity Bean and Session Bean ?
Entity Bean is a Java class which implements an Enterprise Bean interface and
provides the implementation of the business methods. There are two types:
Container Managed Persistence(CMP) and Bean-Managed Persistence(BMP).
Session Bean is used to represent a workflow on behalf of a client. There are two
types: Stateless and Stateful. Stateless bean is the simplest bean. It doesn't
maintain any conversational state with clients between method invocations.
Stateful bean maintains state between invocations.
====================================
J2EE General Questions
What is J2EE?
J2EE is an environment for developing and deploying enterprise applications. The
J2EE platform consists of a set of services, application programming interfaces
(APIs), and protocols that provide the functionality for developing multitiered,
web-based applications.
What is the J2EE module?
A J2EE module consists of one or more J2EE components for the same container
type and one component deployment descriptor of that type.
What are the components of J2EE application?
A J2EE component is a self-contained functional software unit that is assembled
into a J2EE application with its related classes and files and communicates with
other components. The J2EE specification defines the following J2EE
components:
Application clients and applets are client components.
Java Servlet and JavaServer PagesTM (JSPTM) technology components are web
components.
Enterprise JavaBeansTM (EJBTM) components (enterprise beans) are business components.
Resource adapter components provided by EIS and tool vendors.
What are the four types of J2EE modules?
Application client module
Web module
Enterprise JavaBeans module
Resource adapter module
What does application client module contain?
The application client module contains:
class files,
an application client deployment descriptor.
Application client modules are packaged as JAR files with a .jar extension.
What does web module contain?
The web module contains:
JSP files,
class files for servlets,
GIF and HTML files, and
a Web deployment descriptor.
Web modules are packaged as JAR files with a .war (Web ARchive) extension.
What does Enterprise JavaBeans module contain?
The Enterprise JavaBeans module contains:
class files for enterprise beans
an EJB deployment descriptor.
EJB modules are packaged as JAR files with a .jar extension.
What does resource adapt module contain?
The resource adapt module contains:
all Java interfaces,
classes,
native libraries,
other documentation,
a resource adapter deployment descriptor.
Resource adapter modules are packages as JAR files with a .rar (Resource adapter ARchive) extension.
How many development roles are involved in J2EE application?
There are at least 5 roles involved:
Enterprise Bean Developer
Writes and compiles the source code
Specifies the deployment descriptor
Bundles the .class files and deployment descriptor into an EJB JAR file
Web Component Developer
Writes and compiles servlet source code
Writes JSP and HTML files
Specifies the deployment descriptor for the Web component
Bundles the .class, .jsp, .html, and deployment descriptor files in the WAR file
J2EE Application Client Developer
Writes and compiles the source code
Specifies the deployment descriptor for the client
Bundles the .class files and deployment descriptor into the JAR file
Application Assembler The application assembler is the company or person who receives application
component JAR files from component providers and assembles them into a J2EE application EAR
file. The assembler or deployer can edit the deployment descriptor directly or use tools that correctly
add XML tags according to interactive selections. A software developer performs the following tasks
to deliver an EAR file containing the J2EE application:
Assembles EJB JAR and WAR files created in the previous phases into a
J2EE application (EAR) file
Specifies the deployment descriptor for the J2EE application
Verifies that the contents of the EAR file are well formed and comply with the
J2EE specification
Application Deployer and Administrator
Configures and deploys the J2EE application
Resolves external dependencies
Specifies security settings & attributes
Assigns transaction attributes and sets transaction controls
Specifies connections to databases
Deploys or installs the J2EE application EAR file into the J2EE server
Administers the computing and networking infrastructure where J2EE
applications run
Oversees the runtime environment
But a developer role depends on the job assignment. For a small company, one developer may take these 5 roles altogether.
What APIs are available for developing a J2EE application?
Enterprise JavaBeans Technology(3 beans: Session Beans, Entity Beans and Message-Driven Beans)
JDBC API(application level interface and service provider interface or driver)
Java Servlet Technology(Servlet)
Java ServerPage Technology(JSP)
Java Message Service(JMS)
Java Naming and Directory Interface(JNDI)
Java Transaction API(JTA)
JavaMail API
JavaBeans Activation Framework(JAF used by JavaMail)
Java API for XML Processiong(JAXP,SAX, DOM, XSLT)
Java API for XML Registries(JAXR)
Java API for XML-Based RPC(JAX-RPC)-SOAP standard and HTTP
SOAP with Attachments API for Java(SAAJ)-- low-level API upon which JAX-RPC depends
J2EE Connector Architecture
Java Authentication and Authorization Service(JAAS)
What is difference between J2EE 1.3 and J2EE 1.4?
J2EE 1.4 is an enhancement version of J2EE 1.3. It is the most complete Web services platform ever.
J2EE 1.4 includes:
Java API for XML-Based RPC (JAX-RPC 1.1)
SOAP with Attachments API for Java (SAAJ),
Web Services for J2EE(JSR 921)
J2EE Management Model(1.0)
J2EE Deployment API(1.1)
Java Management Extensions (JMX),
Java Authorization Contract for Containers(JavaACC)
Java API for XML Registries (JAXR)
Servlet 2.4
JSP 2.0
EJB 2.1
JMS 1.1
J2EE Connector 1.5
The J2EE 1.4 features complete Web services support through the new JAX-RPC 1.1 API, which supports service
endpoints based on servlets and enterprise beans. JAX-RPC 1.1 provides interoperability with Web services based on the
WSDL and SOAP protocols.
The J2EE 1.4 platform also supports the Web Services for J2EE specification (JSR 921), which defines deployment
requirements for Web services and utilizes the JAX-RPC programming model.
In addition to numerous Web services APIs, J2EE 1.4 platform also features support for the WS-I Basic Profile 1.0. This
means that in addition to platform independence and complete Web services support, J2EE 1.4 offers platform Web
services interoperability.
The J2EE 1.4 platform also introduces the J2EE Management 1.0 API, which defines the information model for J2EE
management, including the standard Management EJB (MEJB). The J2EE Management 1.0 API uses the Java
Management Extensions API (JMX).
The J2EE 1.4 platform also introduces the J2EE Deployment 1.1 API, which provides a standard API for deployment of
J2EE applications.
The J2EE 1.4 platform includes security enhancements via the introduction of the Java Authorization Contract for
Containers (JavaACC). The JavaACC API improves security by standardizing how authentication mechanisms are
integrated into J2EE containers.
The J2EE platform now makes it easier to develop web front ends with enhancements to Java Servlet and JavaServer Pages
(JSP) technologies. Servlets now support request listeners and enhanced filters. JSP technology has simplified the page and
extension development models with the introduction of a simple expression language, tag files, and a simpler tag extension
API, among other features. This makes it easier than ever for developers to build JSP-enabled pages, especially those who
are familiar with scripting languages.
Other enhancements to the J2EE platform include the J2EE Connector Architecture, which provides incoming resource
adapter and Java Message Service (JMS) pluggability. New features in Enterprise JavaBeans (EJB) technology include
Web service endpoints, a timer service, and enhancements to EJB QL and message-driven beans.
The J2EE 1.4 platform also includes enhancements to deployment descriptors. They are now defined using XML Schema
which can also be used by developers to validate their XML structures.
Note: The above information comes from SUN released notes.
Is J2EE application only a web-based?
NO. A J2EE application 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 administration. It typically has a graphical user interface created from Swing or AWT APIs, or a command-line
interface. When user request, it can open an HTTP connection to establish communication with a servlet running in the
web tier.
Are JavaBeans J2EE components?
NO. JavaBeans components are not considered J2EE components by the J2EE specification. JavaBeans components
written for the J2EE platform have instance 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 outlined in the JavaBeans component architecture.
Is HTML page a web component?
NO. Static HTML pages and applets are bundled with web components during application assembly, but are not considered
web components by the J2EE specification. Even the server-side utility classes are not considered web components,either.
What is the container?
A container is a runtime support of a system-level entity. Containers provide components with services such as lifecycle
management, security, deployment, and threading.
What is the web container?
Servlet and JSP containers are collectively referred to as Web containers.
What is the thin client?
A thin client is a lightweight interface to the application that does not have such operations like query databases, execute
complex business rules, or connect to legacy applications.
What are 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) technology.
What is deployment descriptor?
A deployment descriptor is an Extensible Markup Language (XML) text-based 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.
What is the EAR file?
An EAR file is a standard JAR file with an .ear extension, named from Enterprice ARchive file. A J2EE application with
all of its modules is delivered in EAR file.
What is JTA and JTS?
JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Jave Transaction Service. JTA
provides a standard interface and allows you to demarcate transactions in a manner that is independent of the transaction
manager implementation. The J2EE SDK implements the transaction manager with 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 is a high level transaction interface that your application uses to control transaction. and JTS is a low level
transaction interface and ejb uses behind the scenes (client code doesn't directly interact with JTS. It is based on object
transaction service(OTS) which is part of CORBA.
What is JAXP?
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.
What is J2EE Connector?
The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support
access to enterprise information systems that can be plugged into any J2EE product. Each type of database or EIS has a
different resource adapter.
What is JAAP?
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) framework
that extends the Java 2 platform security architecture to support user-based authorization.
What is Model 1?
Using JSP technology alone to develop Web page. Such term is used in the earlier JSP specification. Model 1 architecture
is suitable for applications that have very simple page flow, have little need for centralized security control or logging, and
change little over time. Model 1 applications can often be refactored to Model 2 when application requirements change.
What is Model 2?
Using JSP and Servelet together to develop Web page. Model 2 applications are easier to maintain and extend, because
views do not refer to each other directly.
What is Struts?
A Web page development framework. Struts combines Java Servlets, Java Server 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?
In the MVC design pattern, application flow is mediated by a central Controller. 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 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 mappings,
usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which
can make an application significantly easier to create and maintain.
Controller--Servlet controller which supplied by Struts itself; View --- what you can see on the screen, a JSP page and
presentation components; Model --- System state and a business logic JavaBeans.
Do you have to use design pattern in J2EE project?
Yes. If I do it, I will use it. Learning design pattern will boost my coding skill.
Is J2EE a super set of J2SE?
Yes
======================================================================
Objectives for SCJP (before jdk1.4)
Declarations and Access Control
1.1 Write code that declares, constructs and initializes arrays of any base type using any of the permitted forms both for declaration and for
initialization.
1.2 Declare classes, inner classes, methods, instance variables, static variables, and automatic (method local) variables making appropriate use of
all permitted modifiers (such as public, final, static, abstract, and so forth). State the significance of each of these modifiers both singly and in
combination, and state the effect of package relationships on declared items qualified by these modifiers.
1.3 For a given class determine if a default constructor will be created and if so state the prototype of that constructor.
1.4 Identify legal return types for any method given the declarations of all related methods in this or parent classes.
Flow Control and Exception Handling
2.1 Write code using if and switch statements and identify legal argument types for these statements.
2.2 Write code using all forms of loops including labeled and unlabeled, use of break and continue, and state the values taken by loop counter
variables during and after loop execution.
2.3 Write code that makes proper use of exceptions and exception handling clauses (try, catch, finally) and declares methods and overriding
methods that throw exceptions.
Garbage Collection
3.1 State the behavior that is guaranteed by the garbage collection system.
3.2 Write code that explicitly makes objects eligible for garbage collection.
Language Fundamentals
4.1 Identify correctly constructed package declarations, import statements, class declarations (of all forms including inner classes) interface
declarations, method declarations (including the main method that is used to start execution of a class), variable declarations, and identifiers.
4.2 State the correspondence between index values in the argument array passed to a main method and command line arguments.
4.3 Identify all Java programming language keywords. Note: There will not be any questions regarding esoteric distinctions between keywords
and manifest constants.
4.4 State the effect of using a variable or array element of any kind when no explicit assignment has been made to it.
4.5 State the range of all primitive formats, data types and declare literal values for String and all primitive types using all permitted formats
bases and representations.
Operators and Assignments
5.1 Determine the result of applying any operator (including assignment operators and instance of) to operands of any type class scope or
accessibility or any combination of these.
5.2 Determine the result of applying the boolean equals (Object) method to objects of any combination of the classes java.lang.String,
java.lang.Boolean and java.lang.Object.
5.3 In an expression involving the operators &, |, &&, || and variables of known values state which operands are evaluated and the value of the
expression.
5.4 Determine the effect upon objects and primitive values of passing variables into methods and performing assignments or other modifying
operations in that method.
Overloading, Overriding, Runtime Type and Object Orientation
6.1 State the benefits of encapsulation in object oriented design and write code that implements tightly encapsulated classes and the relationships
"is a" and "has a".
6.2 Write code to invoke overridden or overloaded methods and parental or overloaded constructors; and describe the effect of invoking these
methods.
6.3 Write code to construct instances of any concrete class including normal top level classes, inner classes, static inner classes, and anonymous
inner classes.
Threads
7.1 Write code to define, instantiate and start new threads using both java.lang.Thread and java.lang.Runnable.
7.2 Recognize conditions that might prevent a thread from executing.
7.3 Write code using synchronized, wait, notify or notifyAll to protect against concurrent access problems and to communicate between threads.
7.4 Define the interaction among threads and object locks when executing synchronized, wait, notify or notifyAll.
THE JAVA.AWT PACKAGE*
8.1 Write code using component, container, and LayoutManager classes of the java.awt package to present a Graphical User Interface with
specified appearance and resize behavior, and distinguish the responsibilities of layout managers from those of containers.
8.2 Write code to implement listener classes and methods, and in listener methods, extract information from the event to determine the affected
component, mouse position, nature, and time of the event.
8.3 State the event classname for any specified event listener interface in the java.awt.event package.
THE JAVA.LANG PACKAGE*
9.1 Write code using the following methods of the java.lang.Math class: abs, ceil, floor, max, min, random, round, sin, cos, tan, and sqrt.
9.2 Describe the significance of the immutability of string objects.
THE JAVA.UTIL PACKAGE*
10.1 Make appropriate selection of collection classes/interfaces to suit specified behavior requirements.
THE JAVA.IO PACKAGE*
11.1 Write code that uses objects of the file class to navigate a file system.
11.2 Write code that uses objects of the classes InputStreamReader and outputStreamWriter to translate between Unicode and either platform
default or ISO 8859-1 character encoding and
11.3 Distinguish between conditions under which platform default encoding conversion should be used and conditions under which a specific
conversion should be used.
11.4 Select valid constructor arguments for FilterInputStream and FilterOutputStream subclasses from a list of classes in the java.io.package.
11.5 Write appropriate code to read, write and update files using FileInputStream, FileOutputStream, and RandomAccessFile objects.
11.6 Describe the permanent effects on the file system of constructing and using FileInputStream, FileOutputStream, and RandomAccessFile
objects.
NOTE: The * section means the new test scope may not include such section