Wednesday, January 31, 2007

the different scope values for the ?

The different scope values for are

1. page
2. request
3.session
4.application



SOURCE : www.referjava.com

Difference between forward and sendRedirect?

When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

SOURCE : www.referjava.com

What is a Hidden Comment?

A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page.
You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>.
JSP Syntax
<%-- comment --%>



SOURCE : www.referjava.com

How you can destroy the session in Servlet?

You can call invalidate() method on the session object to destroy the session. e.g. session.invalidate();


SOURCE : www.referjava.com

How to track a user session in Servlets?

The interface HttpSession can be used to track the session in the Servlet. Following code can be used to create session object in the Servlet: HttpSession session = req.getSession(true);


SOURCE : www.referjava.com

What is Session Migration?

Session Migration is a mechanism of moving the session from one server to another in case of server failure. Session Migration can be implemented by:
a) Persisting the session into database
b) Storing the session in-memory on multiple servers.



SOURCE : www.referjava.com

the advantage of Cookies over URL rewriting?

Sessions tracking using Cookies are more secure and fast. Session tracking using Cookies can also be used with other mechanism of Session Tracking like url rewriting.
Cookies are stored at client side so some clients may disable cookies so we may not sure that the cookies may work or not.

In url rewriting requites large data transfer from and to the server. So, it leads to network traffic and access may be become slow.



SOURCE : www.referjava.com

Why do u use Session Tracking in HttpServlet?

In HttpServlet you can use Session Tracking to track the user state. Session is required if you are developing shopping cart application or in any e-commerce application.


SOURCE : www.referjava.com

What is HTTPSession Class?

HttpSession Class provides a way to identify a user across across multiple request. The servlet container uses HttpSession interface to create a session between an HTTP client and an HTTP server. The session lives only for a specified time period, across more than one connection or page request from the user.


SOURCE : www.referjava.com

What are different types of Session Tracking?

Mechanism for Session Tracking are:
a) Cookies
b) URL rewriting
c) Hidden form fields
d) SSL Sessions


SOURCE : www.referjava.com

What is Session Tracking?

HTTP is stateless protocol and it does not maintain the client state. But there exist a mechanism called "Session Tracking" which helps the servers to maintain the state to track the series of requests from the same user across some period of time.


SOURCE : www.referjava.com

What is Session ID?

A session ID is an unique identification string usually a long, random and alpha-numeric string, that is transmitted between the client and the server. Session IDs are usually stored in the cookies, URLs (in case url rewriting) and hidden fields of Web pages.

SOURCE : www.referjava.com

What is a Session?

A Session refers to all the request that a single client makes to a server. A session is specific to the user and for each user a new session is created to track all the request from that user. Every user has a separate session and separate session variable is associated with that session. In case of web applications the default time-out value for session variable is 20 minutes, which can be changed as per the requirement.

SOURCE : www.referjava.com

What are the uses of Servlets?

Servlets are used to process the client request.
* A Servlet can handle multiple request concurrently and be used to develop high performance system
* A Servlet can be used to load balance among serveral servers, as Servlet can easily forward request.

SOURCE : www.referjava.com

What must be implemented by all Servlets?

The Servlet Interface must be implemented by all servlets.

SOURCE : www.referjava.com

What do you understand by servlet mapping?

Servlet mapping defines an association between a URL pattern and a servlet. You can use one servlet to process a number of url pattern (request pattern). For example in case of Struts *.do url patterns are processed by Struts Controller Servlet.

SOURCE : www.referjava.com

What is ServletContext?

ServletContext is an Interface that defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.).


SOURCE : www.referjava.com

the type of protocols supported by HttpServlet?

It extends the GenericServlet base class and provides an framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.


SOURCE : www.referjava.com

What are the lifecycle methods of Servlet?

The interface javax.servlet.Servlet, defines the three life-cycle methods. These are:
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
The container manages the lifecycle of the Servlet. When a new request come to a Servlet, the container performs the following steps.
1. If an instance of the servlet does not exist, the web container
* Loads the servlet class.
* Creates an instance of the servlet class.
* Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet.
2. The container invokes the service method, passing request and response objects.
3. To remove the servlet, container finalizes the servlet by calling the servlet's destroy method.


SOURCE : www.referjava.com

the advantages of Servlets over CGI programs?

Java Servlets have a number of advantages over CGI and other API's. They are:

Platform Independence
Java Servlets are 100% pure Java, so it is platform independence. It can run on any Servlet enabled web server. For example if you develop an web application in windows machine running Java web server. You can easily run the same on apache web server (if Apache Serve is installed) without modification or compilation of code. Platform independency of servlets provide a great advantages over alternatives of servlets.
Performance
Due to interpreted nature of java, programs written in java are slow. But the java servlets runs very fast. These are due to the way servlets run on web server. For any program initialization takes significant amount of time. But in case of servlets initialization takes place very first time it receives a request and remains in memory till times out or server shut downs. After servlet is loaded, to handle a new request it simply creates a new thread and runs service method of servlet. In comparison to traditional CGI scripts which creates a new process to serve the request. This intuitive method of servlets could be use to develop high speed data driven web sites.
Extensibility
Java Servlets are developed in java which is robust, well-designed and object oriented language which can be extended or polymorphed into new objects. So the java servlets takes all these advantages and can be extended from existing class the provide the ideal solutions.
Safety
Java provides a very good safety features like memory management, exception handling etc. Servlets inherits all these features and emerged as a very powerful web server extension.
Secure
Servlets are server side components, so it inherits the security provided by the web server. Servlets are also benefited with Java Security Manager.


SOURCE : www.referjava.com

What are methods of HttpServlet?

The methods of HttpServlet class are :
* doGet() is used to handle the GET, conditional GET, and HEAD requests
* doPost() is used to handle POST requests
* doPut() is used to handle PUT requests
* doDelete() is used to handle DELETE requests
* doOptions() is used to handle the OPTIONS requests and
* doTrace() is used to handle the TRACE requests.


SOURCE : www.referjava.com

Differentiate between doGet and doPost method?

doGet is used when there is are requirement of sending data appended to a query string in the URL. The doGet models the GET method of Http and it is used to retrieve the info on the client from some server as a request to it. The doGet cannot be used to send too much info appended as a query stream. GET puts the form values into the URL string. GET is limited to about 256 characters (usually a browser limitation) and creates really ugly URLs.

POST allows you to have extremely dense forms and pass that to the server without clutter or limitation in size. e.g. you obviously can't send a file from the client to the server via GET. POST has no limit on the amount of data you can send and because the data does not show up on the URL you can send passwords. But this does not mean that POST is truly secure. For real security you have to look into encryption which is an entirely different topic.



SOURCE : www.referjava.com

Differentiate between Servlet and Applet

Servlets are server side components that executes on the server whereas applets are client side components and executes on the web browser. Applets have GUI interface but there is not GUI interface in case of Servlets.

SOURCE : www.referjava.com

Tuesday, January 30, 2007

What is meant by cookies ? Explain ?

A Cookie is a small bit of textual information send by an website to the browser with some information about the user. The browser sends it back to the webserver upon subsequent visits of the user to that particular website.

SOURCE : www.referjava.com

Can we send object using Sockets ?

Sure. Why not? Socket I/O is exposed at streams. We can send/receive objects to/from streams using serialization.


SOURCE : www.referjava.com

What is difference in between Java Class and Bean ?

A Bean can have associated support classes: a BeanInfo class providing information about the bean, its properties and its events, and also property editors and a graphical customizer.

SOURCE : www.referjava.com

What is bean ? Where it can be used ?

A JavaBean is basically a Java class which satisfies a few simple rules (it must have a no-arg constructor, properties have getters and setters; actually, you can get around the last rule by supplying a BeanInfo object for your bean). JavaBeans were originally conceived for graphical application builder tools, but that emphasis has shifted considerably and they're now used almost everywhere.

SOURCE : www.referjava.com

Where the CardLayout is used ?

CardLayout manages two or more components that share the same display space. It lets you use one container (usually a panel) to display one out of many possible component children (like flipping cards on a table). A program can use this layout to show a different child component to different users. For example, the interface shown to an administrator might have additional functionality from the interface shown to a regular user. With card layout, our program can show the appropriate interface depending on the type of user using the program. Another typical use of card layout would be to let end user toggle among different displays and choose the one they prefer. In this case, the program must provide a GUI for the user to make the selection.

SOURCE : www.referjava.com

What are 4 drivers available in JDBC ?

Type 1: JDBC-ODBC Bridge
The type 1 driver, JDBC-ODBC Bridge, translates all JDBC calls into ODBC (Open DataBase Connectivity) calls and sends them to the ODBC driver. As such, the ODBC driver, as well as, in many cases, the client database code, must be present on the client machine. May be used when an ODBC driver has already been installed on client machine and performance is not an issue.
Type 2: Native-API/partly Java driver
JDBC driver type 2 -- the native-API/partly Java driver -- converts JDBC calls into database-specific calls for databases such as SQL Server, Informix, Oracle, or Sybase. The type 2 driver communicates directly with the database server; therefore it requires that some binary code be present on the client machine. Can be used when application is not for internet.
Type 3: Net-protocol/all-Java driver
JDBC driver type 3 -- the net-protocol/all-Java driver -- follows a three-tiered approach whereby the JDBC database requests are passed through the network to the middle-tier server. The middle-tier server then translates the request (directly or indirectly) to the database-specific native-connectivity interface to further the request to the database server. If the middle-tier server is written in Java, it can use a type 1 or type 2 JDBC driver to do this.Type 3 drivers are best suited for environments that need to provide connectivity to a variety of DBMS servers and heterogeneous databases and that require significantly high levels of concurrently connected users where performance and scalability are major concerns.
Type 4: Native-protocol/all-Java driver
The native-protocol/all-Java driver (JDBC driver type 4) converts JDBC calls into the vendor-specific database management system (DBMS) protocol so that client applications can communicate directly with the database server. Level 4 drivers are completely implemented in Java to achieve platform independence and eliminate deployment administration issues. Useful for Internet-related applications.


SOURCE : www.referjava.com

Why do you Canvas ?

The Canvas class of java.awt is used to provide custom drawing and event handling. It provides a general GUI component for drawing images and text on the screen. It does not support any drawing methods of its own, but provides access to a Graphics object through its paint() method. The paint() method is invoked upon the creation and update of a canvas so that the Graphics object associated with a Canvas object can be updated.


SOURCE : www.referjava.com

What is Difference between AWT and Swing ?

Swing provides a richer set of components than AWT. They are 100% Java-based. AWT on the other hand was developed with the mind set that if a component or capability of a component weren’t available on one platform, it wouldn’t be available on any platform. Due to the peer-based nature of AWT, what might work on one implementation might not work on another, as the peer-integration might not be as robust. There are a few other advantages to Swing over AWT:


Swing provides both additional components and added functionality to AWT-replacement components
Swing components can change their appearance based on the current "look and feel" library that's being used.
Swing components follow the Model-View-Controller (MVC) paradigm, and thus can provide a much more flexible UI.
Swing provides "extras" for components, such as:
Icons on many components
Decorative borders for components
Tool tips for components
Swing components are lightweight (less resource intensive than AWT)
Swing provides built-in double buffering
Swing provides paint debugging support for when you build your own components

Swing also has a few disadvantages:


It requires Java 2 or a separate JAR file
If you're not very careful when programming, it can be slower than AWT (all components are drawn)
Swing components that look like native components might not act exactly like native components.



SOURCE : www.referjava.com

What is JFC ?

Java Foundation Classes include:


Standard AWT 1.1
Accessibility interface
Lightweight components: which are user interface components that do not subclass an existing AWT interface element. They do not use native interface elements as provided by the underlying windowing system. This means that they are less limiting than standard AWT components.
Java look and feel
Support for native look and feel
Services such as Java2D and Drag and Drop.


SOURCE : www.referjava.com

What is the base class for all swing components ?

JComponent (except top-level containers)

SOURCE : www.referjava.com

What is JNI ?

JNI is an acronym of Java Native Interface. Using JNI we can call functions which are written in other languages from Java. Following are its advantages and disadvantages:
Advantages:


You want to use your existing library which was previously written in other language.
You want to call Windows API function.
For the sake of execution speed.
You want to call API function of some server product which is in c or c++ from java client.

Disadvantages:

You can’t say write once run anywhere.
Difficult to debug runtime error in native code.
Potential security risk.
You can’t call it from Applet.


SOURCE : www.referjava.com

What is JAR file ?

JavaARchive files are a big glob of Java classes, images, audio, etc., compressed to make one simple, smaller file to ease Applet downloading. Normally when a browser encounters an applet, it goes and downloads all the files, images, audio, used by the Applet separately. This can lead to slower downloads.


SOURCE : www.referjava.com

What are statements in JAVA ?

Statements are equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon ( :


Assignment expressions
Any use of ++ or --
Method calls
Object creation expressions

These kinds of statements are called expression statements.
In addition to these kinds of expression statements, there are two other kinds of statements. A declaration statement declares a variable. A control flow statement regulates the order in which statements get executed. The for loop and the if statement are both examples of control flow statements.


SOURCE : www.referjava.com

When is update method called ?

Whenever a screen needs redrawing (e.g., upon creation, resizing, validating) the update method is called. By default, the update method clears the screen and then calls the paint method, which normally contains all the drawing code.


SOURCE : www.referjava.com

What is the order of method invocation in an Applet ?

public void init() : Initialization method called once by browser.
public void start() : Method called after init() and contains code to start processing. If the user leaves the page and returns without killing the current browser session, the start () method is called without being preceded by init ().
public void stop() : Stops all processing started by start (). Done if user moves off page.
public void destroy() : Called if current browser session is being terminated. Frees all resources used by applet.


SOURCE : www.referjava.com

How will you initialize an Applet ?

Write my initialization code in the applets init method or applet constructor.



SOURCE : www.referjava.com

What is the use of Servlets ?

Servlets may be used at different levels on a distributed framework. The following are some examples of servlet usage:


To accept form input and generate HTML Web pages dynamically.
As part of middle tiers in enterprise networks by connecting to SQL databases via JDBC.
In conjunction with applets to provide a high degree of interactivity and dynamic Web content generation.
For collaborative applications such as online conferencing.
A community of servlets could act as active agents which share data with each other.
Servlets could be used for balancing load among servers which mirror the same content.
Protocol support is one of the most viable uses for servlets. For example, a file service can start with NFS and move on to as many protocols as desired; the transfer between the protocols would be made transparent by servlets. Servlets could be used for tunneling over HTTP to provide chat, newsgroup or other file server functions.


SOURCE : www.referjava.com

How do you communicate in between Applets & Servlets ?

We can use the java.net.URLConnection and java.net.URL classes to open a standard HTTP connection and "tunnel" to the web server. The server then passes this information to the servlet in the normal way. Basically, the applet pretends to be a web browser, and the servlet doesn't know the difference. As far as the servlet is concerned, the applet is just another HTTP client.


SOURCE : www.referjava.com

Explain RMI Architecture?

RMI uses a layered architecture, each of the layers could be enhanced or replaced without affecting the rest of the system. The details of layers can be summarised as follows:


Application Layer: The client and server program
Stub & Skeleton Layer: Intercepts method calls made by the client/redirects these calls to a remote RMI service.
Remote Reference Layer: Understands how to interpret and manage references made from clients to the remote service objects.
Transport layer: Based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies.

SOURCE : www.referjava.com

What is the difference between C++ & Java?

Well as Bjarne Stroustrup says "..despite the syntactic similarities, C++ and Java are very different languages. In many ways, Java seems closer to Smalltalk than to C++..". Here are few I discovered:


Java is multithreaded
Java has no pointers
Java has automatic memory management (garbage collection)
Java is platform independent (Stroustrup may differ by saying "Java is a platform" )
Java has built-in support for comment documentation
Java has no operator overloading
Java doesn’t provide multiple inheritance
There are no destructors in Java.



SOURCE : www.referjava.com

What do you know about the garbage collector?

Garbage collector is a runtime component of Java which sits on top of the heap: memory area from which Java objects are created and periodically scans it for objects which are eligible to be reclaimed when there are no references to these objects in the program. There is simply no way to force garbage collection, but you can suggest your intention of getting the object garbage collecetd to Java Virtual Machine by calling

code:
--------------------------------------------------------------------------------

System.gc().





SOURCE : www.referjava.com

Monday, January 29, 2007

Differences Between XML and HTML

XML
User definable tags
Content driven
End tags required for well formed documents
Quotes required around attributes values
Slash required in empty tags


HTML
Defined set of tags designed for web display
Format driven
End tags not required
Quotes not required
Slash not required.




SOURCE : www.referjava.com

What is SOAP and how does it relate to XML?

The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange of information in distributed computing environments. SOAP consists of three components: an envelope, a set of encoding rules, and a convention for representing remote procedure calls. Unless experience with SOAP is a direct requirement for the open position, knowing the specifics of the protocol, or how it can be used in conjunction with HTTP, is not as important as identifying it as a natural application of XML.


SOURCE : www.referjava.com

What is DOM and how does it relate to XML?

The Document Object Model (DOM) is an interface specification maintained by the W3C DOM Workgroup that defines an application independent mechanism to access, parse, or update XML data. In simple terms it is a hierarchical model that allows developers to manipulate XML documents easily Any developer that has worked extensively with XML should be able to discuss the concept and use of DOM objects freely. Additionally, it is not unreasonable to expect advanced candidates to thoroughly understand its internal workings and be able to explain how DOM differs from an event-based interface like SAX.

SOURCE : www.referjava.com

typical Ajax lifecycle within the browser:

Visit: The user visits a site the usual way, i.e. by clicking on a link or typing a URL.
Initialisation The page initially loads. Callbacks are established to handle user input, a loop might be established to continously refresh page elements.
Event Loop:
Browser Event An event occurs, such as a keypress.
Server Request The browser sends a request to the server.
...Server processes the event>
Server Response A moment later, the server responds, and the response is passed into a request callback function, one that was specified when the request was issued.
Browser Update The request callback function updates the DOM, including any Javascript variables, according to the response.


SOURCE : www.referjava.com

Downsides of Ajax

Limited Capabilities: Some Ajax applications are certainly doing things people never dreamed were possible on the web, but there are still substantial restrictions of the web platform. For example: multimedia capabilities, local data storage, real-time graphics, interaction with hardware such as printers and webcams. Support for some of these are improving in recent browsers, some can be achieved by delegating to Flash, but many are simply not possible, and if required, would rule out Ajax.
Performance Concerns: Constant interaction between browser and server can make an application feel unresponsive. There are, however, quite a few well-known patterns for performance optimisation such as browser-side caching. These usually suffice, even for fast-paced applications like stock trading, but Ajax still might not work for really time-critical applications such as machine control.
Internet Access Required: The user can't access an Ajax application in the absence of a network connection.
Second Programming Language: Serious Ajax applications require some knowledge of Javascript. Many developers are discovering that Javascript is actually a more capable language than at first assumed, but there is nevertheless an imposition to use a language different to that on the server-side.
Easily Abused: As with any powerful technology, Ajax concepts can be abused by careless programmers. The patterns on this site are intended to guide developers towards more usable solutions, but the fact remains that Ajax isn't always used in a manner that supports usability.


SOURCE : www.referjava.com

Give an example of using the point-to-point model.

The point-to-point model is used when the information is specific to a single client. For example, a client can send a message for a print
out, and the server can send information back to this client after completion of the print job.

SOURCE : www.referjava.com

How does a typical client perform the communication? -

1. Use JNDI to locate administrative objects.
2. Locate a single ConnectionFactory object.

3. Locate one or more Destination objects.

4. Use the ConnectionFactory to create a JMS Connection.

5. Use the Connection to create one or more Session(s).

6. Use a Session and the Destinations to create the MessageProducers and MessageConsumers needed.

7. Perform your communication.



SOURCE : www.referjava.com

What is the Role of the JMS Provider?

The JMS provider handles security of the messages, data conversion and the client triggering. The JMS provider specifies the level of
encryption and the security level of the message, the best data type for the non-JMS client.

SOURCE : www.referjava.com

What is publish/subscribe messaging?

With publish/subscribe message passing the sending application/client establishes a named topic in the JMS broker/server and publishes messages to this queue. The receiving clients register (specifically, subscribe) via the broker to messages by topic; every subscriber to a topic receives each message published to that topic. There is a one-to-many relationship between the publishing client and the subscribing
clients.


SOURCE : www.referjava.com

What are the types of messaging?

There are two kinds of Messaging. Synchronous messaging involves a client that waits for the server to respond to a message.
Asynchronous messaging involves a client that does not wait for a message from the server. An event is used to trigger a message from a
server.

SOURCE : www.referjava.com

How may messaging models do JMS provide for and what are they?

JMS provides for two messaging models, publish-and-subscribe and point-to-point queuing.

SOURCE : www.referjava.com

What type messaging is provided by JMS

Both synchronous and asynchronous.

SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

Does RMI-IIOP support dynamic downloading of classes?

No, RMI-IIOP doesn't support dynamic downloading of the classes as it is done with CORBA in DII (Dynamic Interface Invocation).Actually RMI-IIOP combines the usability of Java Remote Method Invocation (RMI) with the interoperability of the Internet Inter-ORB Protocol (IIOP).So in order to attain this interoperability between RMI and CORBA,some of the features that are supported by RMI but not CORBA and vice versa are eliminated from the RMI-IIOP specification.


SOURCE : www.referjava.com

How many types of protocol implementations does RMI have?

RMI has at least three protocol implementations: Java Remote Method Protocol(JRMP), Internet Inter ORB Protocol(IIOP), and Jini Extensible Remote Invocation(JERI). These are alternatives, not part of the same thing, All three are indeed layer 6 protocols for those who are still speaking OSI reference model.


SOURCE : www.referjava.com

What are the services in RMI ?

An RMI "service" could well be any Java method that can be invoked remotely. The other service is the JRMP RMI naming service which is a lookup service.

SOURCE : www.referjava.com

What are the services in RMI ?

An RMI "service" could well be any Java method that can be invoked remotely. The other service is the JRMP RMI naming service which is a lookup service.

What is the difference between RMI & Corba ?

The most significant difference between RMI and CORBA is that CORBA was made specifically for interoperability across programming languages. That is CORBA fosters the notion that programs can be built to interact in multiple languages. The server could be written in C++, the business logic in Python, and the front-end written in COBOL in theory. RMI, on the other hand is a total Java solution, the interfaces, the implementations and the clients--all are written in Java.

RMI allows dynamic loading of classes at runtime. In a multi-language CORBA environment, dynamic class loading is not possible. The important advantage to dynamic class loading is that it allows arguments to be passed in remote invocations that are subtypes of the declared types. In CORBA, all types have to be known in advance. RMI (as well as RMI/IIOP) provides support for polymorphic parameter passing, whereas strict CORBA does not. CORBA does have support for multiple languages which is good for some applications, but RMI has the advantage of being dynamic, which is good for other applications.


SOURCE : www.referjava.com

Explain RMI Architecture?

RMI uses a layered architecture, each of the layers could be enhanced or replaced without affecting the rest of the system. The details of layers can be summarised as follows:


Application Layer: The client and server program
Stub & Skeleton Layer: Intercepts method calls made by the client/redirects these calls to a remote RMI service.
Remote Reference Layer: Understands how to interpret and manage references made from clients to the remote service objects.
Transport layer: Based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies.


SOURCE : www.referjava.com

Will there be debugging mechanisms built into RMI?

RMI supports a simple call-logging facility for debugging. But there are no current plans to support a full-featured, interactive, remote debugger.


SOURCE : www.referjava.com

Does RMI require me to use an HTTP server?

No. You can set your java.rmi.server.codebase property to use any valid URL protocol, such as file or ftp. Using an HTTP server just makes your life simpler by providing an automated mechanism for class file downloading.



SOURCE : www.referjava.com

Sunday, January 28, 2007

How can you retrieve data from the ResultSet?

Step 1.

JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.

Eg.

ResultSet rs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

Step2.

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.


SOURCE : www.referjava.com

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.

Eg.

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();

SOURCE : www.referjava.com

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:

Eg.

String url = "jdbc:odbc:Fred";

Connection con = DriverManager.getConnection(url, "Fernanda", "J8");



SOURCE : www.referjava.com

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.

SOURCE : www.referjava.com

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:

Eg.

Class.forName("jdbc.DriverXYZ");



SOURCE : www.referjava.com

the steps involved in establishing a connection?

This involves two steps: (1) loading the driver and (2) making the connection.


SOURCE : www.referjava.com

What are wrapper classes?

Wrapper classes are classes that allow primitive types to be accessed as objects.


SOURCE : www.referjava.com

the difference between String and StringBuffer?

String objects are constants, whereas StringBuffer objects are not.

String class supports constant strings, whereas StringBuffer class supports growable, modifiable strings.


SOURCE : www.referjava.com

uses of toLowerCase( ) and toUpperCase( ) methods?

The method toLowerCase( ) converts all the characters in a string from uppercase to

lowercase.

The method toUpperCase( ) converts all the characters in a string from lowercase to

uppercase.

SOURCE : www.referjava.com

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.

SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

What is 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.

SOURCE : www.referjava.com

What is meant by Stream

A Stream is an abstraction that either produces or consumes information.

There are two types of Streams. They are:

Byte Streams : Byte Streams provide a convenient means for handling input and output of bytes.

Character Streams : Character Streams provide a convenient means for handling input and output of characters.

Byte Stream classes : Byte Streams are defined by using two abstract classes. They are:InputStream and OutputStream.

Character Stream classes : Character Streams are defined by using two abstract classes. They are : Reader and Writer.



SOURCE : www.referjava.com

Which class is extended by all other classes?

Object class is extended by all other classes.

SOURCE : www.referjava.com

What is the purpose of the System class?

The purpose of the System class is to provide access to system resources.

SOURCE : www.referjava.com

What is the purpose of the Runtime class?

The purpose of the Runtime class is to provide access to the Java runtime system.


SOURCE : www.referjava.com

What are the interfaces defined by java.lang?

Cloneable, Comparable and Runnable.


SOURCE : www.referjava.com

What is meant by daemon thread? In java runtime, what is it's role

Daemon thread is a low priority thread which runs intermittently in the background doing the garbage collection operation for the java runtime system.

SOURCE : www.referjava.com

What are all the methods available in the Thread class?

1.isAlive()

2.join()

3.resume()

4.suspend()

5.stop()

6.start()

7.sleep()

8.destroy().


SOURCE : www.referjava.com

What is the signature of the constructor of a thread class?

Thread(Runnable threadob,String threadName).


SOURCE : www.referjava.com

What are the two types of multitasking?

1.process-based

2.Thread-based.

SOURCE : www.referjava.com

Can we have catch block with out try block?

No. Try/Catch or Try/finally form a unit.

SOURCE : www.referjava.com

What is the ‘finally’ block?

Finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also execute.

SOURCE : www.referjava.com

What is ‘Resource leak’?

Freeing up other resources that might have been allocated at the beginning of a method.


SOURCE : www.referjava.com

the difference between ‘Exception’ and ‘error’ in java?

Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. With exception class we can subclass to create our own custom exception.

Error defines exceptions that are not excepted to be caught by you program. Example is Stack Overflow.


SOURCE : www.referjava.com

the difference between ‘throw’ and ‘throws’ ?And it’s application?

Exceptions that are thrown by java runtime systems can be handled by Try and catch blocks. With throw exception we can handle the exceptions thrown by the program itself. If a method is capable of causing an exception that it does not
handle, it must specify this behavior so the callers of the method can guard
against that exception.

SOURCE : www.referjava.com

Saturday, January 27, 2007

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.

SOURCE : www.referjava.com

What is the Collections API?

The Collections API is a set of classes and interfaces that support operations on collections of objects.

SOURCE : www.referjava.com

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.

SOURCE : www.referjava.com

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.

SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

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.

SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

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.

SOURCE : www.referjava.com

What is native code?

The native code is code that after you compile it, the compiled code runs on a specific hardware platform.

SOURCE : www.referjava.com

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.

SOURCE : www.referjava.com

What is the Java Virtual Machine?

The Java Virtual Machine is a software that can be ported onto various hardware-based platforms.

SOURCE : www.referjava.com

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

SOURCE : www.referjava.com

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.

SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

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.

SOURCE : www.referjava.com

Can you make an instance of an abstract 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.

SOURCE : www.referjava.com

Where and how can you use a private constructor.

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.


SOURCE : www.referjava.com

difference between final, finally and finalize?

final - declare constant
o finally - handles exception
o finalize - helps in garbage collection.


SOURCE : www.referjava.com

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.


SOURCE : www.referjava.com

Friday, January 26, 2007

What are the similarities and differences between RMI and CORBA?

Similarities

Hide communication to remote objects behind method calls
Use stub/skeleton approach
Provide a Naming Service
Differences

RMI is Java-only, CORBA is multi-language
CORBA is more sophisticated - will have greater overhead
CORBA offers many additional services e.g. persistence, events, application-domain services.

SOURCE : www.referjava.com

What is the role of an interface in CORBA?

An interface is used to define the services (methods) provided by an object and their parameters and results. The remote server provides an object which implements the interface. The client requests the interface from the ORB and the returned object must provide all the methods defined in the contract represented by the interface.

SOURCE : www.referjava.com

What are the roles of a skeleton and a stub in CORBA?

A stub and a skeleton are automatically generated from the IDL description of an interface. The stub behaves to the caller just like the called object - it provides the same methods and implements the same interfaces. However, when the methods are called, the stub interacts with the network to pass the request to the skeleton. The skeleton calls the appropriate method on the called object and passes the results back to the stub, which returns them to the caller.


SOURCE : www.referjava.com

What is the purpose of a request in CORBA?

A request is used to transfer the name of the method (the service) and the parameters between the client and the server.

SOURCE : www.referjava.com

What is an ORB?

An ORB or Object Request Broker is software that allows servers to register the objects they provide and clients to find objects providing the services they want and then to interact with them.


SOURCE : www.referjava.com

What is a heterogeneous distributed system?

A collection of communicating machines running different operating systems.


SOURCE : www.referjava.com

What are the goals of CORBA?

CORBA aims to allow interaction between potentially distributed component objects created by different manufacturers in different languages (location transparency and language transparency).


SOURCE : www.referjava.com

What is CORBA?

Common Object Request Broker Architecture - provides services to support intercommunication between objects. It is a framework and a specification for object collaboration and sharing across a heterogeneous distributed network of machines and applications.

SOURCE : www.referjava.com

How do I copy files?

Using the cd command, move to the directory that contains the file you wish to copy.
Type a command similar to the below command.

cp myfile.txt \usr\bin

In the above example, you would substitute "myfile.txt" with the name of the file you wish to copy, and "\usr\bin" with the directory you're copying to.


SOURCE : www.referjava.com

How do I find text within files in Linux?

One of the easiest methods of locating text contained within a file on a computer running Linux is to use the grep command. Below is a basic example of a command used to locate any htm file containing the word "help".

grep "help" *.htm


SOURCE : www.referjava.com

How do I delete a file or folder?

Linux / Unix users can delete files through the console by using the rm command.

SOURCE : www.referjava.com

How to create a directory / folder?

To create a directory in Linux, Unix, or any variant through the shell, use the mkdir Linux / Unix command.

SOURCE : www.referjava.com

How do I find files in Linux / Unix?

Linux / Unix and their variants have several different ways of locating files. See each of the below commands for additional information about the command and how they can be used to locate files.

find
locate
wheris
which.

SOURCE : www.referjava.com

DOS VS. Unix

Commands in DOS and Unix

DOS Unix

attrib chmod
backup tar
dir ls
cls clear
copy cp
del rm
deltree rm -R rmdir
edit vi pico
format fdformat mount umount
move / rename mv
type less
cd cd chdir
more < file more file
md mkdir
win startx



SOURCE : www.referjava.com

How, exactly, do XML and SGML differ?

First of all, XML leaves out many features of SGML There are a few areas where XML and SGML really differ:
XML's white space handling rules are much less elaborate than those of SGML. One effect is that in a few, rarely-encountered, cases, an XML processor will pass through a some white space (mostly line-ends) that an SGML processor will suppress. It is very unlikely that an XML author or user will ever notice this.
XML defines, for documents, the property of being well-formed; this does not really correspond to any SGML concept.
XML has a very specific built-in method for handling international (non-ASCII) text. It is compatible with SGML, but at the moment, few SGML processors are properly internationalized.

SOURCE : www.referjava.com

Is XML HTML?

No. An XML processor can read clean, valid, HTML, and with a few small changes an HTML browser like Netscape Navigator or Microsoft Internet Explorer would be able to read XML (the designers of XML would really like the authors of Navigator and Internet Explorer to make those changes).
The biggest difference between XML and HTML is that in XML, you can define your own tags for your own purposes, and if you want, share those tags with other users.

SOURCE : www.referjava.com

Is XML SGML?

Yes. XML has been carefully designed with the goal that every valid XML document should also be an SGML document. There are some areas of difference between XML and SGML, but these are minor, should not cause practical problems, and will almost certainly reconciled with SGML in the near future.

SOURCE : www.referjava.com

the steps necessary to parse XML documents?

Superficially, this is a fairly basic question. However, the point is not to determine whether candidates understand the concept of a parser but rather have them walk through the process of parsing XML documents step-by-step. Determining whether a non-validating or validating parser is needed, choosing the appropriate parser, and handling errors are all important aspects to this process that should be included in the candidate's response.

SOURCE : www.referjava.com

What is SOAP and how does it relate to XML?

The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange of information in distributed computing environments. SOAP consists of three components: an envelope, a set of encoding rules, and a convention for representing remote procedure calls. Unless experience with SOAP is a direct requirement for the open position, knowing the specifics of the protocol, or how it can be used in conjunction with HTTP, is not as important as identifying it as a natural application of XML.

SOURCE : www.referjava.com

What is DOM and how does it relate to XML?

The Document Object Model (DOM) is an interface specification maintained by the W3C DOM Workgroup that defines an application independent mechanism to access, parse, or update XML data. In simple terms it is a hierarchical model that allows developers to manipulate XML documents easily Any developer that has worked extensively with XML should be able to discuss the concept and use of DOM objects freely. Additionally, it is not unreasonable to expect advanced candidates to thoroughly understand its internal workings and be able to explain how DOM differs from an event-based interface like SAX.

SOURCE : www.referjava.com

the differences between XML and HTML?

XML
User definable tags
Content driven
End tags required for well formed documents
Quotes required around attributes values
Slash required in empty tags

HTML
Defined set of tags designed for web display
Format driven
End tags not required
Quotes not required
Slash not required.


SOURCE : www.referjava.com

Thursday, January 25, 2007

difference between a primary key and a unique key

Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn’t allow NULLs, but unique key allows one NULL only.

SOURCE : www.referjava.com

What is a join and List different types of joins

Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table. Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.


SOURCE : www.referjava.com

What is the Referential Integrity

Referential integrity refers to the consistency that must be maintained between primary and foreign keys, i.e. every foreign key value must have a corresponding primary key value.


SOURCE : www.referjava.com

difference between DELETE TABLE and TRUNCATE TABLE commands

Posted: Sat Jan 13, 2007 6:30 am Post subject: difference between DELETE TABLE and TRUNCATE TABLE commands

--------------------------------------------------------------------------------

DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it won't log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back.


SOURCE : www.referjava.com

query that will display ...

create a query that will display the total no.of employees and, of that total, the no.of employees hired in 1995,1996,1997, and 1998. create appropriate column headings.

select Count(*) as NumberOfEmployees,

EmployeesHiredIn1995_1996_1997_1998 =

(select count(*) from employees

where hiredate like '%1995%'

or hiredate like '%1996%'

or hiredate like '%1997%'

or hiredate like '%1998%')

from employees


SOURCE : www.referjava.com

Is Oracle is a Multidimensional database? If yes How?

Yes, Oracle is a Multidimensional database, as it provides much faster response time for analytical queries.Data in a multi-dimensional database is stored as business people views it, allowing them to slice and dice the data to answer business questions

this statement is supported by the prescence of cube and rollup operators in oracle 9i which indicates that it is a multidimensional dbs.

SOURCE : www.referjava.com

difference between varchar and varchar2

varchar means fixed length char, supported by MSSQL server 2000

varchar2 means variable length char, supported by Oracle.

SOURCE : www.referjava.com

Difference between oracle8i and oracle9i

The biggest difference between Oracle8i and Oracle9i is that Oracle9i lets You resize the SGA memory areas dynamically i.e., the Database Buffer Cache DB_CACHE_SIZE or the SHARED_POOL_SIZE, etc., can be resized when the database is up and running. The same is not possible with Oracle8i. You can get more information from OTN.


SOURCE : www.referjava.com

diff bet'n "NULL in C" and "NULL in Oracle

Null in C is Nothing or Void which can be compared with normal operators but inoracle Null can't be compared with normal operators like '=' or greater than or smallerthan.so be careful in using this feature of oracle because it can lead to several problems as like if u compared a password with oracle internal password and a user supplies a nullin password ur comparison may false like if INPUT_PASSWORD<>ORIGINAL_PASSWORD then raise_application_error(-20225,'"Incorrect Password");

NULL in SQL in an unknown value. It neither zero nor any valid value. It cannot be mapulated, but it can only be compared.



SOURCE : www.referjava.com

diffrence between and constraints and triggers

Constraints are used to maintain the integrity and atomicity of database .in other words it can be said they are used to prevent invalid data entry . the main 5 constraints are
NOT NULL,PRIMARY KEY,FOREIGN KEY,UNIQUE KEY and CHECK

Triggers are bascically stored procedures which automaticallly fired when any insert,update or delete is issued on table.

SOURCE : www.referjava.com

diff bet'n JNDI lookup(), list(), listBindings() & search

lookup() attempts to find the specified object in the given context. I.e., it looks for a single, specific object and either finds it in the current context or it fails.

list() attempts to return an enumeration of all of the NameClassPair's of all of the objects in the current context. I.e., it's a listing of all of the objects in the current context but only returns the object's name and the name of the class to which the object belongs.

listBindings() attempts to return an enumeration of the Binding's of all of the objects in the current context. I.e., it's a listing of all of the objects in the current context with the object's name, its class name, and a reference to the object itself.

search() attempts to return an enumeration of all of the objects matching a given set of search criteria. It can search across multiple contexts (or not). It can return whatever attributes of the objects that you desire. Etc. It's by far the most complex and powerful of these options but is also the most expensive.


SOURCE : www.referjava.com

what is JNDI and purpose of JNDI

The Java Naming and Directory Interface (JNDI) provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object.
Because JNDI is independent of any specific implementation, applications can use JNDI to access multiple naming and directory services, including existing naming and directory services such as LDAP, NDS, DNS, and NIS. This allows J2EE applications to coexist with legacy applications and systems.

SOURCE : www.referjava.com

What is EJB ?

Enterprise Java Bean

The three types of EJBs are: (1) session beans perform processing, (2) entity beans represent data, which can be a row or a table in a database, and (3) message driven beans are generated to process Java Messaging Service (JMS) messages.

SOURCE : www.referjava.com

How EJB Invocation happens?

Retrieve Home Object reference from Naming Service via JNDI. Return Home Object reference to the client. Create me a new EJB Object through Home Object interface. Create EJB Object from the Ejb Object. Return EJB Object reference to the client. Invoke business method using EJB Object reference. Delegate request to Bean (Enterprise Bean).


SOURCE : www.referjava.com

Can you control when passivation occurs?

The developer, according to the specification, cannot directly control when passivation occurs. Although for Stateful Session Beans, the container cannot passivate an instance that is inside a transaction. So using transactions can be a a strategy to control passivation. The ejbPassivate() method is called during passivation, so the developer has control over what to do during this exercise and can implement the require optimized logic. Some EJB containers, such as BEA WebLogic, provide the ability to tune the container to minimize passivation calls. Taken from the WebLogic 6.0 DTD -”The passivation-strategy can be either “default” or “transaction”. With the default setting the container will attempt to keep a working set of beans in the cache. With the “transaction” setting, the container will passivate the bean after every transaction (or method call for a non-transactional invocation).


SOURCE : www.referjava.com

Brief description about local interfaces?

EJB was originally designed around remote invocation using the Java Remote Method Invocation (RMI) mechanism, and later extended to support to standard CORBA transport for these calls using RMI/IIOP. This design allowed for maximum flexibility in developing applications without consideration for the deployment scenario, and was a strong feature in support of a goal of component reuse in J2EE.

Many developers are using EJBs locally -- that is, some or all of their EJB calls are between beans in a single container.

With this feedback in mind, the EJB 2.0 expert group has created a local interface mechanism. The local interface may be defined for a bean during development, to allow streamlined calls to the bean if a caller is in the same container. This does not involve the overhead involved with RMI like marshalling etc. This facility will thus improve the performance of applications in which co-location is planned.

Local interfaces also provide the foundation for container-managed relationships among entity beans with container-managed persistence.


SOURCE : www.referjava.com

difference between MessageDrivenBeans & Stateless Session

In several ways, the dynamic creation and allocation of message-driven bean instances mimics the behavior of stateless session EJB instances, which exist only for the duration of a particular method call. However, message-driven beans are different from stateless session EJBs (and other types of EJBs) in several significant ways:

Message-driven beans process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls.

Message-driven beans have no home or remote interface, and therefore cannot be directly accessed by internal or external clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS Queue or Topic.

Note: Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary.

The Container maintains the entire lifecycle of a message-driven bean; instances cannot be created or removed as a result of client requests or other API calls.

SOURCE : www.referjava.com

Definition for AJAX

AJAX (Asynchronous JavaScript and XML) is a web development technique for creating interactive web based applications that can asynchronously interchange data between server and client.

SOURCE : www.referjava.com

What will Class.forName 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.

SOURCE : www.referjava.com

How can you create JDBC statements and what are they?

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

SOURCE : www.referjava.com

What are the different types of Statements?

Regular statement (use createStatement method), prepared statement (use prepareStatement method) and callable statement (use prepareCall).

SOURCE : www.referjava.com

What does setAutoCommit do?

When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode:

con.setAutoCommit(false);.


SOURCE : www.referjava.com

How do you 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.

CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();


SOURCE : www.referjava.com

Wednesday, January 24, 2007

How can you retrieve data from the ResultSet?

JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.

ResultSet rs = stmt.executeQuery(”SELECT COF_NAME, PRICE FROM COFFEES”);
String s = rs.getString(”COF_NAME”);

SOURCE : www.referjava.com

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:

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:

Class.forName(”jdbc.DriverXYZ”);


SOURCE : www.referjava.com

What is Action Servlet?

The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests.

SOURCE : www.referjava.com

code of any Action Class?

Here is the code of Action Class that returns the ActionForward object.

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class TestAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
return mapping.findForward("testAction");
}
}



SOURCE : www.referjava.com

What is ActionForm?

An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.


SOURCE : www.referjava.com

What is Struts Validator Framework?

Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class. The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

SOURCE : www.referjava.com

What is Jakarta Struts Framework?

Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.

SOURCE : www.referjava.com

how can we communicate from struts to ejb?

strut frame work have Action class. This Action class contain execute() method.this method interact with model......your model code maybe in EJB/JDBC/Hibernate.......u can call that methods in execute().

with in the execute() u can call business delegate---> service loactor--->jndi--->to SessionFacade.


In Struts architecture Action class contain execute() method, within execute() method you can access database through jdbc or EJB. You can call the reference of entity bean class by jndi call and easily fetch data from database.


SOURCE : www.referjava.com

Is struts thread safe? Give an example?

Struts is not only thread-safe but thread-dependant. The response to a request is handled by a light-weight Action object, rather than an individual servlet. Struts instantiates each Action class once, and allows other requests to be threaded through the original object. This core strategy conserves resources and provides the best possible throughput. A properly-designed application will exploit this further by routing related operations through a single Action.

SOURCE : www.referjava.com

difference between perform() and execute() method ?

Perform method is the method which was deprecated in the Struts Version 1.1. In Struts 1.x, Action.perform() is the method called by the ActionServlet. This is typically where your business logic resides, or at least the flow control to your JavaBeans and EJBs that handle your business logic. As we already mentioned, to support declarative exception handling, the method signature changed in perform. Now execute just throws Exception. Action.perform() is now deprecated; however, the Struts v1.1 ActionServlet is smart enough to know whether or not it should call perform or execute in the Action, depending on which one is available.

SOURCE : www.referjava.com

What are the various Struts tag libraries?

Struts is very rich framework and it provides very good and user friendly way to develop web application forms. Struts provide many tag libraries to ease the development of web applications. These tag libraries are:

* Bean tag library - Tags for accessing JavaBeans and their properties.
* HTML tag library - Tags to output standard HTML, including forms, text boxes, checkboxes, radio buttons etc..
* Logic tag library - Tags for generating conditional output, iteration capabilities and flow management
* Tiles or Template tag library - For the application using tiles
* Nested tag library - For using the nested beans in the application.

SOURCE : www.referjava.com

How Struts relates to J2EE?

Struts framework is built on J2EE technologies (JSP, Servlet, Taglibs), but it is itself not part of the J2EE standard.

SOURCE : www.referjava.com

difference between and

: This tag is used to output locale-specific text (from the properties files) from a MessageResources bundle.

: This tag is used to output property values from a bean. is a commonly used tag which enables the programmers to easily present the data.

SOURCE : www.referjava.com

What are the components of Struts?

Struts is based on the MVC design pattern. Struts components can be categories into Model, View and Controller.
Model: Components like business logic / business processes and data are the part of Model.
View: JSP, HTML etc. are part of View
Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.


SOURCE : www.referjava.com

How you will handle exceptions in Struts?

In Struts you can handle the exceptions in two ways:
a) Declarative Exception Handling: You can either define global exception handling tags in your struts-config.xml or define the exception handling tags within .. tag.
Example:

key="database.error.duplicate"

path="/UserExists.jsp"

type="mybank.account.DuplicateUserException"/>

b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the exception.


SOURCE : www.referjava.com

Perfect definition for Servlet

A Java application that runs in a Web server or application server and provides server-side processing such as accessing a database and e-commerce transactions. Widely used for Web processing, servlets are designed to handle HTTP requests (get, post, etc.) and are the standard Java replacement for a variety of other methods, including CGI scripts, Active Server Pages (ASPs) and proprietary C/C++ plug-ins for specific Web servers (ISAPI, NSAPI).

SOURCE : www.referjava.com

Lifecycle of servlet

Lifecycle of servlet

1. init()
2. service()
3. destroy().


SOURCE : www.referjava.com

Difference between ServletContext and PageContext?

ServletContext gives the info about the container while PageContext gives info about the requests.
ServletContext is generated one per application while PageContext is generated for every page in ur application.

SOURCE : www.referjava.com

Define JSP?

JSP - JAVA SERVER PAGES

A server side technology. Have dynamic scripting capabilities that works along with HTML (Hypertext Markup Language) .

SOURCE : www.referjava.com

Lifecycle of JSP

There are two life cycle phases in JSP:
1) Translation phase:
Here the jsp page is converted to a servlet page and compiled to .class file

2)Execution phase:
Compiled code is executed.

The methods used for the life cycle of JSP are:
1.jspInit()
2.jspService()
3.jspDestroy().

SOURCE : www.referjava.com

Why do I need JSP technology if I already have servlets

JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-based applications. However, JSP technology was designed to simplify the process of creating pages by separating web presentation from web content. In many applications, the response sent to the client is a combination of template data and dynamically-generated data. In this situation, it is much easier to work with JSP pages than to do everything with servlets.

SOURCE : www.referjava.com

How is JSP technology different from other products?

JSP technology is the result of industry collaboration and is designed to be an open, industry-standard method supporting numerous servers, browsers and tools. JSP technology speeds development with reusable components and tags, instead of relying heavily on scripting within the page itself. All JSP implementations support a Java programming language-based scripting language, which provides inherent scalability and support for complex operations.

SOURCE : www.referjava.com

What is a JSP page?

A JSP page is a page created by the web developer that includes JSP technology-specific and custom tags, in combination with other static (HTML or XML) tags. A JSP page has the extension .jsp or .jspx; this signals to the web server that the JSP engine will process elements on this page. Using the web.xml deployment descriptor, additional extensions can be associated with the JSP engine.

SOURCE : www.referjava.com

How do JSP pages work?

A JSP engine interprets tags, and generates the content required - for example, by calling a bean, accessing a database with the JDBC API or including a file. It then sends the results back in the form of an HTML (or XML) page to the browser. The logic that generates the content is encapsulated in tags and beans processed on the server.

SOURCE : www.referjava.com

Does JSP technology require the use of other Java platform APIs?

JSP pages are typically compiled into Java platform servlet classes. As a result, JSP pages require a Java virtual machine that supports the Java platform servlet specification.

SOURCE : www.referjava.com

How is a JSP page invoked and compiled?

Pages built using JSP technology are typically implemented using a translation phase that is performed once, the first time the page is called. The page is compiled into a Java Servlet class and remains in server memory, so subsequent calls to the page have very fast response times.

SOURCE : www.referjava.com

Can I create XML pages using JSP technology?

Yes, the JSP specification does support creation of XML documents. For simple XML generation, the XML tags may be included as static template portions of the JSP page. Dynamic generation of XML tags occurs through bean components or custom tags that generate XML output.

SOURCE : www.referjava.com

How do I use JavaBeans components (beans) from a JSP page

The JSP specification includes standard tags for bean use and manipulation. The useBean tag creates an instance of a specific JavaBeans class. If the instance already exists, it is retrieved. Otherwise, it is created. The setProperty and getProperty tags let you manipulate properties of the given object.

SOURCE : www.referjava.com

How can I delete a cookie from within a JSP page?

A cookie, mycookie, can be deleted using the following scriptlet:

<%

//creating a cookie
Cookie mycookie = new Cookie("aName","aValue");
response.addCookie(mycookie);

//delete a cookie
Cookie killMyCookie = new Cookie("mycookie", null);
killMyCookie.setMaxAge(0);
killMyCookie.setPath("/");
response.addCookie(killMyCookie);

%>


SOURCE : www.referjava.com

How can I prevent the word "null"

You could make a simple wrapper function, like this

<%!


String blanknull(String s) {

return (s == null) ? "" : s;

}

%>

then use it inside your JSP form, like





SOURCE : www.referjava.com

can I declare methods within my JSP page?

You can declare methods for use within your JSP page as declarations. The methods can then be invoked within any other methods you declare, or within JSP scriptlets and expressions. Do note that you do not have direct access to any of the JSP implicit objects like request, response, session and so forth from within JSP methods. However, you should be able to pass any of the implicit JSP variables as parameters to the methods you declare.


for example:

<%!
public String whereFrom(HttpServletRequest req) {
HttpSession ses = req.getSession();
...
return req.getRemoteHost();
}
%>
<%
out.print("Hi there, I see that you are coming in from ");
%>
<%= whereFrom(request) %>
Another Example
file1.jsp:
<%@page contentType="text/html"%>
<%!
public void test(JspWriter writer) throws IOException{
writer.println("Hello!");
}
%>
file2.jsp
<%@include file="file1.jsp"%>


<%test(out);% >




SOURCE : www.referjava.com

Keywords in Java

There are 50 keywords in Java. The keyword assert is added in version Java1.4 and enum in Java1.5.

SOURCE : www.referjava.com

Access Specifiers in Java ?

There are four access specifiers in java
1. public
2. private
3. protected
4. default

A class with public access can be seen by all classes from all packages.
A class with private access can be visible in the same class.
A class with protected access can be seen by classes in the same package and by a subclass, even if the subclass is in a different package.
A class with default access can be visible only by classes within the same package.

SOURCE : www.referjava.com

Difference between protected and default ?

A default member may be accessed only if the class belongs to the same package, whereas a protected member can be accessed by a subclass even if the subclass is in a different package.

SOURCE : www.referjava.com

List Primitive variables ?

1. byte
2. short
3. int
4. long
5. float
6. double
7. boolean
8. char.

SOURCE : www.referjava.com

Instance Variables

Instance variables are defined inside the class, but outside of any method. They are only initialized when the class is instantiated. Instance variables are the fields that belong to each unique object.


SOURCE : www.referjava.com

Tuesday, January 23, 2007

what are Local Variables ?

Variables declared within a method. That means the variable is not just initialized within the method, but also declared within the method. As local variables starts its life inside the method, it's also destroyed when the method has completed. Local variables are always on stack and not on heap.


SOURCE : www.referjava.com

What is Array?

Arrays are objects that store multiple variables of the same type or variables that are all subclasses of the same type.

SOURCE : www.referjava.com

What are Constructors?

A constructor is always invoked when a new object is created. Every class has atleast one constructor. Constructor must have the same name as the class name. Constructors don't have a return type. The default constructor is a no-arg constructor.


SOURCE : www.referjava.com

How to request for Garbage Collection?

You can request for garbage collection with System.gc();


SOURCE : www.referjava.com

What is an Exception?

An abnormal condition that occurs during normal program flow.

There are two types of exception:
1. checked
2. unchecked.

SOURCE : www.referjava.com

Difference between String and StringBuffer ?

String objects are immutable and String reference variables are not.
StringBuffer objects are mutable.


SOURCE : www.referjava.com

What is a Thread?

A Thread is a line of execution. It is an instance of class java.lang.Thread.
There is one thread per call stack.

SOURCE : www.referjava.com

How can you define a Thread?

You can define and instantiate a Thread in two ways:

Extend the java.lang.Thread class
Implement the Runnable interface.

SOURCE : www.referjava.com

States of Thread

A thread has five states:

1. New Runnable
2. Running
3. Waiting/Blocked/sleeping
4. Dead.

SOURCE : www.referjava.com

Interfaces in Collection

1. List
2. Set
3. Map
4. Queue
5. SortedSet
6. SortedMap.

SOURCE : www.referjava.com

What is Object ?

Object is instance of class, object has its own state and has access to all of the behaviour defined by the Class.
Object or instance is an execution copy of a class.

SOURCE : www.referjava.com

What is class?

A template that describes the kinds of state and behaviour that objects of its type support.

Class is a structure that defines data and methods to work on that data.

SOURCE : www.referjava.com

Constructors available in thread class

1.Thread()
2.Thread(Runnable target)
3.Thread(Runnable target, String name)
4.Thread(String name).

SOURCE : www.referjava.com

What is Struts ?

it is an open source framework. It follows the MVC design pattern

Struts is a frame work , has its own library(api) which makes easy to develope loosly coupled web applications using jsp and servlet.

SOURCE : www.referjava.com

Abstract class ?

An abstract class can never be instantiated. Its sole purpose is to be extended. There should be atleast one abstract method in an abstract class.

abstract methods end in a semi colon. They only declare the methods but contain no body for the method. A concrete subclass of an abstract class must implement all the methods in the subclass.

. abstract class must bs declared as absrtact using "abstract" key word.
. abstact class can't be instantiated.
. may not contain abstract method ie its not necessary to have abstarct method in abstract class.
. class which extends abstract class must implement all the abstract methods in the abstract class else should be declared as abstract class.

SOURCE : www.referjava.com

Garbage Collection

In Java, garbage collection provides automated memory management. Its purpose is to delete objects that can't be reached.

we can make an object eligible for garbage collection ..and we can request garbage collector usaing System.gc() or Runtime.gc() methods ......... but we can never force garbage collection.

SOURCE : www.referjava.com

What are the components of Event Delegation Model ?

The components are:
1. Event Classes
2. Event Listeners
3. Implicit event handlers
4. Adapters

SOURCE : www.referjava.com

What are Event Classes?

The EventObject class is the top most class in the hierarchy in java.util package. It contains the methods: getSource() - returns the object that initiated the event getId() - returns the nature of the event.

Event Listeners

An object that delegates the task of handling an event to an event listener. When an event occurs an event object of the appropriate type is created.


ActionListener
MouseListener
MouseMotionListener
ComponentListener
ContainerListener
ItemListener
KeyListener
WindowListener

SOURCE : www.referjava.com

difference between a constructor and a method?

A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator. A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

SOURCE : www.referjava.com

What is final?

A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).

SOURCE : www.referjava.com

Can an application have multiple classes having main method?

Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.

SOURCE : www.referjava.com

What are Checked and UnChecked Exception?

A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method· Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

SOURCE : www.referjava.com

inner class doubt

First, "A a1 = new A();" will create an Object of class A, setting the private String name of this Object to A0. Then "a1.m1();" is executed - and so "new A().new B();" will be executed. A new A-object is created, setting its name to A1 and a B (tied to this A) is created with an innerCounter of 0 (incrementing the static innerCounter to 1). Then this A's name and this Bs name are printed, giving A1B0. Next, "a1.m2();" is executed - so "new A.B();" is executed. A new B will be created (tied to our "old" object we crerated first, referenced by a1). This B's name will be B1, incrementing the innerCounter to 2. Our A, referenced by a1, still has "his" name A0, so A0B1 will be printed. Last, "a1.m3();" will be executed, and so "new B();". Again, a new B will be created, tied to our first A-object, referenced by a1. So A0B2 is printed.First, "A a1 = new A();" will create an Object of class A, setting the private String name of this Object to A0. Then "a1.m1();" is executed - and so "new A().new B();" will be executed. A new A-object is created, setting its name to A1 and a B (tied to this A) is created with an innerCounter of 0 (incrementing the static innerCounter to 1). Then this A's name and this Bs name are printed, giving A1B0. Next, "a1.m2();" is executed - so "new A.B();" is executed. A new B will be created (tied to our "old" object we crerated first, referenced by a1). This B's name will be B1, incrementing the innerCounter to 2. Our A, referenced by a1, still has "his" name A0, so A0B1 will be printed. Last, "a1.m3();" will be executed, and so "new B();". Again, a new B will be created, tied to our first A-object, referenced by a1. So A0B2 is printed.

SOURCE : www.referjava.com

What is serialization?

Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.

SOURCE : www.referjava.com

difference between protected and friendly access specifier

Protected data and methods are accessible to all the classes within the same package and to all the subclasses of any package. Now if this holds true, why the following prog. failed to compile.


// file A.javapackage p1;
public class A{
protected int i = 10;
public int getI() {
return i;
}
}
// file B.java package p2;
import p1.*;
public class B extends p1.A{
public void process(A a)
{
a.i = a.i * 2;
}
public static void main(String[] args) {
A a = new B();
B b = new B();
b.process(a);
System.out.println( a.getI() );
}
}

SOURCE : www.referjava.com

What is Overriding?

In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization. e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.

SOURCE : www.referjava.com

difference between declaring a variable & defining variable

In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization. e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.

SOURCE : www.referjava.com

Can a top level class be private or protected?

No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.

SOURCE : www.referjava.com

What is serialization?

Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.

SOURCE : www.referjava.com

Example for Constructor

class Parent {
String s="Parent" ;
public Parent(){
method(); }
public void method()
{
System.out.println(s);
}
}
class Child extends Parent {
String s = "Child";
public Child(){
}
public void method(){
System.out.println(s);
}
}
public class Doubt {
public static void main(String[] args)
{
Child child = new Child();
}
}

SOURCE : www.referjava.com

Who Found Java?

First James Goslig found OAK, it was redefined from c++ in 1991. Then it was Renamed as JAVA in 1995.

SOURCE : www.referjava.com