Saturday, September 03, 2005

Java Job Interview Questions & Answers

Java Job Interview Questions & Answers


The site is : http://www.javacamp.org/jobinterview.html if u have any more doughts regarding this go through the site ok

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.
________________________________________
1. For more tips, go to this special tips page
2. 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.
3. How to deal with a question that is inappropriate?
o Briefly answer the question and move to a new topic.
o Ignore the question and redirect the discussion toward a different topic.
o If the question is blatant and offensive, you have every right to terminate the interview and walk out.
o 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."
4. What lessons have you learnt from "Apprentice" show?
At least 8 lessons:
1. Have a Strategy
2. Find Out What the Boss/Client Wants and Give it to Them
3. Deal With the Person in Charge
4. Be Positive
5. Have the Courage to Speak Your Mind
6. Stand Up For Yourself
7. Be Flexible
8. There's Life After Being Fired
Return to top
________________________________________
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.
1. More Java related interview questions.
2. 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.
3. Why Java does not support multiple inheritence ?
Java DOES support multiple inheritance via interface implementation.
4. What is the difference between final, finally and finalize?
o final - declare constant
o finally - handles exception
o finalize - helps in garbage collection
5. 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 .
6. 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 built-in overloaded method in the out object.
7. 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.
8. 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.
9. What is the output of xWhen 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: x10. 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.
11. 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.
12. 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

Java Language Questions
________________________________________
1. 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.
________________________________________
2. 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:
1. The Java Virtual Machine (Java VM)
2. The Java Application Programming Interface (Java API)
________________________________________
3. What is the Java Virtual Machine?
The Java Virtual Machine is a software that can be ported onto various hardware-based platforms.
________________________________________
4. 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.
________________________________________
5. 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.
________________________________________
6. What is native code?
The native code is code that after you compile it, the compiled code runs on a specific hardware platform.
________________________________________
7. 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.
________________________________________
8. 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.
________________________________________
9. 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.
________________________________________
10. 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.
________________________________________
11. 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().
________________________________________
12. 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.
________________________________________
13. 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.
________________________________________
14. Which containers use a border layout as their default layout?
The Window, Frame and Dialog classes use a border layout as their default layout.
________________________________________
15. 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.
________________________________________
16. 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.
________________________________________
17. 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.
________________________________________
18. 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.
________________________________________
19. 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.
________________________________________
20. 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.
________________________________________
21. 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.
________________________________________
22. What method is used to specify a container's layout?
The setLayout() method is used to specify a container's layout.
________________________________________
23. Which containers use a FlowLayout as their default layout?
The Panel and Applet classes use the FlowLayout as their default layout.
________________________________________
24. What is thread?
A thread is an independent path of execution in a system.
________________________________________
25. What is multithreading?
Multithreading means various threads that run in a system.
________________________________________
26. 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.
________________________________________
27. 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.
________________________________________
28. 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.
________________________________________
29. Can each Java object keep track of all the threads that want to exclusively access to it?
Yes.
________________________________________
30. What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.
________________________________________
31. 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.
________________________________________
32. 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.
________________________________________
33. What are the high-level thread states?
The high-level thread states are ready, running, waiting, and dead.
________________________________________
34. What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects.
________________________________________
35. What is the List interface?
The List interface provides support for ordered collections of objects.
________________________________________
36. 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.
________________________________________
37. What is the Vector class?
The Vector class provides the capability to implement a growable array of objects
________________________________________
38. 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.
________________________________________
39. 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.
________________________________________
40. What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection.
________________________________________
41. 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.
________________________________________
42. 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.
________________________________________
43. Is sizeof a keyword?
The sizeof operator is not a keyword in Java.
________________________________________
44. What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects.
________________________________________
45. 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
________________________________________
46. 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.
________________________________________
47. Name Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.
________________________________________
48. What is a native method?
A native method is a method that is implemented in a language other than Java.
________________________________________
49. How can you write a loop indefinitely?
for(;;)--for loop; while(true)--always true, etc.
________________________________________
50. 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.
________________________________________
51. 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.
________________________________________
52. Which class is the superclass for every class.
Object
________________________________________
53. 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.
________________________________________
54. What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.
________________________________________
55. What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.
________________________________________
56. Which Container method is used to cause a container to be laid out and redisplayed?
validate()
________________________________________
57. 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.
________________________________________
58. What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.
________________________________________
59. What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.
________________________________________
60. 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.
________________________________________
61. 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.
________________________________________
62. 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.
________________________________________
63. 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).
________________________________________
64. 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.
________________________________________
65. 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.
________________________________________
66. 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.
________________________________________
67. 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.
________________________________________
68. 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.
________________________________________
69. 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.
________________________________________
70. 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.
________________________________________
71. Which package has light weight components?
javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.
________________________________________
72. What are peerless components?
The peerless components are called light weight components.
________________________________________
73. 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.
________________________________________
74. 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.
________________________________________
75. 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.
________________________________________
76. 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.
________________________________________
77. 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.
________________________________________
78. 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.
________________________________________
79. What is the Map interface?
The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.
________________________________________
80. Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its superclasses.
________________________________________
81. Name primitive Java types.
The primitive types are byte, char, short, int, long, float, double, and boolean.
________________________________________
82. 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.
________________________________________
83. How can a GUI component handle its own events?
A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.
________________________________________
84. 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.
________________________________________
85. 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.
________________________________________
86. 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.
________________________________________
87. 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.
________________________________________
88. 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.
________________________________________
89. 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.
________________________________________
90. What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different return types.
________________________________________
91. 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.
________________________________________
92. 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.
________________________________________
93. Name Container classes.
Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane
________________________________________
94. What class allows you to read objects directly from a stream?
The ObjectInputStream class supports the reading of objects from input streams.
________________________________________
95. 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.
________________________________________
96. 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.
________________________________________
97. 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.
________________________________________
98. 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.
________________________________________
99. What is the List interface?
The List interface provides support for ordered collections of objects.
________________________________________
100. 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.
________________________________________
101. 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.
________________________________________
102. 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.
________________________________________
103. 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.
________________________________________
104. 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.
________________________________________
105. 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.
________________________________________
106. 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.
________________________________________
107. 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.
________________________________________
108. 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.
________________________________________
109. 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.
________________________________________
110. How you restrict a user to cut and paste from the html page?
Using javaScript to lock keyboard keys. It is one of solutions.
________________________________________
111. Is Java a super set of JavaScript?
No. They are completely different. Some syntax may be similar.
________________________________________
112. 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.
________________________________________
113. How the object oriented approach helps us keep complexity of software development under control?
We can discuss such issue from the following aspects:
o Objects allow procedures to be encapsulated with their data to reduce potential interference.
o Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places.
o 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.
________________________________________
114. 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.
________________________________________
115. 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.
________________________________________
116. 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.
________________________________________
117. What is the difference between interface and abstract class?
o interface contains methods that must be abstract; abstract class may contain concrete methods.
o interface contains variables that must be static and final; abstract class may contain non-final and final variables.
o members in an interface are public by default, abstract class may contain non-public members.
o interface is used to "implements"; whereas abstract class is used to "extends".
o interface can be used to achieve multiple inheritance; abstract class can be used as a single inheritance.
o interface can "extends" another interface, abstract class can "extends" another class and "implements" multiple interfaces.
o interface is absolutely abstract; abstract class can be invoked if a main() exists.
o interface is more flexible than abstract class because one class can only "extends" one super class, but "implements" multiple interfaces.
o If given a choice, use interface instead of abstract class.
________________________________________



________________________________________
Networking
1. More networking questions
2. 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.
3. 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.
4. 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
Networking Questions
________________________________________
1. 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.
________________________________________
2. 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) { }
________________________________________
3. 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.
________________________________________
4. 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.
________________________________________
5. 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.
________________________________________
6. 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.
________________________________________
7. What does RMI stand for?
It stands for Remote Method Invocation.
________________________________________
8. 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
1. More XML questions

XML FAQS
________________________________________
1. What Is XML?
XML stands for Extensible Markup Language. It is a text-based meta-markup language defined by the World Wide Web Consortium. It has become the standard for data interchange on the Web.
2. 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.
3. What does XML look like?
4.
5.
6.
7. Hello guys!
8.

9.

10. What is the difference between HTML and XML?
HTML and XML both are based on Standard Generalized Markup Language(SGML), but
o 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.)
o HTML specifies its representation, whereas XML identifies the content for the data.
o Unlike HTML, XML tags are well-formed. XML data is searchable, format-free and reusable.
11. What is XML attribute?
Attribute is an additional information attached to a tag. For example
subject="Discuss XML issues">

here we go


The "to", "from" and "subject" are attributes of "message" tag.
12. How to deal with double quotes in attribute assignment?
Use a single quote to enclose a double quotes, for example,

13. What is an empty tag?
Empty tag is a tag with ending "/>" and used to mark something in your well-formed tags. It doesn't contain any content, so it is called "empty tag". It has two forms:

Note: not

or

or

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

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.
15. 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.
16. What is XML Prolog?
Prologs come at the very beginning of XML documents. Like HTML's tag , XML prolog is a declaration that is used to indicate the start of XML file like the following:

or

or

It contains some or all of three attributes:
o version -- not optional
o encoding -- default UTF-8
o 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
________________________________________
17. 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.
18. 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:

where 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
An XML file may have multiple processing instructions to tell different applications to do similar things.
19. 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.
20. Is XML tag case-sensitive?
Yes. XML tags are case-sensitive. The start and end tags should be matched exactly.
21. Why do people say that XML is portable?
There are several reasons. First, it is written in a text format, which is readable by both human beings and text-editing software. Second, applications can parse and process XML documents, and human beings can also read them in case there is an error in processing. Third, XML document does not include formatting instructions, it can be displayed in various ways. Keeping data separate from formatting instructions means that the same data can be published to different media.
22. How to let browser display XML file?
There are two ways to do so:
o 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).
o use a programming language to handle the XML document in programming code,like Java or JavaScript.
23. 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
________________________________________
24. How to use JavaScript to display XML document?
To illustrate it, we use a simple XML document hello.xml as follows:



Hello guys!


In an HTML file called getxml.html:






Get data from XML document


Here comes:




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:
________________________________________
25. What is DTD tag?
A DTD tag is a tag used in DTD definition file. It starts with . It tells parser how to handle xml file.
26. What is CDATA?
A CDATA is a section mark which works like
...
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 . If you have a section which contains many & or <, you can mark it, so the XML processor will not parse it.
27. What is the basic syntax for the document type declaration?
The basic syntax:

where the 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:





28. How the internal DTD looks like?
29.
30. 31.
32.
33. ]>
34.
35.
36. ....
37.

38. What is the syntax of element declaration?
39.
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.
40. What is the meaning of the following statement?
41.
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.
42. What syntax should be used to describe a more children elements?
For example, if a and b represent child elements:
o a+ -- one or more occurences of a
o a* -- zero or more occurences of a
o a? -- a or nothing
o a, b -- a followed by b
o a | b -- a or b, but not both
o (expression) -- a unit may have more of above expressions
43. What the following tells us in a dtd file?
44. 1.
45. 2.
46. 3.
47. 4.
48. 5.
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.
49. 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.
50. 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 slide-title. It is so called "hyphenation hierarchy. Otherwise, the title definition will work for every title in xml file.
51. 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.
52. 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:


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.
...local subset definitions here...
]>
53. How to declare a public DTD?
Replace SYSTEM to PUBLIC and give url to that dtd.
"http://www.somewhere.com/someones/slideshow1.dtd" >
54. 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:

title CDATA #REQUIRED
date CDATA #IMPLIED
author CDATA "unknown"
>



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.
55. 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:

...
]>

...
©right; ...
Wherever the ©right; is parsed, it will be replaced with entity copyright sign ©.
56. How to declare a parameter entity reference?
Use 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.






]>



HELLO FROM HTML


WELCOME TO THE WILD WORLD

&TODAY;

Save above file as greeting.xml, use your browser to look at it. You may get a similar display, except that the 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.
57. How to declare an image tag in a DTD file?
You can declare an image tag in the following form:
1.
2. alt CDATA #IMPLIED
src CDATA #REQUIRED
type CDATA "image/gif"
>
3.
4.

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.
58. What is conditional section?
Conditional section is a way to let XML document to choose which dtd should be "included" or "ignored". Use 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:
... XML-only definitions
]]>
... SGML-only definitions
]]>
... common definitions
59. How many entities are catagorized in dtd?
o Internal entity: An entity that is referenced in its own document content.
o External entity: An entity that is referenced in another file.
o General entity: including internal or external entity
o Parameter entity: An entity that contains DTD specifications that are referenced from within the DTD.
o Parsed entity: An entity that contains XML(text and markup) and is therefore parsed.
o Unparsed entity: An entity that contains binary data(like images)
Return to top
________________________________________
60. 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.

xmlns CDATA #FIXED "http://www.example.com/slideshow">
...
or
<br /> Overview<br />
or
...>
...

or
...>
...

Overview

...

or
xmlns:xhtml='urn:...'>
...


Here we use "http:", you may use "urn:" instead.
61. 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.
62. Where to use XML?
XML can be used in many places:
o Data representation in Web, especially for Java client/server web.
o Data interchange in all sorts of transactions as long as both sides agree on.
o Document-Driven Programming(DDP)
o Binding
o Archiving
63. What is JAXP?
JAXP stands for Java APIs for XML, which let you write your Web application entirely in the Java programming language. There are two broad categories:
o Document-oriented -- processes XML documents using various parsers.
o Procedure-oriented -- including JAX-RPC, JAXM, and JAXR.
64. What is RELAX NG?
RELAX NG stands for Regular Language description for XML. It is simpler than XML structure schema and an emerging standard under the auspices of OASIS. NG stands for Next Generation. For more information on RELAX NG, see www.oasis-open.org/committees/relax-ng/
65. What is XML schema
XML Schema is a large, complex standard that has two parts. One part specifies structure relationships. (This is the largest and most complex part.) The other part specifies mechanisms for validating the content of XML elements by specifying a (potentially very sophisticated) datatype for each element. For more information on XML schema, visit www.w3c.org/XML/Schema
66. What is JAXM?
JAXM stands for Java APIs for XML Messaging. It provides a standard way to send XML documents over the internet form the Java platform. It is based on the SOAP 1.1 and SOAP with Attaqchements specifications which define a basic framework for exchanging XML messages. It can make one-way (asynchronous) messaging, rout of a message to more than one party and guarantee the delivery, whereas the JAX-RPC cannot.
67. How to get a Point-to-Point connection via JAXM?
All JAXM connections are created by using connection factory methods.
SOAPConnectionFactory factory = SOAPConnectionFactory.newInstance();
SOAPConnection con = factory.createConnection();
68. How to get a connection to the Messaging Provider via JAXM?
There are two ways to obtain this connection.
ProviderConnectionFactory pcFactory = ProviderConnectionFactory.newInstance();
ProviderConnection pcCon = pcFactory.createConnection();

or

Context ctx = getInitialContext();
ProviderConnectionFactory pcFactory = (ProviderConnectionFactory)ctx.lookup("SomeMsgProvider");
ProviderConnection con = pcFactory.createConnection();
69. How XML is related with other technologies?
There are many XML related technologies directly or non-directly:
o SAX -- Simple API for XML: reads and writes XML data in a server.
o DOM -- Document Object Model: converts an XML document into a collection of objects.
o JDOM -- Java DOM: processes more data-oriented structures.
o dom4j -- DOM for Java: a factory-based implementation, easier to modify for complex, special-purpose apps.
o DTD -- Document Type Definition: specifies the kinds of tags that can be included in XML document.
o Namespace -- writes an XML document that uses two or more sets of XML tags in modular fashion.
o XSL -- Extensible Stylesheet Language: specifies how to identify data, not how to display it.
o XSLT -- Extensible Stylesheet Language for Transformations: specifies what to convert an XML tag into.
o XSL-FO -- Extensible Stylesheet Language for Formatting Objects: specifies how to link multiple areas on a page.
o SAAJ -- SOAP with Attachments API for Java.
o JAXR -- Java API for XML Registries, used to look and find web services.
o TREX -- Tree Regular Expressions for XML, part of RELAX NG
o SOX -- Schema for Object-Oriented XML
o Schematron -- Schema for Object-Oriented XML, an assetion based schema by www.ascc.net.
o ebXML -- Electronic Business with XML developed by UN/CEFACT and OASIS
o cxml -- Commerce XML, more info at www.rosettanet.org
o etc.
70. What is the difference between SAX and DOM?
The Simple API for XML(SAX) and the Document Object Model(DOM) are both defined by the W3C. Unlike a SAX parser, a DOM parser allows random access to particular pieces of data in an XML document. Another difference is that with a SAX parser, you can only read an XML document, but with a DOM parser, you can build an object representation of the document and manipulate it in memory, adding a new element or deleting an existing one.
71. How to transform a DOM tree to an XML document?
Use the following code:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("xxxList.xml");
Node rootNode = document.getDocumentElement();
NodeList list = document.getElementsByTagName("xxxx");

//add node
Text tnNode = document.createTextNode("yyyy");
newNameNode.appendChild(tnNode);
....

TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();

DOMSource source = new DOMSource(document);

File newXML = new File("newXML.xml");
FileOutputStream os = new FileOutputStream(newXML);
StreamResult result = new StreamResult(os);

transformer.transform(source, result);
72. How to transform an XML document to an HTML document?
To perform the transformation, you need to obtain an XSLT transformer and use it to apply the style sheet to the XML data. The following code fragment obtains a transformer by instantiating a TransformerFactory object, reading in the style sheet and XML files, creating a file for the HTML output, and then finally obtaining the Transformer object transformer from the TransformerFactory object tFactory.
TransformerFactory tFactory = TransformerFactory.newInstance();

String stylesheet = "xxx.xsl";
String sourceId = "newXML.xml";

File yyyHTML = new File("yyyHTML.html");
FileOutputStream os = new FileOutputStream(yyyHTML);

Transformer transformer = tFactory.newTransformer(new StreamSource(stylesheet));
transformer.transform(new StreamSource(sourceId), new StreamResult(os));
73. What are major subcomponents of XSL?
The XML Stylesheet Language (XSL) has three major subcomponents:
1. XSL-FO -- The largest subcomponent. It describes font sizes, page layouts, and how information "flows" from one page to another.
2. 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.
3. XPath -- A specification that lets you specify a path to an element.
74. What is transformation language in XSL?
Extensible Styles Language(XSL) has two parts:
a transformation language(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.
75. What is JAX-RPC?
JAX-RPC stands for Java API for XML-based RPC(Remote Procedure Call). 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.
76. 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.
77. 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:
o It must have a public default constructor.
o It must not implement (either directly or indirectly) the java.rmi.Remote interface.
o Its fields must be supported JAX-RPC types.
o 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
________________________________________
78. 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.
79. 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).
80. 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
81. 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.
2. 3. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4.
5. Welcome to see xhtml
6.
7.

Welcome to XHTML!


8.
9.
The following is the display on your browser.
________________________________________

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 to see the features.

________________________________________


82. How to display data from XML file in a tabular format?
83. Let's use the customer.xml above as a source file and use table tags to
84. display it.
85.
86. Here we display data from XML
87.
88.
89.
90.
91.

Here we display data from XML


92.

93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
108.
111.
114.
117.
120.
121.
122.
NameCustomer IDPurchaseDepartmentProduct

106.
107.

109.
110.

112.
113.

115.
116.

118.
119.

123.
124.

125.
126.
127.
128. The following is the display of the above html file. If you cannot see the
129. correct result from this page, it is probably that your browser may not accept
130. 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

________________________________________


131. How to use XML DSO applet to connect XML file?
132. Use above customer.xml file as an example. Use applet tag to make a
133. connection as follows:
134. replace xml tags
135.
136.
137. with
138.
139. 140. code="com.ms.xml.dso.XMLDSO.class"
141. id="customers"
142. width="0" height="0"
143. mayscript="true">
144.
145.
Make sure the com.ms.xml.dso.XMLDSO.class is available for loading.

Return to top
________________________________________
JDBC
1. More JDBC questions
Return to top

Link shows these questions
JDBC Questions
________________________________________
1. 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.
________________________________________
2. What are the two major components of JDBC?
One implementation interface for database manufacturers, the other implementation interface for application and applet writers.
________________________________________
3. 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.
________________________________________
4. What are the common tasks of JDBC?
o Create an instance of a JDBC driver or load JDBC drivers through jdbc.drivers
o Register a driver
o Specify a database
o Open a database connection
o Submit a query
o Receive results
________________________________________
5. How to use JDBC to connect Microsoft Access?
Please see this page for detailed information.
________________________________________
6. What are four types of JDBC driver?
1. 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.
2. 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.
3. Type 3 Drivers
Call the database API on the server.Flexible. Pure Java and no native code.
4. Type 4 Drivers
The hightest level of driver reimplements the database network API in Java. No native code.
7. ________________________________________
8. What packages are used by JDBC?
There are at least 8 packages:
0. java.sql.Driver
1. Connection
2. Statement
3. PreparedStatement
4. CallableStatement
5. ResultSet
6. ResultSetMetaData
7. DatabaseMetaData
________________________________________
9. There are three basic types of SQL statements, what are they?
0. Statement
1. callableStatement
2. PreparedStatement
________________________________________
10. What are the flow statements of JDBC?
A URL string -->getConnection-->DriverManager-->Driver-->Connection-->Statement-->executeQuery-->ResultSet.
________________________________________
11. What are the steps involved in establishing a connection?
This involves two steps: (1) loading the driver and (2) making the connection.
________________________________________
12. 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");
________________________________________
13. 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.
________________________________________
14. 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");
________________________________________
15. 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();
________________________________________
16. 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 ");
________________________________________
17. 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
________________________________________
18. 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:
o beforeFirst(): Default position. Puts cursor before the first row of the result set.
o first(): Puts cursor on the first row of the result set.
o last(): Puts cursor before the last row of the result set.
o afterLast() Puts cursor beyond last row of the result set. Calls to previous moves backwards through the ResultSet.
o absolute(pos): Puts cursor at the row number position where absolute(1) is the first row and absolute(-1) is the last row.
o relative(pos): Puts cursor at a row relative to its current position where relative(1) moves row cursor one row forward.
________________________________________
19. What are the different types of Statements?
0. Statement (use createStatement method)
1. Prepared Statement (Use prepareStatement method)
2. Callable Statement (Use prepareCall)
________________________________________
20. 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 '\'}");
________________________________________
21. 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.
________________________________________
22. 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);
________________________________________
23. 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().
________________________________________
24. 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 ?");
________________________________________
25. 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();
________________________________________
26. 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();
}
}
________________________________________
27. 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");
________________________________________
28. 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:
o ResultSet.TYPE_FORWARD_ONLY Default behavior in JDBC 1.0, application can only call next() on the result set.
o ResultSet.SCROLL_SENSITIVE ResultSet is fully navigable and updates are reflected in the result set as they occur.
o 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.
________________________________________
29. How to set update type parameter?
In the constructors of Statements and PreparedStatements, you may use
o ResultSet.CONCUR_READ_ONLY The result set is read only.
o 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_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
________________________________________
30. 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.
31. 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);
________________________________________
32. 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.
________________________________________
33. 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();
________________________________________
34. 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.
o java.sql.Date -- (00/00/00)
o java.sql.Time -- (00:00:00)
o java.sql.Timestamp -- in nanoseconds
Note that they are subclasses of java.util.Date.
________________________________________
35. 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
1. More JSP questions
2. 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.
3. 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:
1. the tag handler class that defines the tag's behavior
2. the tag library descriptor file that maps the XML element names to the tag implementations
3. 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:
MyJSPTag or
JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags

to declare a bean and use

to set value of the bean class and use
<%=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:
o Custom tags can manipulate JSP content; beans cannot.
o Complex operations can be reduced to a significantly simpler form with custom tags than with beans.
o Custom tags require quite a bit more work to set up than do beans.
o 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.
o Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.
4. what are the two kinds of comments in JSP and whats the difference between them
<%-- JSP Comment --%>


JSP Questions
________________________________________
1. 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.
________________________________________
2. 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.
________________________________________
3. 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:
o request
o response
o pageContext
o session
o application
o out
o config
o page
o exception
________________________________________
4. How many JSP scripting elements and what are they?
There are three scripting language elements:
1. declarations
2. scriptlets
3. expressions
________________________________________
5. 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.
________________________________________
6. Is JSP technology extensible?
YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
________________________________________
7. What are the two kinds of comments in JSP and what's the difference between them?
<%-- JSP Comment --%>

________________________________________
8. 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.
________________________________________
9. 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:
0. the tag handler class that defines the tag's behavior
1. the tag library descriptor file that maps the XML element names to the tag implementations
2. 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:
MyJSPTag or
JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags

to declare a bean and use

to set value of the bean class and use
<%=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:
o Custom tags can manipulate JSP content; beans cannot.
o Complex operations can be reduced to a significantly simpler form with custom tags than with beans.
o Custom tags require quite a bit more work to set up than do beans.
o 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.
o Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.

Return to top
________________________________________
Servlet
1. More Servlet questions
2. 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
3. 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.
4. 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.
5. 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.
6. 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).
7. Which interface must be implemented by all servlets?
Servlet interface.
Servlet Questions
________________________________________
1. What is the servlet?
Servlets are modules that extend request/response-oriented servers, such as Java-enabled 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.
2. 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.
3. 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.
4. 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.
5. 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.
6. 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.
7. 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.
8. 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.
9. 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.
10. 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)
11. 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.
12. 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.
13. 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.



Return to top
________________________________________
Struts
1. More Struts questions
2. What is Struts?
Struts is a web page development framework and an open source software that helps developers build web applications quickly and easily. 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.

Struts Questions
________________________________________
1. What is Struts?
Struts is a web page development framework and an open source software that helps developers build web applications quickly and easily. 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.
2. Who makes the Struts?
Struts is hosted by the Apache Software Foundation(ASF) as part of its Jakarta project, like Tomcat, Ant and Velocity.
3. Why it called Struts?
Because the designers want to remind us of the invisible underpinnings that hold up our houses, buildings, bridges, and ourselves when we are on stilts. This excellent description of Struts reflect the role the Struts plays in developing web applications.
4. Do we need to pay the Struts if being used in commercial purpose?
No. Struts is available for commercial use at no charge under the Apache Software License. You can also integrate the Struts components into your own framework just as if they were writtern in house without any red tape, fees, or other hassles.
5. What are the core classes of Struts?
Action, ActionForm, ActionServlet, ActionMapping, ActionForward are basic classes of Structs.
6. What is the design role played by Struts?
The role played by Structs is controller in Model/View/Controller(MVC) style. The View is played by JSP and Model is played by JDBC or generic data source classes. The Struts controller is a set of programmable components that allow developers to define exactly how the application interacts with the user.
7. How Struts control data flow?
Struts implements the MVC/Layers pattern through the use of ActionForwards and ActionMappings to keep control-flow decisions out of presentation layer.
8. What configuration files are used in Struts?
1. ApplicationResourcesl.properties
2. struts-config.xml
These two files are used to bridge the gap between the Controller and the Model.
9. What helpers in the form of JSP pages are provided in Struts framework?
o struts-html.tld
o struts-bean.tld
o struts-logic.tld
10. Is Struts efficient?
o The Struts is not only thread-safe but thread-dependent(instantiates each Action once and allows other requests to be threaded through the original object.
o ActionForm beans minimize subclass code and shorten subclass hierarchies
o The Struts tag libraries provide general-purpose functionality
o The Struts components are reusable by the application
o The Struts localization strategies reduce the need for redundant JSPs
o The Struts is designed with an open architecture--subclass available
o The Struts is lightweight (5 core packages, 5 tag libraries)
o The Struts is open source and well documented (code to be examined easily)
o The Struts is model neutral
________________________________________

Return to top
________________________________________
EJB
1. More EJB questions
2. 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
3. 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.
EJB Questions
________________________________________
1. 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.
2. 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.
3. 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.
4. What are the key features of the EJB technology?
1. EJB components are server-side components written entirely in the Java programming language
2. 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.
3. EJB architecture is inherently transactional, distributed, portable multi-tier, scalable and secure.
4. EJB components are fully portable across any EJB server and any OS.
5. EJB architecture is wire-protocol neutral--any protocol can be utilized like IIOP,JRMP, HTTP, DCOM,etc.
5. What are the key benefits of the EJB technology?
o Rapid application development
o Broad industry adoption
o Application portability
o Protection of IT investment
6. How many enterprice beans?
There are three kinds of enterprise beans:
o session beans,
o entity beans, and
o message-driven beans.
7. 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.
8. 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.
________________________________________

Return to top
________________________________________
J2EE
1. More J2EE questions
2. 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:
o Java API for XML-Based RPC (JAX-RPC 1.1)
o SOAP with Attachments API for Java (SAAJ),
o Web Services for J2EE(JSR 921)
o J2EE Management Model(1.0)
o J2EE Deployment API(1.1)
o Java Management Extensions (JMX),
o Java Authorization Contract for Containers(JavaACC)
o Java API for XML Registries (JAXR)
o Servlet 2.4
o JSP 2.0
o EJB 2.1
o JMS 1.1
o 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.
3. 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.
4. Is J2EE a super set of J2SE?
Yes
J2EE General Questions
________________________________________
1. 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.
2. 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.
3. 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:
o Application clients and applets are client components.
o Java Servlet and JavaServer PagesTM (JSPTM) technology components are web components.
o Enterprise JavaBeansTM (EJBTM) components (enterprise beans) are business components.
o Resource adapter components provided by EIS and tool vendors.
4. What are the four types of J2EE modules?
1. Application client module
2. Web module
3. Enterprise JavaBeans module
4. Resource adapter module
5. What does application client module contain?
The application client module contains:
o class files,
o an application client deployment descriptor.
Application client modules are packaged as JAR files with a .jar extension.
6. What does web module contain?
The web module contains:
o JSP files,
o class files for servlets,
o GIF and HTML files, and
o a Web deployment descriptor.
Web modules are packaged as JAR files with a .war (Web ARchive) extension.
7. What does Enterprise JavaBeans module contain?
The Enterprise JavaBeans module contains:
o class files for enterprise beans
o an EJB deployment descriptor.
EJB modules are packaged as JAR files with a .jar extension.
8. What does resource adapt module contain?
The resource adapt module contains:
o all Java interfaces,
o classes,
o native libraries,
o other documentation,
o a resource adapter deployment descriptor.
Resource adapter modules are packages as JAR files with a .rar (Resource adapter ARchive) extension.
9. How many development roles are involved in J2EE application?
There are at least 5 roles involved:
0. 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
1. 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
2. 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
3. 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
4. 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.
10. What APIs are available for developing a J2EE application?
o Enterprise JavaBeans Technology(3 beans: Session Beans, Entity Beans and Message-Driven Beans)
o JDBC API(application level interface and service provider interface or driver)
o Java Servlet Technology(Servlet)
o Java ServerPage Technology(JSP)
o Java Message Service(JMS)
o Java Naming and Directory Interface(JNDI)
o Java Transaction API(JTA)
o JavaMail API
o JavaBeans Activation Framework(JAF used by JavaMail)
o Java API for XML Processiong(JAXP,SAX, DOM, XSLT)
o Java API for XML Registries(JAXR)
o Java API for XML-Based RPC(JAX-RPC)-SOAP standard and HTTP
o SOAP with Attachments API for Java(SAAJ)-- low-level API upon which JAX-RPC depends
o J2EE Connector Architecture
o Java Authentication and Authorization Service(JAAS)
11. 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:
o Java API for XML-Based RPC (JAX-RPC 1.1)
o SOAP with Attachments API for Java (SAAJ),
o Web Services for J2EE(JSR 921)
o J2EE Management Model(1.0)
o J2EE Deployment API(1.1)
o Java Management Extensions (JMX),
o Java Authorization Contract for Containers(JavaACC)
o Java API for XML Registries (JAXR)
o Servlet 2.4
o JSP 2.0
o EJB 2.1
o JMS 1.1
o 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.
12. 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.
13. 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.
14. 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.
15. 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.
16. What is the web container?
Servlet and JSP containers are collectively referred to as Web containers.
17. 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.
18. What are types of J2EE clients?
o Applets
o Application clients
o Java Web Start-enabled rich clients, powered by Java Web Start technology.
o Wireless clients, based on Mobile Information Device Profile (MIDP) technology.
19. 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.
20. 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.
21. 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.
22. 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.
23. 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.
24. 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.
25. 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.
26. 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.
27. 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.
28. 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.
29. 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.
30. Is J2EE a super set of J2SE?
Yes


Return to top
________________________________________

JMS
1. 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.
2. what type messaging is provided by JMS
Both synchronous and asynschronous
3. 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
________________________________________
Misc
1. What is Maven?
Maven is a Java project management and project comprehension tool developed by http://maven.apache.org. Maven is based on the concept of a project object model (POM) in that all the artifacts produced by Maven are a result of consulting a well defined model for your project. Builds, documentation, source metrics, source cross-references and a countless number of reports are all controlled by your POM. Maven has the following features.
o Making the build process easy
o Providing a uniform build system
o Providing quality project information
o Providing clear development process guidelines
o Providing guidelines for thorough testing practices
o Providing coherent visualization of project information
o Allowing transparent migration to new features
2. What is JPay? The JPay is Java payment API. It supports payments in an open, Web-like environment and allow Java applications to use a third-party payment service to charge users for using an application or accessing content. For more information, please visit this page
3. What is Jeson?
Jetson is an automation toolset designed to simplify and speed the development and deployment of J2EE applications. Jetson enables rapid Enterprise JavaBean (EJB)-based application generation; allows business rules to be exposed as Web services; supports most common databases; and features a security model that conforms to Java Authentication and Authorization Service (JAAS). More information can be found at http://www.JetsonJ2EE.com.
4. What is Jamaica?
Jamaica (like Jasmin) is an abstract assembly language for Java Virtual Machine(JVM). It uses Java language syntax to define class structures and uses mnemonics or symbolic names in instructions for variables, parameters, data fields, constants, and labels. JVM bytecode is hard to read and can be viewed via javap utility to decompile a class file. For example, you may view a compiled class file as follows:
javap -c anyCompiledClassName
You will see the decompiled JVM bytecode displayed on the screen. But when you use Jamaica to write code, it is easy to read. For example, the HelloWorld class may be written as follows.
public class HelloWorld {
public static void main(String[] args) {
%println "Hello, World!"
%println "Hello, World!"
%println "This is NOT an error!"
}
}
The %println is JVM macro. It needs Jamaica to compile and run
5. 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.
6. What software development methodologies are prevailing?
o Rational Unified Process(RUP) -- Model-driven architecture, design and development; customizable framework for scalable processes; developed and marketed by Rational company.
o Enterprise Unified Process(EUP) -- extension of RUP(add: production, retirement, operations,support and enterprise disciplines.)
o Personal Software Process(PSP) -- Self-calibration.
o Team Software Process(TSP) -- Extends PSP with specific roles.
o Agile Modeling (AM)-- Feature-driven, test often.
o Extreme Programming(XP) -- Effective pair-programming.
o 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.
o Note: They are all iterative development methodologies.
7. What are orthogonal dimensions in software development?
There are several popular orthogonal dimensions listed as follows
o Top-down vs. bottom-up.
o Waterfall vs. incremental.
o Iterative vs. concurrent.
o Planned vs. mining.
o Same team vs. different team.
8. 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.
9. 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.
10. What are alpha, beta or gamma version of a software?
o alpha -- the release contains some large section of new code that hasn't been 100% tested.
o beta -- all new code has been tested, no fatal bugs.
o gamma -- a beta that has been around a while and seems to work fine. Only minor fixes are added. The so-called a release.
11. 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.
12. 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.
13. 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.

No comments: