Professional Documents
Culture Documents
Raj Technologies Core Java Hand Book - 15 Days V1.0 PDF
Raj Technologies Core Java Hand Book - 15 Days V1.0 PDF
Class
A class is a collection of related Objects. A class is a collection of data members and methods.
The State of an object will act as data members in the class and the behavior of an object will
act as methods in the class.
eg:
class Employee
{
int empNum;
String empName;
double empSalary;
void setEmpDetails()
{}
void dispEmpDetails()
{}
}
Once the object is created the members of the class are accessed using object with dot (.)
operator as follows
e.empNum = 111;
e.empName = "Raj";
e.setEmpDetails();
Abstraction
Showing only essential details and hiding unnecessary details is called as abstraction
We can even define an abstraction as hiding the implementation details is also known as
abstraction
As an example if we consider the method Arrays.sort() which is used to sort the elements of
the array, here the implementation of sort() method is hidden to us.
Encapsulation
The wrapping upof data and methods together into a container called class and by
providing security to data is called as encapsulation
Emp e;
e.age = -20;//Error
e.setAge(30);
In the above example we cannot access age directly outside the class as age variable is private.
Private members are accessible only within the class. In order to give value to age, it is done
A class is fully encapsulated (secured) when all data members are private
Inheritance
Creating a new class from an existing class is called as inheritance. The process of arranging the
classes in the form of hierarchy is also known as inheritance. Through inheritance we can
achieve reusability of the code. The new class which is creating using exiting class is called as
sub class or derived class or child class. The exiting class is called as super class or base class or
parent class. The Derived class object can access the members of its own class and the
members of Base class.
For example
class Vehicle
{}
class Car extends Vehicle
{}
Forms/Types of Inheritance
In Method Overloading, method name is same but the signature is different. Signature means
number of arguments or type of arguments.
For example, following are the overloaded methods
int area(int n1,int n2,int n3){}
int area (int n1,int n2){}
float area(float n1,float n2){}
In Method Overriding, method name is same and signature is also same. Overriding is
applicable only in inheritance.
For example
class Vehicle
{
void drive()
{}
}
class Car extends Vehicle
{
void drive() //Overridden
{}
}
Java Versions
Following are the different versions released by Java
- JDK 1.0 (Java Development Kit)
- JDK 1.1
- JDK 1.2
- JDK 1.3
- JDK 1.4
- J2SE =>Java 2 standard edition - used to develop standalone applications
- J2EE =>Java 2 Enterprise Edition - used to develop web applications
- J2ME =>Java 2 Micro/Mobile Edition - used to develop mobile applications
- Java 5/Java1.5
- JSE
- JEE
- JME
- Java 6/Java 1.6
- Java 7/Java 1.7
- Java 8/Java 1.8 (March 2014)
1. Simple
Java Programming is simple as it contains lots of APIs (Application Programming
Interfaces) called as libraries.
2. Object Oriented
By using Java, we can develop the applications using Object Oriented Approach. Java
supports all the features of Object Oriented
3. Robust
Robust means strong. If any abnormal situation occurs during the execution of the
Program, the program should not terminate automatically, should provide proper
message to the user and continue with the remaining program. We can develop robust
applications in Java using Exception Handling
4. Platform Independent
A Java Program can run on any platform either 32-bit OS or 64-bit OS. If a java program
is developed on 32-bit OS, it can be executed on 64-bit OS without doing any modifications in
the program. A Java program is like Write Once Run Anywhere. A Java program is a collection
of classes.
X.java
class A
{
main(){}
}
class B
{
main(){}
}
In the above program X. java, it contains two class A and B. In order to compile the Java
program use the following command
> javac X. java
this command will generates two files A.class and B.class which are called as Byte Codes.
These byte codes are platform independent
To Run a Java program, at least one class should contain the main().
To run java program use the following command
>java A => which runs the program from A class main()
>java B => which runs the program from B class main()
5. Interpreted
An interpreter converts the source code object code line by line. In Java, java command
is an interpreter which converts the Java byte code into machine understandable code.
6. Portable
Java is highly portable. In Java the program from one platform to other platform is
shifted with doing any modifications to the program as in Java the size of all primitive data
types is same on all the platforms.
7. Secure
Java is secure as Java does not support pointers. A pointer is a variable which stores the
address of another variable. The disadvantage of pointers is to violate the security.
8. Multithreaded
A thread is a light weight process under execution with in a process. Multithreading is
used to increase the performance of an application. In Java we can develop multi threaded
applications in order to increase the performance of Java application.
9. Dynamic
In Java memory allocation for arrays, strings and any object is done during runtime which is
dynamic.
Once the Java is downloaded and installed, it will get installed in C:\Program
Files\Java\jdk1.8.0 by default which is termed as JAVA_HOME.
We find the javac.exe and java.exe files in JAVA_HOME\bin folder. The commands are used to
compile and run Java programs.
To use these command in our folder we need to set the path to JAVA_HOMe\bin folder as
follows at the command prompt.
>set path = C:\Program Files\jdk1.8.0\bin;%path%;
here %path% is used to append the previous path settings.
The path setting which is done at the command prompt is temporary setting means once we
close the command prompt window, the path settings will also gets removed.
To Run
>java Sum 10 20
In the above program 10 and 20 are the command line arguments which are stored in args
array which is of type String. args[0] contains value 10 and args[1] contains value 20.
Integer.parseInt() is used to convert a String into int type.
Scanner class
Scanner class is used to read the values into variables from keyboard during program execution.
Scanner class is added in Java 5 version. Scanner class is present in the package java.util
package. To the Scanner class in the program we need to import java.util.Scanner as follows
import java.util.Scanner;
Methods in Scanner class
- byte nextByte() which is used to read a byte value
- short nextShort() which is used to read a short value
- int nextInt() which is used to read an int value
Consider the following example program Student.java which uses Scanner class to read the
values into variables from keyboard
Student.java
//To find total and average of given three marks
import java.util.Scanner;
class Student
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println(Enter Roll No );
int rollno = in.nextInt();
System.out.println(Enter Name );
String name = in.next();
System.out.println(Enter 3 Marks );
double mark1 = in.nextDouble();
double mark2 = in.nextDouble();
double mark3 = in.nextDouble();
double total = mark1 + mark2 + mark3;
double avg = total/3;
System.out.println(Roll No =+rollno);
System.out.println(Name = +name);
System.out.println(Total = +total);
System.out.println(Average = +avg);
}
}
Data types
Variables
Arrays.
Like all modern programming languages, Java supports several types of data. In order to
store data we have to think of types of data to be stored. Hence java provides lot of data
types to declare variables and to create arrays.
Data Types:
Name Types
Character char
Integers: This group includes byte, short, int, and long, which
Boolean are for whole-valued signed
boolean
numbers.
Floating-point numbers: This group includes float and double, which represent numbers
with fractional precision.
Characters: This group includes char, which represents symbols in a character set, like
letters and numbers.
Boolean: This group includes boolean, which is a special type for representing true/false
values.
You can use these as simple data types, or user defined data types such as constructing
arrays, or class types. Thus, they form the basis for all other types of data that you can
create.
Java supports integer types such as
byte
short
int
long
Booleans
Java has a simple type for storing logical values, called Boolean. It can consist of one of two
possible values, true or false. This is the type returned by all relational operators, such as a
< b. boolean is also the type required by any conditional expressions that govern the
control statements such as if and for.
Keywords are special reserved words in Java that cannot be used as identifiers (names) for
classes, methods, or variables.
Table shows list of Java keywords and reserved words, which are updated through Java
5.0. const and goto are reserved but are not implemented. enum is the latest keyword
and was added to the language in Java 5.0 (displayed in bold letter in Figure). Remember
that none of the words in this list can be used as identifiers in Java programs.
Operators
Operators are special symbols that perform specific operations on one, two, or three
operands, and then return a result.
The Simple Assignment Operator
One of the most common operators that you'll come upon is the simple assignment
operator "=". You saw this operator in the Bicycle class; it assigns the value on its right and
the operand on its left:
int cadence = 0;
int speed = 0;
int gear = 1;
This operator can also be used on objects to assign object references, as discussed in
Simple Data Objects.
subtraction operator -
multiplication operator *
division operator /
Remainder operator %
== Equal to
!= not equal to
class BitDemo {
public static void main(String[] args) {
int bitmask = 0x000F;
int val = 0x2222;
System.out.println(val & bitmask); // prints "2"
}
}
Operators Precedence
Postfix expr++ expr--
Unary ++expr --expr +expr -expr ~ !
Multiplicative */%
Additive +-
Shift << >> >>>
Relational < > <= >= instanceof
Equality == ! =
Bitwise AND &
Bitwise exclusive OR ^
Bitwise inclusive OR |
Logical AND &&
Logical OR ||
Conditional ?:
Assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Control Statements
The computer programs are written with statements which helps in organizing the
program structure and its meaning. When you write a program, you type statements into a
file. In programs, the individual statement, instructions or function calls of an imperative or
functional program are executed. With the increasing demand of conditions and
complications arising in a particular work or in solving a program, it is necessary to control
the flow of the program. Without control flow statements, the interpreter executes the
statements in the order they appear in the file from left to right, top to bottom. What if you
wanted to change the flow?
For example, you want the program to take some decisions and do different things
depending on different situations such as printing 'Good Morning' or 'Good Evening'
depending on the time of the day?
As you might have guessed, this is achieved using control flow statements.
Table 1 shows categories of control flow statements available in Java and keywords list for
each categories.
Control flow statement category Keyword list
Selection statements if, else, switch, case
The if statement
The if statement executes a block of code only if the specified expression is true. The
condition to the if statement must be an expression that evaluates to a boolean value. . If
the condition evaluates to true, the statement following the if statement is executed. If the
value is false, then the if block is skipped and execution continues with the rest of the
program. You can either have a single statement or a block of code within an if statement.
if (condition)
{
statement1;
}
The following example demonstrates conditional execution based on if statement
condition.
public class IfStatementDemo {
b>a
The If-else Statement
The "if-else" statement is an extension of if statement that provides another option when
'if' statement evaluates to "false" i.e. else block is executed if "if" statement is false. You can
either have a single statement or a block of code within if-else blocks. The else statement is
optional,but if it is present,it must be placed immediately after the code block attached to
the if statement. The code block attached to the else statement is executed when the
condition to the if statement evaluates to false.
The general form of the if statement is given below:
if (condition)
{
statement1;
}
else
{
statement2;
Output
b>a
The chained If-else Statement
Under the chained format the execution evaluates all conditional expressions beginning
from Expression1 (given below) until the first expression is found that evaluates to true.
Then the corresponding statement sequence is executed, or, if none of the expressions
evaluated to true, the statement sequence of the final else part.
if ( Expression1 ) {
Statement1a
Statement1b
...
} else if ( Expression2 ) {
Statement2a
Statement2b
...
} else if ( Expression3 ) {
Statement3a
Statement3b
...
} else {
Statement4a
Statement4b
...
}
The switch case statement, also called a case statement is a multi-way branch with several
choices. A switch is easier to implement than a series of if/else statements. The switch
statement begins with a keyword, followed by an expression that equates to a no long
integral value. Following the controlling expression is a code block that contains zero or
more labeled cases. Each label must equate to an integer constant and each must be unique.
When the switch statement executes, it compares the value of the controlling expression to
the values of each case label. The program will select the value of the case label that equals
the value of the controlling expression and branch down that path to the end of the code
block. If none of the case label values match, then none of the codes within the switch
statement code block will be executed. Java includes a default label to use in cases where
there are no matches. We can have a nested switch within a case block of an outer switch.
switch(expression){
case val1:
code_block1
case val2:
code_block2
.
.
.
default:
code_default;
}
The break statement is used within the code block attached to the switch statement to
terminate a statement sequence. Therefore, if you want to exit in the middle of the switch
statement code block, you must insert a break statement, which causes the program to
continue executing after the current code block.
The argument to the switch must be an integral expression that must evaluate to a 32-bit or
smaller integer type: byte,short,char,or int. Moreover,the legal range of the argument's data
type must cover all the case constants used in the code block. For example,the following
code fragment will not compile successfully:
byte b = 10;
switch( b ){
case 10 :
System.out.print("ten");
break ;
System.out.print("10") ;
break ;
Iteration statements enable program execution to repeat one or more statements, i.e.
iteration statements form loops. In Java, there are three iteration statements: for, while and
do. An enhanced for loop has been added in J2SE 5.
All the sections in the for-header are optional. Any one of them can be left empty, but the
two semicolons are mandatory. In particular, leaving out the <condition> signifies that the
loop condition is true. The (;;) form of for loop is commonly used to construct an infinite
The while statement is a looping construct control statement that executes a block of code
while a condition is true. You can either have a single statement or a block of code within
the while loop. The loop will never be executed if the testing expression evaluates to false.
The loop condition must be a boolean expression.
}
where, the condition may be any expression that evaluates to a boolean value. The code
block attached to the while statement is repeatedly executed unless the condition evaluates
to false. Below is an example that demonstrates the looping construct namely while loop
used to print numbers from 1 to 10.
public class WhileLoopDemo {
This statement is similar to the while statement discussed above. The only difference in
this case is that the code block attached to the do statement is executed before the
condition is checked. Therefore, even in the case of the condition evaluating to false, the
code block executes at least once. A do-while loop begins with the keyword do, followed by
the statements that make up the body of the loop. Finally, the keyword while and the test
expression complete the do-while loop. When the loop condition becomes false, the loop is
terminated and execution continues with the statement immediately following the loop.
You can either have a single statement or a block of code within the do-while loop.
do
{
code_block
} while(condition);
Jump statements are used to unconditionally transfer the program control to another part
of the program. Java has three jump statements: break, continue and return.
The break statement
A break statement is used to abort the execution of a loop. The general form of the break
statement is given below:
break;
class BreakDemo
{
int count = 5;
while(true) {
if(count == 5) {
break;
}}}}
A break may be used with or without a label. When it is used without a label, it aborts the
execution of the innermost switch, for, do, or while statement enclosing the break
statement. When used with a label, the break statement aborts the execution of any
enclosing statement matching the label. When used with a label the syntax is:
break label;
Note: A label is an identifier that uniquely identifies a block of code.
Introduction
An array is a contiguous block of memory locations referred by a common name. The type
of the elements of the array is called the base type of the array. The number of elements it
holds is a fixed attribute called its length. Java supports arrays of all primitive and
reference types.
For e.g.
To store the marks of 5000 students, you can declare an array called marks, of size 5000
and can store the marks of as many students.
Arrays
Why array is needed?
You might come across a situation where you need to store similar type of values for a large
number of data items.
For e.g.
To store the marks of all the students of a university, you need to declare thousands of
variables. In addition, each variable name needs to be unique. It would not be practical to
hold each in a separately named variable. To avoid such situations, you can use arrays.
Instead of using individual variables, we will use a whole number of variables.
An array consists of a name and the number of elements of the array. You can refer to a
specific array element by the array name and the element number, which is known as the
index number.
You should always remember that array index element number always starts with 0(zero).
An array is a container object that holds a fixed number of values of a single type. The
length of an array is established when the array is created. After creation, its length is fixed.
This section discusses arrays in greater detail.
Creating Arrays
The length of an array is fixed at the time of its creation. An array represents related
entities having the same data type in contiguous or adjacent memory locations. The related
data having data items form a group and are referred to by the same name.
For e.g.
employee[5];
Here, the employee is the name of the array and of size 5. The complete set of values is
known as an array and the individual entities are called as elements of the array.
A specific value in an array is accessed by placing the index value of the desired element in
a square bracket.
Advantages of using Arrays
You can refer to a large number of elements by just specifying the index number and the
array name.
Arrays make it easy to do calculations in a loop.
One-dimensional arrays
Two-dimensional arrays
Multi-dimensional arrays
One-dimensional Arrays
Length of an array
Each array has a constant (final) instance variable that has its length. You can find out how
many elements an array can hold by writing the array name followed by .length. In the
previous example, a.length would be 100. Remember that this is the number of elements in
the array, one more than the maximum subscript.
Accessing Arrays
You need to access various elements of an array to assign, retrieve, and manipulate the
values stored in the array.
You need to specify the name of the array and the index number of the element.
The index position of the first element in the array is 0.
For e.g.
String designations[];
designations[1]=Managing Director;
You can declare and allocate memory to a user-defined array in a single statement.
Syntax:
You can also declare and initialize arrays in the same statement.
For e.g.
For e.g.
In a two-dimensional array,
For e.g.
If you think of a one-dimensional array as a column of values you can think of a two-
dimensional array as a table of values like so:
r0 0 1 2 3
r1 1 2 3 4
r2 2 3 4 5
r3 4
r4 3 5
4 5 7
6 6
Here we have an array with five rows and four columns. It has twenty total elements.
However, we say it has dimension five by four, not dimension twenty. This array is not the
same as a four by five array like this one:
c0 c1 c2 c3 c4
r0 0 1 2 3 4
r1 1 2 3 4 5
r2 2 3 4 5 6
r3 3 4 5 6 7
We need to use two numbers to identify a position in a two-dimensional array. These are
the element's row and column positions. For instance if the above array is called J then
J[0][0] is 0, J[0][1] is 1, J[0][2] is 2, J[0][3] is 3, J[1][0] is 1, and so on.
Two dimensional arrays are declared, allocated and initialized much like one dimensional
arrays. However we have to specify two dimensions rather than one, and we typically use
two nested for loops to fill the array.
The array examples above are filled with the sum of their row and column indices. Here's
some code that would create and fill such an array:
class FillArray {
public static void main (String args[]) {
int[][] M;
M = new int[4][5];
for (int row=0; row < 4; row++) {
for (int col=0; col < 5; col++) {
M[row][col] = row+col;
}
}
}
}
Object
An instance of a class is called as object. The members of the class are accessed by using
objects.
Creating Objects
The following syntax gives the creation of object in Java
ClassName ObjName = new ClassName();
eg:
Employee e = new Employee();
Once the object is created for the class, the members of the class are accessed by using object
with dot( . ) operator. For example,
e.empNum=111;
e.empName = "Raj";
e.setEmpDetails();
e.dispEmpDetails();
this reference
this reference is used to refer to the current object. this reference is generally used to
differentiate data members of a class and arguments of a method when the name are same.
}
}
Example Program
//ConstructorDemo.java
class Rectangle
{
int length;
int breadth;
static keyword
static keyword can be used for data members(variables) of a class, methods of the class
and inner classes. static keyword cannot be used for top level class and local variables. static
members are accessible directly with the class name without creating objects. Objects can even
access static members. A static variable acts as a global variable within class means all the
objects of the class can share static variable memory. When the class gets loaded into JVM, first
it will allocate memory for static variables and this memory is allocated only once then object
gets created by allocating memory for instance variables. Static methods can only other static
members directly. A non static member cannot be referenced from static context.
//StaticDemo.java
class Sample
{
int m;//instance variable or non-static variable
static int n;//class or static variable
void xxx() //instance or non-static method
{
m = 10;
n = 20;
}
}
void display()
{
System.out.println(m=+m+ +n=+n);
}
}
class StaticDemo
{
public static void main(String[] args)
{
Sample s1 = new Sample();
s1.xxx();
s1.display();//m=10 n=20
Sample s2 = new Sample();
s2.display();//m=0 n=20
s2.yyy();
s1.display();//m=10 n=40
s2.display();//m=0 n=40
Sample.n=50;
s1.display();//m10 n=50
s2.display();//m=0 n=50
}
}
Inheritance
The process of creating a new class from an existing class is called as inheritance. The existing
class is called as base class or parent class or super class. The new class which is created using
existing class is called as derived class or child class or sub class. Through inheritance we
achieve reusability of the code means the object of derived class can access the members of
base class.
In Java extends keyword is used to create a new class from an existing class. For example,
class Vehicle
{
.
}
class Car extends Vehicle
{
.
}
Examples of inheritance
Inheritance is a is-a relationship. When we use extends keyword from one class to another
class, is-a meaning should come between the class.
Example Program
//InheritanceDemo1.java - Simple Inheritance
class Base
{
int i;
int j;
void inputIJ(int i,int j)
{
this.i=i;
this.j=j;
}
void displayIJ()
{
System.out.println("i="+i+" "+"j="+j);
}
}
class Derived extends Base
{
int k;
void inputK(int k)
{
this.k=k;
}
void displayK()
{
System.out.println("k="+k);
}
}
Polymorphism
Polymorphism means many forms. Polymorphism is of two types Compile time polymorphism
and run time polymorphism.
Java does not support Operator overloading due to ambiguities to the programmers.
Example Program
super reference
super is used to refer to the base class members from derived class method
super() is the first statement added implicitly to every constructor
To call parameterized constructor of base class from derived class constructor, call it
explicitly
call to super() must be the first statement in constructors
final keyword
final keyword can be used for a variable, method and class.
Consider the following table for the final keyword
Variable Method Class
- It is a constant means the - It cannot be overridden - It cannot be sub classed
final variable value cannot be means final methods of base means final class cannot have
modified class cannot be overridden in sub classes
Example: sub classes Example:
final int MAX_VALUE = 100; Example: final class Base{}
MAX_VALUE = 200;//Error class Base class Derived extends Base{}
{ //Error
final void xxx()
{}
}
Class Derived extends Base
{
void xxx() //Error
{}
}
Abstract classes
Abstract classes are used to form the rules or specifications
A method which is just declared is called as abstract method
An abstract class contains zero or more abstract methods
We cannot create the objects for abstract classes but we can create references referring
to the sub class object
eg:
Sample s = new Sample();//Error
Sample s1 = new Sample1();//valid
Example Program
//AbstractDemo.java
abstract class Vehicle
{
abstract void drive();
void applyBreak()
{
System.out.println("Applying Break");
}
}
}
}
Interfaces
It is used to form the rules or specifications
Does not force "is-a" relationship
In an interface all methods are public and abstract by default
In an interface all variables are public, static and final by default
eg:
interface I1
{
int n;
void xxx();
void yyy();
}
If a class implements an interface, then we need override all methods else make the
class as abstract
We cannot create objects for interfaces but we can create references referring to the
sub class object
Example Program
//InterfaceDemo.java
interface Shape
{
void draw();
}
class Circle implements Shape
{
public void draw()
{
System.out.println("Drawing a Circle");
}
}
Packages
- A package is a collection of related classes and interfaces (.class files)
- "package" keyword is used to create package
eg:
package mypack;
- package statement should be the first statement in the source code file
eg
package mypack;
import ...
import ...
class A
{}
class B
{}
- we can have only one package statement in a source code file
- The classes under the package should be stored in a folder whose name is same as the
package name
- Only public classes / members are accessible outside the package
- To use the classes of one package into another package, we need to import the package
import mypack.A;
import mypack.B;
or
import mypack.*; * indicates all classes
Predefinded packages
- java.lang
- java.util
- java.io
- java.sql
- java.awt
Example Program
//Calculator.java
package mypack1;
//PackageDemo.java
package mypack2;
import mypack1.*;
public class PackageDemo {
Object
String
System
StringBuffer
StringBuilder
Byte
Short
Character
Integer
Long
Float
Double
Boolean
Object class
Object is the top most class sitting in Java Hierarchy. All the classes under java are sub classes of
Object class. If a class does not extend other class, the by default the class extends Object class.
Object class is also known as Cosmic super class
Object class contains 11 methods which are given below.
1. clone()
- used to create a duplicate object
eg:
Emp e = new Emp();
Emp e1 = e.clone();//e1 is duplicate Object
2. equals()
- used to compare the hashcodes of objects
eg:
e.equals(e1);//true
3. finalize()
- used to do the cleanup operations like closing of files,
closing of database connections etc
- finalize() is called just prior to the garbage collection
4. getClass()
- used to return the name of the class of an object
The above methods wait(), notify() and notifyAll() are discussed in Multitheading.
In the above diagram s1 refers to an object Hello in the heap memory. In Java objects are
created in heap memory. When you make s1 to refer to the object World, the object Hello
will not be replaced with World instead of that Java will allocate another memory for World
and s1 will be now referring the object World. The object Hello is no longer referenced by
s1. Now the object Hello is ready for garbage collection. The objects which are no longer
referenced are ready for garbage collection and these objects will be removed from heap
memory during garbage collection process.
In the above diagram s1 and s2 refers to the same object Hello in the head memory. To check
whether the both the references are referring to the same object we use ==. To check
whether the values present in the objects are same or not we use equals().
Example Program
//StringDemo.java
public class StringDemo {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1==s2);//true
System.out.println(s1.equals(s2));//true
System.out.println(s1.hashCode()+" "+s2.hashCode());
String s3 = new String("Welcome");
String s4 = new String("Welcome");
System.out.println(s3==s4);//false
System.out.println(s3.equals(s4));//true
}
StringBuffer class
StringBuffer is mutable means the object value present in StringBuffer can be modified.
All the methods in StringBuffer class are synchronized
For Example:
StringBuffer sb = new StringBuffer("Hello");
sb.append("World");
System.out.println(sb);//HelloWorld
StringBuilder class
StringBuilder is mutable means the object value present in StringBuilder can be modified.
System.gc()
System.gc() method is used to send a request to do garbage collection somewhat prior. When
we send the request to garbage collector, it is not guaranteed that garbage collection will do
the garbage collection process immediately. Garbage collection may do garbage collection.
Wrapper classes
For every primitive type there is a corresponding reference type called as wrapper class
All wrapper classes are final
Wrapper classes are used to convert reference type to primitive type
Examples
String s = "100";
int n = Integer.parseInt(s);
String s = "3.14";
double d = Double.parseDouble(s);
which converts String value 3.14 into double value
Types of Errors
In a programming language there are three types of errors which are given below
- Syntax errors or compile time errors
- Semantic errors or logical errors
- Run time Errors or Exceptions
Exception
An exception is a runtime error which occurs during program execution and terminates the
program abnormally.
Consider the following example code
class ExceptionDemo
{
public static void main(String[] args)
{
System.out.println(Begin of the program);
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
int result = n1/n2;
System.out.println(Result = +result);
System.out.println(End of the Program);
}
}
and terminates the program abnormally by throwing an exception by Java Runtime without
executing the remaining part of the program as divide by zero is an exception in Java
try
catch
finally
throw
throws
In the above keywords try, catch, finally are called as blocks where as throw and throws
keywords are called as clauses.
try
{
st-1;
st-2;
..
st-n;
}
catch(Exception e)
{
//handle the exception
}
The statements which may throw an exception will be written in try block. When an exception
occurs in try block, the java runtime will throw an exception which is caught by the catch block
and handles this exception in the catch block and remaining part of the program executed
without terminating the program.
Categories of Exceptions
There are two categories of Exceptions which are given belo
Checked Exceptions
UnChecked Exceptions
Checked Exceptions
The exceptions which are taken care during compilation by following the specifications are
checked exceptions. Other than RuntimeExceptions like IOException, InterruptedException,
SQLException etc are checked exceptions.
If a method throws an exception, then this method need to be caught(try & catch) or declared
to be thrown (throws)
UnChecked Exceptions
The exceptions which occurs during runtime are not checked during compilation are unchecked
exceptions. All RuntimeExceptions like ArithmeticException,ArrayIndexOutOfBoundsException,
NumberFormatException etc are UnChecked Exceptions.
- ArithmeticException
- trying to divide with zero
- ArrayIndexOutOfBoundsException
- trying to access an array out of index
- StringIndexOutOfBoundsException
- trying to access a character from a string which is out of index
- NegativeArraySizeException
- when the array size is negative
- NumberFormatException
- trying to convert a string into number which is not possible
- NullPointerException
- trying to access a member of a class using object when the object is pointing to null
Note:
In case of try with multiple catch blocks, the order of catch blocks cannot be from super class to
sub class
Consider the following example program for try with multiple catch blocks.
//MultipleCatchDemo.java
class MultipleCatchDemo
{
public static void main(String[] args)
{
try
{
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
int res = n1/n2;
System.out.println("Result = "+res);
}
catch(ArithmeticException e)
{
System.out.println("Cannot divide by zero");
}
finally block
finally block is executed irrespective of exception present in try block. Finally block is generally
used to do the clean up operations like closing of files, database connections. If an exception
occurs in try block or not we need to close the connections, these closing operations are
written in finally block
syntax
try
{
sts;
}
catch(Exception e)
{
sts;
}
finally
{
sts;
}
Consider the following example program which creates a user defined exception
WithdrawException. WithdrawException is thrown when the user withdraws an amount
which is more than the current balance from the account.
//CustomExceptionDemo.java
class WithdrawException extends Exception
{
WithdrawException(String s)
{
super(s);
}
WithdrawException(){}
}
class Account
{
void withdraw(int amt) throws WithdrawException
{
if (amt > 5000)
throw new WithdrawException("Balance is less");
else
System.out.println("Balance = "+(5000-amt));
}
}
class CustomExceptionDemo
{
public static void main(String[] args)
{
Account a = new Account();
Example 1
class Base
{
void xxx()
{}
}
class Derived extends Base
{
void xxx() throws Exception //Error
{}
}
If a base method is not throwing any exception then overriden method should not throw any
exception
If a Base class method throws an exception, then the overridden method may not throw an
exception, may throw an exception which is same as the exception thrown by base class
method, may throw an exception which is sub class to the exception thrown by base class
method. The overridden method should not throw an exception which is super class to the
exception thrown by base class method.
For example,
Using Thread class
class MyThread extends Thread
{
public void run()
{
//logic goes here
}
}
MyThread t = new MyThread();
t.start();//invokes the run() of MyThread class
When we want to create a thread, the class should override the run() method and we need to
invoke the run() by calling start() method using Thread object. When we call start() of Thread
class, a thread will get created and the CPU will allocate separate time to execute the thread
during running of the application which in turn increases the performance of the application.
When the object of the Thread class is created , the state of the thread is New state, we the
thread calls the method start() it creates a thread and the thread will be waiting for the CPU
resource and is ready to run when the CPU becomes free and this state is Runnable state, when
the CPU is free it executes the run() and the thread will be in the state Running state. A thread
goes to blocked state when the thread performs Input Output operations, when sleep() is
invoked on the thread, when wait() is called on the thread. A thread will return back to
Runnable state from Bloked state, after completion of IO operations, when the milli seconds
expire in the sleep() method, when notify() or notifyAll() methods called. A thread goes to Dead
state when the stop() method is invoked.
//ThreadDemo.java
//Methods of Thread class
class MyThread extends Thread
{
public void run()
{
Thread t = Thread.currentThread();
System.out.println(t);//Thread[Thread-0,5,main]
t.setName("MyThread");
System.out.println(t);//Thread[MyThread,5,main]
System.out.println(t.getName());//MyThread
t.setPriority(8);
/* If the prority is <1 or >10, it will
throw an exception IllegalArgumentException
*/
System.out.println(t);//Thread[MyThread,8,main]
System.out.println(t.getPriority());//8
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
ThreadX:10
ThreadY:1
join()
join() is used in between parent thread and child thread
When join() is invoked on a thread, until the thread completes run(), the other threads
will not use CPU resource
Note:
If start() is invoked multiple times, it will throw an IllegalThreadStateException
If an exception occurs in a thread, it will terminate only the thread, not the program
yield()
When yield() is invoked on a thread, it will a chance to other threads with the same priority. If
there are no threads with the same priority, the current thread will continue using the cpu
resource
Synchronization
If two or more threads access the same resource, then there is a getting concurrency
problems
Synchronization is used to avoid concurrency problems
"synchronized" keyword is used for synchronization
synchronized keyword can be used for a method or block of statements
Consider the following diagram where two threads access the same resource.
Inter-thread communication
Interthread communication is done using wait(),notify() and notifyAll() methods
These methods belongs to Object class
These methods need to be used in synchronized context only else it will throw
IllegalMonitorStateException
Example Program
//InterThreadDemo.java
class ThreadSum extends Thread
{
int sum;
public void run()
{
for(int i = 1;i<=100;i++)
sum = sum + i;
Deadlock
When threads are waiting for the resource for longer period of time leads to deadlock
In the above diagram Thread t1 has kept a lock on recourse R1 and thread t2 has kept a lock on
resource R2. When Thread t1 wants to use resource R2 and thread t2 wants to use resource R1,
but the these resources are not released the locks and these threads will be waiting for the
resources for longer time and this leads to deadlock.
Arrays vs Collections
Arrays is a collection of elements of similar type where as Collections are used to collect
the elements of different type
Arrays are fixed size where as Collections are variable size(not fixed)
In Arrays we can store primitive type as well as reference type where as in Collections
we can store only reference type
Collections Hierarchy
The top most interfaces in Collections are Collection and Map
Consider the following Collection Hierarchy diagram.
Following will give the difference between different collection classes and interfaces.
Collection vs Map
Collection is used to collect the elements where as Map is used to collect key-value
pairs
List vs Set
List is ordered where as Set is unordered
List allows duplicates where as Set does not allow duplicates
Stack
Stack is used to collect the elements in the form of Last In First Out(LIFO)
ArrayList vs Vector
In ArrayList the methods are not synchronized where as in Vector the methods are
synchronized
ArrayList is not thread safe where as Vector is thread safe
HashSet vs LinkedHashSet
HashSet is unordered where as LinkedHashSet is ordered
HashSet vs TreeSet
The elements in HashSet are not sorted where as the elements in TreeSet are sorted
HashMap vs Hashtable
In HashMap the methods are not synchronized where as in Hashtable the methods are
synchronized
HashMap is not thread safe where as Hashtable is thread safe
HashMap vs LinkedHashMap
HashMap is unordered where as LinkedHashMap is ordered based on keys
HashMap vs TreeMap
The elements in HashMap are not sorted where as the elements in TreeMap are sorted
based on keys
Consider the example program which uses these methods using ArrayList class
//ArrayListDemo.java
import java.util.*;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(10);//al.add(new Integer(10));//prior to Java 5
al.add(20);
al.add("xxx");
al.add("yyy");
System.out.println(al);//[10,20,xxx,yyy]
al.add(2,"ppp");
System.out.println(al);//[10,20,ppp,xxx,yyy]
al.set(2,"qqq");
System.out.println(al);//[10,20,qqq,xxx,yyy]
al.remove(2);
System.out.println(al);//[10,20,xxx,yyy]
al.remove("xxx");
System.out.println(al);//[10,20,yyy]
String s = (String)al.get(2);
System.out.println(s);//yyy
System.out.println("Size = "+al.size());//Size = 3
}
addFirst()
addLast()
removeFirst()
removeLast()
Iterator interface
Iterator interface is used to traverse the elements of list or set from first to last
ListIterator
ListIterator interface extends Iterator interface
ListIterator is used to traverse the elements of list or set from first to last as well as last
to first
Methods of ListIterator
boolean hasPrevious()
Object previous()
Example program using Iterator and ListIterator interfaces to traverse the list
//IteratorDemo.java
import java.util.*;
public class IteratorDemo {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.add(10);
ll.add(20);
ll.add("xxx");
ll.add("yyy");
System.out.println(ll);//[10,20,xxx,yyy]
Iterator iter = ll.iterator();
while(iter.hasNext())
System.out.println(iter.next());
ListIterator listIter = ll.listIterator();
while(listIter.hasNext())
System.out.println(listIter.next());
while(listIter.hasPrevious())
System.out.println(listIter.previous());
}
//UsingGenericsDemo.java
import java.util.*;
public class UsingGenericsDemo {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("xxx");
al.add("yyy");
al.add("zzz");
for(String s : al)
System.out.println(s);
for(int i=al.size()-1;i>=0;i--)
System.out.println(al.get(i));
}
Set interface
Set interface is used to collect the elements. In Set the elements are unordered and duplicates
are not allowed.
Example Program
//SetDemo.java
import java.util.*;
public class SetDemo {
public static void main(String[] args) {
//HashSet
HashSet hs = new HashSet();
hs.add("c");
hs.add("a");
hs.add("e");
hs.add("b");
hs.add("d");
hs.add("a");//not an error - will not be added into the set
System.out.println(hs);//[d,e,b,c,a]
//LinkedHashSet
LinkedHashSet lhs = new LinkedHashSet();
lhs.add("c");
lhs.add("a");
lhs.add("e");
lhs.add("b");
lhs.add("d");
System.out.println(lhs);//[c,a,e,b,d]
When we add elements into TreeSet, it will arrange the elements in the form of tree using
binary search tree
The arrangement of elements is shown below in the diagram.
Once the elements are arranged in TreeSet, the elements are traversed using inorder traversal
which traverses the elements in ascending order.
Comparator interface
Comparator interface is used to add the elements into TreeSet by comparing the elements
Methods
int compare(Object,Object)
The TreeSet class implements the Comparator interface and overrides the method compare().
The operations which are performed at the top of the Stack are
push inserts an element at the top of the stack.
Pop deletes an element from the top of the stack
Peek returns the element from the top of the stack
Methods
boolean empty()
Object push(Object o)
Object pop()
Object peek()
Example program
//StackDemo.java
import java.util.*;
public class StackDemo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Stack st = new Stack();
int ele,ch;
while(true)
{
System.out.println("1.Push");
System.out.println("2.Pop");
System.out.println("3.Peek");
System.out.println("4.Display");
System.out.println("5.Exit");
System.out.println("Enter Choice");
ch = in.nextInt();
switch(ch)
{
case 1:System.out.println("Enter element");
ele = in.nextInt();
st.push(ele);break;
case 2:if (st.empty())
System.out.println("Stack Underflow");
else
{
ele = (int)st.pop();
System.out.println("Poped Element "+ele);
} break;
Vector class
Vector is a collection of elements which are ordered. The methods present in Vector class are
synchronized.
The following example programs create a Vector and traverses the elements of the Vector using
Enumeration interface (legacy interface).
//VectorDemo.java
import java.util.*;
public class VectorDemo {
public static void main(String[] args) {
Vector v = new Vector();
v.add(10);
v.add(20);
v.add("xxx");
v.add("yyy");
System.out.println(v);//[10,20,xxx,yyy]
Enumeration e = v.elements();
while(e.hasMoreElements())
System.out.println(e.nextElement());
}
}
Map interface
Map interface is used to collect the elements in the form of key-value pairs. Map is unordered
and Map does not allow duplicates.
Consider the following example program for Map
//MapDemo.java
import java.util.*;
public class MapDemo {
public static void main(String[] args) {
To traverse Maps convert Map into Set by using entrySet() method then apply the Iterator
interface on the Set.
The following program is used to iterate Maps
//IterateMapDemo.java
import java.util.*;
public class IterateMapDemo {
public static void main(String[] args) {
HashMap hm = new HashMap();
hm.put("monitor",5000);
hm.put("keyboard",300);
Open a stream pointing a specific data source: a file, a socket, URL, etc.
Then read or write data from/to this stream.
Close the stream.
The following example accepts a character from the user and prints it back in the prompt.
import java.io.*;
public class InOutDemo
{
public static void main(String s[]) throws IOException
{
System.out.println((char)System.in.read());
}
}
In the above example you can see that the data read by System.in.read is casted into char,
because read() method returns a byte. The input and output stream read and write bytes
respectively. This means readers can read and writers can write characters.
Streams
InputStream Class
The java.io.InputStream class fall under abstract superclass for all input streams. When
there is need to read bytes of data from a stream, it declares three basic methods.
Moreover, it has methods to close and flush streams, to check the number of bytes of data
available to be read, to skip over input, to mark a position in a stream and reset back to that
position and also to determine whether marking and resetting back are supported. The
following list provides the details of some important methods in the InputStream class.
public int read(byte[] data, int offset, int length) throws IOException
Constructors
Test methods
Action methods
List methods
Constructors
There are several constructors in the File class ther allow Java code to specify the initial
values of an object. Constructors for the File class are:
File(String filename)
Action methods
Public instance methods in the File class perform actions on the specified file. Let's take a
look at them:
import java.io.*;
public class FileDemo1
{
public static void main(String []s) throws IOException
{
File f=new File("C:/raj.txt");
if(f.exists())
{
System.out.println("raj.txt exists");
}else
{
System.out.println("The new file getting created");
f.createNewFile();
//f.mkdir() can be used to create a directory
}
System.out.println("Is it a File ? : " + f.isFile());
System.out.println("Is it a Directory ? : " + f.isDirectory());
System.out.println("Is it Hidden ? : " + f.isHidden());
System.out.println("Is it Readable ? : " + f.canRead());
System.out.println("Its length is ? : " + f.length());
if(f.length()==0)
{
System.out.println("Deleting the file now");
f.delete();
}
}
}
The following example demonstrates the use of listFiles() method along with recursion
principle to extract the list of files and directory names under the C:/WINDOWS directory.
import java.io.*;
public class RandomAccessDemo
{
public static void main(String []s) throws IOException
{
RandomAccessFile f=new RandomAccessFile("C:/RandomAccessDemo.java","r");
String str="";
while(str!=null)
{
try
{
System.out.println(str=f.readLine());
}
catch(Exception e)
{
System.exit(0);
}
}
}
}
File Streams
Most of the examples in this chapter have used the streams System.in and System.out.
These are convenient for examples, but in real life, you will more commonly attach streams
to data sources like files and network connections. You will use the java.io.FileInputStream
and java.io.FileOutputStream classes, which are concrete subclasses of InputStream and
OutputStream, to read and write files.
Reading Files:
FileInputStream is a pure subclass of InputStream that provides an input stream connected
to a particular file.
import java.io.*;
public class ReadBytes
{
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("C:/Sample.txt");
int n;
while ((n = fis.available()) > 0) {
byte[] b = new byte[n];
int result = fis.read(b);
if (result == -1) break;
String s = new String(b);
System.out.print(s);
} // End while
} // End try
catch (IOException e)
{
System.err.println(e);
}
System.out.println();
}
}
Writing Files :
The FileOutputStream class is a concrete subclass of OutputStream that provides output
streams connected to files.
This class has all the usual methods of output streams, such as write(), flush(), and
close().They are used exactly as they are for any other output stream. There are three main
FileOutputStream() constructors:
import java.io.*;
public class WriteBytes
{
public static void main(String[] args) {
try
{
File f=new File("C:/Sample.txt");
FileOutputStream fos = new FileOutputStream(f);
The read() method reads a single character and also returns a character that can be read
as an integer in the range from 0 to 65535 or it can be -1 if the end of the stream is reached.
The abstract read() method reads characters into a portion of an array that starts at the
offset up to length number of characters. It returns the number of characters read or 1
only if the end of the stream is reached.
If you look at the different character input streams in the java.io package, they are
Strings
Character arrays
Pipes
As InputStreamReader is a character input stream, it uses a byte input stream as its data
source, converting it into Unicode characters. LineNumberReader is a character input
stream and a subclass of BufferedReader that tracks the number of lines of text that have
been read from it. PushbackReader, is a character input stream and a subclass of
FilterReader, that uses another input stream as its input source. It also adds the ability to
push characters back onto the stream.
The void write() method They take a character and writes single character in 16 low-
order bits.
The abstract void write() method They take a character array and writes a portion of
an array of characters
Character output streams
In the java.io package, you will find many character output streams. There you can view
branches of this inheritance tree. It has not only Readers, but also other important
branches available.
The destination for the data in OutputStreamWriter is used with the help of byte output
stream. Buffering is employed by BufferedWriter to a character output stream. Therefore, it
enhances the efficiency of the output by combining many small write requests into a single
large request. An abstract class FilterWriter functions as a superclass for character output
streams. The stream helps in filtering the data written to them before writing it to some
other character output stream.
OutputStreamReader
OutputStreamWriter is similar to InputStreamReader. The output characters, which are in
Unicode, are converted to the underlying format of the machine using an
OutputStreamWriter. The converted characters are written to an OutputStream. The
underlying default format is typically ASCII. However, you can state a specific encoding
scheme with an alternate constructor.
Buffering
Buffering is used to increase the performance of write and read operations.
A program can convert an unbuffered stream into a buffered stream using the wrapping,
where the unbuffered stream object is passed to the constructor for a buffered stream
class, for example,
To improve your efficiency, you read from the object of BufferedInputStream instead of
reading directly from the underlying InputStream. And you will not have to go back to the
operating system to read individual bytes. See Fig. 6:
Fig. 6: Buffering
Here is an example of using the BufferedInputStream, note how similar it is with the
previous example when InputStreamReader is replaced by BufferedInputStream:
import java.io.*;
public class BufIn{
public static void main(String argv[]){
try{
FileInputStream fin = new FileInputStream("c:\BufIn.java");
BufferedInputStream bin = new BufferedInputStream(fin);
int ch=0;
Fig. 7: BufferedOutputStream
BufferedReader and BufferedWriter
A BufferedReader and a BufferedWriter act like BufferedOutputStream and
BufferedInputStream, except they deal with reading and writing characters. For a
BufferedReader, you specify an underlying Reader and optionally a buffer size. For a
BufferedWriter, you specify an underlying Writer and optionally a buffer size.
BufferedReader has one additional method, called readLine(), which allows us to simply
read an entire line of characters from the underlying Reader.
Serialization
Serialization of a class is enabled by the class implementing the java.io.Serializable
interface. Classes that do not implement this interface will not have any of their state
serialized or deserialized. All subtypes of a serializable class are themselves serializable.
import java.io.*;
public class Student implements Serializable
{
int roll;
String name;
transient String phone;
}
The ObjectOutputStream class
For example to write an object of the student class into a file that can be read by the
example in ObjectInputStream:
import java.io.*;
Sample code for reading the object stored in the previous example:
import java.io.*;
public class ObjectReader
{
public static void main(String []s) throws Exception
{
File f=new File("C:/Demo.txt");
FileInputStream fis = new FileInputStream(f);
ObjectInputStream oos = new ObjectInputStream(fis);
Object ob=oos.readObject();
Student st=(Student)ob;
System.out.println("The roll is " + st.roll);
System.out.println("The name is " + st.name);
System.out.println("The phone number is " + st.phone);//transient member
}
}
Externalizable
Externalizable interface are implemented by a class to give the class complete control over
the format and contents of the stream for an object and its supertypes. These methods
must explicitly coordinate with the supertype to save its state. These methods supercede
customized implementations of writeObject and readObject methods.
Once you learn SQL, you can migrate from one database to another as the SQL is going to
be the same for almost all relational databases.
The purpose of this section of the chapter is to provide the basics of the Structured Query
Language. Some basic points about SQL:
is a Structured Query Language
allows access to a database
is an ANSI standard computer language
can make simple queries to any database
can retrieve the data from database as a result of query
can insert new rows, update existing rows and delete the non-required
rows from tables
can make new tables and other database objects
is portable, so moving from one database to another with little
modification is possible
Is easy to learn
Database drivers are software programs that establish a connection between a client
application and a database. The drivers convert the query made by the application into the
database specific calls and thereby establishing communication. Drivers send SQL
statements generated by the client application to a database server and receive result and
other responses from the server. There are several types of drivers available. Some of them
are discussed below.
Many database servers use vendor specific protocols. In other words, the programmer has
to learn a new language each time, to talk to a different database. Microsoft solved the
problem by providing a common standard for communicating with databases, called Open
Database Connectivity (ODBC).
(See Fig. 1 a database client connected to many databases)
Java applications and applets use JDBC drivers to communicate with database servers.
Java application
JDBC/ODBC Vendor-
Bridge supplied JDBC
ODBC driver driver
Database Database
Ever since the release of JDBC API, a number of JDBC drivers have been developed. These
drivers provide varying levels of capability. JDBC drivers into the following types:
Type1. JDBC-ODBC Bridge plus ODBC Driver
This is a combination of the JDBC-ODBC bridge and an ODBC driver. This driver translates
JDBC calls to ODBC calls and relies on an ODBC driver to communicate with the database.
This driver is included with the JDK. However this driver requires deployment and proper
configuration of an ODBC driver. The bridge is handy for testing, but it is not recommended
for production use. It is a cumbersome solution for both Internet and Intranet because it
needs both the drivers to be installed on the users machine. A block diagram of JDBC-ODBC
bridge is shown in Fig. 3.
Database
Server (C)
Fig. 3: Access to a database by JDBC-ODBC bridge
Type 2. Native API Partly Java Driver
This type of drivers is partly written in Java and partly in the native code. This driver
category consists of drivers that communicate with databases servers in the servers native
protocol. For example, as shown in Fig. 4, an Oracle driver would use the SQL*Net protocol.
Similarly a DB2 driver would use an IBM database protocol. These drivers are implemented
in a combination of binary code and Java, and they must be installed on each client
machines. The only benefit is that its installation is easier than installing both the JDBC-
ODBC bridge and an ODBC driver.
Database
Server (C)
Fig. 5: Access to a database by JDBC-Net pure Java driver
Java Type4
Database JDBC Database
Driver Server
Client Vender Specific
(Pure-
protocol
Java)
Type1: Class.forName("sun.jdbc.odbc.driver.JdbcOdbcDriver");
Type4: Class.forName("oracle.jdbc.driver.OracleDriver");
Type1:
"username","password");
Statement - createStatement()
PreparedStatement - prepareStatement()
CallableStatement - prepareCall()
eg:
Statement vs PreparedStatement
If the same SQL command is executed multiple times in the program, then it is
suggested to use PreparedStatement
PreparedStatement is dynamic
Note: Any SQL command is executed by using above methods but to manage the return
type we need to use the respective methods
eg:
st1.executeQuery("select * from books");
st2.executeQuery();
eg:
st1.close();
st2.close();
7. Close the connection
con.close();
In order to use Type 1 driver to connect to Oracle we need to create DSN which refers to
the Oracle Data base driver.
Open Control Panel -> System and Security -> Administrative Tools->
Data Sources (ODBC) -> Click on Add -> Select the driver "Microsoft ODBC for Oracle" and
click Finish
Username : scott
Click Ok
In Win7/Win8 (64-Bit)
//JdbcType1Demo.java
import java.sql.*;
public class JdbcType1Demo {
public static void main(String[] args) {
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:java1","scott","tiger");
System.out.println("Connected");
con.close();
}catch(Exception e)
}
JDBC Type 4 driver example program
//JdbcType4Demo.java
import java.sql.*;
public class JdbcType4Demo {
public static void main(String[] args) {
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",
"scott","tiger");
System.out.println("Connected");
con.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}
/*
To use Type 4 for oracle, set the classpath to ojdbc14.jar as follows
Right Click on Project (MyProj1) ->Build Path->Configure Build Path ->Click on the tab
Libraries ->
Click on Add External jars -> Select the file ojdbc14.jar from your folder and click Open -
>Click Ok
*/
Statement interface Example
//JdbcStatementDemo
import java.sql.*;
public class JdbcStatementDemo {
public static void main(String[] args) throws SQLException{
Statement st = null;
Connection con = null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
CallableStatement interface
Function vs procedure
A function can return only one value using return statement where as a procedure can
return multiple values using out parameters.
//JdbcCallableStatementDemo1.java
//to call function
import java.sql.*;
public class JdbcCallableStatementDemo1 {
public static void main(String[] args) {
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",
"scott","tiger");
CallableStatement st = con.prepareCall("{call ? := f_get_price(?)}");
st.registerOutParameter(1,Types.INTEGER);
st.setInt(2,111);
st.execute();
int price = st.getInt(1);
System.out.println("price ="+price);
st.close();
con.close();
}catch(Exception e)
{
System.out.println(e);
}
}
}
//JdbcCallableStatementDemo2.java