Search

EJB 2.0 Drawbacks

  • Complex Products
  • Unmaintainable System
  • Non-portable, frame-work committed business components
  • Unpredictable System
  • Why EJB 2.0 is complex / complicated?
    • Session bean - to write say hello method

      in EJB 2.x, you need to write
      home interface
      component interface
      bean

      in EJB 3.x, you need to write
      interface (with annotation)
      bean (with annotation)

      EJB 2.x; lookup is the only way to get server object/resource
      EJB 3; DI (dependency injection) & lookup are the available way


      there are more points. But basically, with EJB 3 responsibility of container is heavy & responsibility of developer is light weight; so that development is less & maintenance is easy.

Seam, EJB and Hibernate useful tips



 
Here are some tips I have gathered during our Seam project.

@Create - Signals that this method should be called upon instantiation of the JavaBean.

@Stateless - Makes an EJB3 object

@Stateful - (SESSION) Caches in memory between server requests

@In - These variables will automatically be set by Seam through injection of the variables labeled by the annotation. i.e
String zipCode; (Behind the curtain: zipCode = request.getParameter("zipCode"); )

@Out - Same as above. This variable is also automatically set by Seam. Behind the curtain this variable is set in the HttpSession object.
( request.setAttribute("bestRestaurant", restaurant); )
What you also must remember is that if you want to use the outjected object, you only call it with its name. Not component name first.
i.e. If you stateful session bean is named @Name("someName") and you have a @Out String test, then when you use it in the view, you must write #{test} and not #{someName.test}
You can also say @Out(required = false) which means that the Object can be null. Otherwize it cannot.

@DataModel annotation exposes an attribute of type java.util.List to the JSF page as an instance of javax.faces.model.DataModel. This allows us to use the list in a JSF with clickable links for each row. The DataModel is made available in a session context variable named the variable name.

@PersistenceContext(type=EXTENDED)
EntityManager em;
This stateful bean has an EJB3 extended persistence context. The messages retrieved in the query remain in the managed state as long as the bean exists, so any subsequent method calls to the stateful bean can update them without needing to make any explicit call to the EntityManager.
Remember, its a good idea to clear the entitymanager once in a while if you do lots of searches

@Factory("messageList")
public void findMessages() {
messageList = em.createQuery("from Message msg order by msg.datetime desc").getResultList();
}
The first time we navigate to the JSP page, there will be no value in the messageList context variable. The @Factory annotation tells Seam to create an instance of MessageManagerBean and invoke the findMessages() method to initialize the value. We call findMessages() a factory method for messages.

@Remove
@Destroy
public void destroy() {}
All stateful session bean Seam components must have a method with no parameters marked @Remove that Seam uses to remove the stateful bean when the Seam context ends, and clean up any server-side state.

@NamedQuery(name="findProeveByAddress",
query = "SELECT p " +
"FROM Proeve p, PersonAdresseAdressetype paa "
+ "WHERE paa.person = p.person "
+ "AND (lower(p.person.fornavn) like :fornavn OR lower(p.person.mellomnavn) like :fornavn) "
+ "AND (lower(p.person.etternavn) like :etternavn) "
+ "AND (lower(p.person.foedselsnummer) like :foedselsnr) "
+ "AND (lower(paa.adresse.adressefelt1) like :adresse) "
+ "AND (lower(p.kommune.navn) like :kommunenavn) "
+ "order by p.person.etternavn, p.avlagt desc"
)

@Lob - Used for storing large string/byte objects. Becomes text or blob.

Join Fetch - Makes the fetch eager. Be careful using join fetch. What I mean with that is that you should only use fetch when you are going to call methods
on the object being fetched. Otherwize it will be a performance issue.

@Enumerated(EnumType.STRING) - Makes the enum as string in the database

@Observer("proeveSearchDirty")
public void clear() {
proeveSokList = null;
}
With the observer annotation you can call on methods by giving it a name from other seam components.
For instance you can raise event which will call the observer method after an persist is made

@RaiseEvent("proeveSearchDirty")
public String persist() {
return super.persist();
}

If you want to override the default "Successfully created/updated/removed" from Seam and your EntityHome objects, then you can either override the methods
in the Home class. i.e
@Override
public String getCreatedMessage() {
return "Saved";
}

@Override
public String getUpdatedMessage() {
return "Updated";
}

@Override
public String getDeletedMessage() {
return "Removed";
}
Or you can put it in the messages.properties file with the notation:
*EntityName*.created. For instance:
Adresse_created=Lagret
Adresse_updated=Oppdatert
Adresse_deleted=Slettet
The messages.properties will be the default even if you have overrided the methods in your Home objects.

Hibernate Introduction

Hibernate is a Object relational mapping framework. What it will help us is in saving the objects into the relational world.

Employee.java

public class Employee {

private String Name;

private int Emp_Id;

private String Designation;

private String Reportee;

private int Access_Carad_No;

    

    public String getName() {

        return Name;

    }

    public void setName(String name) {

        Name = name;

    }

    public int getEmp_Id() {

        return Emp_Id;

    }

    public void setEmp_Id(int emp_Id) {

        Emp_Id = emp_Id;

    }

    public String getDesignation() {

        return Designation;

    }

    public void setDesignation(String designation) {

        Designation = designation;

    }

    public String getReportee() {

        return Reportee;

    }

    public void setReportee(String reportee) {

        Reportee = reportee;

    }

    public int getAccess_Carad_No() {

        return Access_Carad_No;

    }

    public void setAccess_Carad_No(int access_Carad_No) {

        Access_Carad_No = access_Carad_No;

    }


 


 

}


 

Now we have the domain class definition with us. Now we will put a mapping file which will map this class to the data model in the database. We are not creating the table in the database as we will use hibernate to generate the data model. Though in real life application you would have your data model already created and placed in the database.

Employee.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>    

<class name="Employee.java" table="Employee" schema="hiberpract">

<id name="Emp_Id" column="EMP_ID">

<generator class="increment"></generator>

</id>


 

<property name="Name" column="NAME"></property>

<property name="Designation" column="DESIGNATION"></property>

<property name="Reportee" column="REPORTEE"></property>

<property name="Access_Carad_No" column="ACCCESS_CARD_NO"></property>


 


 

</class>

</hibernate-mapping>

Now we will provide hibernate the details to connect to the database. Similar to JDBC coding, the connection details and drivers need to be provided to Hibernate. This is done in a XML file

Hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<!-- Database connection settings -->

<property name="connection.driver_class">com.mysql.jdbc.Driver </property>

<property name="connection.url">jdbc:mysql://localhost:3306/Hiberpract </property>

<property name="connection.username">root</property>

<property name="connection.password">root</property>


 

<!-- JDBC connection pool (use the built-in) -->

<property name="connection.pool_size">1

</property>


 

<!-- SQL dialect - This tells the SQL grammer to be used -->

<property name="dialect">org.hibernate.dialect.HSQLDialect

</property>


 

<!-- Enable Hibernate's automatic session context management -->

<property name="current_session_context_class">thread</property>


 

<!-- Disable the second-level cache -->

<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider

</property>


 

<!-- Log out all the sql that hibernate is issuing to datbase.

This is very useful for debugging -->

<property name="show_sql">true</property>


 

<!-- Create the table looking at class and mapping. Very useful in development

Use validate in production environments. -->

<property name="hbm2ddl.auto">create</property>

        <property name="format_sql">true</property>

<!-- Mapping file. -->

<mapping resource="Employee.hbm.xml"/>


 

</session-factory>

</hibernate-configuration>

Now we will write a utility class which will start the session factory of hibernate, if it is not started and will return the Session factory. This is the most used pattern of boot strapping Hibernate. Session factory contains all the configuration information at runtime. A Session is retrieve from the Session factory. A session is a light weight object which provide services to interact with database. You can think of Session like JDBC connection, thought it may not open the database connection if not required.

HiberUtil.java:

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;


 


 


 

public class HiberUtil

    {


 

        private static SessionFactory sessionFactory;


 

        static{

            try{

                //By default it will look for hibernate.cfg.xml in the class path

                sessionFactory=new Configuration().configure().buildSessionFactory();

            }catch(Throwable ex){

                throw new ExceptionInInitializerError(ex);

            }

        }


 

        public static SessionFactory getSessionFactory(){

            return sessionFactory;

        }


 

        public static void shutdown(){

            //Close caches and connection pool

            getSessionFactory().close();

        }


 

    }


 


Now Let's create the base class having main method..

HiberBase.java

import org.hibernate.Session;

import org.hibernate.Transaction;


 


 

public class HiberBase {


 

    public static void main(String[] args) {


 

        //Get the session from the Session factory

        Session session = HiberUtil.getSessionFactory().openSession();


 

        Transaction tx= session.beginTransaction();


 

        Employee Emp = new Employee();

        Emp.setName("Utkarsh");


 

        session.save(Emp);


 

        //System.out.println(studentId);


 

        tx.commit();

        session.close();

    }

}

In the above example we saw how to configure hibernate using XML mapping.

Overview of EJB and Lifecycle





The container is responsible for loading, activating, and in general maintaining the "life-cycle" of objects it provides. EJB have a fairly complex life-cycle. There are several kinds of EJB:
Session Beans: These may be either stateful or stateless, and are primarily used to encapsulate business logic, carry out tasks on behalf of a client, and act as controllers or managers for other beans.
 

Entity Beans: Entity beans represent persistent objects or business concepts that exist outside a specific application's lifetime. They are typically stored in a relational database. Entity beans can be developed using bean-managed persistence, which is implemented by the developer, or container-managed persistence, implemented by the container.

 
Message-Driven Beans: Message-driven beans listen asynchronously for Java Message Service (JMS) messages from any client or component and are used for loosely coupled, typically batch processing.

Ant Tutorial


  • Build.xml is the backbone file for running ANT.
  • It has one project tag and at least one target tag.
  • Project Tag has three attributes
    • Name:- Project Name
    • Default:-Default target to be called
    • Basedir:- Basic Directory to do the needful.(More specifically it contains the absolute path.)
  • Example:
    <project name="My Project" default="compile" basedir=".">

  • Then the target tag
    • Name:- target name(Required)
    • Depends:-if dependent on other targets..(We can even use if statement like if there exist the property then the target is dependent on other target )
    • Description:- description.
  • Example:
    <target name="clean" description="Removing the all generated files.">
    <delete dir="${dir.build}"/>
    <delete dir="${dir.dest}"/>
    </target>
  • Then the property tag.
    • Name:-name of the property
    • Location:- It contains the property name.
    • Value:- we can place the property value between ${"name }
    • File:- The name of the property file.
  • Example:
    <property name="build" value="${build}"/>
    <property name="build" location="src"/>
    <property file="build.properties"/>
  • Sample: build.xml
<project name="My Project" default="compile" basedir=".">
<property name="build" value="${build}"/> 

 
<property name="src" location="src"/> 

 
<property file="build.properties"/> 

 
<project name="My Project" default="jar" basedir=".">
<property name="dir.src" value="src"/>
<property name="dir.build" value="build"/>
<property name="dir.dest" value="dest"/>
<target name="clean" description="Removing the all generated files.">
<delete dir="${dir.build}"/>
<delete dir="${dir.dest}"/>
</target>
<target name="prepare" depends="clean">
<mkdir dir="${dir.build}"/>
<mkdir dir="${dir.dest}"/>
<mkdir dir="${dir.src}"/>
</target>
<target name="compile" depends="prepare" description="Compilation of all source code.">
<javac srcdir="${dir.src}" destdir="${dir.build}"/>
</target>
<target name="jar" depends="compile" description="Generates Sample.jar file in the dest folder">
<jar jarfile="${dir.dest}/sample.jar" basedir="${dir.build}"/>
</target>
</project>
<target name="buildWar" depends="init" description="build a war file"/>

 
<target name="init" if="build"/>

 
<target name="init" unless="build"/>

Hibernate Notes



 

  • The Hibernate project has the structure as shown in the figure as above.
  • We need one hibernate.cfg.xml file for hibernate configuration which handles connection pulling and other stuff like driver name, username of the database, password of the database, and the following properties..

Hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
  <property name="hibernate.connection.driver_class">

com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">

jdbc:mysql://localhost/hibernatetutorial</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.connection.password"></property>
  <property name="hibernate.connection.pool_size">10</property>
  <property name="show_sql">true</property>
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
  <!-- Mapping files -->
  <mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>

  • Here the Hibernate tutorial is the database supposed to be created at local host.
  • The dialect property says that we are suing the MySQL database.
  • The show sql property lets us see the comments at the console which ultimately increases readability.
  • Every Class file having the attributes have a classname.hbm.xml file which is the conf file for mapping between POJO and the database. For example we have "contact.hbm.xml" file for contact class.
  • Hibernate accesses all the data through POJO objects and then interacts with the database. For interacting with the database it uses the HQL(Hibernate Query Language)
  • Hibernate uses the Plain Old Java Objects (POJOs) classes to map to the database table. We can configure the variables to map to the database column.

Code for Contact.java:


/**
  * Java Class to map to the datbase Contact Table
 */
public class Contact {
  private String firstName;
  private String lastName;
  private String email;
  private long id;

  /**
 @return Email
 */
  public String getEmail() {
  return email;
  }

  /**
 @return First Name
 */
  public String getFirstName() {
  return firstName;
  }

  /** 
 @return Last name
 */
  public String getLastName() {
  return lastName;
  }

  /**
 @param string Sets the Email
 */
  public void setEmail(String string) {
  email = string;
  }

  /**
 @param string Sets the First Name
 */
  public void setFirstName(String string) {
  firstName = string;
  }

  /**
 @param string sets the Last Name
 */
  public void setLastName(String string) {
  lastName = string;
  }

  /**
 @return ID Returns ID
 */
  public long getId() {
  return id;
  }

  /**
 @param l Sets the ID
 */
  public void setId(long l) {
  id = l;
  }
}

Mapping the Contact class with the Contact Table.

Code for Contact.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="roseindia.tutorial.hibernate.Contact" table="CONTACT">
   <id name="id" type="long" column="ID" >
   <generator class="assigned"/>
  </id>

  <property name="firstName">
   <column name="FIRSTNAME" />
  </property>
  <property name="lastName">
  <column name="LASTNAME"/>
  </property>
  <property name="email">
  <column name="EMAIL"/>
  </property>
 </class>

</hibernate-mapping>


 


 

Then we need to create a hibernatetutorial database using MySQL running at localhost.

For updating or inserting the data in the database we first need to create the session of hibernate. For that we need to use hibernate session factory which returns the session for hibernate.

The hibernate-session is the main runtime interface between java and Hibernate.

The most important method for this is sessionobj.save(POJOobject);.

The code for FirstExample.java

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


/**

 * Hibernate example to inset data into Contact table
 */
public class FirstExample {
  public static void main(String[] args) {
  Session session = null;

  try{
  // This step will read hibernate.cfg.xml 

and prepare hibernate for use
  SessionFactory sessionFactory = new 

Configuration().configure().buildSessionFactory();
 session =sessionFactory.openSession();
  //Create new instance of Contact and set 

values in it by reading them from form object
 System.out.println("Inserting Record");
  Contact contact = new Contact();
  contact.setId(3);
  contact.setFirstName(
"Utkarsh");
  contact.setLastName(
"Thakkar");
  contact.setEmail(
"yjk@yahoo.com");
  session.save(contact);
  System.out.println("Done");
  }catch(Exception e){
  System.out.println(e.getMessage());
  }finally{
  // Actual contact insertion will happen at this step
  session.flush();
  session.close();

  }
  
  }
}

Dependency Injection (DI)

The first reference to what would eventually become Dependency Injection appeared in 1994 in a paper by Robert C. Martin called "The Dependency Inversion Principle".

In "The Dependency Inversion Principle" (or DIP), the author states the three defining factors of "bad code":

  • It is hard to change because every change affects too many other parts of the system (Rigidity)
  • When you make a change, unexpected parts of the system break (Fragility)
  • It is hard to reuse in another application because it cannot be disentangled from the current application (Immobility)

According to Martin, interdependency causes these coding problems (we'll call them RFI for Rigidity, Fragility, and Immobility). To fix RFI issues in your OO code, DIP has two basic rules:


 

1. High level modules should not depend upon low level modules, both should depend upon abstractions.

In other words, high level modules – which contain your business logic and all of the important meat of your application – should not depend on lower level components. The reason for this is if these lower level components were to change, the changes might affect the higher level components as well. This is the defining concept behind dependency inversion, that the prevailing wisdom of having higher-level modules dependent on lower-level modules is in fact a bad idea.

2. Abstractions should not depend upon details, details should depend upon abstractions.

This is another way to say that before you begin coding to the abstraction – the interface or abstract class – you should find the common behaviors in the code and work backwards. Your interface abstraction should cater to the intersection between the needs of your business logic and the common behaviors of the lower level modules. You should also leave the details of how these behaviors are implemented to the implementation classes.

Spring Light weighted Framework

Strategies

  • Loose coupling with dependency injection
  • Declarative programming with AOP
  • Boilerplate reduction with templates
  • Minimally invasive and POJO-oriented


Spring Keywords

  • Spring Web Flow
  • BlazeDS Integration
  • Spring-WS
  • Spring Security
  • Spring-DM
  • DmServer
  • Bundlor
  • TcServer
  • Spring Batch
  • Spring Integration
  • Spring LDAP
  • Spring IDE / STS
  • Spring Rich Client
  • Spring .NET
  • Spring BeanDoc
  • Groovy/Grails

MVC Design Patterns

Context

MVC is an architectural pattern that is used when developing interactive application such as a shopping cart on the Internet.

Problem

User interfaces change often, especially on the internet where look-and-feel is a competitive issue. Also, the same information is presented in different ways. The core business logic and data is stable.

Solution

Use the concept of dividing the concerns to divide the application into three areas

  • Model :- Encapsulates the core data and the functionality
  • View :- Encapsulates the presentation of the data there can be many views of the common data
  • Controller:- accepts input from the user and makes request from the model for the data to produce a new view

The model represents the structure of the data and the operations that can be performed on that data.

The view represents the data that is in a presentable format.

The controller translates the user action like mouse events, submit, keystrokes, words spoken with user input to call the call the specific operation with the model.

MVC example- Java Pet Store

It demonstrates a real-world approach to application development, where the presentation of data is separated from the process of obtaining data from objects which interact with the enterprise or database tier.

The design can be divided into the following tiers:

  • Client Tier
  • Web tier
  • Enterprise Bean Tier
  • Enterprise Information System Tier


 

The Client Tire is the only part which is visible to the end user of the application so it handles the view part it is also connected to the other tiers using some well defined interfaces.

The separate Client tier design provides flexibility and extensibility .


 

Variable arguments

You can use a construct called varargs to pass an arbitrary number of values to a method.

You will most commonly see varargs with the printing methods; for example, this printf method:

public PrintStream printf(String format, Object... args)


 

allows you to print an arbitrary number of objects. It can be called like this:

System.out.printf("%s: %d, %s%n", name, idnum, address);


 

or like this

System.out.printf("%s: %d, %s, %s, %s%n", name, idnum, address, phone, mail);

or with yet a different number of arguments.


 

Overloading of Methods

  • The Java programming language supports overloading methods, and Java can distinguish between methods with different method signatures. This means that methods within a class can have the same name if they have different parameter lists
  • You cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart.
  • The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.


     

  • Note: 
    • Overloaded methods should be used sparingly, as they can make code much less readable.


 

Copying arrays using System class method

The System class has an arraycopy method that you can use to efficiently copy data from one array into another:

public static void arraycopy(Object src,

int srcPos,

Object dest,

int destPos,

int length)

The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy.

The following program, ArrayCopyDemo, declares an array of char elements, spelling the word "decaffeinated". It uses arraycopy to copy a subsequence of array components into a second array:


 

class ArrayCopyDemo {

public static void main(String[] args) {

char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',

             'i', 'n', 'a', 't', 'e', 'd' };

char[] copyTo = new char[7];


 

System.arraycopy(copyFrom, 2, copyTo, 0, 7);

System.out.println(new String(copyTo));

}

}

The output from this program is:

caffein

Java Variables

Types of Variables

  • Instance Variable: Non-static fields are also known as instance variables because their values are unique to each instance of a class.
  • Class Variables:class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence; regardless of how many times the class has been instantiated.
  • Local Variables: Variables between the opening and closing braces of a method.
  • Parameters: The Arguments of a method or a constructor.

Naming Conventions

  • By convention it should start with the letter.
  • Avoid $ and _ characters in the names.
  • Whitespaces are not allowed.
  • Keyword or any reserved word should not be used.
  • For constants separate the words with the _.

Object initialization

  • As with class initialization, the simplest kind of object initialization is automatic initialization of object fields to default values.
  • Example:

    class ObjectInitializationDemo1

    {

    boolean b;

    byte by;

    char c;

    double d;

    float f;

    int i;

    long l;

    short s;

    String st;

    public static void main (String [] args)

    {

    ObjectInitializationDemo1 oid1 = new ObjectInitializationDemo1 ();

    System.out.println ("oid1.b = " + oid1.b);

    System.out.println ("oid1.by = " + oid1.by);

    System.out.println ("oid1.c = " + oid1.c);

    System.out.println ("oid1.d = " + oid1.d);

    System.out.println ("oid1.f = " + oid1.f);

    System.out.println ("oid1.i = " + oid1.i);

    System.out.println ("oid1.l = " + oid1.l);

    System.out.println ("oid1.s = " + oid1.s);

    System.out.println ("oid1.st = " + oid1.st);

    }

    }

  • Output

    b = false

    by = 0

    c =  

    d = 0.0

    f = 0.0

    i = 0

    l = 0

    s = 0

    st = null


     

  • There is no class loading and byte code verifying in between.
  • The same way the explicit assignment is done.
  • The default constructer initializes the contents of the object. For that it uses <init> methodfrom JVM perspective
  • The same way as in class initialization the object initialization also allows us to refer to the previously initialized field.
  • Object Block Initailazation

    {

          System.out.println ("Initializing object " + hashCode ());

          int localVariable = 1;

       }

  • In many situations, you will not use object block initializers because you can use constructors to perform complex initialization tasks. 
  • For situations like:  Anonymous inner classes often require object block initializers to perform complex initialization tasks.


    Anonymous inner classes require object block initializers because anonymous inner classes have no names, constructors take on the names of their classes, and you cannot declare constructors in classes that have no names.

  • In the case of hierarchies the class at the top most level is first initialized.
  • In object field/block initialization , one can access the field of the subclass but at that time the explicit value is not assigned so it will give us default value.


     

Class initialization

  • Although we tend to think of initialization in terms of assigning values to variables, initialization is so much more. 
  • For example, initialization might involve opening a file and reading its contents into a memory buffer, registering a database driver, preparing a memory buffer to hold an image's contents, acquiring the resources necessary for playing a video, and so on.
  • Java supports initialization via language features collectively known as initializers.
  • Class initialization is different from Object initialization and it happens before Object initialization.


 

  • Class Initialization
    • A program contains no of classes, before the execution of java program the class loader loads the public class having the PSVM.
    • Then the byte code verifier verifies the class.
    • Then class initializes.
    • The class fields are set to default values.
    • For Example:


       

      • static boolean b;//flase
      • static byte by;//0
      • static char c;//
      • static double d;//0.0
      • static float f;//0.0
      • static int i;//0
      • static long l;//0
      • static short s;//0
      • static String st;//null


         

  • We can also explicitly assign values to the class fields.
  • Those values are assigned to the fields just after the class is loaded and before any user defined method including main executes.
  • This initialization is done using <clinit>method of the JVM. It uses machine level instructions to assign those values.
  • Although a subsequently declared class field can refer to a previously declared class field, the reverse is not true: You cannot declare a class field initializer that refers to a class field declared later in source code. In other words, Java does not permit forward references with class field initializers, as the following code fragment demonstrates:
    • static int second = 1 + first;
    • static int first = 3;
  • In the cases when you need to read the contents of the file before the main method executes then we need to use the static block.
    • static
    •    {
    •       System.out.println ("Acquiring filenames");
    •       filenames = new File (".").list ();
    •       System.out.println ("Filenames acquired");
    •    }
  • Class block initializers are useful. For example, Sun's JDBC (Java Database Connectivity) API uses class block initializers to simplify database driver registration. Consider the following code fragment:
    • Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
  • Any variable declared in the block is having the scope only upto that block.
  • JVM allows us to declare any constant field without any explicit initializer, but u have to initialize it before its first use.
    • class ClassInitializationDemo5
    • {
    •    final static double PI;
    •    static
    •    {
    •       PI = 3.14159;
    •       int i;
    •       for (i = 0; i < 5; i++)
    •            System.out.println (i);
    •    }
    •    static int j = i;//this vl cause problem as the I is local to that block
    •    public static void main (String [] args)
    •    {
    •       System.out.println ("PI = " + PI);//this vl show 3.14 as the initialization is done in static block
    •    }
    • }
  • When a class hierarchy is involved, the compiler creates a separate<clinit> method for each class in that hierarchy. At runtime, the JVM loads all hierarchy classes and calls their <clinit> methods in a top-to-bottom order. 

Class Loading while running JVM

  • The Order is
    • Bootstrap classes - Classes that comprise the Java platform, including the classes in rt.jar and several other important jar files.
    • Extension classes - Classes that use the Java Extension mechanism. These are bundled as .jar files located in the extensions directory.
    • User classes - Classes defined by developers and third parties that do not take advantage of the extension mechanism. You identify the location of these classes using the -classpath option on the command line (the preferred method) or by using the CLASSPATH environment variable. 

Wild Cards while specifying the class path

  • A class path entry that contains * will not match class files. To match both classes and JAR files in a single directory foo, use either foo; foo/* or foo/*;foo. The order chosen determines whether the classes and resources in foo are loaded before JAR files in foo, or vice versa.
  • Subdirectories are not searched recursively. For example, foo/* looks for JAR files only in foo, not in foo/bar, foo/baz, etc.
  • If u want to load jars files or class file in a specific order that u have to specify the list itself in the class path but not using the wild cards.
  • Expansion of wildcards is done early, prior to the invocation of a program's main method, rather than late, during the class-loading process itself. Each element of the input class path containing a wildcard is replaced by the (possibly empty) sequence of elements generated by enumerating the JAR files in the named directory. For example, if the directory foo contains a.jar, b.jar, and c.jar, then the class path foo/* is expanded into foo/a.jar; foo/b.jar; foo/c.jar, and that string would be the value of the system property java.class.path.
  • The CLASSPATH environment variable is not treated any differently from the -class path (or -cp) command-line option. That is, wildcards are honoured in all these cases. However, class path wildcards are not honoured in the Class-Path jar-manifest header.

JDK and JRE File Structure

Assuming the JDK software is installed at c:\jdk1.7.0, here are some of the most important directories:

c:\jdk1.7.0

Root directory of the JDK software installation. Contains copyright, license, and README files. Also contains src.zip, the archive of source code for the Java platform.

c:\jdk1.7.0\bin

Executable files for the development tools contained in the Java Development Kit. The PATH environment variable should contain an entry for this directory. For more information on the tools, see the JDK Tools.

c:\jdk1.7.0\lib

Files used by the development tools. These include tools.jar, which contains non-core classes for support of the tools and utilities in the JDK. Also includes dt.jar, the DesignTime archive of BeanInfo files that tell interactive development environments (IDE's) how to display the Java components and how to let the developer customize them for an application.

c:\jdk1.7.0\jre

Root directory of the Java runtime environment used by the JDK development tools. The runtime environment is an implementation of the Java platform. This is the directory represented by the java.home system property.

c:\jdk1.7.0\jre\bin

Executable files and DLLs for tools and libraries used by the Java platform. The executable files are identical to files in /jdk1.7.0/bin. The java launcher tool serves as an application launcher (and replaced the old jretool that shipped with 1.1 versions of the JDK). This directory does not need to be in the PATH environment variable.

c:\jdk1.7.0\jre\bin\client

Contains the DLL files used by the Java HotSpot™ Client Virtual Machine.

c:\jdk1.7.0\jre\bin\server

Contains the DLL files used by the Java HotSpot™ Server Virtual Machine.

c:\jdk1.7.0\jre\lib

Code libraries, property settings, and resource files used by the Java runtime environment. For example:

c:\jdk1.7.0\jre\lib\ext

Default installation directory for Extensions to the Java platform.

  • localedata.jar -- locale data for java.text and java.util.

c:\jdk1.7.0\jre\lib\security

Contains files used for security management. These include the security policy (java.policy) and security properties (java.security) files.

c:\jdk1.7.0\jre\lib\applet

Jar files containing support classes for applets can be placed in the lib/applet/ directory. This reduces startup time for large applets by allowing applet classes to be pre-loaded from the local file system by the applet class loader, providing the same protections as if they had been downloaded over the net.

c:\jdk1.7.0\jre\lib\fonts

Contains TrueType font files for use by the platform.