Sunday, 31 July 2011

Constructor Overloading


CONSTRUCTOR OVERLOADING:
Constructors are chunks of code used to initialize a new object. As with overloaded methods, if you want to provide more than one constructor in a class, each one must have a different signature. Constructors always have the name of the class and no return type.

Example:
public class Movie
{
private String title;
private String rating = “PG”;
public Movie()
{
title = “Last Action- -”;
}
public Movie (String Ntitle)
{
title = Ntitle;
}
}

Calls no argument Constructor ------------------------------- Movie mov1 = new Movie();

Calls Single argument Constructor ---------------------------  Movie mov2 = new Movie("Gone with the wind);


Class can have any number of constructors as long as they have different signatures.

Method Overloading

METHOD OVERLOADING:
In java, it is possible to create methods that have the same name, provided they have different signatures. A signature is formed from its name, together with the number and types of its arguments. The method in return type is not considered a part of the method signature. Method overloading is used when objects are required to perform a similar task but by using different input parameters. When we call a method in an object, java matches up the method name first, and then the number and type of parameters, to decide which method to execute. This process is known as Polymorphism.

Public class Movie
{
float price;
public void setprice()
{
price=3.50;
}
public void setprice (float newprice)
{
price=newprice;
}
}
Movie mov1=new Movie();
mov1.setprice();
mov1.setprice(3.25);

As you can see setprice() is overloaded two times. The first version takes no argument and sets the price to 3.50 and second constructor takes single argument whic sets the price to 3.25.

When an overloaded method is called, java looks for a match between the argument used to call the method and the method's parameters. However, this match need not be exact. In some cases java's automatic type conversion takes the important role in overloaded resolution.

Example:
public class Movie
{
float price;
public void disp()
{
System.out.println(“No parameter”);
}
public void disp(int x, int y)
{
System.out.println(“x = ” + x + “y = “ +y);
}
public void disp(double x)
{
System.out.println(“x =” +x);
}
}
class overload
{
public static void main ( String args[])
{
Overload ob = new overload();
int i = 100;
ob.disp(); //invokes no argument constructor
ob.disp(10,20); //invokes disp(int,int)
ob.disp(i); //invokes disp (double)
ob.disp(100.50) //invokes disp(double)
}
}

Class Movie does not define disp(int). When disp(int) is called from main(), when no matching method is found, java automatically converts an integer into a double. Java uses its automatic type conversion only if no exact match is found.
Java's standard class library has abs() method. This method returns absolute value of all type of numeric types e.g. Int double, float. This method is overloaded in Math class. Whereas in 'C' language there are three methods – abs(),fabs(),labs()- to return absolute of int, float and long values respectively, the java.awt.Graphics class has six different drawImage methods.

As far as java is concerned, these are entirely different methods. The duplicate names are really just a convenience for the programmer.



Constructors


CONSTRUCTORS:

When the object is created, Java performs default initialization, char variables are set to '\u0000', byte, short, int, long to zero, boolean to false, float to 0.0

All objects that are created must be given initial values. We can do it,

  1. By assigning the value to instance variable using dot operator.
  2. Through instance method for e.g get data()
  3. By using constructor method to initialize an object when it is first created.
  • Constructors have the same name as class itself.
  • Constructors do not specify a return type.
  • Constructors is called automatically by the run time system.
For e.g.

class Rectangle
{
int length,width;
Rectangle(int x, int y) //constructors
{
length = x;
width = y;
}
int rectArea()
{
return(length*width);
}
}

class ABC
{
public static void main(String args[])
{
Rectangle rect=new Rectangle();
Rectang lerect1=new Rectangle(15,10) //calling constructor
int area1=rect1.rectArea();
System.out.println(“Area1 = “+ area1);
}
}


                                                              Constructors

If you do not provide any constructors, a default no-arg constructor is provided for you. This constructor takes no arguments and does nothing. If you want a specific no argument constructor as well as constructors that take arguments, you must explicitly provide your own no argument constructor.

DEFAULT CONSTRUCTOR:
If no constructors are declared in a class, the compiler will create a default constructor that takes no parameter.
When you create a new Movie object, the compiler decides which constructor to call, based on the argument specified in parentheses in the new statement. Constructor can call another constructor of the same class by using this() syntax. By using this(), you can avoid duplicate code in multiple constructors. This technique is used when initialization routine is complex.

Public class Movie
{
private String title;
private String rating;
public Movie()
{
this(“G”);
}
public Movie (String newRating)
{
raing = newRating;
}
}
RULES: The call to this() must be the first statement in the constructor. The argument to this() must match those of the target constructor.

Saturday, 19 March 2011

Java Classes, objects and methods

INTRODUCTION:
Java gives you the capability to do object-oriented programming. Object-oriented programming enables the programmer to group together data and the code that uses data into discrete units. Objects in java are defined using java classes. Anything we wish to represent in a java program must be encapsulated in a class that defines the state and behaviour of the basic program components known as object. Classes creates objects and objects use methods to communicate between them.
In java, the data items are called fields and the functions are called methods. calling a specific method in an object is described as sending a message to the object. A class provides a sort of template for an object and behaves like a basic data type such as int.

DEFINING A CLASS:
A class is a user defined data type used to implement an abstract object, giving you the capability to use object-oriented programming with java.
Once the class-type has been defined, we can create 'variables' of that type. These variables are termed as instances of class, which are actual objects.

The general form of a class definition is:
             Class name [extends superclassname]
             {
                   [variable declarations;]
                   [method declarations;]
             }
Everything written inside the square brackets is optional. Thus, the following would be a valid class definition.
             Class empty
             {
             }
Classname and Superclass name are any valid java identifiers. The keywords extends indicates that the properties of the superclassname class are extended to thr class classname. This concept is known as inheritance.

ADDING VARIABLES:
Data is encapsulated in a class by placing data fields inside the body of the class definition. These variables are called instance variables because they are created whenever an object of the class is instantiated. Instance variables can be declared exactly the same way as we declare local variables.

Example:
     Class Movie
     {
          String title;
          int length;
          int cost;
          char type;
     }

The class movie contains four instance variables, out of which one is of type string, two are of type int and one is of type char. The two int variables can be declared in one line as
      int length, cost;

ADDING METHODS:
A class has no life without methods. The objects created by such class cannot respond to any message. Therefore it is necessary to add methods for manipulating the data contained in the class. Methods are declared inside the class immediately after the variable declaration.
The general form of method declaration is:
     type method-name (parameter-list)
     {
          method-body;
     }

Where, -methodname denotes the name of the method.
            -type denotes the type of value the method returns
            -parameter-list denotes the list of parameters to be passed into the method.

The parameter-list must always be enclosed in parantheses. The variables in the list are separated by commas. In the case where no input data is required , the declaration must retain the empty parantheses.

Let us consider Movie class again and add a method getData() to it.
    Class Movie
    {
       String title;
       int length;
       int cost;
       char type;
       void getData (String s,int x,int y, char z)
        {
           title = s;
           length = x;
           cost = y;
           type = z;
        }
       }
Nothe that the method has a return type void because it does not return any value. The getData method is basically added to provoide values to the instance variables.

CREATING OBJECTS:
In java, objects are essentially a block of memory that contains space to store all the instance variables. The other name of creating an object is instantiating an object.

To create an object a new keyword is used as an operator. This operator creates an object of the specified class and returns a reference to thst objects.

The syntax of creating an object is as follows:
Class-name object-name;         //declare
Object-name = new class-name () ;         //instantiate

Example:
      Movie mov1;
      mov1 = new Movie();

The first statement declares a variable to hold the object reference and the second actually assigns the object reference to the variable. Both statements can be combined into one as shown below:
      Movie mov1 = new Movie();
Where Movie is the class name , mov1 is the object created by the default empty constructor of the class. We can create any number of objects of a class. Each object has it's own copy of instance variables of its class. Thus, any changes to the variables of one object have no effect on the variables of the another. Two or more references can be created to the same object just by assigning one object reference variable to another.

Example:
     Movie mov2 = new Movie();
     Movie mov3 = mov2;
Here, Both mov3 and mov2 refer to the same object.

Java's two reference of same object


Saturday, 12 March 2011

Decision making and looping

INTRODUCTION:
The iteration statements aloow a set of instructions to be performed repeatedly until a certain condition is fulfilled. The iteration statements are also called loops or looping statements. Java provides three kinds of loops:
  • While loop
  • do-while loop
  • for loop
All three constructs of java repeat a set of statements as long as a specified condition remains true. The specified condition is generally referred to as a loop control. For all three loop statements, a true condition is any nonzero value. A zero value indicates a false condition.

THE WHILE STATEMENT:
The most simple and general looping structure available in java is the while statement. The syntax of while loop is:
   while(condition)
   {
      // loop-body
    }
Where the loop body may contain a single statement, a compound statement or an empty statement. The loop iterates while the condition evaluates to true. When the expression becomes false, the program control passes to the line after the loop body code.

//program for while loop

class whiletest
 {
    public static void main(String args[])
      {
         int n=10;
         while(n>0)
         {
           System.out.println("tick", +n);
           n--;
          }
       }
}

THE DO STATEMENT:
Unlike the while loop, the do-while is an exit-controlled loop i.e it evaluates its text-expression at the bottom of the loop after executing it's loop-body statements. This means that a do-while loop always executes at least once. The syntax of the do-while loop is:
    do
    {
         loop-body;
     }
while(condition);

Example: 
 Class doWhileCheck
  {
     Public static void main (String args[])
      {
         int n=10;
          do
            {
               System.out.println("tick" +n);
                n--;
            }
             while(n>0);
        }
   }
THE FOR STATEMENT:
The for loop is the easiest to understand of the java loops. All its loop-control elements are gathered in one place (on the top of the loop), while in the other loop construction of C++ , they( top-contol elements) are scattered about the program. The Syntax of the for loop statement is:

for( initialization expression(s); test condition; update expression)
{
   loop-body;
}

//program showing usage of for loop
class forTest
{
   public static void main(String args[])
 {
    int i;
    for( i=1; i<=10; i++)
     System.out.println(i);
 }
}

Following figure outlines the working of a for loop:

Execution of a for loop
 


Thursday, 10 March 2011

Decision making and branching

Introduction:
Generally a program executes it's statements from beginning to end. But not many programs execute all their statements in strict order from beginning to end. Most programs decide what to do in response to changing circumstances.
In a program statements may be executed sequentially, selectively or iteratively. Every programming language provides constructs to support sequence,selection or iteration.
When a program breaks the sequential flow and jumps to another part of the code, it is called selection or branching.
When the branching is based on a particular condition, it is known as conditional branching.
If branching takes place without any condition, it is known as unconditional branching.

Java language supports two types of selections statements: if and switch. In addition, in certain circumstances '?' operator can be used as an alternative to if statements.

DECISION MAKING WITH IF STATEMENT:
An if statement tests a particular condition; if the condition evaluates to true , a course of action is followed i.e a statement or set of statements is executed . Otherwise (if the condition evaluates to false) ,the course-of-action is ignored.
The if statement may be implemented in different forms depending on the complexity of conditions to be tested.
  • Simple if statement
  • if....else statement
  • Nested if....else statement
  • else if ladder
SIMPLE IF STATEMENT:
The syntax of the if statement is shown below:
if(expression)
statements;

Where a statement may consist of a single statement , a compound statement, or nothing. The expression must be enclosed in parantheses. If the expression evaluates to true, the statement is executed, otherwise ignored.

Following figure illustrates the if construct of java:

Flow Chart of IF control
 Example:
if(a>10)
if(b<15)
c=(a-b)*(a+b);

If the value of a is greater than 10, then the following statement is executed which in turn is another if statement. This if statement tests b and if b is less than 15, then c is claculated.

THE IF....ELSE STATEMENT:
This form of if allows either-or condition by providing an else clause. The syntax of the if-else statement is the following:

if(expression)
  statement-1;
else
  statement-2;

If the expression evaluates to true i.e., a non-zero value, the statement-1 is executed, otherwise statement-2 is executed. The statement-1 and statement-2 can be a single statement, or a compound statement, or a null statement.

Following figure illustrates the if else construct of java:

Flow chart of if-else control
 Example:
int a,b;

if(a<=b)
   a=0;
else
   b=0;

NESTED IF....ELSE STATEMENT:
A Nested if is an if that has another if in it's 'if's' body or in it's else's body. The nested if can have one of the following three forms:

1.    if(expression1)
        {
          if(expression2)
           statement-1;
         else
           statement-2;
        }
      else
         body of else;

2.     if(expression1)
        body-of-if;
       else
       {
          if(expression2)
           statement-1;
         else
           statement-2;
        }

3.      if(expression1)
        {
          if(expression2)
           statement-1;
         else
           statement-2;
        }
      else
     {
       if(expression3)
           statement-3;
      else
         statement-4;
     }

THE ELSE-IF LADDER:
A common programming construct in the java is the if-else-if ladder , which is often also called the if-else-if staircase because of it's appearence.

It takes the following general form:
if(expression1) statement1;
  else
      if(expression2) statement2;
  else
      if(expression3) statement3;
   :
   else statement n;

The expressions are evaluated from top downward. As soon as expression evaluates to true , the statement associated with it is executed and the rest of the ladder is bypassed. If none of the expression are true, the final else gets executed. If the final else is missing , no action takes place if all other conditions are false.

Although it is technically correct to have indentation in the if-else-if ladder as shown above. however, it generally leads to overly deep indentation . For this reason, the if-else-if ladder is generally indented like this:

if(expression1)
  statement 1;
elseif(expression2)
  statement 2;
elseif(expression3)
  statement 3;
    :
else
  statement n;

THE SWITCH STATEMENT:
Java provides a multiple branch selection statement known as switch. This selection statement successively tests the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constant are executed.
The general form of switch is:
switch(expression)
{
case value1:
   Codesegment 1
case value2:
   Codesegment 2
   ...
case valuen:
   Codesegment n
default:
   default Codesegment
}

A switch statement is used for multiple way selection that will branch to different code segments based on the value of a variable or an expression . The optional default label is used to specify the code segment to be executed when the value of the variable or expression does not match with any of the case values. if there is no break statement as the last statement in the code segment for a certain case, the execution will continue on into the code segment for the next case clause without checking the case value.

NESTED SWITCH:
You can use switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch statement defines in its own block, no conflicts arise between the case statements in the inner switch and those in the outer switch.

switch(count)
{
   case 1:
   switch(target)
   {
       case 0:
       System.out.println("target is zero");
       break;
       case 1:
       System.out.println("target is one");
       break;
   }
break;
    case2: //. . .

Here the case 1: statement is inner switch does not conflict with the case 1: statement in the outer switch. The count variable is only compared with the list of cases at the outer level. if the count is 1 , then target is compared with the inner list cases.

No two case constants in the same switch can have individual values. A switch statement enclosed by an outer switch can have case constants in common.

THE ?: OPERATOR:
Java has an operator that can be used as an alternative to if statement. You are familier with this operator, the conditional operator ?: This operator can be used to relace if-else statements of the general form:

     if (expression 1)
        expression 2;
     else
         expression 3;

The above form of if can be alternativlely written using ?: as follows:

       expression 1? expression 2: expression 3;

Wednesday, 9 March 2011

Java Tokens

A Java program is a collection of tokens, comments and white spaces. There are five types of tokens included in java language. They are:
  • Reserved keywords
  • Identifiers
  • Literals
  • Operators
  • Seperators
Java Character Set:
Characters used to write java tokens are the smallest units of java language. These characters are defined by the unicode character set, an emerging standard that tries to create characters for a large number of scripts world wide. The unicode is a 16  bit character coding system.

Keywords:
Keywords implement specific features of the language. There are 60 reserved keywords defined in the java language. These keywords combined with the syntax of the operators and separators, from the definition of the java language. These keywords cannot be used as names for a variable, class or method.

Java Reserved Keywords
 Identifiers:
Identifiers are used for class names, method names, and variable names. An identifier may beb any sequence of uppercase and lowercase letters,numbers, or the underscore and dollar-sign characters. They must not begin with a number.
Again java is case sensitive , so First is different from first. Some examples of valid identifiers are:
avg            temp              b5                count              ptest              this_is_fine

Invalid variable names include:
2count            high-temp            Not/fine

Literals:
A constant value in java is created by using a literal representation of it. Literals can be digits, letters, and other characters. Major five types of literals in java are:
  • Integer literals
  • Floating-point literals
  • Character literals
  • String literals
  • Boolean literals
Each of them has a type associated with it. The type describes how the values behave and how they are stored. Example of some literals are given below:
10098.6          'Y'             "This is an answer"

A literal can be used anywhere a value of it's type is allowed.

Operators:
An operator is a symbol that takes one or more arguments and operates on them to produce a result.

Separators:
In java, there are a few characters that are used as seperators . Semicolon(;) is the most commonly used seperator in java. It is used to terminate statements. The seperators are shown below:


Java Seperators


Tuesday, 8 March 2011

Structure of java program

A Java program may contain many classes of which main() is defined in only one class. Classes contain data members and methods that operate on the data members of the class. Methods may contain datatype declarations and executable statements. To write a java program, we first define classes and then put them together. The different sections of a java program are shown in the below figure:


                                           Structure of java program

Document Section:
This section comprises a set of comment lines giving the name of the program, the author and the other details which the programmer would like to refer to at a larger stage. Comments must explain why and what of classes and how of algorithms. This would greatly help in maintaining the program.

Package Statement:
Package statement is the first statement aloowed in java. This statement declares the package name and informs the compiler that the classes defined here belong to this package.

Example:
package course;

The package statement is optional i.e., our classes may or may not be a part of package.

Import Statements:
After a package statement and before any class definition , may appear a number of import statements.

Example:
import course.selection;

This statement instructs the interpreter to load the selection class combined in package course. We can access classses that that are part of other named package susing import statements.

Interface Statements:
An interface is like a class but includes a group of method declarations. This is also an optional section and is used only when we wish to implement multiple inheritance features in the program.

Class Definitions:
A Java program may contain single or multiple class definitions. They are the primary and essential elements of java program. These classes are used to map the objects of real-world problems. The number of classes used depends on the complexity of the program.

Main Method Class:
This class is essential part of a java program since every java stand-alone program requires a main method as its starting point. The main method creates objects of various classes and establishes communication between them. The program terminates on reaching the end of main, and the control passes back to the operating system.




Monday, 7 March 2011

Overview of java programming

Java is general purpose, object-oriented programming language. Two types of java programs canbe developed.
  • Stand-alone applications
  • Web Applets
Stand-alone applications are programs written in java to carry out certain tasks on a stand-alone local computer. A stand-alone java program can be executed in two steps:
  1. Compiling source code into byte code using javac compiler.
  2. Executing the byte code program using java interpreter.
Web Applets are small java programs developed for internet applications.They are developed for doing everything like creating simple animated graphics, complex games, utilities etc.

SIMPLE JAVA PROGRAM:

//A Simple java program
Class Simple
{
public static void main (String args[])
    {
     System.Out.Println ("A Simple Java Program");
     }
}

We will explain the above program step by step.

Comment
The First line is a single line comment which will be ignored during compilation. Comments make you understand what your program does. Use /*-----*/ for multiple line comments.

Class Declaration
In java, everything must be declared in a class, which is declared by the keyword Class. Public is a keyword which makes the class available and accessible to any one.
(Simple) one is a java identifier that specifies the name of the class to be defined.

Opening Brace
In java, every class definition begins with an opening brace "{" and ends with a closing brace "}". Pair of "{}" braces define the scope of any method or class.

The Main Line
public static void main (String args[])
This linbe begins the main() method. This is the line at which program will begin executing. All java applications begin execution by calling main(). The main() must be declared as Public, since it must be called by code outside of it's class when the program is started.
The keyword void simply tells the compiler that the main() does not return a value. The keyword static allows main() to be called without having to instantiate a particular instance of the class.

The Output Line
System.Out.Println ("A Simple Java Program");
This line outputs the string followed by a new line on the screen. Output is accomplished by the built-in  println() method. System is a predefined class that provides access to the system, and out is the output stream that is connected to the console.

All statements in java ends with a semicolon(;).

Benefits of OOPS

There are several benefits of OOP to both program designer and the user. Object orientation solves many problems which are associated with the development and quality of software products. New technology gives greater programmer productivity, good quality of software and low maintanance cost. The main advantages are:
  • We can eliminate redundant code and extend the use of existing classes.
  • Programs can be build from the standard working modules that communicate with one another and to start writing the code from scratch. This shows to saving of development time and higher productivity.
  • The data hiding rules helps the programmer to make secure programs that cannot be invaded by code in other parts of the program.
  • It has multiple objects to coexist without any interference.
  • It has map objects in the problem domain to those objects in the program.
  • partition of work is easy in a project based on objects.
  • The data-centered design approach capture more details of a model in an implementable form.
  • Object oriented systems can be easily upgraded from small to large systems.
  • It is possible to easily manage software complexity.

Thursday, 24 February 2011

Operators used in java

Java provides rich operator enviroment. Most of it's operartors can be divided into the following four groups: Arithmetic, bitwise, relational and logical.

Arithmetic operators:
Arithmetic operators are used in mathematical expressions in same awy as they are used in algebra.
The following table lists the arithmetic operators:

Arithmetic Operators in java

The operands of the arithmetic operators must be of numeric type. you cannot use them on Boolean types, but you can use them on  char types. Since the char type in java is subset of int type.

Bitwise Operators:
Java defines several bitwise operators which can be applied to integer types, long,int,short,char and byte. These operators act upon individual bits of their operands.
They are summarized in following table:
                                                                                  Bitwise Operators in Java
Relational Operators:
The relational operators determine the relationship that one operand has to the other. Specifically they determine equlatity and ordering . The relational operators are shown here:

                                                                       Realationa Operators in Java
The outcome of these operators is a boolean value. The relational operators are most frequently used in the expressions that control the if statement and the various loop statements.
  Boolean Logical Operators:
The Boolean logical opertators are shown here operate only on boolean operands. All of the binary logical operators combine two boolean values to form a resultant boolean value.

Boolean Logical operators

Wednesday, 23 February 2011

OOP Principles

All object-oriented programming laanguages provide mechanisms that help you implement the object-oriented model. They are encapsulation, inheritance, and polymorphism.

ENCAPSULATION:
Encapsulation is the emchanism that binds together the code and the data it manuplates, and keeps safe from outside interference and misuse. It is a protective wrapper that prevents the code and data from being arbitrarily accessed by other code defined outside the wrapper. Access to the code and data inside the wrapper is tightly controlled through a well defined interface.

In java, the basis of encapsulation is Class. Since the purpose of a class is to encapsulate complexity. A class defines the structure and behaviour (code and data) that will be shaared by sset of objects . Each object of given class contains the structure and behaviour defined by the class. For this reason, objects are sometimes referred to as INSTANCES OF A CLASS. Thus, a class is a logical construct ; an object has physical reality.

INHERITANCE:
Inheritance is the process by which one object acquires the properties of another object. This is important because it supports the concept of hierarchical classification

There is one SUPERCLASS and one SUBCLASS in the process of inheritance.
Superclass is the main class or Base class from which another class or Child class is inherited. and Subclass is the derived class wwhich inherits all the properties if the main class.

POLYMORPHISM:
Ploymorphism ( from the reek, meaning "many forms") is a feature that allows one interface to be used for a general class of actions . The specific action is determined by the exact nature of the situation.
More generally. the concept of polymorphism is often expressed by the phrases, "one interface , multiple methods." This means it is possible to design a generic interface to a group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is complier's job to select the specific action as it applies to each situation.

Example:
Consider a stack ( which is last in first out list ). you might have a program that requires three types of stacks. one stack is used for integer values , one for floating point values, and one for characters. The algorithm that implement each stack is same, even though the data being stored differs. In a non object oriented language, you would be required to create three different sets of stack routines , with each set using different  names. However, because of polymorphism, in java you can specify a general set of stack routines that all share the same names. 

Servlets

Servlets are miniature programs that must be run inside another program called a container. The container is responsible for brokering communication between the servlet and the outside world.
Apart from that servlets are like every Java Application. They can import packages, write to the hard drive, and even install viruses on your machine. By default, servlets are trusted code. The reason is that if someone has enough permission on your computer to install a servlet, he already has enough power to tie the whole machine in knots anyway.

Servlets are not java appliactions. They must run inside a container instead of form a command line.
Servlets are not the only way for the server to communicate with a browser.  A web Server is an HTTP application. It receives communication via the HTTP protocol and it communicates with the browser via HTTP also. You can write your own HTTP server-side application that processes its own requests, bypassing both servlets and servlet container


HOW SERVLETS WORK:
Servlets are really parts of an application and require a servlet container to run. This servlet container is responsible for instantiating your servlet and calling the appropriate methods in the servlet at the appropriate times.

When you type the name of a servlet, you are really making a call to a program that is located on a server and not on your machine.
Figure below shows the process graphically:

How Servlet works
 The Servlet container is responsible for instantiating your servlets.
  • You type in the URL of a servlet that you want to call.
  • The browser creates a request that contains the servlet and name of you machine so that the server will know who to send feedback to.
  • The server receives the request and hands it to the servlet container. The servlet container is a program that knows how to run servlets.
  • The servlet container checks to see if any instances of this servlet are already in memory. if not, it loads an instance and run the servlet init() method.
  • The servlet container waits for the init() method to finish. it then calls the service() method. in your servlet from a new thread.
  • The service() method calls the doGet() or doPost() method depending on what the request type is.
  • A second user's browser requests that the same servlet be run on its behalf.
  • The servlet container notices that an instance of the servlet is already in memory. so, it creates a new thread and starts running the same servlet that you are running.
  • This new thread calls the service() method.
  • If this is an HTTP servlet, the service() method calls the doGet() or doPost() methods.
  • The first thread finishes and a response is sent to  the web server, which forwards it to your browser.
  • The second thread finishes and a response is sent to the web server, which forwards it to the second user's browser.
  • At a certain point in future, the servlet container decides to deinstantiate the servlet. At that point it calls the destroy() method once for each instance in memory
The servlet lifecycle is represented in following figure.
Servlet Lifecycle



Tuesday, 22 February 2011

J2EE Components

J2EE applications are made up of components. A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with it's related classes and files and that communicates with other components. The J2EE specification defines the following J2EE components:
  • Application clients and applets are components that run on the client.
  • Java servlet and Java server pages(JSP) technology components are web component that run on server.
  • Enterprise Java Beans (EJB) components (enterprise beans) are business components that run on the server.

The structure of an HTTP response

An HTTP message sent by a server to a client is called an HTTP response.The initial line of HTTP response is called the status line. It has three parts, separated by spaces: the HTTP version, a response status code that tells the result of the request, and an english phrase describing the status code.

HTTP defines many status codes: common ones that you have noticed are 200 and 404. Here are two examples of a status line that could be sent in the response:
HTTP/1.0 200 OK
HTTP/1.0 404 Not Found

When the browser receives a status code that implies a problem, it displays an appropriate message to the user. if some data is associated with the response, headers like Content-Type and Content-Length that describe the data may also be present. A typical HTTP response looks like this:

HTTP/1.0 200 OK
Date: Tue, 10 jan 2002 23:56:12 GMT
Content-Type: text/html
Content-Length: 52

Monday, 21 February 2011

The Structure of HTTP Request

An HTTP message sent by client to server is called HTTP request.
The initial line for an HTTP request has three parts, separated by spaces.
  • A method name.
  • The local path of the requested resource(URI)
  • The version of HTTP being used.
A typical request is : GET /reports/sales/index.html HTTP/1.0

Here GET is the method name, /reports/sales/index.html is the resouce URI, and HTTP/1.0 is the HTTP version of the request.

The method name specifies the action that the client is requesting the server to perform.
HTTP 1.0 requests can have only one of the following three methods GET, HEAD, or POST.
HTTP 1.1 adds five more : PUT, OPTIONS, DELETE, TRACE, and CONNECT.

GET:
The HTTP GET method is used to retrieve a resource. It means " GET THE RESOURCE IDENTIFIED BY THIS URI". The resource is usually passive resource . A GET method request may be used for an active resource if there are few or no parameters to be passed.
If parameters are required, they are passed by appending a query string to the URI. For example,

GET method of HTTP Request
HEAD:
An HTTP HEAD request is used to retrieve the meta-information about a resource. Therefore, the response for a HEAD request contains only the header.
The Structure of HEAD request is exactly same as that of a GET request.
HEAD is commonly used to check the time when the resource was last modified on the server before sending it to the client. A HEAD request can save a lot of bandwidth, especially if the resource is very big.

POST:
A POST request is used to the server in order to be processed. It means, " POST THE DATA TO THE ARCHIVE RESOURCES IDENTIFIED BY THIS URI." The block of data is sent in message body.

HTML pages use POST to submit the HTML FORM data. Figure below shows the example of HTTP POST request generated by a typical form submission.

Example of HTTP POST request


PUT:
A PUT Request is used to add a resource to the server. It means"PUT THE DATA SENT IN THE MESSAGE BODY AND ASSOCIATE IT WITH THE GIVEN REQUEST-URI."

For Example, when we PUT a local file named sample.html to the server myhome.com using the URI http://www.myhome.com/files/example.html, the file becomes a resource on that server and is associated with the URI
http://www.myhome.com/files/example.html.






Introduction to J2EE architecture

J2EE is a technology that aims to simplify the design and implementation of enterprise applications

An enterprise application is an application which probably has legacy existing applications and database that you want to continue using them while adding or migrating to a new set of applications that exploit internet, e-commerce and other new technologies.