CORE JAVA J DK 1.5 R.Jerome, Technical Consultant, CalydonTech, [email protected].

211
CORE JAVA JDK 1.5 R . J e r o m e , T e c h n i c a l C o n s u l t a n t , C a l y d o n T e c h , j e r o m e @ c a l y d o n t e c h . c o m

Transcript of CORE JAVA J DK 1.5 R.Jerome, Technical Consultant, CalydonTech, [email protected].

CORE JAVAJDK 1.5

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

m

R.Jerome, Technical Consultant, CalydonTech, [email protected]

In procedural program: Programming logic follows certain procedures

and the instructions are executed one after another.

Data is exposed to the whole program In OOP program:

Unit of program is object, which is nothing but combination of data and code.

It is accessible with in the object and which in turn assures the security of the code.

PROCEDURAL VS OBJECT-ORIENTED

CLASS Class is a template for multiple objects with

similar features and It is a blue print for objects. It defines a type of object according to the

data the object can hold and the operations the object can perform.

Classes are the fundamental units in an object-oriented programming.

We use a class to create objects( instances ). Each instance carries its own data.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

m

Class Instance

Rubber stamp Stamped image

Photographic negative Printed photo

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

OBJECT An object is a software entity( unit ) that

combines a set of data with a set of operations to manipulate that data.

 A class defines a type of object. That is, each object belongs to some class and object is also called as an instance.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mMETHOD

A method is the basic unit of functionality contained in a class.

It contains the executable body that can be applied to specific object of the class.

The functions and subroutines of a procedural language( like C ) are called as methods in an object-oriented language. Like function, a method includes: a name parameters used to input some values( optional ) a return type that gives output to another part of

the program( atleast void) a body of executable code

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

OBJECT CLASS

All classes in JavaTM technology are directly or indirectly derived from the Object class. Some of the subclasses of Object class are - Boolean, Number, Void, Math, String, StringBuffer etc.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mOBJECT'S HASH CODE

Objects in Java have hash codes associated with them.

An object's hash code is a signed number that identifies the object (for example, an instance of the parent class).

An object's hash code may be obtained by using the object's hashCode() method

The method hashCode() is defined in the Object class and is inherited by all Java objects.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mOBJECT'S HASH CODE

class class1{ void sample1(){ System.out.println("Hai"); }}

class class2{ void sample2(){ System.out.println("Bye"); }}

class obj_comparison{

public static void main(String args[]){ class1 object1 = new class1(); class1 object2 = new class1(); class2 object3 = new class2(); System.out.println("hash code 1 = object1.hashCode()); System.out.println("hash code 2 = object2.hashCode()); System.out.println(object1.equals(object2)); object1 = object2; System.out.println(object1.equals(object2)); System.out.println("hash code 1 = object1.hashCode()); System.out.println("hash code 2 = object2.hashCode()); //object1 = object3; // cannot be assigned, coz both the objects are pointing different classes.}}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mVARIABLES

A variable is an item of data used to store the state of objects. A variable has a: data type: The data type indicates the type of

value that the variable can hold. name: The variable name must follow rules for

identifiers. Declaring and Initializing Variables <data type> <name> [=initial value];

Two types of variables in Java: Primitive Variables Reference Variables

Note: Values enclosed in <> are required values, while those values in [] are optional.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

Primitive Variables: Variables with primitive data types such as int or

long. Stores data in the actual memory location of where the variable is present

 Reference Variables: Variables that store the address in the memory

location Points to another memory location where the actual data is present

VARIABLES

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mJAVA'S PRIMITIVE DATA TYPES

boolean 1-bit. May take on the values true and false only. true and false are defined constants of the language and

are not the same as True and False, TRUE and FALSE, zero and nonzero, 1 and 0 or any other numeric value.

Booleans may not be cast into any other type of variable nor may any other variable be cast into a boolean.

byte 1 signed byte (two's complement). It covers values from -

128 to 127. short

2 bytes, signed (two's complement), -32,768 to 32,767 int

4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647.

Like all numeric types ints may be cast into other numeric types (byte, short, long, float, double).

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

long 8 bytes signed (two's complement). Ranges from -

9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

float 4 bytes, IEEE 754. Covers a range from

1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative).

Like all numeric types floats may be cast into other numeric types (byte, short, long, int, double).

double 8 bytes IEEE 754. Covers a range from

4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative).

char 2 bytes, unsigned, Unicode, 0 to 65,535 Chars are not the same as bytes, ints, shorts or Strings.

JAVA'S PRIMITIVE DATA TYPES

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

JAVA'S PRIMITIVE DATA TYPESEx1: Print the Min and Max Limits of Primitive Data Types

public class Main { public static void main(String args[ ] ) {

System.out.println("Min byte value = " + Byte.MIN_VALUE); System.out.println("Max byte value = " + Byte.MAX_VALUE); System.out.println("Min short value = " + Short.MIN_VALUE); System.out.println("Max short value = " + Short.MAX_VALUE); System.out.println("Min int value = " + Integer.MIN_VALUE); System.out.println("Max int value = " + Integer.MAX_VALUE); System.out.println("Min float value = " + Float.MIN_VALUE); System.out.println("Max float value = " + Float.MAX_VALUE); System.out.println("Min double value = " + Double.MIN_VALUE); System.out.println("Max double value = " + Double.MAX_VALUE); }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

JAVA'S PRIMITIVE DATA TYPESEx2: Print the default initial values of Primitive Data Types

public class ClassInitializer1 { static boolean bool; static byte by; static char ch; static double d; static float f; static int i; static long l; static short sh; static String str;

public static void main(String[] args) { System.out.println("bool = " + bool); System.out.println("by = " + by); System.out.println("ch = " + ch); System.out.println("d = " + d); System.out.println("f = " + f); System.out.println("i = " + i); System.out.println("l = " + l); System.out.println("sh = " + sh); System.out.println("str = " + str); }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

OPERATORS

An operator is a symbol that operates on one or more arguments to produce a result.

Operator Type Symbols

Assignment Operators

=

Arithmetic Operators - + * / % ++ --

Relational Operators > < >= <= == !=

Logical Operators && || & | ! ^

Bit wise Operator & | ^ >> >>>

Compound Assignment Operators

+= -= *= /= %= <<= >>= >>>=

Conditional Operator ?:

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

OPERATORSOperator Purpose

+ addition of numbers, concatenation of Strings

+= add and assign numbers, concatenate and assign Strings

- Subtraction

-= subtract and assign

* Multiplication

*= multiply and assign

/ Division

/= divide and assign

% take remainder

%= take remainder and assign

++ increment by one

-- decrement by one

> greater than

>= greater than or equal to

< less than

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

OPERATORSOperator Purpose

<= less than or equal to

! boolean NOT

!= not equal to

&& boolean AND

|| boolean OR

== boolean equals

= Assignment

~ bitwise NOT

?: Conditional

| bitwise OR

|= bitwise OR and assign

^ bitwise XOR

^= bitwise XOR and assign

& bitwise AND

&= bitwise AND and assign

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

OPERATORSOperator Purpose

>> shift bits right with sign extension

>>= shift bits right with sign extension and assign

<< shift bits left

<<= shift bits left and assign

>>> unsigned bit shift right

>>>= unsigned bit shift right and assign

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

LOGICAL OPERATORS

Logical operators return a true or false value based on the state of the Variables. There are six logical operators. They are AND/Logical And (&&), Conditional AND/Boolean Logical And (&), OR/Logical OR (||), Conditional OR/Boolean Logical OR (|), Exclusive OR / Boolean Logical exclusive OR (^) NOT (!)

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

LOGICAL OPERATORS && (logical) and & (boolean logical)

The basic difference between && and & operators is that && supports short-circuit evaluations (or partial evaluations), while & does not.

Given an expression exp1 && exp2 where: && will evaluate the expression exp1, and

immediately return a false value if exp1 is false. If exp1 is false, then the operator never evaluates

exp2 because the result of the operator will be false regardless of the value of exp2.

In contrast, the & operator always evaluates both exp1 and exp2 before returning an answer.

X1 X2 Result

TRUE TRUE TRUE

TRUE FALSE FALSE

FALSE TRUE FALSE

FALSE FALSE FALSE

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

LOGICAL OPERATORS || (logical) and | (boolean logical)

The basic difference between || and | operators is same as && and &

X1 X2 Result

TRUE TRUE TRUE

TRUE FALSE TRUE

FALSE TRUE TRUE

FALSE FALSE FALSE

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

LOGICAL OPERATORS ^ (boolean logical exclusive OR)

X1 X2 Result

TRUE TRUE FALSE

TRUE FALSE TRUE

FALSE TRUE TRUE

FALSE FALSE FALSE

! ( logical NOT)

X1 X2

TRUE FALSE

FALSE TRUE

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

BITWISE OPERATORS Java provides Bit wise operators to manipulate the contents of variables at the bit

level. These variables must be of numeric data type ( char, short, int, or long). Java provides seven bitwise operators. They are AND, OR, Exclusive-OR,

Complement, Left-shift, Signed Right-shift, and Unsigned Right-shift.

A B ~A A & B A | B A ^ B

1 1 0 1 1 0

1 0 0 0 1 1

0 1 1 0 1 1

0 0 1 0 0 0

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

BITWISE OPERATORSEx: Bitwise Operators

public class BitwiseOperatorsDemo {

public BitwiseOperatorsDemo() {int x = 0xFAEF; //1 1 1 1 1 0 1 0 1 1 1 0 1 1 1 1int y = 0xF8E9; //1 1 1 1 1 0 0 0 1 1 1 0 1 0 0 1int z;System.out.println("x & y : " + (x & y));System.out.println("x | y : " + (x | y));System.out.println("x ^ y : " + (x ^ y));System.out.println("~x : " + (~x));System.out.println("x << y : " + (x << y));System.out.println("x >> y : " + (x >> y));System.out.println("x >>> y : " + (x >>> y));//There is no unsigned left shift operator

}public static void main(String args[]) {

new BitwiseOperatorsDemo();}

}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

COMPOUND OPERATORS

Ex: Compound Operator Example

public class CompoundOperatorsDemo {

public CompoundOperatorsDemo() {int x = 0, y = 5;x += 3;System.out.println("x : " + x);y *= x;System.out.println("y : " + y);/*Similarly other operators can be

applied as shortcuts.Other compound assignment operators include boolean logical, bitwiseand shift operators*/

}public static void main(String args[]) {

new CompoundOperatorsDemo();}

}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

CONDITIONAL OPERATORS

Ex: Compound Operator Example

public class TernaryOperatorsDemo {

public TernaryOperatorsDemo() {int x = 10, y = 12, z = 0;z = x > y ? x : y;System.out.println("z : " + z);

}public static void main(String args[]) {

new TernaryOperatorsDemo();}

}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

ESCAPE SEQUENCES

Escape Sequence Description

\t Insert a tab in the text at this point.

\b Insert a backspace in the text at this point.

\n Insert a newline in the text at this point.

\r Insert a carriage return in the text at this point.

\f Insert a formfeed in the text at this point.

\' Insert a single quote character in the text at this point.

\" Insert a double quote character in the text at this point.

\\ Insert a backslash character in the text at this point.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

OPERATOR PRECEDENCEOperator Presedence

postfix [] . () expr++ expr– -

unary ++expr - - expr +expr -expr !

creation/caste new (type)expr

multiplicative * / %

additive + -

shift >> >>>

relational < ,<= > >= instanceof

equality == !=

bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

logical AND &&

logical OR ||

ternary ?:

assignment = “op=”

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

WRAPPER CLASS Wrapper class is a wrapper around a primitive data type. It represents primitive data types in their corresponding class

instances These classes will be in java.lang package

Primitive type Wrapper class Constructor Arguments

byte Byte byte or String

short Short short or String

int Integer int or String

long Long long or String

float Float float, double or String

double Double double or String

char Character char

boolean Boolean boolean or String

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

WRAPPER CLASS In Java 5.0 version, additional wrapper classes were introduced

in the java.util.concurrent.atomic package. They provide atomic operations for assignment, addition and

increment. These classes act like variables  and cannot be used as a

substitute for the regular wrapper classes. Few of these new wrapper classes like AtomicInteger and

AtomicLong are the subclasses of the Number Classes. Features

All the methods of the wrapper classes are static. The Wrapper class does not contain constructors. Once a value is assigned to a wrapper class instance it can not be

changed, anymore.

Primitive Wrapper

boolean   AtomicBoolean

int   AtomicInteger

long   AtomicLong

V   AtomicReference<V>

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

WRAPPER CLASS

Ex1: Simple Example for Integer

import java.io.*;import java.lang.Integer.*;public class boxing{ public static void main(String args[]) { short x = 10; int y = (int)x; System.out.println(y);

int x = 3; Integer Ix = x; System.out.println(Ix); }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

WRAPPER CLASSEx2: Integer To Numeric Primitive Types Example

public class boxing // { public static void main(String[] args) { int a=10; Integer intObj = new Integer(a); byte b = intObj.byteValue(); //use byteValue method of Integer class to convert it into byte type. System.out.println(b); short s = intObj.shortValue(); //use shortValue method of Integer class to convert it into short type. System.out.println(s); int i = intObj.intValue(); //use intValue method of Integer class to convert it into int type. System.out.println(i); float f = intObj.floatValue(); //use floatValue method of Integer class to convert it into float type. System.out.println(f); double d = intObj.doubleValue(); //use doubleValue method of Integer class to convert it into double type. System.out.println(d); }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

WRAPPER CLASSEx2: Integer To Numeric Primitive Types Example

class conversion{

public static void main(String args[]){

byte b;int i=257;

double d= 3.142;

System.out.println("\n conversion of int to byte.");b=(byte)i;System.out.println("i and b "+i+ " "+b);

System.out.println("\n conversion of double to int.");i=(int) d;System.out.println("d and i "+d+ " "+i);

System.out.println("\n conversion of double to byte");b=(byte) d;System.out.println("d and b"+d+ " "+b);d=(double)i;

System.out.println("\n conversion of integer to double");System.out.println("i and d"+i+" "+d);

}}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

CONTROL STRUCTURES & LOOPS

If loop If-else loop If-else-if loop Muliple if loop Switch case While loop For loop Do-while loop

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mMETHODS

Syntax

returnType methodName( /* argument list */ ) { /* Method body */ }

static keyword: When you say something is static, it means that data or

method is not tied to any particular object instance of that class.

So even if you’ve never created an object of that class you can call a static method or access a piece of static data

Accessor(Getter) and Mutator(Setter) Method:ExampleClass Test{ private String name; public void setName(String temp){ name=temp; } public String getName(){ return name; }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

NESTED CLASSSyntax

class OuterClass { ... static class StaticNestedClass { ... } class InnerClass { ... }}

The Java programming language allows you to define a class within another class. Such a class is called a nested class

Classified as static and non-static. Nested classes that are declared static are simply called static

nested classes. Non-static nested classes are called inner classes. Non-static nested classes (inner classes) have access to other

members of the enclosing class, even if they are declared private

Static nested classes do not have access to other members of the enclosing class.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

WHY NESTED CLASS

Logical grouping of classes If a class is useful to only one other class, then it is logical to

embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.

Increased encapsulation Consider two top-level classes, A and B, where B needs

access to members of A that would otherwise be declared private.

By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

More readable, maintainable code Nesting small classes within top-level classes places the

code closer to where it is used.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

NESTED CLASSExample

class NestedClass{String Message="Hello I am OuterClass";void printdata(){System.out.println(Message);}

static class StaticClass{void printdata(){//System.out.println(Message+"static inner");-->ErrorSystem.out.println("static inner");}}

class InnerClass{void printdata(){System.out.println(Message+"in inner");}}

public static void main(String a[]){NestedClass obj1=new NestedClass();obj1.printdata();//obj1.StaticClass.printdata();-->error//InnerClass obj2=new InnerClass();-->errorNestedClass.InnerClass obj2=obj1.new InnerClass();//NestedClass.InnerClass obj2=new NesteedClass.InnerClass();obj2.printdata();StaticClass obj3=new StaticClass();obj3.printdata();NestedClass.StaticClass obj4=new NestedClass.StaticClass();obj4.printdata();}}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

CONSTRUCTOR

Every class must have at least one constructor. If there is no constructors for your class, the compiler will supply

a default constructor(no-arg constructor). A constructor is used to construct an object. A constructor looks like a method and is sometimes called a

constructor method. A constructor never returns a value A constructor always has the same name as the class. A constructor may have zero argument, in which case it is called

a no-argument constructor. Constructor arguments can be used to initialize the fields in the

object.

Example 1class Rock { Rock() { System.out.println("Creating Rock"); }}public class SimpleConstructor { public static void main(String[] args) { for (int i = 0; i < 10; i++) new Rock(); }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

CONSTRUCTOR

Example 2class Rock2 { Rock2(int i) { System.out.println("Creating Rock number " + i); }}

public class SimpleConstructor2 { public static void main(String[] args) { for (int i = 0; i < 10; i++) new Rock2(i); }}

Example 3: Constructor Overloadingpublic class MainClass { double radius; MainClass() { }

// Class constructor MainClass(double theRadius) { radius = theRadius; }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mPOLYMORPHISM

As we know that a method has its own signature which is known by method's name and the parameter types.

Java has a powerful feature which is known as method overloading. With the help of this feature we can define two methods of same name with different parameters.

It allows the facility to define that how we perform the same action on different type of parameter.

Polymorphism achieved by both overloading and overriding. Overloading is static where as Overriding is dynamic.

In case of overloading which method will be called is known to compiler at compile time but in case of overriding only in run-time the appropriate method will be called.

Polymorphism is the capability of an action or method to do different things based on the object that it is acting upon.

In other words, polymorphism allows you define one interface and have multiple implementations.

This is one of the basic principles of object oriented programming.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

CONSTRUCTORExample 4: this()

class Sphere { int radius = 0; Sphere() { radius = 1; } Sphere(int radius) { this.radius = radius; }}

Example 5: Calling a Constructor From a Constructorclass Sphere { int radius = 0; double xCenter; double yCenter; double zCenter; Sphere() { radius = 1; }

Sphere(double x, double y, double z) { this(); xCenter = x; yCenter = y; zCenter = z; } Sphere(int theRadius, double x, double y, double z) { this(x, y, z); radius = theRadius; }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

METHOD OVERLOADINGExample 6

class over{void test(){

System.out.println("no parameters"); }

void test(int a){System.out.println("a:"+a); }

void test(int a,int b){System.out.println("a and b:"+a+""+b); }

double test(double a){System.out.println("double a:"+a);return a*a;

}}

class overload{public static void main(String args[]) {

over a=new over();double result;a.test();a.test(10);a.test(10,20);result=a.test(12.6);

System.out.println("result of a.test(12.6) is:"+result);}

}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mACCESS MODIFIERS

You can define the scope of a variable or method or class by using access modifiers. Public Protected Default Private

Modifier Class Package Subclass World

public Y Y Y Y

protected Y Y Y N

no modifier (default)

Y Y N N

private Y N N N

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

INHERITANCE It is one of the most important feature of Object Oriented

Programming. It is the concept that is used for reusability purpose. Inheritance is the mechanism through which we can derived

classes from other classes. The derived class is called as child class or the subclass or we

can say the extended class and the class from which we are deriving the subclass is called the base class or the parent class.

To derive a class in java the keyword extends is used. e.g. When we hear the word vehicle then we got an image in

our mind that it moves from one place to another place it is used for traveling or carrying goods but the word vehicle does not specify whether it is two or three or four wheeler because it is a general word. But the word car makes a more specific image in mind than vehicle, that the car has four wheels . It concludes from the example that car is a specific word and vehicle is the general word. If we think technically to this example then vehicle is the super class (or base class or parent class) and car is the subclass or child class because every car has the features of it's parent (in this case vehicle) class.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

INHERITANCE Types of inheritance

Simple Inheritance Multilevel Inheritance

Simple Ex1: Simpleclass A {  int x;  int y;  int get(int p, int q){    x=p; y=q; return(0);    }    void Show(){      System.out.println(x);      }}class B extends A{  public static void main(String args[]){    A a = new A();    a.get(5,6);    a.Show();    }    void display(){      System.out.println("B");      }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

INHERITANCEMultilevel Ex2: Multilevel

class A {  int x;  int y;  int get(int p, int q){    x=p; y=q; return(0);    }    void Show(){      System.out.println(x);      }}class B extends A{  void Showb(){    System.out.println("B");    }}

class C extends B{  void display(){    System.out.println("C");  }  public static void main(String args[]){    A a = new A();    a.get(5,6);    a.Show();    }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

INHERITANCE super keyword

As the name suggest super is used to access the members of the super class. It is used for two purposes in java.

First: To access the hidden data variables of the super class hidden by the sub class.

Second: To call super class constructor in the subclass

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

INHERITANCEEx1: super keywordclass A{ int a; float b; void Show(){ System.out.println("b in super class: " + b); }}class B extends A{ int a; float b; B( int p, float q){ a = p; super.b = q; } void Show(){ super.Show(); System.out.println("b in super class: " + super.b); System.out.println("a in sub class: " + a); } public static void main(String[] args){ B subobj = new B(1, 5); subobj.Show(); }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

INHERITANCEEx2: Simpleclass A{ int a; int b; int c; A(int p, int q, int r){ a=p; b=q; c=r; }} class B extends A{ int d; B(int l, int m, int n, int o){ super(l,m,n); d=o; } void Show(){ System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); } public static void main(String args[]){ B b = new B(4,3,8,7); b.Show(); } }

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

INHERITANCE - OVERRIDING Overriding means to override the functionality of

any existing method. The argument list should be exactly the same as

that of the overridden method. The return type should be the same or a subtype of

the return type declared in the original overridden method in the super class.

The access level cannot be more restrictive than the overridden method's access level. For example: if the super class method is declared public then the overriding method in the sub class cannot be either private or public. However the access level can be less restrictive than the overridden method's access level.

Instance methods can be overridden only if they are inherited by the subclass.

A method declared final cannot be overridden.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

INHERITANCE - OVERRIDING A method declared static cannot be overridden but

can be re-declared. If a method cannot be inherited then it cannot be

overridden. A subclass within the same package as the instance's

super class can override any super class method that is not declared private or final.

A subclass in a different package can only override the non-final methods declared public or protected.

An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overridden method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.

Constructors cannot be overridden.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

INHERITANCE - OVERRIDINGEx1: class Animal{

public void move(){ System.out.println("Animals can move"); }}class Dog extends Animal{

public void move(){ System.out.println("Dogs can walk and run"); }}public class TestDog{

public static void main(String args[]){ Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object

a.move();// runs the method in Animal class b.move();//Runs the method in Dog class }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

INHERITANCE - OVERRIDINGEx2: class Animal{

public void move(){ System.out.println("Animals can move"); }}

class Dog extends Animal{

public void move(){ System.out.println("Dogs can walk and run"); } public void bark(){ System.out.println("Dogs can bark"); }}

public class TestDog{

public static void main(String args[]){ Animal a = new Animal(); // Animal reference and object Animal b = new Dog(); // Animal reference but Dog object a.move();// runs the method in Animal class b.move();//Runs the method in Dog class //b.bark(); Error because its an object of Animal. }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

INHERITANCE - OVERRIDINGEx3: class Animal{

public void move(){ System.out.println("Animals can move"); }}

class Dog extends Animal{

public void move(){ super.move(); // invokes the super class method System.out.println("Dogs can walk and run"); }

}

public class TestDog{

public static void main(String args[]){

Animal b = new Dog(); // Animal reference but Dog object b.move();//Runs the method in Dog class

}}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

INTERFACES

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

ABSTRACT CLASSES

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mEXCEPTIONS

Exception, that means exceptional errors. Actually exceptions are used for handling errors in programs that occurs during the program execution

Exceptions in java are any abnormal, unexpected events or extraordinary conditions that may occur at runtime.

On such conditions java throws an exception object An exception can occur for many different reasons

A user has entered invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of

communications. The JVM has run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mCATEGORIES OF EXCEPTIONS

Checked or Compile Time Exceptions A checked exception is an exception that is typically a

user error or a problem that cannot be foreseen by the programmer.

For example, if a file is to be opened, but the file cannot be found, an exception occurs.

Un Checked or Runtime exceptions A runtime exception is an exception that occurs that

probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions

are ignored at the time of compilation. Errors

These are not exceptions at all, but problems that arise beyond the control of the user or the programmer.

Errors are typically ignored in your code because you can rarely do anything about an error.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mEXCEPTION HIERARCHY

An exception is a subclass of the Exception class, which are subclasses of the Throwable Interface.

Java exceptions are raised with the throw keyword and handled within a catch block.

Java defines several exception classes inside the standard package java.lang

The most general of these exceptions are subclasses of the standard type RuntimeException

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mLIST OF UNCHECKED OR RUNTIME EXCEPTIONS

Exception Description

ArithmeticException Arithmetic error, such as divide-by-zero.

ArrayIndexOutOfBoundsException

Array index is out-of-bounds.

ArrayStoreException Assignment to an array element of an incompatible type.

ClassCastException Invalid cast.

IllegalArgumentException Illegal argument used to invoke a method.

IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.

IllegalStateException Environment or application is in incorrect state.

IllegalThreadStateException Requested operation not compatible with current thread state.

IndexOutOfBoundsException Some type of index is out-of-bounds.

NegativeArraySizeException Array created with a negative size.

NullPointerException Invalid use of a null reference.

NumberFormatException Invalid conversion of a string to a numeric format.

SecurityException Attempt to violate security.

StringIndexOutOfBounds Attempt to index outside the bounds of a string.

UnsupportedOperationException An unsupported operation was encountered.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mLIST OF CHECKED OR COMPILETIME EXCEPTIONS

Following is the list of Java Checked Exceptions Defined in java.lang.

Exception Description

ClassNotFoundException Class not found.

CloneNotSupportedExceptionAttempt to clone an object that does not implement the Cloneable interface.

IllegalAccessException Access to a class is denied.

InstantiationExceptionAttempt to create an object of an abstract class or interface.

InterruptedExceptionOne thread has been interrupted by another thread.

NoSuchFieldException A requested field does not exist.

NoSuchMethodException A requested method does not exist.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mEXCEPTION METHODS

Following is the list of important methods available in the Throwable class.

public String getMessage()

Returns a detailed message about the exception that has occurred. This message is

initialized in the Throwable constructor.

public Throwable getCause()

Returns the cause of the exception as represented by a Throwable object.

public String toString()

Returns the name of the class concatenated with the result of getMessage()

public void printStackTrace()

Prints the result of toString() along with the stack trace to System.err, the error output

stream.

public StackTraceElement [] getStackTrace()

Returns an array containing each element on the stack trace. The element at index 0

represents the top of the call stack, and the last element in the array represents the

method at the bottom of the call stack.

public Throwable fillInStackTrace()

Fills the stack trace of this Throwable object with the current stack trace, adding to any

previous information in the stack trace.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mCATCHING EXCEPTIONS

A method catches an exception using a combination of the try and catch keywords.

A try/catch block is placed around the code that might generate an exception.

Code within a try/catch block is referred to as protected code

If an exception occurs in protected code, the catch block that follows the try is checked.

try{ //Protected code}catch(ExceptionName e1){ //Catch block}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mCATCHING EXCEPTIONS

Ex1:public static void main(String[] args) { int i, j, numer1 = 5, denom1 = 5, denom2 = 0; try { i = numer1/denom1; System.out.println("numer1/denom1 = " + i); j = numer1/denom2; System.out.println("numer1/denom2 = " + j); } catch(ArithmeticException e) { System.out.println("Arithmetic Exception!"); } System.out.println("Done with test"); }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

CATCHING EXCEPTIONSEx2:public class exception_handling{ public static void main (String args[]) { int array[]={10,20,30}; int num1=15, num2=10; int result=0; try { result = num1/num2; System.out.println("The Answer is" +result); for(int count =0;count <=4; count++) { System.out.println("The value of array are" +array[count]); } } catch (ArrayIndexOutOfBoundsException e) {System.out.println("Error.... Array is out of Bounds"); } catch (ArithmeticException e) { System.out.println ("Sorry.....Can't be divided by Zero"); }}}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mFINALLY BLOCK

A finally block is always executed, regardless of the cause of exit from the try block, or whether any catch block was executed.

Generally finally block is used for freeing resources, cleaning up, closing connections etc.

try { <code>} catch (<exception type1> <parameter1>) { // 0 or more <statements>}} finally { // finally block <statements>}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

FINAL BLOCK EXAMPLEEx3:public class DivideException2 { public static void main(String[] args) { int result = division(100,0); // Line 2 System.out.println("result : "+result); } public static int division(int totalSum, int totalNumber) { int quotient = -1; System.out.println("Computing Division."); try{ quotient = totalSum/totalNumber;

} catch(Exception e){ System.out.println("Exception : "+ e.getMessage()); } finally{ if(quotient != -1){ System.out.println("Finally Block Executes"); System.out.println("Result : "+ quotient); }else{System.out.println("Finally Block Executes. Exception Occurred"); return quotient; } } return quotient; }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

RULES FOR TRY, CATCH AND FINALLY BLOCKS

For each try block there can be zero or more catch blocks, but only one finally block.  

The catch blocks and finally block must always appear in conjunction with a try block. 

A try block must be followed by either at least one catch block or one finally block. 

The order exception handlers in the catch block must be from the most specific exception

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mTHE THROWS/THROW KEYWORDS If a method does not handle a checked exception,

the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.

You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Try to understand the different in throws and throw keywords.

import java.io.*;public class className{ public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } //Remainder of class definition}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mTHE THROWS/THROW KEYWORDS A method can declare that it throws more than

one exception, in which case the exceptions are declared in a list separated by commas.

For example, the following method declares that it throws a RemoteException and an InsufficientFundsException

import java.io.*;public class className{ public void withdraw(double amount) throws RemoteException, InsufficientFundsException { // Method implementation } //Remainder of class definition}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mDECLARING YOU OWN EXCEPTION Keep the following points in mind when

writing your own exception classes All exceptions must be a child of Throwable. If you want to write a checked exception that

is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.

If you want to write a runtime exception, you need to extend the RuntimeException class.

class MyException extends Exception{}

DECLARING YOU OWN EXCEPTIONR

.Jero

me, Te

chnica

l Consu

ltant, C

aly

donTe

ch, je

rom

e@

caly

donte

ch.co

m

Ex4:

// File Name InsufficientFundsException.javaimport java.io.*;

public class InsufficientFundsException extends Exception{ private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; }}

DECLARING YOU OWN EXCEPTIONR

.Jero

me, Te

chnica

l Consu

ltant, C

aly

donTe

ch, je

rom

e@

caly

donte

ch.co

mEx4:

// File Name CheckingAccount.javaimport java.io.*;public class CheckingAccount{ private double balance; private int number; public CheckingAccount(int number) { this.number = number; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) throws InsufficientFundsException { if(amount <= balance) { balance -= amount; } else { double needs = amount - balance; throw new InsufficientFundsException(needs); } } public double getBalance() { return balance; } public int getNumber() { return number; }}

DECLARING YOU OWN EXCEPTIONR

.Jero

me, Te

chnica

l Consu

ltant, C

aly

donTe

ch, je

rom

e@

caly

donte

ch.co

mEx4:

// File Name BankDemo.javapublic class BankDemo{ public static void main(String [] args) { CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500..."); c.deposit(500.00); try { System.out.println("\nWithdrawing $100..."); c.withdraw(100.00); System.out.println("\nWithdrawing $600..."); c.withdraw(600.00); }catch(InsufficientFundsException e) { System.out.println("Sorry, but you are short $" + e.getAmount()); e.printStackTrace(); } }}

DECLARING YOU OWN EXCEPTIONR

.Jero

me, Te

chnica

l Consu

ltant, C

aly

donTe

ch, je

rom

e@

caly

donte

ch.co

mEx5:

class BadTemperature extends Exception{BadTemperature( String reason ){

super ( reason ); }}class TooHot extends BadTemperature{

TooHot(){super ("Default messaeg : Hot");

}TooHot(String message){

super (message); }}class TooCold extends BadTemperature{

TooCold(){super ("Default messaeg : Cold");

}TooCold(String message){

super (message); }}

DECLARING YOU OWN EXCEPTIONR

.Jero

me, Te

chnica

l Consu

ltant, C

aly

donTe

ch, je

rom

e@

caly

donte

ch.co

mEx5:

class TempertureObject{ int temperature;

TempertureObject( int temp ) { temperature = temp; } void test() throws TooHot, TooCold { if ( temperature < 70 ) throw new TooCold("Very Cold"); if ( temperature > 80 ) throw new TooHot("Very Hot"); }}public class ExceptionExample1{ private static void temperatureReport( TempertureObject batch ){

try{ batch.test(); System.out.println( "Perfect Temperature" ); } catch ( BadTemperature bt ){ System.out.println( bt.getMessage( ) ); } } public static void main( String[] args ){ temperatureReport( new TempertureObject( 100 ) ); temperatureReport( new TempertureObject( 50 ) ); temperatureReport( new TempertureObject( 75 ) ); }}

USING BREAK AND RETURN WITH EXCEPTIONSR

.Jero

me, Te

chnica

l Consu

ltant, C

aly

donTe

ch, je

rom

e@

caly

donte

ch.co

mEx6:

public class ExceptionExample6 {public static void main(String[] args) {

int x = 10, y = 2;int counter = 0;boolean flag = true;while (flag) {start:try {

if ( y > 1 )break start;

if ( y < 0 )return;

x = x / y;System.out.println ( "x : " + x + " y : "+y );}catch ( Exception e ) {

System.out.println ( e.getMessage() );}finally {

++counter;System.out.println ( "Counter : " + counter );}--y;

}}}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mJAVA I/O

Java I/O Operations are done by Standard Streams.

They read input from the keyboard and write output to the display.

They also support I/O operations on files. Java also supports three Standard Streams

Standard Input: Accessed through System.in which is used to read

input from the keyboard. Standard Output:

Accessed through System.out  which is used to write output to be display.

Standard Error: Accessed through System.err which is used to write

error output to be display.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mJAVA I/O

Standard Output and Standard Error, both are to write output; having error output separately so that the user may read error messages efficiently.

System.in is a byte stream that has no character stream features.

The java.io package contains two classes, InputStream and OutputStream

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mINPUTSTREAM

The InputStream class is an abstract base class

The InputStream class defines a methods for reading bytes or arrays of bytes, marking locations in the stream, skipping bytes of input, finding out the number of bytes that are

available for reading, resetting the current position within the stream.

An input stream is automatically opened when you create it.

You can explicitly close a stream with the close() method, or let it be closed implicitly when the object is garbage collected.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mINPUTSTREAM

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mOUTPUTSTREAM

The OutputStream class is an abstract base class.

OutputStream defines methods for writing bytes or arrays of bytes to the stream and flushing the stream.

An output stream is automatically opened when you create it.

You can explicitly close an output stream with the close() method, or let it be closed implicitly when the object is garbage collected.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mOUTPUTSTREAM

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

OVERVIEW OF INPUT & OUTPUT STREAMS

FileInputStream and FileOutputStream Used to read data from or write data to a file on the native

file system. PipedInputStream and PipedOutputStream

Implements the input and output components of a pipe. Pipes are used to channel the output from one program (or thread or code block) into the input of another.

A PipedInputStream must be connected to a PipedOutputStream and vice versa.

ByteArrayInputStream and ByteArrayOutputStream Reads data from or writes data to a byte array in memory.

SequenceInputStream Concatenates multiple input streams into one input

stream. StringBufferInputStream

Allows programs to read from a StringBuffer as if it were an input stream.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mOVERVIEW OF FILTERED STREAMS

DataInputStream and DataOutputStream Reads or writes primitive Java data types in a

machine independent format. BufferedInputStream and

BufferedOutputStream This is an efficient stream that buffers data while

reading or writing. LineNumberInputStream

An input stream that keeps track of line numbers while reading.

PushbackInputStream An input stream with a one-byte pushback buffer.

PrintStream An output stream with convenient printing methods.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

INPUTSTREAM METHODS

Method Summary

 intavailable()           Returns the number of bytes that can be read (or skipped over) from this input stream without blocking by the next caller of a method for this input stream.

 voidclose()           Closes this input stream and releases any system resources associated with the stream.

 voidmark(int readlimit)           Marks the current position in this input stream.

 booleanmarkSupported()           Tests if this input stream supports the mark and reset methods.

abstract  intread()           Reads the next byte of data from the input stream.

 intread(byte[] b)           Reads some number of bytes from the input stream and stores them into the buffer array b.

 intread(byte[] b, int off, int len)           Reads up to len bytes of data from the input stream into an array of bytes.

 voidreset()           Repositions this stream to the position at the time the mark method was last called on this input stream.

 longskip(long n)           Skips over and discards n bytes of data from this input stream.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mOUTPUTSTREAM METHODS

Method Summary void close()

          Closes this output stream and releases any system resources associated with this stream.

 void flush()           Flushes this output stream and forces any buffered output bytes to be written out.

 void write(byte[] b)           Writes b.length bytes from the specified byte array to this output stream.

 void write(byte[] b, int off, int len)           Writes len bytes from the specified byte array starting at offset off to this output stream.

abstract  void write(int b)           Writes the specified byte to this output stream.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

WORKING WITH READER CLASSES Java provides the standard I/O facilities for reading

text from either the file or the keyboard on the command line.

The Reader class is used for this purpose that is available in the java.io package.

It acts as an abstract class for reading character streams.

The only methods that a subclass must implement are read(char[], int, int) and close().

The following diagram shows a class-hierarchy of the java.io.Reader class.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

INPUTSTREAMREADER

An InputStreamReader is a bridge from byte streams to character streams i.e. it reads bytes and decodes them into Unicode characters according to a particular platform.

When you create an InputStreamReader, you specify an InputStream from which, the InputStreamReader reads the bytes.

The syntax of InputStreamReader is written as:InputStreamReader <obj_name> = new InputStreamReader(System.in)

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mINPUTSTREAMREADER

Ex1:

import java.io.*;

public class TrivialApplication {

public static void main ( String args[] ) throws IOException {

InputStreamReader input = new InputStreamReader(System.in);

int ch;

String st;

System.out.println("enter a character and push enter");

ch = input.read();

System.out.println("Character value " +(char) ch);

}

} // Application

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

INPUTSTREAMREADEREx2:

import java.io.*;

public class TrivialApplication {

private static final int MAX = 10;

public static void main ( String args[] ) throws IOException {

InputStreamReader input = new InputStreamReader(System.in);

int i;

int ch[ ];

ch = new int [MAX];

System.out.println("write a line of length " + MAX + " push enter");

for (i = 0 ; i < ch.length ; i++){

ch[i] = input.read();

}

for (i = 0 ; i < ch.length ; i++){

System.out.print((char) ch[i]); // write out the array of characters.

}

}

}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

INPUTSTREAMREADEREx3:

import java.io.*;

public class TrivialApplication {

private static final int MAX = 10;

public static void main ( String args[] ) throws IOException {

int i;

byte ch[ ];

ch = new byte [MAX];

System.out.println("write a line of length " + MAX + " push enter");

System.in.read(ch );

for (i = 0 ; i < ch.length ; i++){

System.out.print((char) ch[i]);

}

}

}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

BUFFEREDREADER Creating an instance of BufferedReader allocates memory

storage for data input. The primary need for BufferedsReader is that it makes data

input, which could be a very inefficient process into a more efficient process.

"In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream." This could lead to many reading steps, and reading is one of the slowest aspects of computer processing.

The Buffered reader allows for one reading step by providing data input storage which can then be accessed efficiently.

"The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.“InputStreamReader dave = new InputStreamReader(System.in);

BufferedReader br = new BufferReader(dave);

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

BUFFEREDREADEREx1:

import java.io.*;

class Factorial{

public static void main(String[] args) {

try{

BufferedReader object = new BufferedReader(new

InputStreamReader(System.in));

System.out.println("enter the number");

int a= Integer.parseInt(object.readLine());

int fact= 1;

System.out.println("Factorial of " +a+ ":");

for (int i= 1; i<=a; i++){

fact=fact*i;

}

System.out.println(fact);

}

catch (Exception e){}

}

}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mUSING STREAMS TO READ AND WRITE FILES

Ex1:import java.io.*;class FileStreamsTest { public static void main(String args[]) {

try {FileInputStream fis = new FileInputStream(“in.txt");FileOutputStream fos = new FileOutputStream(“out.txt");

int c; while ((c = fis.read()) != -1) { fos.write(c); } fis.close(); fos.close();} catch (FileNotFoundException e) { System.err.println("FileStreamsTest: " + e);} catch (IOException e) { System.err.println("FileStreamsTest: " + e);}

}}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

USING STREAMS TO READ AND WRITE FILESEx2:

public class Application { public Application ( ) throws IOException{ BufferedReader br = new BufferedReader(new FileReader(new File("test.dat"))); BufferedWriter out = new BufferedWriter(new FileWriter(new File("output.dat")));

String c=""; while(true){ if( (c=br.readLine()) == null)

break; else{

out.writeLine(c); }

} //while out.flush(); br.close(); out.close(); } public static void main(String args[]) throws IOException{

new Application(); }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

FILES The File class deals with the machine dependent files in a

machine-independent manner i.e. it is easier to write platform-independent code that examines and manipulates files using the File class.

This class is available in the java.lang package. The java.io.File is the central class that works with files and directories.

The instance of this class represents the name of a file or directory on the host file system. 

When a File object is created, the system doesn't check to the existence of a corresponding file/directory.

If the file exists, a program can examine its attributes and perform various operations on the file, such as renaming it, deleting it, reading from or writing to it.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

FILES The constructors of the File class are shown in the

table File(path)

 Create File object for default directory (usually where program is located).

 File(dirpath,fname)  Create File object for directory path given as string.

 File(dir, fname)  Create File object for directory.

The Methods of the File class are shown in the table

 Method  Description

 f.exists()  Returns true if file exists.

 f.isFile()  Returns true if this is a normal file.

 f.isDirectory()  true if "f" is a directory.

 f.getName()  Returns name of the file or directory.

 f.isHidden()  Returns true if file is hidden.

 f.lastModified()  Returns time of last modification.

 f.length()  Returns number of bytes in file.

 f.getPath()  path name.

 f.delete()  Deletes the file.

 f.renameTo(f2)  Renames f to File f2. Returns true if successful.

 f.createNewFile()  Creates a file and may throw IOException. 

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

FILESEx1:

import java.io.*;

public class CreateFile1{

public static void main(String[] args) throws IOException{

//File f=new File("C:/Program

Files/Java/jdk1.6.0_06/bin/filsfolder/sample_file.txt");

File f=new File("sample_file.txt");

if(!f.exists()){

f.createNewFile();

System.out.println("New file sample_file.txt has been

created.");

}

}

}

FILESR

.Jero

me, Te

chnica

l Consu

ltant,

Caly

donTe

ch,

jero

me@

caly

donte

ch.co

mEx2:import java.io.File;class dir{

public static void main(String args[]){String dirname="/java";File f1= new File(dirname);if(f1.isDirectory()){System.out.println("Directory of"+dirname);String s[] =f1.list();for(int i=0;i<s.length;i++){File f= new File(dirname +"/"+s[i]);if(f.isDirectory()){

System.out.println(s[i]+"is a directory");}else{

System.out.println(s[i]+"is a file");}

}}else {

System.out.println(dirname +"is not a directory");}

}}

FILESR

.Jero

me, Te

chnica

l Consu

ltant,

Caly

donTe

ch,

jero

me@

caly

donte

ch.co

mEx3:import java.io.File;class filedemo{

static void p(String s){System.out.println(s);

}public static void main(String args[]) {

File f1= new File("/java/COPYRIGHT");p("File Name:"+f1.getName());p("path: "+f1.getPath());p("Abs path:"+f1.getAbsolutePath());p(f1.exists() ? "exists":"does not exist");p(f1.canWrite() ? "is writeable":"is not writeable");p(f1.canRead() ?"is readable" :"is not readable");p("is" +(f1.isDirectory() ?"":"not"+"a directory"));p(f1.isFile()?"is normal file":"might be a named

pipe");p(f1.isAbsolute()?"is absolute":"is not absolute");p("File last modifide:"+f1.lastModified());p("FileSize:"+f1.length()+"Bytes");

}}

FILESR

.Jero

me, Te

chnica

l Consu

ltant,

Caly

donTe

ch,

jero

me@

caly

donte

ch.co

mEx4:import java.io.*;

public class ReadFile{ public static void main(String[] args) throws IOException{ File f=new File("C:/Program Files/Java/jdk1.6.0_06/bin/filsfolder/sample_file.txt");

if(!f.exists()&& f.length()<0) System.out.println("The specified file is not exist or nothing in your file");

else{ FileInputStream finp=new FileInputStream(f); byte b; do{ b=(byte)finp.read(); System.out.print((char)b); } while(b!=-1); finp.close(); } } }

FILESR

.Jero

me, Te

chnica

l Consu

ltant,

Caly

donTe

ch,

jero

me@

caly

donte

ch.co

mEx5:import java.io.*;

public class WriteFile{

public static void main(String[] args) throws IOException{

File f=new File("C:/Program Files/Java/jdk1.6.0_06/bin/filsfolder/sample_file.txt"); FileOutputStream fop=new FileOutputStream(f);

if(f.exists()){ String str="How are you babe?"; fop.write(str.getBytes());

fop.flush(); fop.close(); System.out.println("The data has been written"); }

else System.out.println("This file is not exist"); }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

STRING CLASS String class objects work with complete strings

instead of treating them as character arrays as some languages do.

String class objects are immutable (ie. read only). When a change is made to a string, a new object is created

and the old one is disused. This causes extraneous garbage collection if string modifier

methods are used too often.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

METHODS IN STRING CLASS char charAt(int index)

Returns the character at the specified index.

int compareTo(Object o) Compares this String to another Object.

int compareTo(String anotherString) Compares two strings lexicographically.

int compareToIgnoreCase(String str) Compares two strings lexicographically, ignoring case differences.

String concat(String str) Concatenates the specified string to the end of this string.

boolean contentEquals(StringBuffer sb) Returns true if and only if this String represents the same sequence of characters as the specified

StringBuffer.

static String copyValueOf(char[] data) Returns a String that represents the character sequence in the array specified.

static String copyValueOf(char[] data, int offset, int count) Returns a String that represents the character sequence in the array specified.

boolean endsWith(String suffix) Tests if this string ends with the specified suffix.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

METHODS IN STRING CLASS boolean equals(Object anObject)

Compares this string to the specified object.

boolean equalsIgnoreCase(String anotherString) Compares this String to another String, ignoring case considerations.

byte[] getBytes() Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte

array.

void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin) Deprecated. This method does not properly convert characters into bytes. As of JDK 1.1, the preferred way to do this is

via the the getBytes() method, which uses the platform's default charset.

byte[] getBytes(String charsetName) Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array .

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) Copies characters from this string into the destination character array.

int hashCode() Returns a hash code for this string.

int indexOf(int ch) Returns the index within this string of the first occurrence of the specified character.

int indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of the specified character, starting the search at the specified

index.

int indexOf(String str) Returns the index within this string of the first occurrence of the specified substring.

int indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

METHODS IN STRING CLASS String intern()

Returns a canonical representation for the string object.

int lastIndexOf(int ch) Returns the index within this string of the last occurrence of the specified character.

int lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.

int lastIndexOf(String str) Returns the index within this string of the rightmost occurrence of the specified substring.

int lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.

int length() Returns the length of this string.

boolean matches(String regex) Tells whether or not this string matches the given regular expression.

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) Tests if two string regions are equal.

boolean regionMatches(int toffset, String other, int ooffset, int len) Tests if two string regions are equal.

String substring(int beginIndex) Returns a new string that is a substring of this string.

String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string.

char[] toCharArray() Converts this string to a new character array.

String toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale.

String toLowerCase(Locale locale) Converts all of the characters in this String to lower case using the rules of the given Locale.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

METHODS IN STRING CLASS String toString()

This object (which is already a string!) is itself returned.

String toUpperCase() Converts all of the characters in this String to upper case using the rules of the default locale.

String toUpperCase(Locale locale) Converts all of the characters in this String to upper case using the rules of the given Locale.

String trim() Returns a copy of the string, with leading and trailing whitespace omitted.

static String valueOf(boolean b) Returns the string representation of the boolean argument.

static String valueOf(char c) Returns the string representation of the char argument.

static String valueOf(char[] data) Returns the string representation of the char array argument.

static String valueOf(char[] data, int offset, int count) Returns the string representation of a specific subarray of the char array argument.

static String valueOf(double d) Returns the string representation of the double argument.

static String valueOf(float f) Returns the string representation of the float argument.

static String valueOf(int i) Returns the string representation of the int argument.

static String valueOf(long l) Returns the string representation of the long argument.

static String valueOf(Object obj) Returns the string representation of the Object argument.

STRING EXAMPLESR

.Jero

me, Te

chnica

l Consu

ltant,

Caly

donTe

ch,

jero

me@

caly

donte

ch.co

mEx1:

public class StringsDemo {

public static void main(String[] args) {

byte[] bytes = {2, 4, 6, 8};

char[] characters = {'a', 'b', 'C', 'D'};

StringBuffer strBuffer = new StringBuffer("abcde");

// Examples of Creation of Strings

String byteStr = new String(bytes);

String charStr = new String(characters);

String buffStr = new String(strBuffer);

System.out.println("byteStr : "+byteStr);

System.out.println("charStr : "+charStr);

System.out.println("buffStr : "+buffStr);

}

}

STRING EXAMPLESR

.Jero

me, Te

chnica

l Consu

ltant,

Caly

donTe

ch,

jero

me@

caly

donte

ch.co

mEx2:

public class StringsDemo2 {

public static void main(String[] args) {String str1 = "My name is bob";String str2 = "My name is bob";String str3 = "My name " + "is bob"; //Compile time expressionString name = "bob";String str4 = "My name is " + name;String str5 = new String("My name is bob");System.out.println("str1 == str2 : " + (str1 == str2));System.out.println("str2 == str3 : " + (str2 == str3));System.out.println("str3 == str1 : " + (str3 == str1));System.out.println("str4 == str5 : " + (str4 == str5));System.out.println("str1 == str4 : " + (str1 == str4));System.out.println("str1 == str5 : " + (str1 == str5));System.out.println("str1.equals(str2) : " + str1.equals(str2));System.out.println("str2.equals(str3) : " + str2.equals(str3));System.out.println("str3.equals(str1) : " + str3.equals(str1));System.out.println("str4.equals(str5) : " + str4.equals(str5));System.out.println("str1.equals(str4) : " + str1.equals(str4));System.out.println("str1.equals(str5) : " + str1.equals(str5));}}

STRING EXAMPLESR

.Jero

me, Te

chnica

l Consu

ltant,

Caly

donTe

ch,

jero

me@

caly

donte

ch.co

m

Ex3:

StringDemo3

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

STRINGBUFFER CLASS The StringBuffer class is used to represent characters that

can be modified. This is simply used for concatenation or manipulation of

the strings.  StringBuffer is mainly used for the dynamic string

concatenation which enhances the performance. A string buffer implements a mutable sequence of

characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence

of characters, but the length and content of the sequence can be changed through certain method calls.

append() This is the append() function used for the concatenate the string in

string buffer. This is better to use for dynamic string concatenation. This function works like a simple string concatenation such as : String str = str + "added string";.

insert() This is the insert() function used to insert any string or character at the

specified position in the given string.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

STRINGBUFFER CLASS reverse()

This is the reverse() function used to reverse the string present in string buffer.

setCharAt() This is the setCharAt() function which is used to set the specified character in buffered

string at the specified position of the string in which you have to set the given character.

charAt() This is the charAt() function which is used to get the character at the specified position

of the given string.

substring() This is the substring() function which is used to get the sub string from the buffered

string from the initial position to end position (these are fixed by you in the program).

deleteCharAt() This is the deleteCharAt() function which is used to delete the specific character from

the buffered string by mentioning that's position in the string.

length() This is the length() function is used to finding the length of the buffered string.

delete() This is the delete() function is used to delete multiple character at once from n position

to m position (n and m are will be fixed by you.) in the buffered string.

capacity() This is the capacity() function is used to know about the current characters kept which

is displayed like : number of characters + 6.

STRINGBUFFER EXAMPLESR

.Jero

me, Te

chnica

l Consu

ltant,

Caly

donTe

ch,

jero

me@

caly

donte

ch.co

mEx1:import java.io.*;public class stringBuffer{ public static void main(String[] args) throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String str; try{ System.out.print("Enter your name: "); str = in.readLine(); str += ", This is the example of SringBuffer class and it's functions."; //Create a object of StringBuffer class StringBuffer strbuf = new StringBuffer(); strbuf.append(str); System.out.println(strbuf); strbuf.delete(0,str.length()); //append() strbuf.append("Hello"); strbuf.append("World"); //print HelloWorld System.out.println(strbuf);

STRINGBUFFER EXAMPLESR

.Jero

me, Te

chnica

l Consu

ltant,

Caly

donTe

ch,

jero

me@

caly

donte

ch.co

mEx1://insert() strbuf.insert(5,"_Java "); System.out.println(strbuf); //reverse() strbuf.reverse(); System.out.print("Reversed string : "); System.out.println(strbuf); strbuf.reverse(); System.out.println(strbuf);//setCharAt() strbuf.setCharAt(5,' '); System.out.println(strbuf); //charAt() System.out.print("Character at 6th position : "); System.out.println(strbuf.charAt(6)); //print J //substring() System.out.print("Substring from position 3 to 6 : "); System.out.println(strbuf.substring(3,7));

STRINGBUFFER EXAMPLESR

.Jero

me, Te

chnica

l Consu

ltant,

Caly

donTe

ch,

jero

me@

caly

donte

ch.co

mEx1://deleteCharAt() strbuf.deleteCharAt(3); System.out.println(strbuf); //capacity() System.out.print("Capacity of StringBuffer object : "); System.out.println(strbuf.capacity()); //print 21 //delete() and length() strbuf.delete(6,strbuf.length()); System.out.println(strbuf); //no anything } catch(StringIndexOutOfBoundsException e){ System.out.println(e.getMessage()); } }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

STRINGBUILDER CLASS StringBuilder class methods are similar to StringBuffer

ones but they are unsynchronized (ie. not for multithreaded applications). They are also much faster.

sets value Accessor methods: capacity(), length(), charAt(i), indexOf(g), lastIndexOf(g)

Modifier methods: append(g), delete(i1, i2), insert(iPosn, g), getChars(i), setCharAt(iposn, c), substring(), replace(i1,i2,gvalue), reverse(), trimToSize(g ), toString(g)

StringBuilder defString=new StringBuilder(); // sets size to 16 char StringBuilder nulString=new StringBuilder(6); // explicitly sets size

StringBuilder aString=new StringBuilder("start value"); // sets value

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

STRINGTOKENIZER CLASS StringTokenizer class objects may be created by one of

three constructor methods depending on the parameters used.

The first parameter string is the source text to be broken at the default set of whitespace delimiters (space, tab, newline, cr, formfeed).

If a second parameter is passed, that string is assumed to be the set of delimiting characters. Use the escaper \ character when representing the string quote character " or any non-typeable delimiters such as tab (\t).

If a true flag is added as a third parameter, any delimiters found are also returned as string tokens.

The StringTokenizer methods are: int countTokens(), boolean hasMoreTokens() and String nextToken().

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

STRINGTOKENIZER CLASS

Ex1:

import java.util.*;public class Test{ public static void main(String args[]) { int idx=0; int tokenCount; String words[]=new String [500]; String message="The text of the message to be scanned."; StringTokenizer st=new StringTokenizer(message); tokenCount=st.countTokens(); System.out.println("Number of tokens = " + tokenCount); while (st.hasMoreTokens()) // is there stuff to get? {words[idx]=st.nextToken(); idx++;} for (idx=0;idx<tokenCount; idx++) {System.out.println(words[idx]);} }}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mCOLLECTIONS

A collection represents a group of objects, known as its elements.

This framework is provided in the java.util package.

Objects can be stored, retrieved, and manipulated as elements of

collections.

Collection is a Java Interface. Collections can be used in various

scenarios like Storing phone numbers, Employee names database etc.

They are basically used to group multiple elements into a single unit.

Some collections allow duplicate elements while others do not.

Some collections are ordered and others are not.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

COLLECTIONS

A Collections Framework mainly contains the following 3 parts

Set of interfaces

Concrete class implementations for most of the interfaces

Set of standard utility methods and algorithms

The framework also provides several abstract implementations,

which are designed to make it easier for you to create new and

different implementations for handling collections of data.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

CORE COLLECTION INTERFACES

Collection Set List SortedSet Map SortedMap

Note: Collection and Map are the two top-level interfaces.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mCOLLECTION INTERFACES

Map

Sorted Map

Collection

List Set

Sorted Set

Note : The typical application of a Map is to provide access to values stored by keys. The set of collection operations are all there, but you work with a key-value pair instead of an isolated element. Map is therefore designed to support the basic

operations of get() and put() , which are not required by Set.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

HIERARCHICAL RELATIONSHIPS

The Collection interface is a group of objects, with

duplicates allowed.

The Set interface extends Collection but forbids duplicates.

The List interface extends Collection, allows duplicates,

and introduces positional indexing.

The Map interface extends neither Set nor Collection.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

COLLECTION INTERFACES

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

CONCRETE CLASSES

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

OPERATIONS

o boolean add(Object element)o boolean remove(Object element)o int size()o boolean isEmpty()o boolean contains(Object element)o Iterator iterator()

The iterator() method of the Collection interface returns an Iterator. An Iterator is similar to the Enumeration interface witch has the methods

hasNext(),next(),remove()

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mGROUP OPERATIONS

boolean containsAll(Collection collection) boolean addAll(Collection collection) void clear() void removeAll(Collection collection) void retainAll(Collection collection)

The containsAll() method allows you to discover if the current collection contains all the elements of another collection

The addAll() method ensures all elements from another collection are added to the current collection

The clear() method removes all elements from the current collection

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

JAVA ARRAY LIST

A java ArrayList is used to store an “ordered” group of elements where duplicates

are allowed.

Implements all optional list operations, and permits all elements, including null.

This class is similar to Vector, except that it is unsynchronized.

The size, isEmpty, get, set, iterator, and listIterator operations run in constant time.

ArrayList’s give great performance on get() and set() methods, but do not perform

well on add() and remove() methods when compared to a LinkedList.

An ArrayList capacity is the size of the array used to store the elements in the list.

As elements are added to an ArrayList, its capacity grows automatically. It is an

Array based implementation where elements of the List can be accessed directly

through get() method.

Example :ArrayListDemo.java

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

JAVA LINKED LIST

A LinkedList is used to store an “ordered” group of elements where

duplicates are allowed.

A LinkedList is based on a double linked list where elements of the List

are typically accessed through add() and remove() methods

Example :LinkedListExample.java

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

JAVA VECTOR

The Vector class implements a growable array of objects where the size

of the vector can grow or shrink as needed dynamically.

Like an array, it contains components that can be accessed using an

integer index.

An application can increase the capacity of a vector before inserting a

large number of components; this reduces the amount of incremental

reallocation.

Example :VectorDemo.java

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

JAVA HASH SET

The HashSet class implements the Set interface.

It makes no guarantee that the order of elements will remain constant over time.

This class is not synchronized and permits a null element.

This class offers constant time performance for the basic operations (add,

remove, contains and size), assuming the hash function disperses the elements

properly among the buckets.

To prevent unsynchronized access to the Set: Set s =

Collections.synchronizedSet(new HashSet(…));

Example :HashSetExample.java

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

JAVA HASH TABLE

HashTable is synchronized.

Iterator in the HashMap is fail-safe while the enumerator for the Hashtable

isn’t.

Hashtable doesn’t allow nulls

Example :HashTableDemo.java

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

JAVA TREE SET

This class implements the Set interface and guarantees that the sorted set

will be in ascending element order, sorted according to the natural order of

the elements or by the comparator provided at set creation time,

depending on which constructor is used.

This implementation not synchronized provides guaranteed log(n) time

cost for the basic operations (add, remove and contains

Example :TreeSetExample.java

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mMAP INTERFACE

The Map interface is not an extension of the Collection

interface. Instead, the interface starts off its own interface

hierarchy for maintaining key-value associations. The

interface describes a mapping from keys to values, without

duplicate keys,

The interface methods can be broken down into three sets

of operations: altering, querying, and providing alternative

views

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

Alteration Operations

Allow you to add and remove key-value pairs from the map. Both the key and value can be null. However, you should

not add a Map to itself as a key or value.

o Object put(Object key, Object value)

o Object remove(Object key)

o void putAll(Map mapping)

o void clear()

Query Operations

Allow you to check on the contents of the map

o Object get(Object key)

o boolean containsKey(Object key)

o boolean containsValue(Object value)

o int size()

o boolean isEmpty()

Providing Alternative Views

o public Set keySet()

o public Collection values()

o public Set entrySet()

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mHASHMAP AND TREEMAP CLASSES

two general-purpose Map implementations: HashMap and TreeMap

For inserting, deleting, and locating elements in a Map, the HashMap

offers the best alternative.

to traverse the keys in a sorted order, then TreeMap is your better

alternative

Depending upon the size of your collection, it may be faster to add

elements to a HashMap, then convert the map to a TreeMap for sorted

key traversal.

Using a HashMap requires that the class of key added have a well-

defined hashCode() implementation.

With the TreeMap implementation, elements added to the map must be

sortable.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

import java.util.*;public class MapExample {public static void main(String args[]) {Map map = new HashMap();Integer ONE = new Integer(1);for (int i=0, n=args.length; i<n; i++) {String key = args[i];Integer frequency = (Integer)map.get(key);if (frequency == null) {frequency = ONE;} else {int value = frequency.intValue();frequency = new Integer(value + 1);}map.put(key, frequency);}System.out.println(map);Map sortedMap = new TreeMap(map);System.out.println(sortedMap);}}

Example:MapExample.java

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mANNOTATION

Java, being a wonderful object-oriented language provided support for Annotations starting from 5.0.

Annotations in Java is all about adding meta-data facility to the Java Elements.

Annotation can be seen in class declaration, method declaration, field declaration etc.

The added Annotation to Java Elements have proven themselves to be considerably useful in many instances.

Types Built-in Annotations in Java 3User-defined Annotations

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

ANNOTATION

The above class, Employee is preceded with the final keyword which tells that this class cannot be sub-classed.

So, the introduction of the final keyword adds some additional information over the class definition telling that no other class can extend the Employee class.

Therefore, the final keyword forms a part in providing meta-data information in the class definition.

So, this is one variation of Annotation. Annotations are generally a way to add meta-data information to an

element (an element can be a class, method, field, or anything) and these meta-data are processed by the tools (compilers, javadoc, etc.).

Annotations are differentiated from other elements like class, interface etc., by preceding an '@' symbol before it.

Employee.java

final class Employee{private String name;private String id;// Getters and setters for Employee

class.}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

ANNOTATION

Don't get confused with the interface keyword. It has nothing to do with annotations.

'@' along with interface is the start of the annotation definition and TestAnnotation in the above case is the name of the Annotation.

Whether annotations can be applied to class (a class-level annotation), or a method (method-level annotation) or a field (field-level annotation) is specified in the declaration of the annotation itself.

This is referred to as Annotating an Annotation itself.

TestAnnotation.java

public @interface TestAnnotation{// Property Definition here.

}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

ANNOTATION

Meta-Annotations (meta-data about meta-data) Target Annotation Retention Annotation

Target Annotation If @TestAnnotation annotation can only be applied to

methods, then there is a Meta-Annotation (meta-data about meta-data) which tells for which element type this annotation is applicable.

The target element tells that the @TestAnnotation annotation can be applied only to methods and not to any other element types.

TestAnnotation.java

@Target(ElementType.METHOD)public @interface TestAnnotation{// Property Definitions here.}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

ANNOTATION The argument to @Target Annotation can be one from the

possible set of values of any Java Element, which is defined in a well-defined Enum called ElementType.

Here are the possible values taken by this Enum TYPE – Applied only to Type. A Type can be a Java class or

interface or an Enum or even an Annotation. FIELD – Applied only to Java Fields (Objects, Instance or Static,

declared at class level). METHOD – Applied only to methods. PARAMETER – Applied only to method parameters in a method

definition. CONSTRUCTOR – Can be applicable only to a constructor of a

class. LOCAL_VARIABLE – Can be applicable only to Local variables.

(Variables that are declared within a method or a block of code). ANNOTATION_TYPE – Applied only to Annotation Types. PACKAGE – Applicable only to a Package.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

ANNOTATION

Retention Annotation Assume that we have some Annotations defined in the source

code. We have a mechanism through which we can say that to what

extent the Annotations should be retained. The three possible ways of telling this are

Retain the Annotation in the Source Code only Retain the Annotation in the Class file also. Retain the Annotation Definition during the Run-time so that JVM can

make use of it. The Annotation that is used to achieve this is @Retention and it

takes a possible values of SOURCE, CLASS and RUNTIME defined in RetentionPolicy Enumeration.

TestAnnotation.java

@Target(ElementType.METHOD)@Retention(RetentionPolicy.CLASS)public @interface TestAnnotation{

// Property Definitions here.}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mBUILT-IN ANNOTATIONS IN JAVA

There are some pre-defined annotations available in the Java Programming language. They are, 1. Override 2. Deprecated 3. SuppressWarnings

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mOVERRIDE ANNOTATIONS

@Override annotation essentially tells to the compiler that, whenever such an annotation is defined in a method of some class, then that method must be an overridden method.

If not, then the compilers can report them as errors.

Annotation

@Retention(RetentionPolicy.CLASS)@Target(ElementType.RUNTIME)public @interface Override{}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

OVERRIDE ANNOTATIONS

This tells to the compiler that the method that is annotated with @Override is an overridden method.

So, the compiler immediately climbs up to the base class to find the existence of such a method.

If no such method is found in the base class, then the compiler can report an error message.

Employee.java

public class Employee {protected void startWork() {

// Code that will start to do some work. }

}

Manager.java

public class Manager extends Employee {@Overrideprotected void startWork(){

// Code that will start to do some work.}

}

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

THE @DEPRECATED ANNOTATION The Interfaces and the Classes in an Application get

updated every now and then. Interfaces used by the Clients may undergo so many

revisions in the form of new methods being added and existing methods being removed or updated.

Imagine the case where a method defined in a class or an interface has now become obsolete and we should warn the Client Applications not to make use of them.

One dangerous way is to remove the method itself from the Interface. But this solution has a huge impact on the code that is dependant on this interface.

Another elegant way is to mark the old method as deprecated which informs the client not to use this method anymore because in the future versions this old method may not be supported.

Clients may prepare themselves not to depend on the old method anymore.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

THE @DEPRECATED ANNOTATION

The class MyOldClass has a method myDeprecatedMethod() which is tagged as Deprecated.

Now if any of the Client code tries to access this method, then the following warning message is issued by the compiler.

Ex:

public class MyOldClass {@Deprecatedpublic void myDeprecatedMethod(){

// Obsolete code here.}public void myAlternativeMethod(){

// Revised code here.}

}

THE @SUPPRESSWARNINGS ANNOTATION

These types of annotations ensure that the compiler will shield the warning message in the annotated elements and also in all of its sub-elements.

The @SuppressWarnings annotation tells the compiler to suppress the warning messages it normally show during compilation time.

It has some level of suppression to be added to the code, these level including: all, deprecation, fallthrough, finally, path, serial and unchecked.

In the example above if we don’t use @SuppressWarnings annotation the compiler will report that the constructor of the Date class called above has been deprecated.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

mEx:

public class SuppressWarningsExample { @SuppressWarnings(value={"deprecation"}) public static void main(String[] args) { Date date = new Date(2008, 9, 30); System.out.println("date = " + date); } }

USER-DEFINED ANNOTATIONS

Below are the general guidelines to be followed while defining annotations: Annotation declaration should start with an ‘at’ sign like @,

following with an interface keyword, following with the annotation name.

Method declarations should not have any parameters. Method declarations should not have any throws clauses. Return types of the method should be one of the following:

primitives String Class enum array of the above types

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

mAuthor.java

import java.lang.annotation.*;public @interface Author{

String name();}

USER-DEFINED ANNOTATIONS

The annotation member elements can be set to have default values. Here’s an example

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

mAnnotatedClass.java (Using Annotation Author)

public class AnnotatedClass{@Author(name = "Author1")public void annotatedMethod1(){}

}

Author.java (Setting default value)

import java.lang.annotation.*;public @interface Author{

String name() default "unknown";}

AnnotatedClass.java (Using Annotation Author)

public class AnnotatedClass{@Author //author name is omitted herepublic void annotatedMethod1(){}

}

USER-DEFINED ANNOTATIONS There are specific annotations which can only

be used in the context of annotations. The annotations are

Target (Discussed Earlier) Retention (Discussed Earlier) Documented Inherited

Documented Annotation By default, the annotation and related information

does not appear in the class javadoc. A marker annotation @Documented in provided to

cause the annotation related information to be added in the class javadoc.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

m

USER-DEFINED ANNOTATIONS R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

mAuthor.java

import java.lang.annotation.*;

@Target(value = {ElementType.CONSTRUCTOR, ElementType.METHOD,

ElementType.TYPE})

@Retention(RetentionPolicy.RUNTIME)

public @interface Author{

String name() default "unknown";

}

Version.java

import java.lang.annotation.*;

@Target(value = {ElementType.CONSTRUCTOR, ElementType.METHOD,

ElementType.TYPE})

@Retention(RetentionPolicy.RUNTIME)

public @interface Version{

double number();

}

USER-DEFINED ANNOTATIONS R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

mAnnotatedClass.java

@Author(name = "Johny")

@Version(number = 1.0)

public class AnnotatedClass{

@Author(name = "Author1")

@Version(number = 2.0f)

public void annotatedMethod1() {

}

@Author(name = "Author2")

@Version(number = 4.0)

public void annotatedMethod2() {

}

}

USER-DEFINED ANNOTATIONS R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

mSee the Annotation details

AnnotationReader.java

Out Put

C:\caly\ano>java AnnotationReader

Finding annotations on java.lang.Class

Version number:1.0

Author name:Johny

Finding annotations on java.lang.reflect.Method

Author name:Author1

Version number:2.0

Finding annotations on java.lang.reflect.Method

Author name:Author2

Version number:4.0

INHERITED ANNOTATIONS R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

mCarAnnotation.java

import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface CarAnnotation {

public String maker(); }

AbstractBMWCar.java

@CarAnnotation(maker="BMW") public class AbstractBMWCar { }

BMWRoadsterCar.java

public class BMWRoadsterCar extends AbstractBMWCar { }

INHERITED ANNOTATIONS

The annotation member elements can be set to have default values. Here’s an example

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

mCarAnnotationTest.javapublic class CarAnnotationsTest { public static void main(String[] args) { Class[] classes = {AbstractBMWCar.class, BMWRoadsterCar.class}; for (Class classObj : classes) { Annotation[] annotations = classObj.getAnnotations(); System.out.println("No. of annotations: " + annotations.length); for (Annotation annotation : annotations) { CarAnnotation carAnnotation = (CarAnnotation)annotation; System.out.println(carAnnotation.maker()); } } } }

Output with @inherited annotationNo. of annotations: 1 BMW No. of annotations: 1 BMW

Output without @inherited annotation

No. of annotations: 1 BMW No. of annotations: 0

JDBC We are faced with dozens of available database products, and

each one talks to our applications in its own private language.

Java's JDBC API gives us a shared language through which our

applications can talk to database engines

Working with leaders in the database field, JavaSoft developed

a single API for database access--JDBC

An SQL-level API means that JDBC allows us to construct SQL

statements and embed them inside Java API calls. In short,

you are basically using SQL.

But JDBC lets you smoothly translate between the world of the

database and the world of the Java application.

Your results from the database, for instance, are returned as

Java variables, and access problems get thrown as exceptions.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

m

STRUCTURE OF JDBC JDBC accomplishes its goals through a set of Java interfaces, each implemented

differently by individual vendors.

The set of classes that implement the JDBC interfaces for a particular database

engine is called a JDBC driver.

JDBC is to hide the specifics of each database and let you worry about just your

application.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

m

TYPES OF JDBC DRIVERS

Driver types are used to categorize the technology used to connect to the database.

A JDBC driver vendor uses these types to describe how their product operates

Four Type of Drivers JDBC-ODBC bridge plus ODBC driver - Type 1. Native-API, partly Java driver - Type 2. JDBC-Net, pure Java driver -Type 3. Native-protocol, pure Java driver - Type 4.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

m

TYPE1 - JDBC DRIVERS

Also known as the JDBC-ODBC bridge. The bridge is usually used when there is no pure-Java driver

available for a particular database The driver is implemented in the

sun.jdbc.odbc.JdbcOdbcDriver class and comes with the Java 2 SDK, Standard Edition.

Type 1 is the simplest of all but platform specific i.e only to Microsoft platform.

The Java Native Interface (JNI) is used to call ODBC functions from the JDBC driver.

A Type 1 driver needs to have the bridge driver installed and configured before JDBC can be used with it.

Type 1 drivers cannot be used in an applet since applets cannot load native code

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

m

TYPE2 - JDBC DRIVERS

Also known as the Native-API driver. The driver converts JDBC method calls into native calls of

the database API The type 2 driver is not written entirely in Java as it

interfaces with non-Java code that makes the final database calls

Java native methods are used to invoke the API functions that perform database operations.

Type 2 drivers are generally faster than Type 1 drivers. Type 2 drivers need native binary code installed and

configured to work. Client -> JDBC Driver -> Vendor Client DB Library ->

Database

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

m

TYPE3 - JDBC DRIVERS

Also known as the network-protocol driver. The middle-tier (application server) converts JDBC calls

directly or indirectly into the vendor-specific database protocol

type 3 driver is written entirely in Java. The same driver can be used for multiple databases The type 3 driver is platform-independent These drivers use a networking protocol and middleware to

communicate with a server. The server then translates the protocol to DBMS function

calls specific to DBMS. Client -> JDBC Driver -> Middleware-Net Server -> Any

Database

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

m

TYPE4 - JDBC DRIVERS Also known as the native-protocol driver. converts JDBC calls directly into the vendor-specific database protocol The type 4 driver is written completely in Java and is hence platform

independent. It is installed inside the Java Virtual Machine of the client. As the database protocol is vendor-specific, separate drivers, usually

vendor-supplied, need to be used to connect to the database. A Type 4 driver uses Java to implement a DBMS vendor networking

protocol. Client Machine -> Native protocol JDBC Driver -> Database server

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

m

DESCRIPTION OF CODE

Connection

This is an interface in java.sql package that specifies connection with

specific database like: MySQL, Ms-Access,Oracle etc and java files.

The SQL statements are executed within the context of the Connection

interface.

Class.forName(String driver)

This method is static. It attempts to load the class and returns class instance

and takes string type value (driver) after that matches class with given string.

DriverManager

It is a class of java.sql package that controls a set of JDBC drivers. Each

driver has to be register with this class.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

m

DESCRIPTION OF CODE

getConnection(String url, String userName, String

password)

This method establishes a connection to specified database url. It

takes three string types of arguments like:

url: - Database url where stored or created your database

userName: - User name of MySQL

password: -Password of MySQL

con.close()

This method is used for disconnecting the connection. It frees all

the resources occupied by the database.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

m

JDBC API DriverManager

"Driver Manger" Manages all the Drivers found in JDBC environment, load the most appropriate

driver for connectivity.

Connection :- Connection class creates objects which represents connection and it's object also helps in creating

object of Statement, PreparedStatement and CallableStatement classes.

Statement Statement object is used to execute query and also store it's value to "Resultset" object.

PreparedStatement It can be used in place of "Statement", PreparedStatement's performance is high as compared to

"Statement" class, represents a precompiled SQL statement .

Callable Statement Callable statement support stored procedure of RDBMS' ,using it's object you can execute stored

procedure of database application.

ResultSet :- Resultset object is used to store the result retrieve from database using "Statement" or

"PreparedStatement" , etc

SQLException:- SqlException class is used to represent error or warning during access from database or during

connectivity

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

m

A LIST OF JDBC DRIVER VENDORS R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

mVendor Type Supported Databases

Agave Software Design 3 Oracle, Sybase, Informix, ODBC supported databases

Asgard Software 3 Unisys A series DMSII database

Borland 4 InterBase 4.0

Caribou Lake Software 3 CA-Ingres

Connect Software 4 Sybase, MS SQL Server

DataRamp 3 ODBC supported databases

IBM 2/3 IBM DB2 Version 2

IDS Software 3Oracle, Sybase, MS SQL Server, MS Access, Informix, Watcom, ODBC supported databases

JavaSoft 1 ODBC supported databases

OpenLink 3 CA-Ingres, Postgres95, Progress, Unify

SAS 4 SAS, and via SAS/ACCESS, Oracle, Informix

Sybase 3/4 Sybase SQL Server, SQL Anywhere, Sybase IQ

Symantec 3Oracle, Sybase, MS SQL Server, MS Access, Watcom, ODBC supported databases

Visigenic 3 ODBC supported databases

WebLogic 2/3Oracle, Sybase, MS SQL Server/ODBC supported databases

LIST OF JDBC DRIVERS R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

m

Database DriverIBM DB2 jdbc:db2://<HOST>:<PORT>/<DB>

COM.ibm.db2.jdbc.app.DB2Driver

JDBC-ODBC Bridge jdbc:odbc:<DB>sun.jdbc.odbc.JdbcOdbcDriver

Mcrosoft SQL Server jdbc:weblogic:mssqlserver4:<DB>@<HOST>:<PORT>weblogic.jdbc.mssqlserver4.Driver

Oracle Thin jdbc:oracle:thin:@<HOST>:<PORT>:<SID>oracle.jdbc.driver.OracleDriver

PointBase Embedded Server jdbc:pointbase://embedded[:<PORT>]/<DB>com.pointbase.jdbc.jdbcUniversalDriver

Cloudscape jdbc:cloudscape:<DB>COM.cloudscape.core.JDBCDriver

Cloudscape RMI

jdbc:rmi://<HOST>:<PORT>/jdbc:cloudscape:<DB>RmiJdbc.RJDriver

Firebird (JCA/JDBC Driver) jdbc:firebirdsql:[//<HOST>[:<PORT>]/]<DB>org.firebirdsql.jdbc.FBDriver

IDS Server jdbc:ids://<HOST>:<PORT>/conn?dsn='<ODBC_DSN_NAME>'ids.sql.IDSDriver

Informix Dynamic Server jdbc:informix-sqli://<HOST>:<PORT>/<DB>:INFORMIXSERVER=<SERVER_NAME>com.informix.jdbc.IfxDriver

LIST OF JDBC DRIVERS R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

m

Database DriverHypersonic SQL (v1.2 and earlier) jdbc:HypersonicSQL:<DB>

hSql.hDriverHypersonic SQL (v1.3 and later) jdbc:HypersonicSQL:<DB>

org.hsql.jdbcDriverMicrosoft SQL Server (JTurbo Driver) jdbc:JTurbo://<HOST>:<PORT>/<DB>

com.ashna.jturbo.driver.DriverMicrosoft SQL Server (Sprinta Driver) jdbc:inetdae:<HOST>:<PORT>?database=<DB>

com.inet.tds.TdsDriverMicrosoft SQL Server 2000 (Microsoft Driver)

jdbc:microsoft:sqlserver://<HOST>:<PORT>[;DatabaseName=<DB>]com.microsoft.sqlserver.jdbc.SQLServerDriver

MySQL (MM.MySQL Driver) jdbc:mysql://<HOST>:<PORT>/<DB>org.gjt.mm.mysql.Driver

Oracle OCI 8i jdbc:oracle:oci8:@<SID>oracle.jdbc.driver.OracleDriver

Oracle OCI 9i jdbc:oracle:oci:@<SID>oracle.jdbc.driver.OracleDriver

PostgreSQL (v6.5 and earlier) jdbc:postgresql://<HOST>:<PORT>/<DB>postgresql.Driver

PostgreSQL (v7.0 and later) jdbc:postgresql://<HOST>:<PORT>/<DB>org.postgresql.Driver

LIST OF JDBC DRIVERS R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

m

Database Driver

InstantDB (v3.13 and earlier) jdbc:idb:<DB>jdbc.idbDriver

InstantDB (v3.14 and later) jdbc:idb:<DB>org.enhydra.instantdb.jdbc.idbDriver

Interbase (InterClient Driver) jdbc:interbase://<HOST>/<DB>interbase.interclient.Driver

Sybase (jConnect 4.2 and earlier) jdbc:sybase:Tds:<HOST>:<PORT>com.sybase.jdbc.SybDriver

Sybase (jConnect 5.2) jdbc:sybase:Tds:<HOST>:<PORT>com.sybase.jdbc2.jdbc.SybDriver

Hypersonic SQL (v1.2 and earlier)

jdbc:HypersonicSQL:<DB>hSql.hDriver

JDBC EXAMPLESR

.Jero

me, Te

chnica

l Consu

ltant, C

aly

donTe

ch,

jero

me@

caly

donte

ch.co

m

JDBC Examples

MSAccess

JdbcMSAccess.java

MSAccess

JdbcMsAccessControl.java

Oracle

JdbcOracle.java

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

SCROLLABLE RESULTSET

Create a Statement, using the createStatement() API method of the Connection. The Statement must have the type ResultSet.TYPE_SCROLL_INSENSITIVE or ResultSet.TYPE_SCROLL_SENSITIVE and the concurrency ResultSet.CONCUR_UPDATABLE, in order to return scrollable result sets.

Execute the query to the database, using the executeQuery(String sql) API method. The data produced by the given query is a ResultSet.

Get the cursor position, with the getRow() API method and check if it is before the first row, with the isBeforeFirst()API method.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

SCROLLABLE RESULTSET

Invoke the next() API method to move the cursor to next row, and last() API method to move cursor to the last row. In order to check if it is in the last row, we can call the isLast() API method.

Move the cursor to the end of this ResultSet object, just after the last row, with the afterLast() API method and use the isAfterLast() API method to check if it is after the last row.

Move cursor to other rows, with the absolute(int row) API method and check again its position.

Invoke the relative(int rows) API method to move the cursor

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

SCROLLABLE - UPDATABLE

connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

rs.absolute(5); rs.updateString("Office", "HQ222"); rs.updateRow();

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

THE JAVA VIRTUAL MACHINE

Provides hardware platform specifications Reads compiled byte codes that are platform-

independent Is implemented as software or hardware Is implemented in a Java technology

development tool or a Web browser

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

THE JAVA VIRTUAL MACHINE

JVM provides definitions for the: Instruction set (central processing unit [CPU]) Register set Class file format Stack Garbage-collected heap Memory area Fatal error reporting High-precision timing support

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

GARBAGE COLLECTION

Allocated memory that is no longer needed should be deallocated.

In other languages, deallocation is the programmer’s responsibility.

The Java programming language provides a system-level thread to track memory allocation.

Characteristics: Checks for and frees memory no longer needed Is done automatically Can vary dramatically across JVM

implementations

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

THE JAVA RUNTIME ENVIRONMENT

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mOPERATION OF THE JRE WITH A JUST-IN-TIME (JIT) COMPILER

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

JVM TASKS

The JVM performs three main tasks: Loads code Verifies code Executes code

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

THE CLASS LOADER

Loads all classes necessary for the execution of a program

Maintains classes of the local file system in separate namespaces

Prevents spoofing

THE BYTECODE VERIFIER

Ensures that: The code adheres to the JVM specification. The code does not violate system integrity. The code causes no operand stack overflows

or underflows. The parameter types for all operational code

are correct. No illegal data conversions (the conversion of

integers to pointers) have occurred.

R.Je

rom

e, Te

chnica

l Consu

ltant,

Caly

donTe

ch,

jero

me@

caly

donte

ch.co

m

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

THREADS

Multithreaded programming has these characteristics: Multiple threads are from one Runnable instance. Threads share the same data and code.

The three parts of at thread are: CPU Code Data

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

THREADS

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

BASIC CONTROL OF THREADS

Test threads: isAlive()

Access thread priority: getPriority() setPriority()

Put threads on hold: Thread.sleep() // static method join() Thread.yield() // static method

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

THE OBJECT LOCK FLAG

Every object has a flag that is a type of lock flag.

The synchronized enables interaction with the lock flag.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

RELEASING THE LOCK FLAG

The lock flag is released in the following events: Released when the thread passes the end of the

synchronized code block Released automatically when a break, return, or

exception is thrown by the synchronized code block

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mTHREAD STATE DIAGRAM WITH SYNCHRONIZATION

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

DEADLOCK

A deadlock has the following characteristics: It is two threads, each waiting for a lock from the

other. It is not detected or avoided. Deadlock can be avoided by: Deciding on the order to obtain locks Adhering to this order throughout Releasing locks in reverse order

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mTHREAD INTERACTION – WAIT AND NOTIFY

Scenario: Consider yourself and a cab driver as two

threads. The problem:

How do you determine when you are at your destination?

The solution: You notify the cab driver of your destination and

relax. The driver drives and notifies you upon arrival at

your destination.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

THREAD INTERACTION

Thread interactions include: The wait and notify methods

The pools: Wait pool Lock pool

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

mTHREAD STATE DIAGRAM WITH WAIT AND NOTIFY

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

NETWORKING

The term network programming refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.

The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level communication details, allowing you to write programs that focus on solving the problem at hand

Protocols TCP UDP

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

SOCKET PROGRAMMING The server instantiates a ServerSocket object, denoting

which port number communication is to occur on. The server invokes the accept() method of the

ServerSocket class. This method waits until a client connects to the server on the given port.

After the server is waiting, a client instantiates a Socket object, specifying the server name and port number to connect to.

The constructor of the Socket class attempts to connect the client to the specified server and port number. If communication is established, the client now has a Socket object capable of communicating with the server.

On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client's socket.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

NETWORKING

CLASSES

ServerSocket getLocalPort() accept() bind(SocketAddress host, int backlog)

Socket connect(SocketAddress host, int timeout) getInetAddress() getPort() getRemoteSocketAddress() getInputStream() getOutputStream()

InetAddress

R.Je

rom

e, Te

chnica

l Consu

ltant,

Caly

donTe

ch,

jero

me@

caly

donte

ch.co

m

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

NETWORK EXCEPTIONS

BindException ConnectException InterruptedIOException NoRouteToHostException PortUnreachableException ProtocolException SocketException SocketTimeoutException UnknownHostException SSLException UnknownServiceException

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

DESIGN PATTERNS

Creational Patterns --- Abstract Factory --- Builder --- Factory Method --- Prototype --- Singleton

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

DESIGN PATTERNS

Structural Patterns --- Adapter(Wrapper Pattern) --- Bridge --- Decorator --- Façade --- Proxy Behavioral Patterns --- Chain of Responsibility --- Observer

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

RMI (REMOTE METHOD INVOCATION)

The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed application in java.

The RMI allows an object to invoke methods on an object running in another JVM.

The RMI provides remote communication between the applications using two objects stub and skeleton.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

STUB

The stub is an object, acts as a gateway for the client side.

All the outgoing requests are routed through it.

It resides at the client side and represents the remote object.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

STUB

When the caller invokes method on the stub object, it does the following tasks: It initiates a connection with remote Virtual

Machine (JVM), It writes and transmits (marshals) the

parameters to the remote Virtual Machine (JVM), It waits for the result It reads the return value or exception, and It finally, returns the value to the caller.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

SKELETON

The skeleton is an object, acts as a gateway for the server side object.

All the incoming requests are routed through it.

When the skeleton receives the incoming request, it does the following tasks: It reads the parameter for the remote method It invokes the method on the actual remote

object, and It writes and transmits the result to the caller.

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

RMI

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

STEPS TO WRITE THE RMI

Create the remote interface Provide the implementation of the remote

interface Compile the implementation class and create

the stub and skeleton objects using the rmic tool

Start the registry service by rmiregistry tool Create and start the remote application Create and start the client application

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

RMI EXAMPLE

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

RMI EXAMPLE

R.Je

rom

e, Te

chnica

l Consu

ltant, C

aly

do

nTe

ch, je

rom

e@

caly

donte

ch.co

m

RMI EXAMPLE