Tuesday, 25 February 2014

Static in Java



Static is a keyword which can be applied to a variable, method and block. So in Java there are static variable, static method and static block.

1- Static variable-

Static variable is belong to class rather than (object) instance of the class. It means that only one instance of a static field exists even if you create a million instances of the class or you don't create any. It will be shared by all instances.

Static variables are mainly used for memory management. Static variable get the memory only once, if any object changes the value of the static variable, it will retain its value.

When we'll use static keyword before a variable that variable will be known as static variable.

Ex1-

class Test{ 
static int i=0;
 
Test(){ 
i++; 
System.out.println(i); 
 
public static void main(String args[]){ 
 
Test t1=new Test(); 
Test t2=new Test(); 
Test t3=new Test(); 
 
}} 

Output-
1
2
3


2- Static Method-

When we'll use static keyword before a method that method will be known as static method. Static method is belong to class rather than (object) instance of the class. We'll call a static method by class name.

Restrictions-
1-Static method can access only static data.
2-this and super keyword can not be use in static method.


Ex2-

class Test{ 
  static int add(int a, int b, int c){ 
  return a+b+c; 
  } 
 
  public static void main(String args[]){ 
  int sum=Test.add(1,2,3); 
  System.out.println(sum); 
  } 

Output-
6

Ex3-

class Employee{ 
     int empId; 
     String empName; 
     static String orgnization = "IBM"; 
      
     static void test(){ 
     orgnization = "Oracle"; 
     } 
 
     Employee(int e, String n){ 
     empId = e; 
     empName = n; 
     } 
 
     void showData ()
     {
     System.out.println(empId +" - "+empName+" - "+orgnization);
     } 
 
    public static void main(String args[]){ 
    Employee.test(); 
 
    Employee e1 = new Employee (4231,"Mark"); 
    Employee e2 = new Employee (4232,"Stephen"); 
    Employee e3 = new Employee (4233,"David");
    Employee e4 = new Employee (4244,"Kevin"); 
 
    e1.showData();
    e2.showData();
    e3.showData();
    e4.showData();
    } 


Output:
4231 Mark Oracle
4232 Stephen Oracle
4233 David Oracle
4234 Kevin Oracle


3- Static block-


When we use static before a block of code or simply a block such block is known as static block.
Static block always execute before main method.

Ex4-
public class StaticBlockDemo
{
// static block begin
  static
  {
  System.out.println("Hello");
  }

// static block end

 public static void main(String args[])
 {
  System.out.println("World");
 }

}

Output-
Hello World



IQ) why main method is static?
Ans- No, Object is required to call static method. That’s why main method is static.  if it was a non-static method, then jvm create object first then call main() method that will lead the problem of extra memory allocation.

IQ) Can we overload main method?

Ans- Yes, Main method in Java can be overloaded like any other method in Java but JVM will only call main method with specified signature as public static void main(String args[]).

Friday, 21 February 2014

Constructor in Java

To understand the constructor, it is similarly important to understand how it differs from a method. Any student of Java, especially one studying for certification, needs to know those differences; in this article, I will concretely spell them out. Table 1, at the end of this article, summarizes the key constructor/method distinctions.

Purpose and function

Constructors have one purpose in life: to create an instance of a class. This can also be called creating an object, as in:

Platypus p1 = new Platypus();
FEATURED RESOURCE

The purpose of methods, by contrast, is much more general. A method's basic function is to execute Java code.

Signature differences

Constructors and methods differ in three aspects of the signature: modifiers, return type, and name. Like methods, constructors can have any of the access modifiers: public, protected, private, or none (often called package or friendly). Unlike methods, constructors can take only access modifiers. Therefore, constructors cannot be abstract, final, native, static, or synchronized.

The return types are very different too. Methods can have any valid return type, or no return type, in which case the return type is given as void. Constructors have no return type, not even void.

Finally, in terms of the signature, methods and constructors have different names. Constructors have the same name as their class; by convention, methods use names other than the class name. If the Java program follows normal conventions, methods will start with a lowercase letter, constructors with an uppercase letter. Also, constructor names are usually nouns because class names are usually nouns; method names usually indicate actions.


Constructors and methods use the keyword this quite differently. A method uses this to refer to the instance of the class that is executing the method. Static methods do not use this; they do not belong to a class instance, so this would have nothing to reference. Static methods belong to the class as a whole, rather than to an instance. Constructors use this to refer to another constructor in the same class with a different parameter list. Study the following code:

public class Platypus {
       String name;
       Platypus(String input) {
               name = input;
       }
       Platypus() {
               this("John/Mary Doe");
       }
       public static void main(String args[]) {
               Platypus p1 = new Platypus("digger");
               Platypus p2 = new Platypus();
       }
}
In the code, there are two constructors. The first takes a String input to name the instance. The second, taking no parameters, calls the first constructor by the default name "John/Mary Doe".


If a constructor uses this, it must be in the constructor's first line; ignoring this rule will cause the compiler to object.

The use of "super"

Methods and constructors both use super to refer to a superclass, but in different ways. Methods use super to execute an overridden method in the superclass, as the following example illustrates:

class Mammal {
       void getBirthInfo() {
               System.out.println("born alive.");
       }
}
class Platypus extends Mammal {
       void getBirthInfo() {
               System.out.println("hatch from eggs");
               System.out.print("a mammal normally is ");
               super.getBirthInfo();
       }
}

In the above program, the call to super.getBirthInfo() calls the overridden method of the Mammal superclass.

Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain. An example follows:

public class SuperClassDemo {
        SuperClassDemo() {}
}
class Child extends SuperClassDemo {
       Child() {
               super();
       }
}
In the above (and trivial!) example, the constructor Child() includes a call to super, which causes the class SuperClassDemo to be instantiated, in addition to the Child class.

Compiler-supplied code

The new Java programmer may stumble when the compiler automatically supplies code for constructors. This happens if you write a class with no constructors; the compiler will automatically supply a no-argument constructor for you. Thus, if you write:


public class Example {}
it is functionally equivalent to writing:

public class Example {
       Example() {}
}
The compiler also automatically supplies code when you do not use super (using zero or more parameters) as the first line of a constructor. In this case, the computer automatically inserts super. Thus, if you write:

public class TestConstructors {
       TestConstructors() {}
}
it is functionally equivalent to writing:

public class TestConstructors {
       TestConstructors() {
               super;
       }
}

The sharp-eyed beginner may wonder how the above program can call the parent class's constructor when TestConstructor is not extending any class. The answer is that Java extends the Object class when you do not explicitly extend a class. The compiler automatically supplies a no-argument constructor if no constructor is explicitly declared, and automatically supplies a no-argument super call when a constructor has no explicit call to super. So the following two code snippets are functionally equivalent:

public class Example {}
and

public class Example {
       Example() {
             super;
       }
}
Inheritance

What is wrong with the following scenario? A lawyer is reading the will of A. Class. Members of the Class family are gathered around a large conference table, some sobbing gently. The lawyer reads, "I, A. Class, being of sound mind and body, leave all my constructors to my children."


The problem is that constructors cannot be inherited. Fortunately for the Class children, they will automatically inherit any of their parents' methods, so the Class children will not become totally destitute.

Remember, Java methods are inherited, constructors are not. Consider the following class:

public class Example {
        public void sayHi {
                system.out.println("Hi");
        }
        Example() {}
}
public class SubClass extends Example {
}
The SubClass class automatically inherits the sayHi method found in the parent class. However, the constructor Example() is not inherited by the SubClass.

Summarizing the differences

Just as the platypus differs from the typical mammal, so too do constructors differ from methods; specifically in their purpose, signature, and use of this and super. Additionally, constructors differ with respect to inheritance and compiler-supplied code. Keeping all these details straight can be a chore; the following table provides a convenient summary of the salient points. You can find more information regarding constructors and methods in the Resources section below.

Java Naming conventions

Java is a case sensitive language and to build Java programs you need to use a lot of Built-in API classes and methods. And beginners find it really hard to memorize the method names and Class names exactly without changing the case.
But actually you need not remember the case. It would be overkill to memorize it. But if you follow the Java Naming conventions, then you need not memorize the case of the methods and classes that you will be using. 99% of the classes in the JAVA API follow this naming convention. Only 1% of the names break this rule and that is also due to programmers forgetting to name it properly (its true!). So here we goes…

1. Classes:

Class names always begin with a capital letter (eg. java.util.Scanner). And if there are mutiple words in the class name then each word must also begin with a capital letter (eg. java.util.GregorianCalendar). Also package names always start with lowercase characters (util, lang, io, etc). And if there are multiple words in the package name, then you need to use uppercase for all words except for the starting word. This naming method is popularly called as UpperCamelCase which is a type of CamelCase! Interfaces also use same convention.

1
class MyClass {
2
}
2. Objects/Variables:

Java Naming convention specifies that instances and other variables must start with lowercase and if there are multiple words in the name, then you need to use Uppercase for starting letters for the words except for the starting word. This is called as lowerCamelCase.

1
String myName;
2
MyClass myObject;
3
Scanner scannerObject = new Scanner(System.in);
3. Methods:

Methods in Java also follow the same lowerCamelCase convention like Objects and variables.

1
void myMethod() {
2
}
3
String myName = scannerObject.nextLine();
4. Constant Variables:

In Java constant variables are declared using “static final” modifiers. And such variables must contain only UpperCase charachters and multiple words must be seperated using ‘_’.

1
static final char END_OF_FILE = 'e';
2
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Well thats it. Again, all these conventions were created just to improve readability of code. So its your choice to use them or leave them. But if you do use them, your code will look professional. Java Compiler does expect you to use these conventions.

Thursday, 20 February 2014

Design Pattern based on Encapsulation in Java


Many design pattern in Java uses encapsulation concept, one of them is Factory pattern which is used to create objects. Factory pattern is better choice than new operator for creating object of those classes whose creation logic can vary and also for creating different implementation of same interface. BorderFactory class of JDK is a good example of encapsulation in Java which creates different types of Border and encapsulate creation logic of Border. Singleton pattern in Java also encapsulate how you create instance by providing getInstance() method. since object
is created inside one class and not from any other place in code you can easily change how you create object without
affect other part of code.

Important points aboue encapsulation in Java.

1. "Whatever changes encapsulate it" is a famous design principle.
2. Encapsulation helps in loose coupling and high cohesion of code.
3. Encapsulation in Java is achieved using access modifier private, protected and public.
4. Factory pattern , Singleton pattern in Java makes good use of Encapsulation.



What is Abstraction ?

Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner. You just cannot create an instance of the abstract class.

If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclass. This is typically how abstract classes come about during the design phase. A parent class contains the common functionality of a collection of child classes, but the parent class itself is too abstract to be used on its own.

Abstract Class:
Use the abstract keyword to declare a class abstract. The keyword appears in the class declaration somewhere before the class keyword.

/* File name : Employee.java */
public abstract class Employee
{
   private String name;
   private String address;
   private int number;
   public Employee(String name, String address, int number)
   {
      System.out.println("Constructing an Employee");
      this.name = name;
      this.address = address;
      this.number = number;
   }
   public double computePay()
   {
     System.out.println("Inside Employee computePay");
     return 0.0;
   }
   public void mailCheck()
   {
      System.out.println("Mailing a check to " + this.name
       + " " + this.address);
   }
   public String toString()
   {
      return name + " " + address + " " + number;
   }
   public String getName()
   {
      return name;
   }
   public String getAddress()
   {
      return address;
   }
   public void setAddress(String newAddress)
   {
      address = newAddress;
   }
   public int getNumber()
   {
     return number;
   }
}
Notice that nothing is different in this Employee class. The class is now abstract, but it still has three fields, seven methods, and one constructor.

Now if you would try as follows:

/* File name : AbstractDemo.java */
public class AbstractDemo
{
   public static void main(String [] args)
   {
      /* Following is not allowed and would raise error */
      Employee e = new Employee("George W.", "Houston, TX", 43);

      System.out.println("\n Call mailCheck using Employee reference--");
      e.mailCheck();
    }
}
When you would compile above class then you would get the following error:

Employee.java:46: Employee is abstract; cannot be instantiated
      Employee e = new Employee("George W.", "Houston, TX", 43);
                   ^
1 error
Extending Abstract Class:
We can extend Employee class in normal way as follows:

/* File name : Salary.java */
public class Salary extends Employee
{
   private double salary; //Annual salary
   public Salary(String name, String address, int number, double
      salary)
   {
       super(name, address, number);
       setSalary(salary);
   }
   public void mailCheck()
   {
       System.out.println("Within mailCheck of Salary class ");
       System.out.println("Mailing check to " + getName()
       + " with salary " + salary);
   }
   public double getSalary()
   {
       return salary;
   }
   public void setSalary(double newSalary)
   {
       if(newSalary >= 0.0)
       {
          salary = newSalary;
       }
   }
   public double computePay()
   {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }
}
Here, we cannot instantiate a new Employee, but if we instantiate a new Salary object, the Salary object will inherit the three fields and seven methods from Employee.

/* File name : AbstractDemo.java */
public class AbstractDemo
{
   public static void main(String [] args)
   {
      Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
      Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);

      System.out.println("Call mailCheck using Salary reference --");
      s.mailCheck();

      System.out.println("\n Call mailCheck using Employee reference--");
      e.mailCheck();
    }
}
This would produce the following result:

Constructing an Employee
Constructing an Employee
Call mailCheck using  Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.
Abstract Methods:
If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as abstract.

The abstract keyword is also used to declare a method as abstract. An abstract method consists of a method signature, but no method body.

Abstract method would have no definition, and its signature is followed by a semicolon, not curly braces as follows:

public abstract class Employee
{
   private String name;
   private String address;
   private int number;
 
   public abstract double computePay();
 
   //Remainder of class definition
}
Declaring a method as abstract has two results:

The class must also be declared abstract. If a class contains an abstract method, the class must be abstract as well.

Any child class must either override the abstract method or declare itself abstract.

A child class that inherits an abstract method must override it. If they do not, they must be abstract and any of their children must override it.

Eventually, a descendant class has to implement the abstract method; otherwise, you would have a hierarchy of abstract classes that cannot be instantiated.

If Salary is extending Employee class, then it is required to implement computePay() method as follows:

/* File name : Salary.java */
public class Salary extends Employee
{
   private double salary; // Annual salary
 
   public double computePay()
   {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }

   //Remainder of class definition
}

What is Encapsulation ?

Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.

Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.

The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.

Example:
Let us look at an example that depicts encapsulation:

/* File name : EncapTest.java */
public class EncapTest{

   private String name;
   private String idNum;
   private int age;

   public int getAge(){
      return age;
   }

   public String getName(){
      return name;
   }

   public String getIdNum(){
      return idNum;
   }

   public void setAge( int newAge){
      age = newAge;
   }

   public void setName(String newName){
      name = newName;
   }

   public void setIdNum( String newId){
      idNum = newId;
   }
}
The public methods are the access points to this class' fields from the outside java world. Normally, these methods are referred as getters and setters. Therefore any class that wants to access the variables should access them through these getters and setters.

The variables of the EncapTest class can be access as below::

/* File name : RunEncap.java */
public class RunEncap{

   public static void main(String args[]){
      EncapTest encap = new EncapTest();
      encap.setName("James");
      encap.setAge(20);
      encap.setIdNum("12343ms");

      System.out.print("Name : " + encap.getName()+
                             " Age : "+ encap.getAge());
    }
}
This would produce the following result:

Name : James Age : 20

What is polymorphism?



 Polymorphism gives us the ultimate flexibility in extensibility. The abiltiy to define more than one function with the same name is called Polymorphism. In java,c++ there are two type of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding).

When you override methods, JVM determines the proper methods to call at the program’s run time, not at the compile time. Overriding occurs when a class method has the same name and signature as a method in parent class.

Overloading occurs when several methods have same names with

Overloading is determined at the compile time.
Different method signature and different number or type of parameters.
Same method signature but different number of parameters.
Same method signature and same number of parameters but of different type

Example of Overloading
     int add(int a,int b)
     float add(float a,int b)
     float add(int a ,float b)
     void add(float a)
     int add(int a)
     void add(int a)                 //error conflict with the method int add(int a)

What is Inheritance ?

Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.
Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes thesuperclass of MountainBikeRoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:
A diagram of classes in a hierarchy.
A hierarchy of bicycle classes.
The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:
class MountainBike extends Bicycle {

    // new fields and methods defining 
    // a mountain bike would go here

}
This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.

What is Class ?

In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.

Example-

class Bicycle {

    int cadence = 0;
    int speed = 0;
    int gear = 1;

    void changeCadence(int newValue) {
         cadence = newValue;
    }

    void changeGear(int newValue) {
         gear = newValue;
    }

    void speedUp(int increment) {
         speed = speed + increment;   
    }

    void applyBrakes(int decrement) {
         speed = speed - decrement;
    }

    void printStates() {
         System.out.println("cadence:" +
             cadence + " speed:" + 
             speed + " gear:" + gear);
    }
}
The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion of bicycle objects. The fieldscadencespeed, and gear represent the object's state, and the methods (changeCadencechangeGearspeedUp etc.) define its interaction with the outside world.
You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete application; it's just the blueprint for bicycles that might be used in an application. The responsibility of creating and using new Bicycle objects belongs to some other class in your application.
Here's a BicycleDemo class that creates two separate Bicycle objects and invokes their methods:
class BicycleDemo {
    public static void main(String[] args) {

        // Create two different 
        // Bicycle objects
        Bicycle bike1 = new Bicycle();
        Bicycle bike2 = new Bicycle();

        // Invoke methods on 
        // those objects
        bike1.changeCadence(50);
        bike1.speedUp(10);
        bike1.changeGear(2);
        bike1.printStates();

        bike2.changeCadence(50);
        bike2.speedUp(10);
        bike2.changeGear(2);
        bike2.changeCadence(40);
        bike2.speedUp(10);
        bike2.changeGear(3);
        bike2.printStates();
    }
}

The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles:
cadence:50 speed:10 gear:2
cadence:40 speed:20 gear:3

What is Object ?

Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle.
Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.
Take a minute right now to observe the real-world objects that are in your immediate area. For each object that you see, ask yourself two questions: "What possible states can this object be in?" and "What possible behavior can this object perform?". Make sure to write down your observations. As you do, you'll notice that real-world objects vary in complexity; your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn off), but your desktop radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming.
A circle with an inner circle filled with items, surrounded by gray wedges representing methods that allow access to the inner circle.
A software object.

Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.
Consider a bicycle, for example:
A picture of an object, with bibycle methods and instance variables.
A bicycle modeled as a software object.

By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6.
Bundling code into individual software objects provides a number of benefits, including:
  1. Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.
  2. Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.
  3. Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.
  4. Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.

Wednesday, 19 February 2014

Display Tag Pagination and Sorting Example


Here is  JSP page to display two dynamic tables using display tag.  <display:table>  tag is used create tables, while <display:column> tag is used create columns. You can make a column sortable by specifying attribute sortable="true" , you can define as many column as you like. If number of column is configurable, you can even use foreach tag from JSTL to loop through configuration data and create columns. Another important attribute is pagesize="5" , which defines how many rows each page will contain, if your data set has more rows than specified by this attribute, then it will appear in next page. You can use this attribute to control pagination in your application. Normally you should keep size so that it can take at-least 3/4th of page and rest can be used for other controls.   There is another attribute of display table tag, export, which is used to control export functionality. If you set this attribute as export=true then display tag will show export option for the table, which allows you to export data in pdfcsvxml and excel format.  For simplicity reason, I have used scriptlet to generate data and populate into list, which will be provided to display tag using a session scope attribute. You should not use Java code inside JSP in production code, instead all your code to generate data should reside in model classes or Servlets. Our first table read data from sessionscope.players attribute and second table read data from sessionscope.stars attribute, which is actuallyList implementations, ArrayList in our case.
      
dependency: 
1) display tag library
2) JSTL core tag library

You can download display tag from http://displaytag.sf.net website, and it comes with all internal dependency e.g. JARs required for creating PDF document or  iText library, Microsoft word and excel document support using Apache POI library and others. I am also using CSS files like displaytag.css, which comes along display tag examples, if you download the JAR.

<%@page import="java.util.ArrayList"%>
<%@page import="com.web.revision.Contact"%>
<%@page import="java.util.List"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="display" uri="http://displaytag.sf.net" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Display tag Pagination and Sorting Example in JSP</title>
        <link rel="stylesheet" href="css/displaytag.css" type="text/css">
        <link rel="stylesheet" href="css/screen.css" type="text/css">
        <link rel="stylesheet" href="css/site.css" type="text/css">

    </head>
    <body>

        <%
            List<Contact> players = new ArrayList<Contact>();
            players.add(new Contact("Virat"98273633"Mohali"));
            players.add(new Contact("Mahendara"98273634"Ranchi"));
            players.add(new Contact("Virender"98273635"Delhi"));
            players.add(new Contact("Ajinkya"98273636"Jaipur"));
            players.add(new Contact("Gautam"98273637"Delhi"));
            players.add(new Contact("Rohit"98273638"Mumbai"));
            players.add(new Contact("Ashok"98273639"Kolkata"));
            players.add(new Contact("Ravi"98273640"Chennai"));

            session.setAttribute("players", players);
            
            List<Contact> stars = new ArrayList<Contact>();
            stars.add(new Contact("Shahrukh"98273633"Delhi"));
            stars.add(new Contact("Sallu"98273634"Ranchi"));
            stars.add(new Contact("Roshan"98273635"Delhi"));
            stars.add(new Contact("Devgan"98273636"Jaipur"));
            stars.add(new Contact("Hashmi"98273637"Delhi"));
            stars.add(new Contact("Abraham"98273638"Mumbai"));
            stars.add(new Contact("Kumar"98273639"Kolkata"));
            stars.add(new Contact("Shetty"98273640"Chennai"));
           
            session.setAttribute("stars", stars);

        %>



        <div id='tab1' class="tab_content" style="display: block; width: 100%">
            <h3>Display tag Pagination and Sorting Example</h3>
            <p>This is FIRST TABLE </p>
            <display:table name="sessionScope.players" pagesize="5"
                           export="true" sort="list" uid="one">
                <display:column property="name" title="Name"
                                sortable="true" headerClass="sortable" />
                <display:column property="contact" title="Mobile"
                                sortable="true" headerClass="sortable" />
                <display:column property="city" title="Resident"
                                sortable="true" headerClass="sortable" />
            </display:table>
        </div>
       
        <div id='tab2' class="tab_content" style="width: 100%">
            <h3>Table 2</h3>
            <p>This is SECOND TABLE</p>
            <display:table name="sessionScope.stars" pagesize="5"
                           export="false" sort="list" uid="two">
                <display:column property="name" title="Name"
                                sortable="true" headerClass="sortable" />
                <display:column property="contact" title="Mobile"
                                sortable="true" headerClass="sortable" />
                <display:column property="city" title="Resident"
                                sortable="true" headerClass="sortable" />
            </display:table>
        </div>
    </body>
</html>