Pages

Sunday, December 29, 2013

HISTORY OF JAVA

HISTORY OF JAVA:


Java is a programming language created by James Gosling from Sun Microsystems (Sun) in 1991. The first publicly available version of Java (Java 1.0) was released in 1995.
Sun Microsystems was acquired by the Oracle Corporation in 2010. Oracle has now the steermanship for Java.
Over time new enhanced versions of Java have been released. The current version of Java is Java 1.7 which is also known as Java 7.
From the Java programming language the Java platform evolved. The Java platform allows software developers to write program code in other languages than the Java programming language and still runs on the Java virtual machine. The Java platform is usually associated with the Java virtual machine and the Java core libraries.


 Java and Open Source:

In 2006 Sun started to make Java available under the GNU General Public License (GPL). Oracle continues this project called OpenJDK.

Saturday, December 28, 2013

My Sql Server 2008 Feature :



1. Both are combined as SSMS (Sql Server management Studio).
2. XML datatype is used.
3. We can create 2(POW (20))-1 databases.
4. Exception Handling
5. Varchar(Max) data type
6. DDL Triggers
7. DataBase Mirroring
8. RowNumber function for paging
9. Table fragmentation
10. Full Text Search
11. Bulk Copy Update
12. Can encrypt the entire database introduced in 2008.
13. Can compress tables and indexes.
14. Date and time are separately used for date and time datatype, geospatial and timestamp with internal time zone is used.
15. Varchar (max) and varbinary (max) is used.
16. Table datatype introduced.
17. SSIS avails in this version.
18. Central Management Server (CMS) is Introduced.
19. Policy based management (PBM) server is introduced.

Sql Server 2005 Feature :



1. Both are combined as SSMS (Sql Server management Studio).
2. XML datatype is introduced.
3. We can create 2(pow(20))-1 databases.
4. Exception Handling
5. Varchar (Max) data type
6. DDL Triggers
7. DataBase Mirroring
8. RowNumber function for paging
9. Table fragmentation
10. Full Text Search
11. Bulk Copy Update
12. Can’t encrypt
13. Can compress tables and indexes. (Introduced in 2005 SP2)
14. Datetime is used for both date and time.
15.Varchar(max) and varbinary(max) is used.
16. No table datatype is included.
17. SSIS is started using.
18. CMS is not available.
19. PBM is not available.

SQL SERVER 2000 , SQL SERVER 2005, SQL SERVER 2008 Version Differences

Sql Server 2000


1. Query Analyser and Enterprise manager are separate.
2. No XML datatype is used.
3. We can create maximum of 65,535 databases.
4. Nill
5. Nill
6. Nill
7. Nill
8. Nill
9. Nill
10. Nill
11. Nill
12. Nill
13. Can’t compress the tables and indexes.
14. Datetime datatype is used for both date and time.
15. No varchar (max) or varbinary(max) is available.
16. No table datatype is included.
17. No SSIS is included.
18. CMS is not available.
19. PBM is not available.

The Basic Steps to Connect Oracle and Java Program


Here show, what the steps to make a connection between Oracle database and your Java program. To do this work, you need the JDBC (Java DataBase Connectivity) driver. The file name of Oracle's JDBC driver is classes12.zip or classes12.jar. By default, Oracle have included this driver at the software installation process. Its location is in the ORACLE_HOME\jdbc\lib directory. For example, if our ORACLE_HOME is C:\Oracle\Ora90 then the JDBC driver will be placed in C:\Oracle\Ora90\jdbc\lib directory.

Make sure to set the Java CLASSPATH correctly. Here is the command line to do it.
(Note: Assume the ORACLE_HOME is C:\Oracle\Ora90)

set CLASSPATH=.;C:\Oracle\Ora90\jdbc\lib\classes12.jar

or

set CLASSPATH=.;C:\Oracle\Ora90\jdbc\lib\classes12.zip

In addition, you can also set the CLASSPATH in your autoexec.bat file on your Windows operating system.

Now, just follow these steps:

STEP 1. Import the java.sql package into your program.
------------------------------------------------------

import java.sql.*;

The syntax above will import all classes in the java.sql package. If you want to import a few of them, you can write the syntax like this

import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.Connection;

It only imports the Driver, DriverManager, and Connection class into your Java program.

STEP 2. Load the Oracle's JDBC driver.
--------------------------------------

There are two ways to load your JDBC driver. The first, use the forName() method of java.lang.Class class.

Class.forName("oracle.jdbc.driver.OracleDriver");

And the second way is use the registerDriver() method of DriverManager class.

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

STEP 3. Create a Connection object.
-----------------------------------

To create a Connection object, use the getConnection() method of DriverManager class. This method takes three parameters: URL, username, and password.

Connection conn =
DriverManager.getConnection(
"jdbc:oracle:thin:@mylaptop:1521:ORADB",       // URL
"budiraharjo",       // username
"SDDNBandung"        // password
);

STEP 4. Create a Statement object.
----------------------------------

The Statement object can be created by call the createStatement() method of Connection object that you made before. So, you can write the following code

Statement mystat = conn.createStatement();

STEP 5. Execute your SQL statement.
-----------------------------------

After you create a Statement object successfully, you can execute a query (SELECT statement) from your Java program using the executeQuery() method of Statement class. The result of execution process will be stored in ResultSet object, so you need to declare an object of ResultSet first. Here is the code.

ResultSet rs = mystat.executeQuery("select custno, custname from customer");

STEP 6. Display your data.
--------------------------

The next step is display your data using the looping control.

while (rs.next()) {
System.out.println(
rs.getInt(1) +      // first column
"\t" +              // the horizontal tab
rs.getString(2)     // second column
);
}

STEP 7. Close your statement and connection.
--------------------------------------------

mystat.close();
conn.close();


Here is the complete code.

/*********************************************************************
* File name  : SimpleOraJava.java
* Author     : Budi Raharjo (PT. Sigma Delta Duta Nusantara, Bandung)
* Blog      : http://mbraharjo.blogspot.com
*
*********************************************************************/

import java.sql.*;

class SimpleOraJava {
  public static void main(String args[]) throws SQLException {
    DriverManager.registerDriver(
      new oracle.jdbc.driver.OracleDriver()
    );
    String serverName = "mylaptop";
    int port = 1521;
    String user = "budi";
    String password = "SDDNBandung";
    String SID = "ORADB";
    String URL = "jdbc:oracle:thin:@" + serverName + ":" + port + ":" + SID;
    Connection conn = DriverManager.getConnection(URL, user, password);
    String SQL = "SELECT CUSTNO, CUSTNAME FROM CUSTOMER";
    Statement stat = conn.createStatement();
    ResultSet rs = stat.executeQuery(SQL);
    while (rs.next()) {
      System.out.println(
        rs.getInt(1) +
        "\t" +
        rs.getString(2)
      );
    }
    stat.close();
    conn.close();  
  }
}
 

Thursday, December 26, 2013

Multithread in Java

Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.

A multithreading is a specialized form of multitasking. Multithreading requires less overhead than multitasking processing.
I need to define another term related to threads: process: A process consists of the memory space allocated by the operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of a process. A process remains running until all of the non-daemon threads are done executing.
Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum.

Life Cycle of a Thread:

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.
Java Thread
Above-mentioned stages are explained here:
  • New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.
  • Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.
  • Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.
  • Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
  • Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.

Thread Priorities:

Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.
Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform dependentant.

Creating a Thread:

Java defines two ways in which this can be accomplished:
  • You can implement the Runnable interface.
  • You can extend the Thread class itself.

Create Thread by Implementing Runnable:

The easiest way to create a thread is to create a class that implements the Runnable interface.
To implement Runnable, a class needs to only implement a single method called run( ), which is declared like this:
public void run( )
You will define the code that constitutes the new thread inside run() method. It is important to understand that run() can call other methods, use other classes, and declare variables, just like the main thread can.
After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class. Thread defines several constructors. The one that we will use is shown here:
Thread(Runnable threadOb, String threadName);
Here, threadOb is an instance of a class that implements the Runnable interface and the name of the new thread is specified by threadName.
After the new thread is created, it will not start running until you call its start( ) method, which is declared within Thread. The start( ) method is shown here:
void start( );

Example:

Here is an example that creates a new thread and starts it running:
// Create a new thread.
class NewThread implements Runnable {
   Thread t;
   NewThread() {
      // Create a new, second thread
      t = new Thread(this, "Demo Thread");
      System.out.println("Child thread: " + t);
      t.start(); // Start the thread
   }
   
   // This is the entry point for the second thread.
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Child Thread: " + i);
            // Let the thread sleep for a while.
            Thread.sleep(50);
         }
     } catch (InterruptedException e) {
         System.out.println("Child interrupted.");
     }
     System.out.println("Exiting child thread.");
   }
}

public class ThreadDemo {
   public static void main(String args[]) {
      new NewThread(); // create a new thread
      try {
         for(int i = 5; i > 0; i--) {
           System.out.println("Main Thread: " + i);
           Thread.sleep(100);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread interrupted.");
      }
      System.out.println("Main thread exiting.");
   }
}
This would produce the following result:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

Create Thread by Extending Thread:

The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class.
The extending class must override the run( ) method, which is the entry point for the new thread. It must also call start( ) to begin execution of the new thread.

Example:

Here is the preceding program rewritten to extend Thread:
// Create a second thread by extending Thread
class NewThread extends Thread {
   NewThread() {
      // Create a new, second thread
      super("Demo Thread");
      System.out.println("Child thread: " + this);
      start(); // Start the thread
   }

   // This is the entry point for the second thread.
   public void run() {
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Child Thread: " + i);
   // Let the thread sleep for a while.
            Thread.sleep(50);
         }
      } catch (InterruptedException e) {
         System.out.println("Child interrupted.");
      }
      System.out.println("Exiting child thread.");
   }
}

public class ExtendThread {
   public static void main(String args[]) {
      new NewThread(); // create a new thread
      try {
         for(int i = 5; i > 0; i--) {
            System.out.println("Main Thread: " + i);
            Thread.sleep(100);
         }
      } catch (InterruptedException e) {
         System.out.println("Main thread interrupted.");
      }
      System.out.println("Main thread exiting.");
   }
}
This would produce the following result:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.

Thread Methods:

Following is the list of important methods available in the Thread class.
SNMethods with Description
1public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.
2public void run()
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object.
3public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for retrieving the name.
4public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.
5public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.
6public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.
7public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
8public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.