Wednesday, July 29, 2009

Introduction to java:
Java
– was created in 1991
– by James Gosling et al. of Sun Microsystems.
– Initially called Oak, in honor of the tree outside Gosling's window, its name
was changed to Java because there was already a language called Oak.

The original motivation for Java
● the need for platform independent language that could be embedded in various consumer electronic products like toasters and refrigerators.
– One of the first projects developed using Java
● a personal hand-held remote control named Star 7.
– At about the same time, the World Wide Web and the Internet were gaining popularity. Gosling et. al. realized that Java could be used for Internet programming

Object Oriented Programming Concept

Class and object:

class Count
{
public static void main(String args[])
throws java.io.IOException
{
int count = 0;
while (System.in.read() != -1)
count++;
System.out.println("Input has " + count +"chars.");
}
}

In the Java language, all methods and variables must exist within a class. So, the first line of the character-counting application defines a class, Count, that defines the methods, variables, and any other classes needed to implement the character-counting application. Since this program is such a simple one, the Count class just defines one method named main ().

Encapsulation :

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.

Polymorphism:

Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

Inheritance:
Inheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order.
When we talk about inheritance the most commonly used key words would be extends and implements. These words would determine whether one object IS-A type of another. By using these keywords we can make one object acquire the properties of another object.

Abstract class:
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 subclassed. 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.

Final class:
A final class is a Java class which cannot be extended. This means that a final class can not become a superclass nor have a subclass.
An example final class is written below:
final class MySecureClass {
// This class cannot be extended
}

Interface and packages

Interface:
An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

Structure of an interface:


interface Animal
{
Public void eat();
Public void travel();
}

Implementation of an interface:
When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.
/* File name : MammalInt.java */
public class MammalInt implements Animal{

public void eat(){
System.out.println("Mammal eats");
}

public void travel(){
System.out.println("Mammal travels");
}

public int noOfLegs(){
return 0;
}

public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

Interface inheritance:

Java does not support multiple class inheritance. Java does, however, support multiple interface inheritance. Therefore, a class can realize multiple "personalities" using something similar to the following construct:
public interface SuperSizable

extends java.io.Serializable, Comparable

{

public void superSize();

}


Packages:
Packages are used in Java in-order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier etc.
A Package can be defined as a grouping of related types(classes, interfaces, enumerations and annotations ) providing access protection and name space management.
Some of the existing packages in Java are::
• java.lang - bundles the fundamental classes
• java.io - classes for input , output functions are bundled in this package

Package hierarchy:
Import statement:
The import statement in Java allows to refer to classes which are declared in other packages to be accessed without referring to the full package name. You do not need any import statement if you are willing to always refer to java.util.List by its full name, and so on for all other classes. But if you want to refer to it as List, you need to import it, so that the compiler knows which List you are referring to.
Multithreading

Thread is an lightweight processes.
 Create a class that extends the Thread class
 Create a class that implements the Runnable interface


1st method: Extending Thread class

 Create a class by extending Thread class and override run() method:
class MyThread extends Thread
{
public void run()
{
// thread body of execution
}
}
 Create a thread:
MyThread thr1 = new MyThread();
 Start Execution of threads:
thr1.start();
 Create and Execute:
new MyThread().start();

An Example:


class MyThread extends Thread {
public void run() {
System.out.println(" this thread is running ... ");
}
}

class ThreadEx1 {
public static void main(String [] args ) {
MyThread t = new MyThread();
t.start();
}
}


2nd method: Threads by implementing Runnable interface

 Create a class that implements the interface Runnable and override run() method:
class MyThread implements Runnable
{
.....
public void run()
{
// thread body of execution
}
}
 Creating Object:
MyThread myObject = new MyThread();
 Creating Thread Object:
Thread thr1 = new Thread( myObject );
 Start Execution:
thr1.start();


An Example:

class MyThread implements Runnable {
public void run() {
System.out.println(" this thread is running ... ");
}
}

class ThreadEx2 {
public static void main(String [] args ) {
Thread t = new Thread(new MyThread());
t.start();
}
}


Life cycle of a thread :

When you are programming with threads, understanding the life cycle of thread is very valuable. While a thread is alive, it is in one of several states. By invoking start() method, it doesn’t mean that the thread has access to CPU and start executing straight away. Several factors determine how it will proceed.

Different states of a thread are :

1. New state – After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive.

2. Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor.

3. Running state – A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool.

4. Dead state – A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.
5. Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread.







Methods in the thread class:
Following is the list of important medthods available in the Thread class.

Method Return Type Description
currentThread( ) Thread Returns an object reference to the thread in which it is invoked.
getName( ) String Retrieve the name of the thread object or instance.
start( ) void Start the thread by calling its run method.
run( ) void This method is the entry point to execute thread, like the main method for applications.
sleep( ) void Suspends a thread for a specified amount of time (in milliseconds).
isAlive( ) boolean This method is used to determine the thread is running or not.
activeCount( ) int This method returns the number of active threads in a particular thread group and all its subgroups.
interrupt( ) void The method interrupt the threads on which it is invoked.
yield( ) void By invoking this method the current thread pause its execution temporarily and allow other threads to execute.
join(n') void This method and join(long millisec) Throws InterruptedException. These two methods are invoked on a thread. These are not returned until either the thread has completed or it is timed out respectively.


1.publicvoidstart()

Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.

2.publicvoidrun()

If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object.

3.publicfinalvoidsetName(Stringname)
Changes the name of the Thread object. There is also a getName() method for retrieving the name.
4.publicfinalvoidsetPriority(intpriority)

Sets the priority of this Thread object. The possible values are between 1 and 10.

5.publicfinalvoidsetDaemon(booleanon)

A parameter of true denotes this Thread as a daemon thread.

6.publicfinalvoidjoin(longmillisec)

The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.

7.Publicvoidinterrupt()

Interrupts this thread, causing it to continue execution if it was blocked for any reason.

8.publicfinalbooleanisAlive()

Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.






Synchronization:
When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time.
The process by which this synchronization is achieved is called thread synchronization.
The synchronized keyword in Java creates a block of code referred to as a critical section. Every Java object with a critical section of code gets a lock associated with the object. To enter a critical section, a thread needs to obtain the corresponding object's lock.
This is the general form of the synchronized statement:
synchronized(object)
{
// statements to be synchronized
}


Dead lock:

When we start using Mutex objects for thread exclusion we must be careful to avoid deadlock. Deadlock is the condition that occurs when all threads are waiting to acquire a resource held by another thread. Because all threads are blocked, they cannot release the locks they hold. And because they cannot release the locks, no other thread can acquire those locks.

Applets



 Java programs are divided into two main categories, applets and applications.

 An application is an ordinary Java program.

 An applet is a kind of Java program that can be run across the Internet.


The Applet class

 To create an applet, you must import the Applet class
 This class is in the java.applet package
 The Applet class contains code that works with a browser to create a display window
 Capitalization matters!
 applet and Applet are different names

Importing the Applet class


 Here is the directive that you need:
import java.applet.Applet;
 import is a keyword
 java.applet is the name of the package
 A dot ( . ) separates the package from the class
 Applet is the name of the class
 There is a semicolon ( ; ) at the end

The life cycle of an applet:

Four methods in the Applet class give you the framework on which you build any serious applet:
• Init: This method is intended for whatever initialization is needed for your applet. It is called after the param tags inside the applet tag have been processed.
• Start : This method is automatically called after the browser calls the init method. It is also called whenever the user returns to the page containing the applet after having gone off to other pages.
• Stop : This method is automatically called when the user moves off the page on which the applet sits. It can, therefore, be called repeatedly in the same applet.
• Destroy : This method is only called when the browser shuts down normally. Because applets are meant to live on an HTML page, you should not normally leave resources behind after a user leaves the page that contains the applet.
• Paint : Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the browser. The paint() method is actually inherited from the java.awt.

Applet classes:

Every applet is an extension of the java.applet.Applet class. The base Applet class provides methods that a derived Applet class may call to obtain information and services from the browser context.
These include methods that do the following:
• Get applet parameters
• Get the network location of the HTML file that contains the applet
• Get the network location of the applet class directory
• Print a status message in the browser
• Fetch an image
• Fetch an audio clip
• Play an audio clip
• Resize the applet
Additionally, the Applet class provides an interface by which the viewer or browser obtains information about the applet and controls the applet's execution. The viewer may:
• request information about the author, version and copyright of the applet
• request a description of the parameters the applet recognizes
• initialize the applet
• destroy the applet
• start the applet's execution
• stop the applet's execution
The Applet class provides default implementations of each of these methods. Those implementations may be overridden as necessary.


Syntax of applet tag:

Syntax ...

Attribute Specifications
• CODE=CDATA (class file)
• CODEBASE=URI (base URI for class files)
• WIDTH=Length (applet width)
• HEIGHT=Length (applet height)
• ARCHIVE=CDATA (archive files)
• OBJECT=CDATA (serialized applet)
• NAME=CDATA (name for inter-applet communication)
• ALT=Text (alternate text)
• ALIGN=[ top | middle | bottom | left | right ] (applet alignment)
• HSPACE=Pixels (horizontal gutter)
• VSPACE=Pixels (vertical gutter)
• common attributes
Example:






Awt(abstract window tool kit)

The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI) programming. AWT features include:
• a rich set of user interface components;
• a robust event-handling model;
• graphics and imaging tools, including shape, color, and font classes;
• layout managers, for flexible window layouts that don't depend on a particular window size or screen resolution;
• data transfer classes, for cut-and-paste through the native platform clipboard.
The AWT is part of the Java Foundation Classes (JFC). For other JFC features

Events:

There are many types of events that are generated by your AWT Application. These events are used to make the application more effective and efficient. Generally, there are twelve types of event are used in Java AWT. These are as follows :
1. Action Event
2. Adjustment Event
3. Component Event
4. Container Event
5. Focus Event
6. Input Event
7. Item Event
8. Key Event
9. Mouse Event
10. Paint Event
11. Text Event
12. Window Event


Controls:
Controls are components that allow a user to interact with your application. The awt supports the following types of controls:

Labels
Push buttons
Check boxes
Choice lists
Lists
Scroll bars
Text components
These controls are subclasses of component.

Layouts:
To add components to a Frame instance, you need to specify the type of component layout scheme to be used. A Layout Manager is used to specify to a container how components within that container should be arranged. Some of the layout given below

Flow layouts
Border layouts
Grid layouts
Card layouts

Swing
Applets classes:
Applets have the file extension "class".
Example - "sampleapplet.class". Some applets consist of more than just a class file. Other files are often needed for the applet to run successfully, such as JPG or GIF images used in the applet.

Before embedding an applet on your page you need to upload all the required files to your host server.

When inserting an applet in your web page you will need to save the applet on your host server as well as the HTML web page that the applet is embedded in. When your page is loaded by any visitor to your site the applet will be loaded and inserted on the page where you had embedded it. Applets have the file extension "class".
Example - "sampleapplet.class". Some applets consist of more than just a class file. Other files are often needed for the applet to run successfully, such as JPG or GIF images used in the applet.

Before embedding an applet on your page you need to upload all the required files to your host server.

When inserting an applet in your web page you will need to save the applet on your host server as well as the HTML web page that the applet is embedded in. When your page is loaded by any visitor to your site the applet will be loaded and inserted on the page where you had embedded it.
Icons:

Menus
Tables

Jdbc concepts
Establishing a connection:
First, you need to establish a connection with the DBMS you want to use. Typically, a JDBC application connects to a target data source using one of two mechanisms:
• Driver Manager: This fully implemented class requires an application to load a specific driver, using a hardcoded URL. As part of its initialization, the DriverManager class attempts to load the driver classes referenced in the jdbc.drivers system property. This allows you to customize the JDBC Drivers used by your applications.

• Data Source: This interface is preferred over Driver Manager because it allows details about the underlying data source to be transparent to your application. A Data Source object's properties are set so that it represents a particular data source.

Establishing a connection involves two steps: Loading the driver, and making the connection.
Loading the Driver
Loading the driver you want to use is very simple. It involves just one line of code in your program. To use the Java DB driver, add the following line of code:
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Your driver documentation provides the class name to use. In the example above, EmbeddedDriver is one of the drivers for Java DB.
Calling the Class.forName automatically creates an instance of a driver and registers it with the DriverManager, so you don't need to create an instance of the class. If you were to create your own instance, you would be creating an unnecessary duplicate, but it would do no harm.
After you have loaded a driver, it can make a connection with a DBMS.
Making the Connection
The second step in establishing a connection is to have the appropriate driver connect to the DBMS.

Creation a data tables :


import java.sql.*;

public class CreateStores {

public static void main(String args[]) {

String url = "jdbc:mySubprotocol:myDataSource";
Connection con;
String createTable;
String createArray;
createArray = "CREATE TYPE COF_ARRAY AS ARRAY(10) OF VARCHAR(40)";
createTable = "CREATE TABLE STORES ( " +
"STORE_NO INTEGER, LOCATION ADDRESS, " +
"COF_TYPES COF_ARRAY, MGR REF MANAGER )";
Statement stmt;

try {
Class.forName("myDriver.ClassName");

} catch(java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}

try {
con = DriverManager.getConnection(url,
"myLogin", "myPassword");

stmt = con.createStatement();

stmt.executeUpdate(createArray);
stmt.executeUpdate(createTable);

stmt.close();
con.close();

} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
}








Entering data into tables updating:

Use of prepared statement:
This JDBC tutorial helps us to use the PreparedStatement interface of java.sql package twice in a program. According to our requirement we can use the PreparedStatement object. The PreparedStatement object represents the precompiled SQL statement. Whenever, the SQL statement is precompiled then it stored in the PreparedStatement object which executes the statement many times and it reduces the time duration of execution. The PreparedStatement uses the '?' with SQL statement that provides the facility for setting an appropriate conditions in it. See brief description below:

import java.sql.*;

public class TwicePreparedStatement{
public static void main(String[] args) {
System.out.println("Twice use prepared statement example!\n");
Connection con = null;
PreparedStatement prest;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql:
//localhost:3306/jdbctutorial","root","root");
try{
String sql = "SELECT * FROM movies WHERE year_made = ?";
prest = con.prepareStatement(sql);
prest.setInt(1,2002);
ResultSet rs1 = prest.executeQuery();
System.out.println("List of movies that made in year 2002");
while (rs1.next()){
String mov_name = rs1.getString(1);
int mad_year = rs1.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
prest.setInt(1,2003);
ResultSet rs2 = prest.executeQuery();
System.out.println("List of movies that made in year 2003");
while (rs2.next()){
String mov_name = rs2.getString(1);
int mad_year = rs2.getInt(2);
System.out.println(mov_name + "\t- " + mad_year);
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}


Obtaining metadata:

Sometimes you need to obtain information about the provider, rowset, table, columns, or other database information without opening the rowset. Data "about" the database structure is called "metadata" and can be retrieved by a number of different methods. One method is to use schema rowsets.
OLE DB Templates provide a set of classes to retrieve schema information; these classes create predefined schema rowsets and are listed in Schema Rowset Classes and Typedef Classes.
Note If you are using OLAP and some of your rowsets are not supported by the schema rowset classes (for example, you have a variable number of columns), you should consider using CManualAccessor or CDynamicAccessor. You can scroll through the columns and use case statements to handle the possible data types for each column.
The Catalog/Schema Model
ANSI SQL defines a "catalog/schema" model for data stores; OLE DB uses this model. In this model, catalogs (databases) contain schemas, and schemas contain tables.
• Catalog A catalog is another name for a database. It is a collection of related schemas. To list the catalogs (databases) belonging to a given data source, use CCatalog. Because many databases have only one catalog, metadata is sometimes simply called "schema information."
• Schema A schema is a collection of database objects that are owned or have been created by a particular user. To list the schemas owned by a given user, use CSchemata.
In Microsoft SQL Server and ODBC 2.x terms, a schema is an owner (for example, "dbo" is a typical schema name). Also, SQL Server stores metadata in a set of tables: one table contains a list of all the tables, and another table contains a list of all the columns. There is no equivalent to a schema in a Microsoft Access database.
• Table Tables are collections of columns arranged in specific orders. To list the tables defined in a given catalog (database), and information about those tables, use CTables).

Wednesday, July 22, 2009

Class and objects

Object Oriented Programming Concept

Class and object:

                                              
                               class Count
                                {
                                public static void main(String args[])
                                throws java.io.IOException
                                               {
                                                      int count = 0;
                                                      while (System.in.read() != -1)
                                                       count++;
        System.out.println("Input has " + count             +"chars.");                  
                                               }
                               }

In the Java language, all methods and variables must exist within a class. So, the first line of the character-counting application defines a class, Count, that defines the methods, variables, and any other classes needed to implement the character-counting application. Since this program is such a simple one, the Count class just defines one method named main().

Introduction to java:

Java

was created in 1991

by James Gosling et al. of Sun Microsystems.

Initially called Oak, in honor of the tree outside Gosling's window, its name

was changed to Java because there was already a language called Oak.

The original motivation for Java

the need for platform independent language that could be embedded in various consumer electronic products like toasters and refrigerators.

One of the first projects developed using Java

a personal hand-held remote control named Star 7.

At about the same time, the World Wide Web and the Internet were gaining popularity. Gosling et. al. realized that Java could be used for Internet programming