Thursday, February 17, 2011

Object Life Cycle in Java


 An object typically goes through most of the following states between the time it is allocated and the time its resources are finally returned to the system for reuse.

  1. Created
  2. In use (strongly reachable)
  3. Invisible
  4. Unreachable
  5. Collected
  6. Finalized
  7. Deallocated
Lets understand these in detail :

Monday, February 14, 2011

java SQL basics 3 : Understanding JDBC Drivers


JDBC drivers are divided into four types or levels. 

The different types of jdbc drivers are:
Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)

Type 1 JDBC Driver

JDBC-ODBC Bridge driver
The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other alternative is available.



Type 1: JDBC-ODBC Bridge
Advantage
The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are already available.
Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this applies even in the reverse process. They are the slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.
let us learn more..

Java SQL basics 2 : Working with ResultSet Objects in JDBC.


IF you come here directly- you are suggested to read the article http://codingbasics.blogspot.com/2011/02/java-sql-basics-1-processing-sql.html

Updating Rows in ResultSet Objects

You cannot update a default ResultSet object, and you can only move its cursor forward.
However, you can create ResultSet objects that can be scrolled (the cursor can move backwards or move to an absolute position) and updated.

The following method, multiplies the PRICE column of each row by the argument percentage:

  public void modifyPrices(float percentage) throws SQLException {
    Statement stmt = null;
    try {
      stmt = con.createStatement();
      stmt = con.createStatement(
        ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
      ResultSet uprs = stmt.executeQuery(
        "SELECT * FROM " + dbName + ".COFFEES");


      while (uprs.next()) {
        float f = uprs.getFloat("PRICE");
        uprs.updateFloat("PRICE", f * percentage);
        uprs.updateRow();
      }


    } catch (SQLException e ) {
      JDBCTutorialUtilities.printSQLException(e);
    } finally {
      stmt.close();
    }
  }
The field ResultSet.TYPE_SCROLL_SENSITIVE creates a ResultSet object whose cursor can move both forward and backward relative to the current position
 and to an absolute position. The field ResultSet.CONCUR_UPDATABLE creates a ResultSet object that can be updated.

The method ResultSet.updateFloat updates the specified column (in this example, PRICE with the specified float value in the row where the cursor is positioned.
ResultSet contains various updater methods that enable you to update column values of various data types.
However, none of these updater methods modifies the database; you must call the method ResultSet.updateRow to update the database.
Learn about Batch Updates using Statement Objects

Java SQL basics 1 : Processing SQL statements with JDBC


In general, to process any SQL statement with JDBC, you follow these steps:

  • Establishing a connection.
  • Create a statement.
  • Execute the query.
  • Process the ResultSet object.
  • Close the connection.

  public static void viewTable(Connection con, String dbName) throws SQLException {
    Statement stmt = null;
    String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from " + dbName + ".COFFEES";
    try {
      stmt = con.createStatement();
      ResultSet rs = stmt.executeQuery(query);
      while (rs.next()) {
        String coffeeName = rs.getString("COF_NAME");
        int supplierID = rs.getInt("SUP_ID");
        float price = rs.getFloat("PRICE");
        int sales = rs.getInt("SALES");
        int total = rs.getInt("TOTAL");
        System.out.println(coffeeName + "\t" + supplierID + "\t" + price + "\t" + sales + "\t" + total);
      }
    } catch (SQLException e ) {
      JDBCTutorialUtilities.printSQLException(e);
    } finally {
      stmt.close();
    }


Lets break each step and understand the code

Friday, January 28, 2011

Practical API design Guidelines - with Technical inputs in Java

Good API  design helps developers to breathe longer and comfortable in an organisation.
Especially , if you are in product developement , putting right foucs at the time of API design helps you a lot in the long run.
Poor APIs call for a vicious circle of  unhappy customers, developers cribbing - " this should not be used like this " - customer doesn't know how to use this , fixing and re-fixing continuously etc.,
In this article, I will try to put the best practices for an API design which i have read in books and from my experience .Lets begin with a small example.

The spirit of writing an API :
APIs are to be designed with not what implementor feels , but what the customer wants.
The moment API discussion starts, the focus shifts so much onto what data structure to be used,algorithms etc.,   which often undermines what the developer who calls your API expects.

 Lets take an example :

  makeDrink(false, true) is in the code.
  It is clear that this API is for making a drink, but what does the paramters convey.
  compare it with the following:
   makeDrink(coffee,hot);
  
  much more clear and no manual is needed, it is clear that it creates a hot coffee.
  But from implementor even the first one is usable as well when creating the api :
  makeDrink (boolean isTea , isHot) but this information is lost to caller.

  The Second Version needs Implementor to do more vork , but adding enumerations viz.,
  enum drinkcategory {Coffee, Tea}
  enum drinktype{ hot,cold)
    This makes it, void makeDrink(drinkcategory dc, drinktype dt); which is more writing an API in the view point of caller.
lets read more


  2. API should be designed to one particular task and do it well.IT must be "absloutely" correct in what it is supposed to do.
3. Set clear expectations of what it will do and what it will not - can't please eveyone in this world with your single api ( sounds a bit exaggearated , but get the spirit of it)
4. API should be treated like a little language designed by you. Give proper naming and symmetry to the API with proper documentation.
5. Mimic patterns in core APIs of the language.
6. Fail-fast behaviour when some error occurs .
7. If you are new to api design, best way is to write code with your apis.use your experiences to remove what is not needed.
8. Keep Exceptions unchecked. A checked exception reflects a problem in interaction with the outside world, such as the network, filesystem, or 0S.
  If the exception signals that parameters are incorrect or than an object is in the wrong state for the operation you're trying to do,   then an unchecked exception (subclass of RuntimeException) is appropriate.
9. Most important of all is having the testability approach for your apis in mind. Its a fact that has to be accepted that one of the  key reasons of why   springs worked ahead of EJB is api unit-testability for developers.
10. APIs should be documented , before they are implemented.


Some Technical inputs  in Java  :


1. Make classes and members private as much as possible. The fields that are visible only should be static and final.
2. Keep Classes immutable as much as possible . Though it means an object for each value, It makes objects thread safe and reusable.
   calendar is an example of a bad design.

3. subclass if and only when "is-a" relationship holds . Just for ease of implementation , public classes should not subclass other public classes.
   Eg : Stack extends vector. - a bad one,.

4. Appropriate Parameter and return types -
Specific Input Parameters moves the errors from runtime to compile time
Use double ahead of float , dont use string if a better a type is possible since strings are slow and error prone.

5. Limit the parameters to a max of 3. Incase of longer parameters use helper classes to hold parameters
6. Interface when it is needed . Just imagine if String is an interface, it would be 1000 times diffuclt to get a semantically correct string.
   on saying that interface has some good advantage if there are fewer methods. I still love runnable interface for having a single method.
7.Interfaces cannot have static methods and constructors.

Hope you like this article, keep posting your comments and suggestions.

Thursday, January 27, 2011

Most frequently used Regular Expressions in Java.


Username :
------------


 ^[a-z0-9_-]{3,15}$

Notes :

 ^             Start of the line
[a-z0-9_-]   supported chars and symbols in the list:  a-z, 0-9 , underscore ,hyphen
{3,15}         Length at least 3 characters and maximum length of 15
$         End of the line.


Password :
----------

((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})

Notes :

  (?=.*\d)  must contains one digit from 0-9
  (?=.*[a-z])  must contains one lowercase characters
  (?=.*[@#$%])  must contains one special symbols in the list "@#$%"

Let us see more

Wednesday, January 26, 2011

SQL Joins Tutorial: Joins are easy. Lets play cricket with them


The Different Types of Joins in SQL Server

Inner join or Equi join
Outer Join
Cross join
Let's suppose we have two tables Emp and Dept whose description is given below:-



CREATE TABLE [Emp](
[Empid] [Int] IDENTITY (1, 1) NOT NULL Primary key,
[EmpNumber] [nvarchar](50) NOT NULL,
[EmpFirstName] [nvarchar](150) NOT NULL,
[EmpLastName] [nvarchar](150) NULL,
[EmpEmail] [nvarchar](150) NULL,
[Managerid] [int] NULL,
[Deptid] [INT]
)
CREATE TABLE [Dept](
[Deptid] [int] IDENTITY (1, 1) NOT NULL primary key,
[DeptName] [nvarchar](255) NOT NULL
)

After the creation of the tables we need to insert the data into these tables. To insert the data the following queries are used:-

insert into Emp (EmpNumber,EmpFirstName,EmpLastName,EmpEmail,Managerid,Deptid)
values('E1','Sachin','Tendulkar','Sachin@mycomp.com',2,2)
insert into Emp (EmpNumber,EmpFirstName,EmpLastName,EmpEmail,Managerid,Deptid)
values('E2','Zaheer','Khan','Zaheer@mycomp.com',1,1)
insert into Emp(EmpNumber,EmpFirstName,EmpLastName,EmpEmail,Managerid,Deptid)
values('E3','Gambhir','Gautam','Gambhir@mycomp.com',1,2)
insert into Emp (EmpNumber,EmpFirstName,EmpLastName,EmpEmail,Managerid,Deptid)
values('E4','Dhoni','MS','Dhoni@mycomp.com',1,NULL)

insert into Dept(DeptName)
values('Bowling')
insert into Dept(DeptName)
values('Batting')
insert into Dept(DeptName)
values('Coach')
insert into Dept(DeptName)
values('Allrounder')

Inner Join

This type of join is also known as the Equi join.
This join returns all the rows from both tables where there is a match.
This type of join can be used in the situation where we need to select only those rows
which have values common in the columns which are specified in the ON clause.

Now, if we want to get Emp id, Emp first name and their Dept name
for those Emps which belongs to at least one Dept, then we can use the inner join.

Query for Inner Join

 SELECT Emp.Empid, Emp.EmpFirstName, Emp.EmpLastName, Dept.DeptName 
 FROM  Emp 
  INNER JOIN dept 
     ON Emp.Deptid=Dept.Deptid

Result

Empid EmpFirstName  DeptName
1     Sachin                  Batting
2     Zaheer                 Bowling
3     Gambhir              Batting

Explanation

In this query, we used the inner join based on the column "Deptid" which is common in both the tables "Emp" and "Dept".
This query will give all the rows from both the tables which have common values in the column "Deptid".
Gambhir Guatam and Sachin Tendulkar has the value "2" in the Deptid column of the table Emp.
In the Dept table, the Dept "Batting" has the value "2" in the Deptid column.
Therefore the above query returns two rows for the Dept "Batting", one for Gambhir Guatam and another for Sachin Tendulkar.

Lets understand more joins

subversion video