Sunday, 12 January 2014

Loading JDBC drivers

Loading JDBC drivers
I split these examples into two specific categories which are good and dumb.  

class dr1
{
    public static void main(String args[]) throws Exception
    {
        Class.forName("oracle.jdbc.driver.OracleDriver");
    }
}


class dr2
{
    public static void main(String args[]) throws Exception
    {
        // Choosing the driver at runtime
        Class.forName(args[0]);
    }
}


class dr3
{
    public static void main(String args[]) throws Exception
    {
        // Choosing the driver at runtime by a temporary
        // property
        Class.forName(System.getProperty("my.driver"));
    }
}

For executing this, you should write

java -Dmy.driver=oracle.jdbc.driver.OracleDriver dr3

The -D option is followed by the property name (without space) and =followed by the driver class. Don't forget the class name. It is damn important!

Note: The second, third and fourth ways have a common problem. Here if we aren't decisive about which driver to use and give it at runtime we need to change the URL (to connect to the database) too. Because, different drivers have different urls. So, there must be some conditional logic written which connects to the database via appropriate URL corresponding to the given class name. This becomes a bit messy. Isn't it?


class dr4
{
    public static void main(String args[])
    {
        // Choosing the driver at runtime by a permanent
        // property
        System.out.println("Driver loaded "+System.getProperty("jdbc.drivers"));
    }
}

Well, where is the code? I'll explain, everything lies in executing the program. You should execute this in this way.

java -Djdbc.drivers=oracle.jdbc.driver.OracleDriver dr4

Now, this loads the driver. The jdbc.drivers is an environment property of Java that corresponds to the JDBC drivers. The default value for this property is null. While executing, you are changing its value to the driver class name.

3 Dumb ways


class dr5
{
    public static void main(String args[])
    {
        // Creating an object for the driver class
        new oracle.jdbc.driver.OracleDriver();
    }
}

I call this dumb because, we are creating an object for this class which is absolutely unnecessary. Here is a simple question to you

Why create an object for a class when you are not going to use it? If you want to load the static block of the class? Isn't it enough to load the class into the memory using Class.forName() instead of creating an object for it?


class dr6
{
    public static void main(String args[]) throws Exception
    {
        // Using the registerDriver
        DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    }
}

This way is double-dumb because you are loading the driver twice. Yes, thestatic block of the oracle.jdbc.driver.OracleDriver already contains a call to the registerDriver(). The statement, new oracle.jdbc.driver.OracleDriver(); loads it into memory (therefore, static block is executed) and creates an object for the driver class and then register the driver.


class dr7 extends oracle.jdbc.driver.OracleDriver
{
    public static void main(String args[])
    {
        System.out.println("Driver is loaded.");
    }
}

Sunday, 25 August 2013

Simple Chat Application

                                           SIMPLE CHAT APPLICATION
1.Download this file compile and run and keep the command prompt open.....
This is the server code....

import java.io.*;
import java.net.*;
class VikramServer
{
    public static void main (String args[]) throws Exception
    {
        try
        {
            String CStr="";
            String UStr="";
            System.out.println("********************* Server**********************");
            ServerSocket SS = new ServerSocket(8888);
            Socket OS = SS.accept();
            DataInputStream Cinp =new DataInputStream(OS.getInputStream());
            DataInputStream Uinp =new DataInputStream(System.in);
            PrintStream PS = new PrintStream(OS.getOutputStream());
            while(true)
                {
                     
                    CStr=Cinp.readLine();
                    System.out.println("Client : " +CStr);
                    if(CStr.equals("exit"))
                          break;  
                      System.out.print("Server : ");  
                      UStr=Uinp.readLine();    
                      PS.println(UStr);
                 
                }
          }catch(Exception e){System.err.println(e);};
             
    }
}

2.Download this file compile and run and keep the command prompt open.....
This is the Client code ....

import java.io.*;
import java.net.*;
class VikramClient
{
    public static void main(String args[]) throws Exception
    {
        try
        {
        String Schat="";
        String Sstr="";
        Socket SC = new Socket("localhost",8888);
        DataInputStream Uinp =new DataInputStream(System.in);
        DataInputStream Sinp =new DataInputStream(SC.getInputStream());
        PrintStream PS = new PrintStream(SC.getOutputStream());
        System.out.println("********************* Client**********************");
        while(true)
            {
                    System.out.print("Client : ");
                    Schat=Uinp.readLine();
                    if(Schat.equals("exit"))
                          break;
                      PS.println(Schat);  
                      Sstr=Sinp.readLine();
                      System.out.println("Server : "+Sstr);
            }
        }catch(Exception e){System.err.println(e);};  
    }
}

Thursday, 11 July 2013

Predict the Output !!!!!

Public class Vikram
{
public static void main(String[] args)
{
http://vikram-programmingwithjava.blogspot.in/
System.out.println("Why is the URL allowed above?");
}
}
Will the Program Compile ???
If Yes what would be the Output and will http://vikram-programmingwithjava.blogspot.in/ be displayed in screen ?
If No what is the error in the program ???
Post your answers below.........

Thursday, 28 March 2013

Program to find maximum and minimum number for a n*n matrix

import java.io.*;
 class test
 {
 public static void main(String[] asd)throws IOException
 {
 BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
 System.out.println("Enter the values of Rows and Columns of Matrix.");
 String num=obj.readLine();
 int r=Integer.parseInt(num);
 num=obj.readLine();
 int c=Integer.parseInt(num);
 int m[][]= new int[r][c];
 int max=0, min=0;
 System.out.println("Enter the values of the matrix not more then "+(r*c)+".");
 for(int i=0;i<r;i++)
 for(int j=0;j<c;j++)
 {
 num=obj.readLine();
 m[i][j]=Integer.parseInt(num);
 }
 System.out.println("Original matrix::");
 for(int i=0;i<r;i++)
 {
 for(int j=0;j<c;j++)
 {
 System.out.print(m[i][j]+" ");
 }
 System.out.println();
 }
 // MAXIMUM element of the matrix max=m[0][0];
 for(int i=0;i<r;i++)
 {
 for(int j=0;j<c;j++)
 {
 if(m[i][j]>max) max=m[i][j];
 }
 }
System.out.println("Maximum of the matrix is "+max+".");
//MINIMUM element of the matrix min=m[0][0];
 for(int i=0;i<r;i++)
 {
 for(int j=0;j<c;j++)
 {
 if(m[i][j]<min) min=m[i][j];
 }
 }
 System.out.println("Minimum of the matrix is "+min+".");
 }
 }

Wednesday, 27 March 2013

Four different ways to create an object in java


1. Using new keyword
This is the most common way to create an object in java. I read somewhere that almost 99% of objects are created in this way.
MyObject object = new MyObject();
2. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();
3. Using clone()
The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();
4. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();

Tuesday, 19 March 2013

How To Create A War File In Netbeans




  1. Right click on your project name in the Explorer
  2. Select Properties
  3. In the Build | Packaging section, check "Compress War file" option.
  4. Select file/folder and select your project then u can see war file in dist folder


Friday, 1 February 2013

Login with Swings


Create a Login form and Index form with netbeans ide and inside Login form you can put two labels Name and password with a jTextField1 and jPasswordField1 and two buttons Submit and Cancel

Login
Submit
  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
        String s=jTextField1.getText();
        String s1=jPasswordField1.getText();
        Index i=new Index();              
        if(s.equals("Vikram")&&s1.equals("vikram"))
        {
            i.setVisible(true);
        }
        else if(!"Vicky".equals(s))
        {
            JOptionPane.showMessageDialog(this,"User Name Is Incorrect");
        }
        else
        {
           
            JOptionPane.showMessageDialog(this,"Password Is Incorrect");
        }
}
Cancel
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) 
{
    System.exit(0);
}
Index
Date can be set to the textfield using the below code :
  
  private void formWindowActivated(java.awt.event.WindowEvent evt) 
{
        Date d=new Date();
        SimpleDateFormat da=new SimpleDateFormat("dd/MM/yyyy");
        jTextField1.setText(da.format(d));
        SimpleDateFormat vi=new SimpleDateFormat("hh:mm:ss");
        jTextField2.setText(vi.format(d));
}