Why to choose Java?
In the computer market, being able to use Java is a crucial knowledge. Java is a development terminology used to build compelling content for websites, stand-alone application, and server-side programs. The Java foundation is the unseen power behind numerous programs we use in a variety of devices, from PCs to gaming consoles, as well as systems. Today, it is used by roughly 9 thousand application designers, and an incredible number of end-users globally. Java is truly everywhere. 1 billion dollars personal computers and 3 billion dollars mobile mobile phones run Java. At the same time, 100% of Blu-ray gamers run this system. There are also more than 900 thousand Java playback environment downloading yearly.
History of Java
Java technology was designed by James gosling, along with some of the application technicians at Sun Microsystems in the early 1990's. The team had the fact that the next stage of processing was the partnership of electronics and customers. Earlier on in this development language's growth, Java was known in a different way, specifically Oak and thereafter Green. The Java terminology venture was originally designed for entertaining television, but back then it was too complicated for current digital wire systems. By 1995, Sun Microsystems presented Java 1.0, and the company marketed it as a Create Once, Run Anywhere terminology. What this means is that, Java programs can be designed on any system, collected as a standard bytecode, and run on any system that is packed with a Java exclusive machine.
Why application designers use of Java
Through Java, application designers can write in one foundation and be assured that it will run on almost any other foundation. Apart from its cross-platform benefits, it is also effective, secure, and convenient, making it necessary to designers. Using this development terminology, application contractors can create highly effective application for a number of devices like set-top box, photo printers, add-ons for computer systems, games, medical devices, and so much more. It can also be used along with additions like OSGi or CORBA to produce highly personalized application or services.
How understand Java?
If you are fascinated to understand Java, there are many institutions that are providing programs in this terminology. You can also develop your skills by surfing around articles added to Oracle's Java designer website, being a member in online Java boards, updates, and deciding upon up for instructor-led programs available on the Internet. Additionally, there are a lot of books you can use to understand Java. With so many solutions to understand Java, there are high opportunities that you can find one that meets your demands.
If you are looking for creating programs across various systems, studying java guides can help you do just that. There are various studying options, which can create it difficult to choose; however, it can also mean having a better possibility of finding a system that meets your choices and needs.
DATABASE CONNECTIVITY
This articles explains the need of database connectivity, the way it is achieved through Java using the JDBC(java database connectivity) APIs.
Need of Database Connetivity
Consider a scenario where you have to develop an application for an airlines company to maintain a record of daily transactions. You install your database server ,lets say SQL server, design the airlines database and ask airlines personnel to use it. Will this daabase alone be of any use to the airline personnel? The answer is NO!. The task of updating SQL server by using SQL statements will be a tedious process. An application will need to be developed that is user friendly and provides a client, the options to retrieve , add, and modify data at the touch of a key.
Sun Microsystems has included JDBC API as a part of J2SDK to develope java applications that can communicate with the databases.The following figure shows the airlines reservation system developed in java interacting with the airlines database using the JDBC API:
PROBLEM:
Java applications cannot directly communicate with a database to submit data and retrieve the results of queries. This is because a database can interpret only SQL statements and not java language statements. For this reason, you need a mechanism to translate java statements into SQL statements . Java Drivers provide us with such a mechanism.
JDBC Drivers
JDBC DRIVERS act as an interface between a java application and a database. It enables connectivity to a database. A driver sends the request of a java aplication to the database . After processing the request, the database sends the response back to the driver . The driver translates and sends the response of the jdbc api. The JDBC API forwards it to the Java application.
JDBC supports four types of drivers
- JDBC-ODBC Bridge driver
- Native-API Partly-Java driver
- JDBC-Net Pure-Java driver
- Native Protocol Pure-Java driver
THE CODING PART...
Java has provided us with the jdbc api classes and interfaces , available in the java.sql and the javax.sql packages.The classes and interfaces perform a number of tasks, such asa establish and close a connection with the database , send a request to a database , retrieve data from a database, and update data in a database. The commomnly used classes and interfaces in the Jdbc API are:
- DriverManager class: loads the driver for a databse .
- Driver interface: Represents a database driver. All JDBC classes must implement the Driver interface.
- Connection interface: Enables you to establish a connection between a java application and a databse.
- Statement interface: Enables you to execute SQL statements.
- ResultSet interface: Represents the information retrieved form a databse.
- SQLException class: Provides information about the exceptions that occur while interacting with databases.
To query database and display the result using Java applications, you need to follow the below mentioned steps:
- Load a driver.
- Connect to a database.
- Create and Execute JDBC statements.
- Handle SQL exceptions.
- Close all the connections.
Now we will discuss step wise implementation of these steps.
Loading a driver:
Java has provided us with two ways of loading a driver, namely:
- Using the forName() method
- Using the registerDriver() method
forName() method: The forName() method is available in the java.lang.Class class. The forName() method loads the JDBCdriver and register the driver with the driver manager. The syntax to load a JDBC driver to access a database is:
Class.forName("<driver_name>");
for eg: You can laod the JDBC-ODBC Bridge using the following method call:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
rigisterDriver() method: You can create an instance of the Driver class to load the jdbc driver. The syntax for that is
Driver d = new sun.jdbc.odbc.JdbcOdbcDriver();
Once you have created the Driver object, call the registerDriver() method to register it with the DriverManager. Or in other words simply call the registerDriver() method using the class name DriverManager and pass the object of the driver class into the registerDriver() method. Syntax of that is:
DriverManager.registerDriver(d);
Connecting to a Database:
interface to establish a connection of the Java application with a database. You can create multiple Connection objects in a Java application to access and retrieve data from multiple databases. The DriverManager class provides the getConnection() method to create a COnnection object. The getConnection() method is an overloaded method that has three forms. Syntax of the same is:
Connection con = DriverManager.getConnectio.("jdbc.odbc.MydataSource");
where jdbc is the protocol, odbc is the subprotocol and MydataSource is the DSN(ie data source name)
Creating and Executing JDBC Statements
You need to create a Statement object to send requests to and retrieve results from a database. The Connection object provides the createStatements() method to create a Statement object. You can use the following code snippet to create a Statement object:
Connection con = DriverManager.getConnection("jdbc:odbc:MyDataSource","NewUser","New password");
Statement stmt = con.createStatement();
The statement interface contains the following methods to send static SQL statements to a database:
- ResultSet executeQuery(String str): Executes an sql statement and returns a single object of the type, ResultSet.
- int ExecuteUpdate(String str): Executes the sql statements and returns the number of data rows that are affected after processing the sql statement
- boolean execute(String str): Executes an SQL statement and returns a boolean value.
Handling SQL Exceptions:
The java.sql package provides the SQLException class, which is derived from the java.lang.Exception class.The SQLException is thrown by various methods in the JDBC API and enables you to determine the reason of the errors that occur while connecting a java application to a database. You can catch the SQLException in a java application using the try and catch exception handling block.
Closing the opened connection
As the resources used in running any process are extremely precious to us so closing all the opened resources is a good coding practice. To close a resource , we use the close() method.
I hereby leave you with a simple program which hal used the above mentioned classes and methods to give you a better understanding of JDBC:
Program code:
import java.sql.*;
import java.io.*;
class DataBaseDemo
{
public static void main(String... aa)
{
try
{
//load the driver class
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("driver loaded");
//create the connection
Connection c = DriverManager.getConnection("jdbc:odbc:mydatabase";"deven";"password");
System.out.println("connected");
// create the statement
Statement s = c.createStatement();
//create the result set
ResultSet rs = s.executeQuery("select emloyeeID, login from human resource.employee");
while(rs.next())
{
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Write your first simple java program.
First of all we need is a placewhere we can write your Java code. All Java programs are written using plain text files such as a notepad.Therefore there is no need of a fancy software.Lets come to write your first program.For this you open a notepad and start writing a code.The program code looks like this:
class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
For your first program we are going to understand step by step process to compile and run a program.
1.The first step is to save the file written on the notepad.
A dialog box is open as show above. Now save your file as "HelloWorld.java". Now I have created an directory in My Documents called "Java" to store the all the Java programs in one place for my convience. You are free to create a another folder on your computer as you prefered.
Note:-
It is very Sincere while saving a file you must save a file as "HelloWorld.java".
class HelloWorld
{
The above code is an instruction to call the class "HelloWorld".
2. Then we need to open a Terminal Window as show below.
Most of the program are window application you are use a cursor to open a file but the above program are a example of console application it does not run on its own window its needs a terminal window to run a program. A terminal window is a source to run a programs that is stored on your hard drive.
Now to open a terminal window, press the "Windows key" and the letter “R” at one time.
Now a dialog box is open and type a cmd and press ok.
3. The Java Compiler
Now what is a java compiler .It is one of the console program is the Java compiler called "javac". Its function is to read the code in the HelloWorld.java file, and then translate it into a language that your computer understand. This process is known as called compiling.In Java every program you write in a notepad they have to be compiled before it can be run.
To run javac from the terminal window,First of all you need to tell your computer where The file is located on your computer.Now you give the directory just like I give here my location is "C:\Program Files\Java\jdk\1.6.0_06\bin". If you have the same directory then use it otherwise search your directory from your computer.
When you found your directory location, type the following command into the terminal window:
set path= *the directory where javac located*
Example:-
set path=C:\Program Files\Java\jdk\1.6.0_06\bin
Now press Enter. The terminal window return you something in a flash, It will be the command prompt. At last the path to the compiler has now been set and ready to use.
4. Change the Directory as you preferred
Now,you think where your HelloWorld.java file is saved in your computer. My file has been saved in a directory called "Java1" in My Documents. The location is as "C:\Documents and Settings\Chandan\My Documents\Java1".
Follow the below code to change the directory in the terminal window, type in the command:
cd *directory where HelloWorld.java file is saved*
Example:-
cd C:\Documents and Settings\paul\My Documents\Java1
5. Compile Your Program
Now you are ready to compile Your program. For that, enter the command:
javac HelloWorld.java
When you hit Enter buttom, the compiler work start and look at the code contained within the HelloWorld.java file, and try to attempt to compile it if yor program does not contain any error. If it contain error, it will display a series of errors on the command prompt which help you fix the code.After fixing the error again try to compile your program in the same manner as discuss above.
Tip: After your HelloWorld program has been successfully compiled, and you will see a new file in the same directory. It will be the “HelloWorld.class”.
6. Run the Program
And at last the only thing is to remain is to run the program. In your terminal window type the command:
java HelloWorld
When you press Enter, the program will run and you will see a output as "Hello World!" written to the terminal window.
This all about your first java program keep going I will discuss the core java in a brief in my next article . Thanks for reading my article.
Array of objects in Java
Arrays are defined as block of continous memory locations which are arranged in one after another. Elements of the Array can be accessed by the index number as: a[2]
Syntax:
data_type[] array_name = new data_type[number of elements];
Example:
int[] name = new int[10];
Array of objects
Objects are instance of a class.
Object can easily be created using following syntax: class_name object_name = new class_name();
Example: Student name = new Student();
but what if we need to create hundreds of objects of the same class. However this can be achieved using above procedure but imagine the the efforts and time required. To accomplish this task, Java introduces array of objects.
syntax: class_name[] object_name = new class_name[number of objects];
Example: Student name = new Student[5];
this code segment will create 5 objects called 'name' of type Student.
here is a beautiful example of apllication of array of objetcs: Students marksheet
Programs states:
Write a java program to accept details of students such as name, ID no, marks in Maths, Physics, and Chemistry. Display the students detail in descending order of their total marks. (Use array of objects)
import java.io.*; //importing input-output files
class Student
{
String name; //declaration of variables
int id;
int mathmarks;
int phymarks;
int chemmarks;
int total;
Student(String naam,int idno, int m,int p,int c) //Initializing variables to user data
{
name=naam;
id=idno;
mathmarks=m;
phymarks=p;
chemmarks=c;
total=m+p+c;
}
void display() //displaying information
{
System.out.println(name+"\t"+id+"\t"+mathmarks+"\t"+phymarks+"\t"+chemmarks+"\t"+total);
}
}
class Studentexe //main class
{
public static void main(String args[]) throws IOException //exception handling
{
System.out.println("Enter the numbers of students:");
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(in.readLine());
Student[] S=new Student[n]; // array of objects declared and defined
for(int i=0;i
System.out.println("Enter the Details of Student no: "+(i+1)); //reading data form the user
System.out.println("Name: ");
String nm=in.readLine();
System.out.println("ID no: ");
int idno=Integer.parseInt(in.readLine());
System.out.println("Maths marks: ");
int m=Integer.parseInt(in.readLine());
System.out.println("Physics marks: ");
int p=Integer.parseInt(in.readLine());
System.out.println("Chem marks: ");
int c=Integer.parseInt(in.readLine());
S[i]=new Student(nm,idno,m,p,c); //calling Student constructor
}
Student temp; //swaping to achieve decsending order of total marks
for(int a=0;a
for(int b=0;b
if(S[b].total {
temp=S[b];
S[b]=S[b+1];
S[b+1]=temp;
}
}
}
System.out.println("\nName"+"\t"+"ID"+"\t"+"Math"+"\t"+"Phy "+"\t"+"Chem"+"\t"+"Total"); //printing data on the output screen
for(int i=0;i
S[i].display();
}
} //main ends here
} //Studentexe class ends here
Note: 1) save the above code as 'Studentexe.java' while executing.
Synchronized block is alternative mechanism for "synchronized" methods.If we inherihate the non synchronized blocks either from base class or interface inface into our derived class and the inheriated non-synchronized method is trying to accessed by multiple threads then we get inconsistent result.To avoid this inconsistent result, the derived class programmer is attempting to write "synchronized" keyword before non synchronized method to make the method is synchronized which is not possible because one cannot change the prototype of base class methods in the context of derived class. Hence the synchronized method concept is unable to the solve the above problem therefore to solve the above problem for getting the consistence we use a concept called "synchronized blocks". Synchronized blocks must be always written in the definition of non-synchronized method.
syntax:
synchronized(object of current class){
//Block of statements;
}
It is not possible to override static methods but it is possible to override the instance methods.synchronized blocks must be always written in non-synchronized instance methods only.
Example:
package ip;public interface Account{
void deposit(int amt);
}
class SAccount implements Account{
int bal=0;
public void deposit(int amt){
synchronized(this){
bal = bal + amt;
System.out.println("user Account bal="+bal);
}
}