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

java-instanceof-Shortcircuit-Relational-operators

Instanceof operator :
Thread t =new Thread();
System.out.println(t instanceof thread); // true
System.out.println(t instanceof object); //true
System.out.println(t instanceof runnable); //true
System.out.println(t instanceof string); // compile time error saying convertible type found java .lang .thread Required: java. .lang .string a instanceof x
The type of a and x must be related, otherwise compile time error saying convertible type.

Ex: Object o= new Object();
System.out.println(o instanceof string); // false

Ex: null instanceof x;
The result always false

Short-circuit operator( && , || ) :
In the normal logical operator (& or |) we have to calculate both arguments compulsory, some times it may creates performance problems ,to improve the performance short-circuit operators were introduce.

Comparison between bitwise and short-circuit operators

  • Bitwise operators can be applicable for both Boolean, integral types,Short - circute operators can be applicable only for Boolean type .
  • Bitwise operators Both operands must be evaluated,Short - circute operators evaluation of second argument is optional.
  • Bitwise operators performance is low ,Short - circute operators performance is high.
x && y ----> If x is true then y will evaluate.
x || y ------> If x is false then y will evaluate.



Example:
int x=10,y=20;
if( (x <y)||(y gt; x/0))
{
System.out.println(“hi”); // hi
else
{
System.out.println(“hello”);
}

Equality operator:
We can use equality operators for the comparision of primitive numbers , characters,boolean values. Return type is Boolean.
Ex: 10 = = 10; // true
10 = = 10.0; // true
‘a’ = = 97 // true
  • We can apply these two operators = = and!= both for primitive types and object references. In the case of primitives these operators via check magnitudes or the values.Smaller data type promote bigger data type automatically. In the case of object references double equal operator always cheeks for address comparison.i.e s1= =s2 true iff and only if both s1 and s2 pointing to the same object.
Ex: Sample s1= new sample( );
Sample s2=new sample( );
Sample s3=s1;
System.out.println (s1= =s2); // false
System.out.println (s1= =s3); // true
System.out.println (s1= =”durga”); // compile time error
  • We can not use double equeal operator for different types of objects, violation leads compile time error saying incomparable types.
Ex: “java”==new Integer(10); // incompatible types
Ex: Sample s=new Sample();
s=null;
s = = null; // the result always false.

Ex: “java”=null ; // false
new Integer(10) = = null; // false
null==null ; // true

Ex:System.out.println( 10 = = 10 = = 10.0); // Compile time error
In the above example 10==10 returns true,true = = 10.0 ---> this shows error

System.out.println( 10 = = 10 = = true) ; // now it returns true

Relational operator ( < , < = , > , >= ) :
These operators applicable for primitives, except Boolean
Ex:10<20 ----> true
20<=50 ----> true
”Java “<”Laxman” -----> Compile time error saying operator java.lang.String,java.lang.String.
Ex:10<=true; compile time error saying can not be applied to boolean , int

Bitwise operator:
AND(&):- If both are true then only the result is true
OR( |):- if at least one is true , then only the result is true
X-OR( ^):- If both are different then only the result is true.

Ex: true & false ----> false
true | false ---> true
true ^ false----> true

Ex: 4& 5 ---> 4
4 | 5 --->5
4^ 5 ----> 1
& , | , ^ ------>
  • we can apply these operator only for Boolean and integral types . we can’t apply these operator for the floating point data types.
Ex:- 4.5 ^5.5----- compile time error saying operator X-oR can’t be applied to double, double.

Bitwise Compliment Operator :
We can apply bitwise compliment operator only for integral types, but not fir Boolean types i.e, ~4 valied
i.e, ~true invalied ---> Compile time error saying operator ~ can’t be applied to Boolean.
boolean compliment operator:
! true ----> false
!false -----> true
! 3 -----> compile time error saying operator ! can’t be applied to int.
conclusion:-
& , | , ^ -------------> we can apply both integral and Boolean.
~ -----------------> only for integral type
! -----------------> only for Boolean type.

Conditional operator :
The only available ternary operator is the conditional operator.
int a=Boolean expression ? value if true : value if false;
int a=(true)?10:12; //10
We can perform nesting of conditional operator also possible.
Ex:- int a=( false) ? 10 : ( true) ? 20 : 40 ; )
Ex:- byte x=( a <>

New operator:
This can be used for create of objects.
new and instanceof are acts as both keywords and operators.
[ ]-----> This can be used for declaration and construction of arrays.

Assignment operator:
(1)simple assignment:
int x=10;
int y=x;

(2) compound assignment:-
In the case of compound assignment operator compiler will take care about type casting problems . i.e it can perform internal automatic typecasting .
i.e Ex:- byte a=10;
a+=10;
System.out.println(a); // 20

Ex:- byte a=10;
a=a+10;
System.out.println(a); //CE saying PLP.
The following are all possible compound assignment operator :
=,+=,-=,*=,%=,>>=,<<=,>>>=,&=,|=,^=,!=

(3)chained assignment operator:-
Ex:- int a ,b ,c ,d ;
int a=b=c=d=40;//valid
int a=b=c=d=40; //invalid
Why because chained assignment is not allowed at the time of declaration.
Ex: int a ,b ,c ,d;
a=b=c=d=40;
a+=b*c/d-=10;
System.out.println(a+”……..”+b+”….”+c+”……”+d); //80….40…..1….30

Precedence of java operator:
(1)Unary ---------- [], x++, x--,++x,--x, ~,!,new,
(2)arithmetic -----*,/,%,+,-
(3) shift operator --- >>,<=,>,>=,>>>
(4)comparison:-<,<=,>,>=,instsnceof
(5)equality:- ==,!=
(6) bitwise :- &,^ ,|
(7) short-circuit:- &&,||
(8) Conditional : - ?,:
(9) assignment:-=,+=,-=,*=,%=,>>=,<<=,>>>-,&=,|=,^=,!=

Evaluation order of operators:
class EvaluationOrder
{
public static void main(String arg[])
{
System.out.println(m1(1) +m1(2)*m1(3)/m1(4)-m1(5)* m1(6));
}
public static int m1(int i)
{
System.out.println(i);
return i;
}
}

1. 1+2*3/4-5*6
2. 1+6/4-5*6
3. 1+1-5*6
4. 1+1-30= -28(result)
  • Before applying any operator , first we have to evaluate all the operands .The order of evaluation of operands is always from left to right . And then after evaluation of operands we have to apply the operators according to precedence


jdbc-connection-url-tutorial

Connection:
A Connection object represents a connection with a database. A connection session includes the SQL statements that are executed and the results that are returned over that connection. A single application can have one or more connections with a single database, or it can have connections with many different databases.
Opening a Connection :
The standard way to establish a connection with a database is to call the method DriverManager.getConnection. This method takes a string containing a URL. The DriverManager class, referred to as the JDBC management layer, attempts to locate a driver than can connect to the database represented by that URL. The DriverManager class maintains a list of registered Driver classes, and when the method getConnection is called, it checks with each driver in the list until it finds one that can connect to the database specified in the URL. The Driver method connect uses this URL to actually establish the connection.

A user can bypass the JDBC management layer and call Driver methods directly. This could be useful in the rare case that two drivers can connect to a database and the user wants to explicitly select a particular driver. Normally, however, it is much easier to just let the DriverManager class handle opening a connection.
The following code exemplifies opening a connection to a database located at the URL "jdbc:oracle:thin:@localhost:1521:xe" with a user ID of "oracle" and "tiger" as the password :
String url = "jdbc:oracle:thin:@localhost:1521:xe";
Connection con = DriverManager.getConnection(url, "oracle", "tiger");

URLs in General Use :
Since URLs often cause some confusion, we will first give a brief explanation of URLs in general and then go on to a discussion of JDBC URLs.
A URL (Uniform Resource Locator) gives information for locating a resource on the Internet. It can be thought of as an address.

The first part of a URL specifies the protocol used to access information, and it is always followed by a colon. Some common protocols are "ftp", which specifies "file transfer protocol," and "http," which specifies "hypertext transfer protocol." If the protocol is "file," it indicates that the resource is in a local file system rather than on the Internet.

ftp://javasoft.com/docs/JDK-1_apidocs.zip
http://java.sun.com/products/JDK/CurrentRelease
file:/home/haroldw/docs/tutorial.html

The rest of a URL, everything after the first colon, gives information about where the data source is located. If the protocol is file, the rest of the URL is the path to a file. For the protocols ftp and http, the rest of the URL identifies the host and may optionally give a path to a more specific site. For example, below is the URL for the JavaSoft home page. This URL identifies only the host:
http://www.javasoft.com
By navigating from this home page, one can go to many other pages, one of which is the JDBC home page. The URL for the JDBC home page is more specific and looks like this:
http://www.javasoft.com/products/jdbc

JDBC URLs :
A JDBC URL provides a way of identifying a database so that the appropriate driver will recognize it and establish a connection with it. Driver writers are the ones who actually determine what the JDBC URL that identifies their particular driver will be. Users do not need to worry about how to form a JDBC URL; they simply use the URL supplied with the drivers they are using. JDBC's role is to recommend some conventions for driver writers to follow in structuring their JDBC URLs.

Since JDBC URLs are used with various kinds of drivers, the conventions are of necessity very flexible. First, they allow different drivers to use different schemes for naming databases. The odbc subprotocol, for example, lets the URL contain attribute values (but does not require them).

Second, JDBC URLs allow driver writers to encode all necessary connection information within them. This makes it possible, for example, for an applet that wants to talk to a given database to open the database connection without requiring the user to do any system administration chores.

Third, JDBC URLs allow a level of indirection. This means that the JDBC URL may refer to a logical host or database name that is dynamically translated to the actual name by a network naming system. This allows system administrators to avoid specifying particular hosts as part of the JDBC name. There are a number of different network name services (such as DNS, NIS, and DCE), and there is no restriction about which ones can be used.

The standard syntax for JDBC URLs is shown below. It has three parts, which are separated by colons:
jdbc::
The three parts of a JDBC URL are broken down as follows:

  • jdbc-the protocol. The protocol in a JDBC URL is always jdbc.
  • -the name of the driver or the name of a database connectivity mechanism, which may be supported by one or more drivers. A prominent example of a subprotocol name is "odbc", which has been reserved for URLs that specify ODBC-style data source names. For example, to access a database through a JDBC-ODBC bridge, one might use a URL such as the following:
jdbc:odbc:fred
In this example, the subprotocol is "odbc", and the subname "fred" is a local ODBC data source.

If one wants to use a network name service (so that the database name in the JDBC URL does not have to be its actual name), the naming service can be the sub protocol. So, for example, one might have a URL like:
jdbc:dcenaming:accounts-payable

In this example, the URL specifies that the local DCE naming service should resolve the database name "accounts-payable" into a more specific name that can be used to connect to the real database.

-a way to identify the database. The subname can vary, depending on the subprotocol, and it can have a subsubname with any internal syntax the driver writer chooses. The point of a subname is to give enough information to locate the database. In the previous example, "fred" is enough because ODBC provides the remainder of the information. A database on a remote server requires more information, however. If the database is to be accessed over the Internet, for example, the network address should be included in the JDBC URL as part of the subname and should follow the standard URL naming convention of
//hostname:port/subsubname

Supposing that "dbnet" is a protocol for connecting to a host on the Internet, a JDBC URL might look like this:

jdbc:dbnet://wombat:356/fred

The "odbc" Subprotocol :
The sub protocol odbc is a special case. It has been reserved for URLs that specify ODBC-style data source names and has the special feature of allowing any number of attribute values to be specified after the surname (the data source name). The full syntax for the odbc sub protocol is:
jdbc:odbc:[;=]*
Thus all of the following are valid jdbc:odbc names:
jdbc:odbc:qeor7
jdbc:odbc:wombat
jdbc:odbc:wombat;CacheSize=20;ExtensionCase=LOWER
jdbc:odbc:qeora;UID=kgh;PWD=fooey

Registering Subprotocols :
A driver developer can reserve a name to be used as the subprotocol in a JDBC URL. When the DriverManager class presents this name to its list of registered drivers, the driver for which this name is reserved should recognize it and establish a connection to the database it identifies. For example, odbc is reserved for the JDBC- ODBC Bridge. If there were, for another example, a Miracle Corporation, it might want to register "miracle" as the subprotocol for the JDBC driver that connects to its Miracle DBMS so that no one else would use that name.
JavaSoft is acting as an informal registry for JDBC subprotocol names. To register a subprotocol name, send email to:
jdbc@wombat.eng.sun.com


Thursday, April 2, 2009

java-switch-break-if-else

Control Flow(Flow-control ):
Flow control describes the order of execution of code at runtime.
i.e it describes the order in which the statement will execute.
Selection statement
(1)if-else
(2)switch
Iteration statement
(1)for (2)while
(3)do-while
Transfer statement
(1)break
(2)continue
(3)return
(4)try-catch-finally
(5)assertion
(1)if –else :
if: {} and else part both are optional. The valid argument for if statement is always Boolean otherwise compile time error.
If Examples:
if(boolean)

Example: int i=10;
if (i) //This is valid in c++, but invalid java
{
System.out.println(“hi”);
}
else
{
System.out.println(“hello”);
}
Ex : int i=10;
if (i==10)
{
System.out.println(“hi”); //hi
}
else
{
System.out.println(“hello”);
}
Ex : int i=10;
if (i=20)
{
System.out.println(“hi”);
else
{
System.out.println(“hello”);
} // Compile time error
Ex: boolean b =true;
if (b=false)
{
System.out.println(“hi”);
else
{
System.out.println(“hello”);
} // hello
Ex : boolean b=true;
if(b)
int i=10; //invalid
System.out.println(i); //Compile time error
Under if with out curly braces only one statement is allowed ,but that statement never be declarative statement violation leads to compile time error.
Ex:- boolean b= true;
if(b)
int i=10; // invalid
Ex:- boolean b=true;
if(b)
{
int i=10; // valid
}

Switch statement:In switch statement {} are mandatory, violation leads to compile time error.
Both case and default are optional.
Eg:- int i=10;
switch(x)
{
……………
……………no case and default statements.
}

The valid arguments of switch statement are byte, int, short, char until 1.4 version, from 1.5 version onwards the corresponding wrapper class objects Byte, Short, Integer, Character are also allowed.switch can take an enum object are also as argument.If we want keep any statement inside switch it must under some case or default, otherwise COMPILE TIME ERROR.
Eg:- int x=4;
switch(x)
{
System.out.println (“hello”); //hello
}
case-labels : All the case –labels must be compile time Constance, otherwise COMPILE TIME ERROR saying Constance expression required.
Ex: int x=40;
int y=10
switch(x)
{
case y: // CE saying Constance expression required.
}
Ex:final int x=40;
int y=10
switch(x)
{
case y: // valid
}
All the case labels must be in the range of switch arguments otherwise compile time error.

Ex: byte b=10;
switch(b)
{
case 10:
case20:
case100:
case10000://CE saying PLP found: int but required: byte
}
The case label should not be duplicated ,violation leads to COMPILE TIME ERROR
Ex:- int x=10;
switch(x)
{
case 98:
case98:
case a:
}//CE
Hence the case labels
(1)must be compile time Constance

(2) must be in the range of switch arguments
(3)must not be duplicated
default case:- The default case we can keep any where, but it is conversion to keep default case is always at last place.
Ex:
switch(x)
case 0:
System.out.println(“0”);
case 1:
System.out.println(“1”);
case 2:
System.out.println(“2”);
default:
System.out.println(“default”);
}
Once any case are default are matched , all the statements will execute from top to bottom until break or end of switch statements. This is called fall-through inside switch.
Ex:- int x=1;
switch(x)
{
default:
System.out.println(“default”);
case 0:
System.out.println(“0”);
case 1:
System.out.println(“1”);
break;
case 2:
System.out.println(“2”);
}