Thursday, July 30, 2009

Java Tutorial with Examples Home Page

Fundamentals
-------------------------------------------------------------------------------------------------------------------
DataTypes                             Identifiers                        Literals                        JavaKeyords

Variable                                Arrays                                Operators                   TypeCasting

FlowControl                        Coding Standards           imports,package      mainMethod,args

Access Modifiers                var-argMethod               AbstructClass          GarbageCollection

InnerClass                            Interface                           Assertions                java execution flow

super,this

java.lang
-------------------------------------------------------------------------------------------------------------------
Class,Object Classes          Enum                                  String                          StringBuffer,StringBuilder

Cloneable,Comparable      Wrapper Classes           Math class                Autoboxing,Autounboxing

System class

OOPS
-------------------------------------------------------------------------------------------------------------------
class,object                          Encapsulation                 Abstraction              Inheritance

Method Overloading        Method Overriding      Constructors         

Collections
-------------------------------------------------------------------------------------------------------------------
All List Classes                   All Set Classes                   All Map Classes       Collections Class

Iterator,ListIterator        Comparator                        Generics                  Timer,TimerTask

StringTokenizer              Locale class

Exceptions
-------------------------------------------------------------------------------------------------------------------
DefaultException             Checked,UnChecked      try,catch,finally      throw , throws
Handler

Threads
-------------------------------------------------------------------------------------------------------------------
Thread Creation               Thread Class Methods      Synchronization     wait,notify,notifyAll

Daemon Threads              Thread group                     Thread Deadlock

java.io
-------------------------------------------------------------------------------------------------------------------
File                                         All Reader Classes          All Writer Classes       All Stream Classes

Serialization

Wednesday, July 8, 2009

servlet-interface

In javax.servlet.Servlet Interface contains the following methods:

public void init (Servletconfig config) throws ServletException.

  • This method called by servlet container to indicate to a servlet that the servlet is being placed into the service.
  • The init () method called by servlet container exactly once after instantiating the servlet.
  • We can override init () method if we have initialization code like getting database connection.
  • The servlet container can not place the servlet into service of the init () methods.
In the following situation the web container destroys that servlet object.
If it throws a servlet exception
If it doesn't return with in a time period defined by the web server.

public void service (servlet Request req, Servlet Response res) throws ServletException, IOException :
  • Called by servlet container to allow to respond to the client request.
  • It should be called after the servlet’s init()method completion

public void destroy() :
  • The servlet container call the destroy () method before removing a servlet instance from service.
  • This normally happens when the servlet container is shut down of the servlet container needs some free memory.
  • This method is only called once all the thread with in the servlet service () method have exited.
  • We can keep cleanup code inside destroy () method.

public servlet config getservletconfig() :
It returns servlet config object which contain initialization and start of information of the servlet object.

public string getServletInfo() :
It returns a string containing information about the servlet such as author version and copy right.


Sample servlet program by implement Servlet interface :


import javax.servlet.*;
import java.io.*;
class BasicServlet implements Servlet
{
public void init ()(Servlet config conf) throws ServletException
{
System.out.println (“input method”);
}

public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException
{
System.out.println (“service method”);
}

public void destroy ()
{
System.out.println (“destroy method”);
}

public ServletConfig getServletConfig ()
{
return null;
}

public String getServletInfo ()
{
return null;
}

public String getServletInfo ()
{
return null;
}
}

Wednesday, July 1, 2009

javax servlet package

  • Javax.servlet: It defines several basic classes and interfaces to build servlets from the scratch irrespective of any protocol.
  • Javax.servlet.http: This package contain several more convenient classes and interfaces (which extends classes and interfaces of javax.servlet package) to build servlets specific to http. It also contain several extra utility classes and interfaces like cookies http session(interface for developing web applications efficiently.
JAVAX.SERVLET PACKAGE:
This package contains the following important interfaces:
1.Servlet Interface: It defines several methods which must be implemented by every servlet in java either directly or indirectly.
- this is the interface which define life cycle methods of interface.
2.Servlet Request : The servlet Request object contain client information which can be used by servlet to generate response.
3.Servlet Response : servlet response object contain the response which can sent to the client . ex:servlet uses servlet response object it send response to the client.
4.Servlet config : it contains the configuration or deployment information of start up information of the servlet.Web container creates a separate servlet and pass configuration information to the server by using this object.
5.Servlet context : Servlet context in the object which can be used by servlet to communicate with web server.For every web application one servlet context object will create by using the servlet context object servlet can get servlet context object.
6. Request Dispatcher: This object can be used by servlet to redirect the requests for another web component (servlet/jsp). This interface contain forward and include methods.
7. Single Thread Model: This interface can be implementing by servlet to generate that it can process only one request at a time.This is the deprecated interface and there is no replacement control 2.4. version.It does not contain any methods. So this is a MARKER INTERFACE.

These packages contain the following important classes.

  1. GenericServlet: to implement Generic protocol independent servlets.
  2. ServletInputStream: provides an input stream for reading binary data from a client request.
  3. ServletOutputStream: provides an output stream for reading binary data from a client request.This package defined the following Exception
  4. ServletException: Defines a general Exception. A servlet can throw when it fare some difficulty whose processing client request.
  5. UnavailableException: Defines an Exception that a servlet throws to indicate that the servlet is unavailable permanently or temporally.

Thursday, June 4, 2009

Serialization Inheritence

Serialization in case of Inheritence:
class Animal implements Serializable
{
int i=10;
}
class Dog extends Animal
{
int j=20;

}

When ever we are adding a child class object to a file ,parent class object will not save to the file .Because parent class objects are not part of state of the child class object.

If any variable is inherited from the perent that variable will also add to the file as a part of child class object.

example:

class SerialDemo

{
public static void main(String arg[])
{
Dog d=new Dog();
System.out.println(d.i+”……..”+d.j);

FileOutputStream fos=new FileOutputStream(“abc.txt”);
ObjectOutputStream oos=new ObjectOutputStream(fos);
Oos.writeObject(d);
FileInputStream fis=new FileInputStream(“abc.txt’);
ObjectInputStream ois=new ObjectInputStream(fis);
Dog d1=9Dog)ois.readObject();
System.out.println(d.i+”……..”+d.j);
}
}
  • If the parent class is serializable by default every child class is also serializable.
  • If we are writing any servlet by extending GenericServlet or HttpServlet it is always Serializable because GenericServlet already implements serializable interface

Note: By just simply seeing a class we can’t tell whether it is serializable or not .We have to check any parent class of this class of this class is serializable or not .If none of the parent class is not serializable then then only we can decode the given class is not serializable.

Serialization in case of Inheritence example:

class Animal
{
int i=10;
}
class Dog extends Animal implements serializable
{
int j=20;
}
class SerialDemo
{
public static void main(String arg[])throws Exception
{
Dog d=new Dog();
d.i=1000;
d.j=2000;

FileOutputStream fos=new FileOutputStream(“abc.txt”);
ObjectOutputStream oos=new ObjectOutputStream(fos);
Oos.writeObject(d);
FileInputStream fis=new FileInputStream(“abc.txt’);
ObjectInputStream ois=new ObjectInputStream(fis);
Dog d1=9Dog)ois.readObject();
System.out.println(d.i+”……..”+d.j);
}
}
  • If the child class is serializable and the parent is non serializable still we are allowed to save the child class objects to the file.
  • If any variable is inherited from the non-serializable parent its value is not allowed to save to the file as its corresponding class is non- serializable.
  • Instead of original value ,default values will save to the file.
  • At the time of de serialization to perform initialization for instance variable which are inherited from non- serializable parents its objects will create .After creation of parent class object ,the values of inherited values will be assigned.
  • At the time of deserialization of an object if any variable is inherited from non- serializable parent then the JVM creates parent class object by calling default no argument constructor.
  • If the parent class doesn’t contain any no argument constructor we can get a RTE saying Java.io.invalidClassException Dog :novalid constructor.

Monday, May 18, 2009

jdbc-data-types-tutorial

Data Types and Conversions :
For the getXXX methods, the JDBC driver attempts to convert the underlying data to the specified Java type and then returns a suitable Java value. For example, if the getXXX method is getString, and the data type of the data in the underlying database is VARCHAR, the JDBC driver will convert VARCHAR to Java String. The return value of getString will be a Java String object.

The following table shows which JDBC types a getXXX method is allowed to retrieve and which JDBC types (generic SQL types) are recommended for it to retrieve. A small x indicates a legal getXXX method for a particular data type; a large X indicates the recommended getXXX method for a data type. For example, any getXXX method except getBytes or getBinaryStream can be used to retrieve the value of a LONGVARCHAR, but getAsciiStream or getUnicodeStream are recommended, depending on which data type is being returned.

The method getObject will return any data type as a Java Object and is useful when the underlying data type is a database-specific abstract type or when a generic application needs to be able to accept any data type.


Use of ResultSet.getXXX methods to retrieve common JDBC data types.
An "x" indicates that the getXXX method may legally be used to retrieve the given JDBC type.

An "X" indicates that the getXXX method is recommended for retrieving the given JDBC type

Using Streams for Very Large Row Values :
ResultSet makes it possible to retrieve arbitrarily large LONGVARBINARY or LONGVARCHAR data. The methods getBytes and getString return data as one large chunk (up to the limits imposed by the return value of Statement.getMaxFieldSize). However, it may be more convenient to retrieve very large data in smaller, fixed-size chunks. This is done by having the ResultSet class return java.io.Input streams from which data can be read in chunks. Note that these streams must be accessed immediately because they will be closed automatically on the next getXXX call on ResultSet. (This behavior is imposed by underlying implementation constraints on large blob access.) 


The JDBC API has three separate methods for getting streams, each with a different return value: 

  • getBinaryStream returns a stream which simply provides the raw bytes from the database without any conversion.
  •  getAsciiStream returns a stream which provides one-byte ASCII characters.
  •  getUnicodeStream returns a stream which provides two-byte Unicode characters. 

    Note that this differs from Java streams, which return untyped bytes and can (for  example) be used for both ASCII and Unicode characters. 

The following code gives an example of using getAsciiStream: 

  java.sql.Statement stmt = con.createStatement();
  ResultSet r = stmt.executeQuery("SELECT x FROM Table2");
  // Now retrieve the column 1 results in 4 K chunks:
  byte buff = new byte[4096];
  while (r.next()) { 
  Java.io.InputStream fin = r.getAsciiStream(1);
  for (;;) {
  int size = fin.read(buff);
  if (size == -1) { // at end of stream
  break;
  }
  // Send the newly-filled buffer to some ASCII output stream:
  output.write(buff, 0, size);
  }
  }


Wednesday, April 15, 2009

JDBC-Result-Set

ResultSet :
A ResultSet contains all of the rows which satisfied the conditions in an SQL statement, and it provides access to the data in those rows through a set of get methods that allow access to the various columns of the current row. The ResultSet.next method is used to move to the next row of the ResultSet, making the next row become the current row.
The general form of a result set is a table with column headings and the corresponding values returned by a query. For example, if your query is SELECT a, b, c FROM Table1, your result set will have the following form:


The following code fragment is an example of executing an SQL statement that will return a collection of rows, with column 1 as an int, column 2 as a String, and column 3 as an array of bytes:

java.sql.Statement stmt = conn.createStatement();
ResultSet r = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (r.next())
{
// print the values for the current row.
int i = r.getInt("a");
String s = r.getString("b");
float f = r.getFloat("c");
System.out.println("ROW = " + i + " " + s + " " + f);
}

Rows and Cursors
A ResultSet maintains a cursor which points to its current row of data. The cursor moves down one row each time the method next is called. Initially it is positioned before the first row, so that the first call to next puts the cursor on the first row, making it the current row. ResultSet rows are retrieved in sequence from the top row down as the cursor moves down one row with each successive call to next. A cursor remains valid until the ResultSet object or its parent Statement object is closed.

In SQL, the cursor for a result table is named. If a database allows positioned updates or positioned deletes, the name of the cursor needs to be supplied as a parameter to the update or delete command. This cursor name can be obtained by calling the method getCursorName.

Note that not all DBMSs support positioned update and delete. The DatabaseMetaData.supportsPositionedDelete and supportsPositionedUpdate methods can be used to discover whether a particular connection supports these operations. When they are supported, the DBMS/driver must ensure that rows selected are properly locked so that positioned updates do not result in update anomalies or other concurrency problems.

Columns :

The getXXX methods provide the means for retrieving column values from the current row. Within each row, column values may be retrieved in any order, but for maximum portability, one should retrieve values from left to right and read column values only once.

Either the column name or the column number can be used to designate the column from which to retrieve data. For example, if the second column of a ResultSet object rs is named "title" and stores values as strings, either of the following will retrieve the value stored in that column:

String s = rs.getString("title");
String s = rs.getString(2);

Note that columns are numbered from left to right starting with column 1. Also, column names used as input to getXXX methods are case insensitive.
The option of using the column name was provided so that a user who specifies column names in a query can use those same names as the arguments to getXXX methods. If, on the other hand, the select statement does not specify column names (as in "select * from table1" or in cases where a column is derived), column numbers should be used. In such situations, there is no way for the user to know for sure what the column names are.

In some cases, it is possible for a SQL query to return a result set that has more than one column with the same name. If a column name is used as the parameter to a getXXX method, getXXX will return the value of the first matching column name. Thus, if there are multi0ple columns with the same name, one needs to use a column index to be sure that the correct column value is retrieved. It may also be slightly more efficient to use column numbers.

Information about the columns in a ResultSet is available by calling the method ResultSet.getMetaData. The ResultSetMetaData object returned gives the number, types, and properties of its ResultSet object's columns.
If the name of a column is known, but not its index, the method findColumn can be used to find the column number.

Tuesday, April 14, 2009

JDBC-CallableStatement

CallableStatement :
A CallableStatement object provides a way to call stored procedures in a standard way for all DBMSs. A stored procedure is stored in a database; the call to the stored procedure is what a CallableStatement object contains. This call is written in an escape syntax that may take one of two forms: one form with a result parameter, and the other without one. A result parameter, a kind of OUT parameter, is the return value for the stored procedure. Both forms may have a variable number of parameters used for input (IN parameters), output (OUT parameters), or both (INOUT parameters). A question mark serves as a placeholder for a parameter.
The syntax for invoking a stored procedure in JDBC is shown below. Note that the square brackets indicate that what is between them is optional; they are not themselves part of the syntax.

{call procedure_name[(?, ?, ...)]}

The syntax for a procedure that returns a result parameter is:

{? = call procedure_name[(?, ?, ...)]}

The syntax for a stored procedure with no parameters would look like this:

{call procedure_name}

Normally, anyone creating a CallableStatement object would already know that the DBMS being used supports stored procedures and what those procedures are. If one needed to check, however, various DatabaseMetaData methods will supply such information. For instance, the method supportsStoredProcedures will return true if the DBMS supports stored procedure calls, and the method getProcedures will return a description of the stored procedures available.
CallableStatement inherits Statement methods, which deal with SQL statements in general, and it also inherits PreparedStatement methods, which deal with IN parameters. All of the methods defined in CallableStatement deal with OUT parameters or the output aspect of INOUT parameters: registering the JDBC types (generic SQL types) of the OUT parameters, retrieving values from them, or checking whether a returned value was JDBC NULL.

Creating a CallableStatement Object
CallableStatement objects are created with the Connection method prepareCall. The example below creates an instance of CallableStatement that contains a call to the stored procedure getTestData, which has two arguments and no result parameter:

CallableStatement cstmt = con.prepareCall(
"{call getTestData(?, ?)}");

Whether the ? placeholders are IN, OUT, or INOUT parameters depends on the stored procedure getTestData.

Thursday, April 9, 2009

PreparedStatement

PreparedStatement : The PreparedStatement interface inherits from Statement and differs from it in two ways:

  • Instances of PreparedStatement contain an SQL statement that has already been compiled. This is what makes a statement "prepared."
  • The SQL statement contained in a PreparedStatement object may have one or more IN parameters. An IN parameter is a parameter whose value is not specified when the SQL statement is created. Instead the statement has a question mark ("?") as a placeholder for each IN parameter. A value for each question mark must be supplied by the appropriate setXXX method before the statement is executed.

Because PreparedStatement objects are precompiled, their execution can be faster than that of Statement objects. Consequently, an SQL statement that is executed many times is often created as a PreparedStatement object to increase efficiency. Being a subclass of Statement, PreparedStatement inherits all the functionality of Statement. In addition, it adds a whole set of methods which are needed for setting the values to be sent to the database in place of the placeholders for IN parameters. Also, the three methods execute, executeQuery, and executeUpdate are modified so that they take no argument. The Statement forms of these methods (the forms that take an SQL statement parameter) should never be used with a PreparedStatement object.

Creating PreparedStatement Objects :
The following code fragment, where con is a Connection object, creates a PreparedStatement object containing an SQL statement with two placeholders for IN parameters:

PreparedStatement pstmt = con.prepareStatement(
"UPDATE table4 SET m = ? WHERE x = ?");

The object pstmt now contains the statement "UPDATE table4 SET m = ? WHERE x = ?", which has already been sent to the DBMS and been prepared for execution.

Tuesday, April 7, 2009

jdbc

JDBC TUTORIAL

JDBC Introduction?

JDBC - ODBC Introduction

Types Of JDBC Drivers

JDBC - URL format tutorial

JDBC Statement

JDBC execute Method

JDBC Prepare Statement

JDBC CallableStatement

JDBC Result Set

JDBC Data types





JDBC EXAMPLES

1. JDBC connection Example code?

2. JDBC code to create a table ?

3. JDBC code ti insert data in DataBase?

4.

jdbc-execute-method

execute method:
The execute method should be used only when it is possible that a statement may return more than one ResultSet object, more than one update count, or a combination of ResultSet objects and update counts. These multiple possibilities for results, though rare, are possible when one is executing certain stored procedures or dynamically executing an unknown SQL string (that is, unknown to the application programmer at compile time). For example, a user might execute a stored procedure and that stored procedure could perform an update, then a select, then an update, then a select, and so on. Typically, someone using a stored procedure will know what it returns.


Because the method execute handles the cases that are out of the ordinary, it is no surprise that retrieving its results requires some special handling. For instance, suppose it is known that a procedure returns two result sets. After using the method execute to execute the procedure, one must call the method getResultSet to get the first result set and then the appropriate getXXX methods to retrieve values from it. To get the second result set, one needs to call getMoreResults and then getResultSet a second time. If it is known that a procedure returns two update counts, the method getUpdateCount is called first, followed by getMoreResults and a second call to getUpdateCount.

Those cases where one does not know what will be returned present a more complicated situation. The method execute returns true if the result is a ResultSet object and false if it is a Java int. If it returns an int, that means that the result is either an update count or that the statement executed was a DDL command. The first thing to do after calling the method execute, is to call either getResultSet or getUpdateCount. The method getResultSet is called to get what might be the first of two or more ResultSet objects; the method getUpdateCount is called to get what might be the first of two or more update counts.

When the result of an SQL statement is not a result set, the method getResultSet will return null. This can mean that the result is an update count or that there are no more results. The only way to find out what the null really means in this case is to call the method getUpdateCount, which will return an integer. This integer will be the number of rows affected by the calling statement or -1 to indicate either that the result is a result set or that there are no results. If the method getResultSet has already returned null, which means that the result is not a ResultSet object, then a return value of -1 has to mean that there are no more results. In other words, there are no results (or no more results) when the following is true:

((stmt.getResultSet() == null) && (stmt.getUpdateCount() == -1))

If one has called the method getResultSet and processed the ResultSet object it returned, it is necessary to call the method getMoreResults to see if there is another result set or update count. If getMoreResults returns true, then one needs to again call getResultSet to actually retrieve the next result set. As already stated above, if getResultSet returns null, one has to call getUpdateCount to find out whether null means that the result is an update count or that there are no more results.

When getMoreResults returns false, it means that the SQL statement returned an update count or that there are no more results. So one needs to call the method getUpdateCount to find out which is the case. In this situation, there are no more results when the following is true:

((stmt.getMoreResults() == false) && (stmt.getUpdateCount() == -1))

The code below demonstrates one way to be sure that one has accessed all the result sets and update counts generated by a call to the method execute:

stmt.execute(queryStringWithUnknownResults);
while (true) {
int rowCount = stmt.getUpdateCount();
if (rowCount > 0) { // this is an update count
System.out.println("Rows changed = " + count);
stmt.getMoreResults();
continue;
}
if (rowCount == 0) { // DDL command or 0 updates
System.out.println(" No rows changed or statement was DDL
command");
stmt.getMoreResults();
continue;
}

// if we have gotten this far, we have either a result set
// or no more results

ResultSet rs = stmt.getResultSet;
if (rs != null) {
. . . // use metadata to get info about result set columns
while (rs.next()) {
. . . // process results
stmt.getMoreResults();
continue;
}
break; // there are no more results

Monday, April 6, 2009

jdbc-statement-tutorial

Statement:
A Statement object is used to send SQL statements to a database. There are actually three kinds of Statement objects, all of which act as containers for executing SQL statements on a given connection: Statement, PreparedStatement, which inherits from Statement, and CallableStatement, which inherits from PreparedStatement. They are specialized for sending particular types of SQL statements: a Statement object is used to execute a simple SQL statement with no parameters; a PreparedStatement object is used to execute a precompiled SQL statement with or without IN parameters; and a CallableStatement object is used to execute a call to a database stored procedure.

The Statement interface provides basic methods for executing statements and retrieving results. The PreparedStatement interface adds methods for dealing with IN parameters; CallableStatement adds methods for dealing with OUT parameters.

Creating Statement Objects
Once a connection to a particular database is established, that connection can be used to send SQL statements. A Statement object is created with the Connection method createStatement, as in the following code fragment:

Connection con = DriverManager.getConnection(url, "sunny", "");
Statement stmt = con.createStatement();

The SQL statement that will be sent to the database is supplied as the argument to one of the methods for executing a Statement object:

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table2);

Executing Statements Using Statement objects:
The Statement interface provides three different methods for executing SQL statements, executeQuery, executeUpdate, and execute. The one to use is determined by what the SQL statement produces.

The method executeQuery is designed for statements that produce a single result set, such as SELECT statements.

The method executeUpdate is used to execute INSERT, UPDATE, or DELETE statements and also SQL DDL (Data Definition Language) statements like CREATE TABLE and DROP TABLE. The effect of an INSERT, UPDATE, or DELETE statement is a modification of one or more columns in zero or more rows in a table. The return value of executeUpdate is an integer indicating the number of rows that were affected (referred to as the update count). For statements such as CREATE TABLE or DROP TABLE, which do not operate on rows, the return value of executeUpdate is always zero.

The method execute is used to execute statements that return more than one result set, more than one update count, or a combination of the two. Because it is an advanced feature that most programmers will never need, it is explained in its own section later in this overview.

All of the methods for executing statements close the calling Statement object's current result set if there is one open. This means that one needs to complete any processing of the current ResultSet object before re-executing a Statement object.

It should be noted that the PreparedStatement interface, which inherits all of the methods in the Statement interface, has its own versions of the methods executeQuery, executeUpdate and execute. Statement objects do not themselves contain an SQL statement; therefore, one must be provided as the argument to the Statement.execute methods. PreparedStatement objects do not supply an SQL statement as a parameter to these methods because they already contain a precompiled SQL statement. CallableStatement objects inherit the PreparedStatement forms of these methods. Using a query parameter with the PreparedStatement or CallableStatement versions of these methods will cause an SQLException to be thrown.

Statement Completion:
When a connection is in auto-commit mode, the statements being executed within it are committed or rolled back when they are completed. A statement is considered complete when it has been executed and all its results have been returned. For the method executeQuery, which returns one result set, the statement is completed when all the rows of the ResultSet object have been retrieved. For the method executeUpdate, a statement is completed when it is executed. In the rare cases where the method execute is called, however, a statement is not complete until all of the result sets or update counts it generated have been retrieved.

Some DBMSs treat each statement in a stored procedure as a separate statement; others treat the entire procedure as one compound statement. This difference becomes important when auto-commit is enabled because it affects when the method commit is called. In the first case, each statement is individually committed; in the second, all are committed together.

Closing Statement Objects:
Statement objects will be closed automatically by the Java garbage collector. Nevertheless, it is recommended as good programming practice that they be closed explicitly when they are no longer needed. This frees DBMS resources immediately and helps avoid potential memory problems.
Using the Method execute

generic-class-generic-method

Generic classes:
We are allowed to define type parameter for the classes.such type of parametrized classes are called generic classes.

//Type parameter T
class Generictest<T,X>
{
T ob; //Generic variable

Generictest(T ob) //Generic constructor
{
this.ob=ob;
}
void show()
{
System.out.println(the type is:ob.getClass().getName());
}
T getob() //Generic method
{
return ob;
}
}
class GenericDemo
{
public static void main(Strin arg[])
{
Generictest<Integer> g=new Generictest<Integer>(10);
g.show(); //java.lang.Integer
System.out.println(g.getob()); // 10

Generictest<String> g=new Generictest<String>(“Laxman”);
g.show(); //java.lang.String
System.out.println(g.getob()); // Laxman
}
}

Bound Types:
We can bound the type parameter I the generic classes by using extends keyword.

Example:
Gen<T>
{
}
We are allowed to create an instance of class by passing any parameter type.
Gen<T extends Number>
{
}

  • we can create a gen object by passing the type parameter which must be child class of number violation leads to error.
i.e Gen<String> g=new Gen<String>();
CTE saying type parameter java.lang.String is not with in its bound.
Extends means both extends as well as implements.

class Gen<T extends X>
{
}
If X is a class any child class of X (including X) is allowed as T.
If X is any interface Any implemented class of X is allowed as T.

Generic Methods:
class
{
public static void main(String arg[])
{
ArrayList<String> st=new ArrayList<String>();
st.add(“aaa”);
st.add(“bbb”);
st.add(“ccc”);
show(s1);

ArrayList<Integer> st=new ArrayList<Integer>();
st.add(10);
st.add(20);
st.add(30);
show(s2);
public static void main(String arg[])
{
System.out.println(s);
}
}
}
wild card(?)character in generic conclusions:
1.m1(ArrayList<String> l)
This can be applied only for ArrayList of String type only.
2.m1(ArrayList<?> l)
This can be applied for ArrayList of any type ? means unknown type.which is known as wild card character .
3.m1(ArrayList<? Extends X> l)
If X is class this method can be applied for ArrayList of any class ,which is the child class of X is allowed.
If X is interface then any class which implements X is allowed .
4.m1(ArrayList <? Super X> l)
any class which is super class of X is allowed as the type parameter.

Conclusions:
class Test
{
public static void main(Strin arg[])
{
ArrayList<String> l=new ArrayList<String>();
l.add(“a”);
l.add(“b”);
l.add(“c”);
show(l);
//If type is string
show(ArrayList<String> l)
{
l.add(“e”);
l.add(10); // invalid (error: we are only allowed to add String objects)
System.out.println(l); // [a,b,c,e]
}
//If type is wild char (?)
show(ArrayList<?> l)
{
l.add(“e”); // error
l.add(“null”); // valid
System.out.println(l);
}
}

  • Here we doesn’t know what kind of parameter is coming for this method.Because this method is applicable for Arraylist of any type of parameter.
  • If we use wild card character ‘?’ in the method declaration ,then we are allowed to perform only READ operation with in that method.
  • we are not allowed to add any element because what kind of arraylist is coming as argument we can’t give any assurance.
  • But we can add null because null is a valid value for any object type.
  • We are allowed to use wild card character ? in the declaration part but we are not allowed to use in the construction part (Right hand side)
Example:
ArrayList<?> l=new ArrayList<String>(); //valid
ArrayList<?> l=new ArrayList<Integer>(); //valid
ArrayList<? Extends Number> l=new ArrayList<Integer>(); //valid
ArrayList<? Extendes Number> l=new ArrayList<Integer>(); // not valid
CTE:incompatable types
Found:ArrayList<string>
Reqire:ArrayList<Number>

ArrayList<String> l=new ArrayList<?>(); //not valid
CTE: unexcepetedtype found:?
Req: class or interface with out bounds.
  • On the right hand side we are not allowed to impose any boundaries by using extends or super key words.
Communication with legacy code:
To provide support for legacy code Sun people compromised some rules of generics.
class Test
{
public static void main(String arg[])
{
ArrayList <String> l=new ArrayList<String> ();
l.add(“a”);
l.add(“b”);
l.add(“c”);
show(l);
}
public static void show(ArrayList l)
{
l.add(“e”);
l.add(new Integer(10));
System.out.println(l); // [ a,b,c ,d,e,10]
}
  • Here we won’t get any errors but we get some warning.
  • To sport 1.4 version methods Sun people some how compromised in this generics area in 1.5 version.
ArrayList l=new ArrayLiat<String>(); // valid

Saturday, April 4, 2009

try-catch

We can handle exceptions by using the fallowing keywords.
1). try 2). catch 3). finally
try
{
//Risky code
}
catch(XException e)
{
//Define the handler
}

Example:
try
{
System.out.println(10/0);
}
catch(ArithematicException e)
{
System.out.println(“caught”);
System.out.println(10/2);
}
System.out.println(“hello”);
output:
caught
5
hello

Example: try {
Statement 1;
Stmt 2;
Stmt 3;
}
catch(XException e){ Statement 4; }
stmt5;

See the below cases:
Case 1:- If there is no Exception ->1,2,3,5 are executes. So normal termination.
Case 2:- If an Exception raised at stmt2 and the corresponding catch block found then 1 fallowed 4,5 are executes. So, normal termination.
Case 3:- If an Exception is raised at stmt2, but the corresponding catch block not found. Then stmt1 fallowed by abnormal termination.
Case 4:- If an Exception raised at stmt2 and the corresponding catch block found; but while executing catch block raises another Execution then stmt1 fallowed by abnormal termination.

Methods For Displaying Error Information :
The class Throwable contains the fallowing methods for displaying Error information.

1. printStackTrace():
Name of the Exception: Description of Exception Stack trace.
catch(ArithmaticException e)
{
e.printStackTrace();
}
System.out.println(“hai..”);
output:
java.lang.ArithmaticException: /by zero at sample.main(Sample.java)
Hai

2. public String toString():
Name of the Exception: Description of Exception

catch(ArithmaticException e)
{
System.out.println(e.toString());
}
System.out.println(“hai..”);
output:
java.lang.ArithmaticException: /by zero
Hai

3. public String getMessage():
Description of Exception
catch(ArithmaticException e)
{
System.out.println(e.getMessage());
}
System.out.println(“hai..”);
output: /by zero
hai

Try with Multiple catch blocks:
• The way of handling the exception is varied from exception to exception, hence it is a good programming practice to keep separate catch block for every exception.
Example:
try
{
System.out.println(10/0);
}
catch(ArithmeticException e) //child
{
//code
}
catch(Exception e) //parent
{
//code
}
Here in the above example ArithmeticException is the child class of Exception class.It is Valid since child --> to ---> parent hierarchy.

Example:

try
{
System.out.println(10/0);
}
catch(Exception e) //parent
{
//code
}
catch(ArithmeticException e) //child
{
//code
}

Here in the above example Exception class is the child class of ArithmeticException class.It is InValid since parent -->to ---> child hierarchy.compile time error(CTE) : Exception has already been caught by catch (ArithmeticException e).

• If multiple catch blocks are defined for the try statement, the order of the catch blocks is important. We should take the catch blocks from child to parent, violation leads to CTE saying “Exception” has already been caught”.

Control Flow in try with multiple catch blocks:
try
{
Statement 1;
Stmt2;
Stmt3;
}
catch(XException e)
{
Stmt 4;
}
catch(YException e1)
{
Stmt 5;
}
Stmt6;

see the below cases:
Case 1:- If there is no Exception ->1,2,3,6 is executes. So normal termination.
Case 2:- If an Exception raised at stmt2 and the corresponding catch block(Y Exception e1) is matches then 1,5,6 are executes. So, normal termination.
Case 3:- If an Exception is raised at stmt2, but the corresponding catch block not found. Then stmt1 fallowed by abnormal termination.

Control Flow in Nested try catch :
try
{
Statement 1;
Stmt2;
Stmt3;
try
{
Stmt4;
Stmt5;
Stmt6;
}
catch(XException e)
{
Stmt7;
}
Stmt8;
}
catch(YException e)
{
Stmt9;
}
Stmt10;

See the below cases:
Case 1:- If there is no Exception ->1, 2, and 3,4,5,6,8,10 is executes. So normal termination.
Case 2:- If an Exception raised at stmt2 and the corresponding catch block is matches then 1,9,10 are executes. So, normal termination.
Case 3:- If an Exception raised at stmt2 and the corresponding catch block not found. 1 fallowed by abnormal termination.
Case 4:- If an Exception raised at stmt5 and the corresponding catch block is matches then 1,2,3,4,7,10 and Normal Termination.
Case 5:- If an Exception raised at stmt5 and the corresponding catch block is not matched but outer catch block has matched 1,2,3,4,9,10 and Normal Termination.
Case 6:- An Exception raised at stmt2 and the corresponding catch block has matched but while executing that catch block another exception raised then fallowed by abnormal termination.
Case 7:- An Exception raised at stmt8 and the corresponding catch block has matched then 1,2,3,9,10 fallowed by Normal Termination. If the catch block has not matched abnormal termination.


Friday, April 3, 2009

array-length-string-length()

length Vs length():
length:This is a variable.applicable for only for array objects represents the number of elements or the size of the array.


Example:

int a=new int[6];
System.out.println(a.length); ------------------> output: 6

  • length variable Can’t apply to String
int a=new int[6]; Here 6 is length,But the index is starts with 0,1,2,3,4,5.If we are try to access the index a[6] we will get a ArrayIndexOutOfBoundsException.
Array length example:
public class LengthExample {
public static void main(String arg[])
{
int a[]=new int[6];
for(int i=0;i <a.length;i++)
{
a[i]=i;
System.out.print(a[i]);
// System.out.println(a[6]); //exception
}

System.out.println(".....length="+a.length);
}
}

output:
012345 length=6


Example:

String s=”Laxman”;
System.out.println(s.length); //error
Given CTE because length variable applicable only for array objects.
  • length(): It is a final method applicable for string objects.
  • It represents the number of characters present in the String Object.
Ex:
String s=”Laxman”;
System.out.println(s.length()); ---------> 6
System.out.println(s.length); ----------> //error
  • In case string also index value start with zero only.
String length() example:
public class StringlengthEx {
public static void main(String arg[])
{
String mystring="abcde";
System.out.println(mystring.length()); //5
System.out.println(mystring.charAt(3)); //d
System.out.println(mystring.indexOf('4')); //2
}
}

Array of strings Example:
public class ArrayStrings {
public static void main(String arg[])
{
String stringarray[]=new String[6];
stringarray[0]="corejava";
stringarray[1]="jdbc";
stringarray[2]="hibernate";
stringarray[3]="servlets";
stringarray[4]="jsp";
stringarray[5]="ejb";
System.out.println("Array length"+stringarray.length);
for(int i=0;i
{
System.out.println(stringarray[i]+"....length="+stringarray[i].length());

}


}
}

output:
Array length6
corejava....length=8
jdbc....length=4
hibernate....length=9
servlets....length=8
jsp....length=3
ejb....length=3