EARN 400$ PER WEEK

Custom Search

Saturday, December 4, 2010

Java Basics

  1. What is a platform?

A platform is the hardware or software environment in which a program runs. Most platforms can be described as a combination of the operating system and hardware, like Windows 2000/XP, Linux, Solaris.

  1. What is the main difference between Java platform and other platforms?

The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms.

The Java platform has two components:

    1. The Java Virtual Machine (Java VM)
    2. The Java Application Programming Interface (Java API)

  1. What is the Java Virtual Machine?

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


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

  1. What is the package?

The package is a Java name-space or part of Java libraries. The Java API is grouped into libraries of related classes and interfaces; these libraries are known as packages.

  1. What is native code?

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

What is the difference between an Interface and an Abstract class? An Abstract class declares have at least one instance method that is declared abstract which will be implemented by the subclasses. An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior.

7. What is the purpose of garbage collection in Java, and when is it used?

The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

8. What is the serialization?

The serialization is a kind of mechanism that makes a class or bean persistent by having its properties or fields and state information saved and restored to and from storage.

9. What is a transient variable?

A transient variable is a variable that may not be serialized. If you don't want some field to be serialized, you can mark that field transient or static

10. Which class is the super class for every class?

Object

11. What is thread?

A thread is an independent path of execution in a system.

12. What is multithreading?

Multithreading means various threads that run in a system.

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

14. How to create multithread in a program?

You have two ways to do so. First, making your class "extends" Thread class. Second, making your class "implements" Runnable interface. Put jobs in a run () method and call start () method to start the thread.

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

  1. What state does a thread enter when it terminates its processing?

When a thread terminates its processing, it enters the dead state.



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

  1. What is the purpose of the wait (), notify (), and notify All () methods?

The wait (), notify (), and notify All () methods are used to provide an efficient way for threads to communicate each other.

  1. What are the high-level thread states?

The high-level thread states are ready, running, waiting, and dead.

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

An Abstract class declares have at least one instance method that is declared abstract which will be implemented by the subclasses. An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior.

Monday, November 15, 2010

IMP FAQ’s related to J2EE:

1. Why beans are used in J2EE architecture instead of writing all the code in jsp's?

In order to separate the business logic and presentation logic beans are used. We write the business logic in the Beans. Where there is a change in business processes we have to modify only the bean code not jsp code and vice versa.

2. Explain MVC (Model-View-Controller) architecture?

MVC: - In model view controller design pattern, the software has split into 3 pieces.

MODEL: Responsible for Managing Data. The business logic (the core business transactions and processing), necessary to accomplish the goal of the interaction (calculations, queries, and / or updates to a database, etc). Business logic should be separated from UI logic. This makes it possible to have different clients (for ex browser and GUI) using the same beans. Separating the 2 also makes the business components easier to re-use, maintain, and update or change.

Ex. Java Beans

VIEW: Responsible for generating the views. It involves the presentation layout (the actual HTML output), for the result of the interaction. For HTML clients, this can be done using JSP.

Ex: JSP

CONTROLLER: Responsible for user interactions & co-ordinate with MODEL &VIEW. It is the Presentation logic (the logical connection between the user and EJB services), necessary to process the HTTP request, control the business logic, and select an appropriate response. This can be provided by Java Servlets or Session Beans.


3. Difference between Application Server & Web server?

Application servers used for enterprise solutions, web servers are used middle tier web applications.

Web servers are used for running web applications, the features are very less to compare application server the application server is specific to application. And it can run all the applications including web application.

Ex:- web-logic, web-sphere, Jbose.

All are providing the more features than web server like tomcat.

4. Which bean can be called as Multi-Threaded bean?

Stateless session bean can be called as Multi-Threaded bean as for every request of users is handled by creating a new threaded for the same object.

5. Difference between SAX and DOM?

SAX stands for Simple API for XML. It is a standard interface for event based XML parsing. Programmers provide handlers to deal with different events as the document is passed.

If we use SAX API to pass XML documents have full of control over what happens when the event occurs as result, customizing the parsing process extensively. For example a programmer might decide to stop an XML document as soon as the parser encounters an error that indicate that the document is invalid rather than waiting until the document is parsed. Thus improve the performance.

DOM stands for Document Object Model. DOM reads an xml document into memory and represents as it as tree. Each node of tree represents a particular piece of data from the original document. The main drawback is that the entire xml document has to be read into memory for DOM to create the tree which might decrease the performance of an application as the xml document get larger.

6. What is difference between stateless and state full session beans?

Stateless:

1) Stateless session bean maintains across method and transaction

2) The EJB server transparently reuses instances of the Bean to service different clients at the per-method level (access to the session bean is serialized and is 1 client per session bean per method.

3) Used mainly to provide a pool of beans to handle frequent but brief requests. The EJB server transparently reuses instances of the bean to service different clients.

4) Do not retain client information from one method invocation to the next. So many require the client to maintain on the client side which can mean more complex client code.

5) Client passes needed information as parameters to the business methods.6) Performance can be improved due to fewer connections across the network.

Stateful:

1) A stateful session bean holds the client session's state.

2) A stateful session bean is an extension of the client that creates it.

3) Its fields contain a conversational state on behalf of the session object's client. This state describes the conversation represented by a specific client/session object pair.

4) Its lifetime is controlled by the client.

5) Cannot be shared between clients.


7. What is a servlet Context? How do you get it?

ServletContext is also called as application object. And this can be used for logging (stores some kind of information) getting context parameters, getting the request dispatcher and storing the global data.

We can get the ServletContext obj using ServletContext.

i.e. ServletContext sc = getServletContext ();

8. What is Servlet Config? How do you get it?

ServletConfig can be used to get the initialization Parameters, to get the reference to the ServletContext. There can be multiple ServletConfig objects in a web application. Each servlet has one Config object.

The configuration information is:

Servlet name, initialization parameters servlet context object.

9. What is Request Dispatcher? How do you get it?

The name itself reveals that it is used to dispatch the control to requesting resource. It is an interface used to include any resource with in our servlet or forward the controller to any other resource. It contains two methods.

Forward (“---url”);

Include (“---url”);

For getting this we have a method in servlet context interface. So we can get it by servlet context object

sc.getRequestDispatcher ();

Tuesday, November 9, 2010

Enterprise Java Beans:

EJB stands for Enterprise Java Bean and is the widely-adopted server side component architecture for J2EE. it enables rapid development of mission-critical application that are versatile, reusable and portable across middle-ware while protecting IT investment and preventing vendor lock-in.

EJB technology is the core of J2EE. It enables developers to write reusable and portable server-side business logic for the J2EE platform.

EJB is a specification for J2EE server, not a product; Java beans may be a graphical component in IDE.

Key Features of the EJB technology:

1. EJB components are server-side components written entirely in the Java programming language

2. EJB components contain business logic only - no system-level programming & services, such as transactions, security, life-cycle, threading, persistence, etc. are automatically managed for the EJB component by the EJB server.

3. EJB architecture is inherently transactional, distributed, portable multi-tier, scalable and secure.

4. EJB components are fully portable across any EJB server and any OS.

5. EJB architecture is wire-protocol neutral--any protocol can be utilized like IIOP, JRMP, HTTP, DCOM, etc.

Benefits of the EJB technology:

o Rapid application development

o Broad industry adoption

o Application portability

o Protection of IT investment

There are three kinds of enterprise beans:

Session Bean: Session Bean is used to represent a work-flow on behalf of a client. There are two types: Stateless and Stateful. Stateless bean is the simplest bean. It doesn't maintain any conversational state with clients between method invocations. Stateful bean maintains state between invocations.

Entity Bean: Entity Bean is a Java class which implements an Enterprise Bean interface and provides the implementation of the business methods. There are two types: Container Managed Persistence (CMP) and Bean-Managed Persistence (BMP).

Message-driven beans: A message-driven bean combines features of a session bean and a Java Message Service (JMS) message listener, allowing a business component to receive JMS. A message-driven bean enables asynchronous clients to access the business logic in the EJB tier.

Persistence in EJB is taken care of in two ways Container managed persistence (CMP) or bean managed persistence (BMP), depending on how you implement your beans:

1. For CMP, the EJB container which your beans run under takes care of the persistence of the fields you have declared to be persisted with the database - this declaration is in the deployment descriptor. So, anytime you modify a field in a CMP bean, as soon as the method you have executed is finished, the new data is persisted to the database by the container.

2. For BMP, the EJB bean developer is responsible for defining the persistence routines in the proper places in the bean, for instance, the ejbCreate (), ejbStore (), ejbRemove () methods would be developed by the bean developer to make calls to the database. The container is responsible, in BMP, to call the appropriate method on the bean. So, if the bean is being looked up, when the create () method is called on the Home interface, then the container is responsible for calling the ejbCreate () method in the bean, which should have functionality inside for going to the database and looking up the data.

EJBContext

EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called Session Context. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions.

Monday, November 8, 2010

Important concepts on Java Server Pages (JSP):

Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSP’s are secure, platform-independent, and best of all; make use of Java as a server-side scripting language.

JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content.

JSP TAGS:

JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries

Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components:

1. the tag handler class that defines the tag's behavior

2. the tag library descriptor file that maps the XML element names to the tag implementations

3. the JSP file that uses the tag library

1. Directive tags:

· Page directive: simple one for import statements.

· Include directive: to include specified file in jsp page.

· Taglib directive: used to create custom tags.

2. Scriplet tags:

· Scriplet tag: to specify java code with in jsp page.

· Expression tag: to evaluate an expression.

· Declaration tag: to declare variables. Etc.

3. Action tags:

· forward action: forward from one jsp page to another jsp

Page similar to “request dispatcher class in servlets”

· Include action: very much similar to include directive

except the imp. Difference. It’s for dynamic content where

as that is for static content.

· Use bean action: working with beans using jsp page.


Implicit Objects:

Certain objects that is available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below:

  1. Request : same as HttpServletRequest object.
  2. Response : same as HttpServletResponse object.
  3. Page : same as java.lang.Object.
  4. Config : same as ServletConfig.
  5. Context : same as servletContext.
  6. Out : same as printWriter object in servlets.
  7. Session: Http: same as Session obj.
  8. Page context: like page Context.
  9. Exception : java.lang.exception.

FAQ’s on JSP:

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

2. How does JSP handle runtime exceptions?

Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP.

3. How do you delete a Cookie within a JSP?

         Cookie mycook = new Cookie (\"name\", \"value\");
         response.addCookie (mycook);
         Cookie killmycook = new Cookie (\"mycook\",\"value\");
         killmycook.setMaxAge (0);
         killmycook.setPath (\"/\");
         killmycook.addCookie (killmycook);

4. How to pass information from JSP to included JSP?

Using <%jsp: param> tag.

5. What is the difference between directive include and jsp include?

<%@ include>: Used to include static resources during translation time.

JSP include: Used to include dynamic content or static content during runtime.

6. What are the different scope values for the ?

The different scope values for are

1. Page
2. Request
3. Session
4. Application

7. Explain the life-cycle methods in JSP?

The generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package.

The HttpJspPage interface extends the JspPage interface which in turn extends the Servlet interface of the javax.servlet package. The generated servlet class thus implements all the methods of these three interfaces. The JspPage interface declares only two methods – jspInit () and jspDestroy () that must be implemented by all JSP pages regardless of the client-server protocol.

However the JSP specification has provided the HttpJspPage interface specifically for the JSP pages serving HTTP requests. This interface declares one method _jspService ().


The jspInit () - The container calls the jspInit () to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.
The _jspservice () - The container calls the _jspservice () for each request, passing it the request and the response objects.


The jspDestroy () - The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.

8. What is a Scriptlet?

A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language. Within scriptlet tags, you can

1. Declare variables or methods to use later in the file
2. Write expressions valid in the page scripting language
3. Use any of the JSP implicit objects or any object declared with a tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.

Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.

9. What is an output comment?

A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as uninterrupted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.

10. What is a Hidden Comment?

A comment 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 -- %>

Examples
<%@ page language="java" %>

<%-- This comment will not be visible to the client in the page source --%>

FAQ's on Java Servlets

  1. What mechanisms are used by a Servlet Container to maintain session information?

Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information

  1. Difference between GET and POST

In GET, your entire form submission can be encapsulated in one URL, like a hyperlink. Query length is limited to 260 characters, not secure, faster, quick and easy.

In POST, your name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the form's output. It is used to send a chunk of data to the server to be processed, more versatile, most secure.

  1. What is session?

The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests.

  1. What is servlet mapping?

The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets.

  1. What is servlet context?

The servlet context is an object that contains a servlet's view of the Web application within which the servlet is running. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use.

6.Which interface must be implemented by all servlets?

Servlet interface.

  1. What information that the ServletRequest interface allows the servlet access to?

Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. The input stream, ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and PUT methods.

  1. What information that the ServletResponse interface gives the servlet methods for replying to the client?

It allows the servlet to set the content length and MIME type of the reply. Provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.

  1. When using servlets to build the HTML, you build a DOCTYPE line, why do you do that?

I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE line tells HTML validators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors.

http://validator.w3.org and 
http://www.htmlhelp.com/tools/validator/ are two major online validators.

10. What's the advantages using servlets than using CGI?

Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. It is efficient, convenient, powerful, portable, secure and inexpensive. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with Java Servlet API, a standard Java extension.

11.Which code line must be set before any of the lines that use the PrintWriter?

setContentType () method must be set before transmitting the actual document.

Wednesday, November 3, 2010

J2EE Architecture and Servlets:

Servlet:

Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet may be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database

Servlets are to servers; applets are to browsers

Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. It is efficient, convenient, powerful, portable, secure and inexpensive. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with Java Servlet API, a standard Java extension.

Servlet Interface

The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more commonly, by extending a class that implements it such as HttpServlet.

Servlets-->Generic Servlet-->HttpServlet-->MyServlet. 

The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients.

When a servlet accepts a call from a client, it receives two objects. They are:

ServeltRequest: this encapsulates the communication from the client to the server

ServletResponse: This encapsulates the communication from the servlet back to the client.

ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

The javax.servlet.Servlet interface defines the three methods known as life-cycle method.


public void init(ServletConfig config) throws ServletException


public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException


public void destroy()


First the servlet is constructed, then initialized with the
init() method.
Any request from client are handled initially by the
service() method before delegating to the doXxx() methods in the case of HttpServlet.

An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.

The servlet is removed from service, destroyed with the
destroy() method then garbage collected and finalized.

Friday, October 29, 2010

HTML vs. HTTP

The server uses HTTP to send HTML to the Client.

HTML:

When a server answers a request ,the server usually sends some type of content to browser ,so that browser can display it .Server often send a browser a set of instructions written in HTML .The HTML tells the browser how to present the content to the user.

HTTP:

Most of the conversations on the web between clients and servers are held using HTTP protocol.

The client sends the HTTP request and the server answers with an HTTP response. HTTP is the protocol clients and servers use on web to communicate.

HTML runs on top of TCP/IP.

TCP is actually responsible of making sure that a file sent from one network node to node ends up as a complete file at the destination, even though the file is split into chunks when it is sent

IP is underlying protocol that routes the chunks from one host to another on their way to the destination.

HTTP then is another network protocol that has web specific features, but it depends on TCP/IP to get complete request and response.

The structure of HTTP conversation is a simple request/response sequence, a browser requests and a server responds.


We can say Apache is an example of a web server that process HTTP requests and Mozilla is an example of a web browser that provides user to view documents returned by web server.