Vous êtes sur la page 1sur 174

R.

Jerome, Technical Consultant, CalydonTech, jerome@caly


JDK 1.5
CORE JAVA
procedural Vs object-oriented

 In procedural program:
 Programming logic follows certain procedures

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.

Class Instance
Rubber stamp Stamped image
Photographic negative Printed photo
Object
 An object is a software entity( unit ) that
combines a set of data with a set of
operations to manipulate that data.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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

Method
 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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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
Object Class
 All classes in JavaTM technology are directly or
indirectly derived from the Object class.
Some of the subclasses of Object class are -

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


Boolean, Number, Void, Math, String,
StringBuffer etc.

Object's Hash Code

 Objects in Java have hash codes associated


with them.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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.
Object's Hash Code
class class1{
void sample1(){
System.out.println("Hai");
}
}

class class2{

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.
}
}
Variables
 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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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

ote: Values enclosed in <> are required values, while those values in [] are optional.
VARIABLES
 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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


  Reference Variables:
 Variables that store the address in the memory
location Points to another memory location
where the actual data is present

Java'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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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
Java's Primitive Data Types
 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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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
Java's Primitive Data Types
Ex1: 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);

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


System.out.println("Max short value = " + Short.MAX_VALUE);
System.out.println("Min intvalue = " + Integer.MIN_VALUE);
System.out.println("Max intvalue = " + 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);
}
}
Java's Primitive Data Types
Ex2: 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;

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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);
}
}
Operators
 An operator is a symbol that operates on one
or more arguments to produce a result.
Operator Type Symbols
Assignment Operators  =

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


Arithmetic Operators  ­        +        *        /        %       
Relational Operators   ++        ­­
>        <        >=        <=        
Logical Operators  ==        !=
&&        ||        &        
Bit wise Operator |        !        ^
&        |        ^                >>     
Compound Assignment     >>>
+=        ­=        *=        /=        
Operators 
Conditional Operator %=  <<=        >>=     >>>=
?:
Operators
Operator Purpose
+ addition of numbers, concatenation of Strings
+= add and assign numbers, concatenate and assign Strings
- Subtraction
-= subtract and assign

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


* 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
Operators
Operator Purpose
<= less than or equal to
! boolean NOT
!= not equal to
&& boolean AND

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


|| 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
Operators
Operator Purpose
>> shift bits right with sign extension
>>= shift bits right with sign extension and assign
<< shift bits left
<<= shift bits left and assign

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


>>> unsigned bit shift right
>>>= unsigned bit shift right and assign
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 (&&),

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 Conditional AND/Boolean Logical And (&),
 OR/Logical OR (||),
 Conditional OR/Boolean Logical OR (|),
 Exclusive OR / Boolean Logical exclusive OR (^)
 NOT (!)

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:

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 && 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
LOGICAL OPERATORS
 || (logical) and | (boolean logical)
 The basic difference between || and | operators is
same as && and &

X1 X2 Result

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE
LOGICAL OPERATORS
 ^ (boolean logical exclusive OR)
X1 X2 Result
TRUE TRUE FALSE
TRUE FALSE TRUE

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


FALSE TRUE TRUE
FALSE FALSE FALSE

!  ( log ical NOT)

X1 X2
TRUE FALSE
FALSE TRUE
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


1 1 0 1 1 0
1 0 0 0 1 1
0 1 1 0 1 1
0 0 1 0 0 0
BITWISE OPERATORS
Ex: 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 1

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


int y = 0xF8E9; //1 1 1 1 1 0 0 0 1 1 1 0 1 0 0 1
int 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();
COMPOUND OPERATORS
Ex: Compound Operator Example
public class CompoundOperatorsDemo {
public CompoundOperatorsDemo() {
int x = 0, y = 5;

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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();
CONDITIONAL OPERATORS
Ex: Compound Operator Example
public class TernaryOperatorsDemo {
public TernaryOperatorsDemo() {
int x = 10, y = 12, z = 0;

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


z = x > y ? x : y;
System.out.println("z : " + z);
}
public static void main(String args[])
{
new TernaryOperatorsDemo();
}
}
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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


\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.
OPERATOR PRECEDENCE
Operator Presedence
postfix [] . () expr++ expr– -
unary ++expr - - expr +expr -expr !
creation/caste new (type)expr
multiplicative */%

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


additive +-
shift >> >>>
relational < ,<= > >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
assignment = “op=”
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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
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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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>
Wrapper class

Ex1: Simple Example for Integer


import java.io.*;
import java.lang.Integer.*;

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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);
}
Wrapper class
Ex2: 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();

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


//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);
}}
Wrapper class
Ex2: Integer To Numeric Primitive Types Example
class conversion
{
public static void main(String args[])
{
byte b;
int i=257;

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


double d= 3.142;

System.out.println("\n conversion of int to byte.");


b=(byte)i;
System.out.println("iand 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);

}
}
Control Structures & Loops
 If loop
 If-else loop

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 If-else-if loop

 Muliple if loop

 Switch case

 While loop

 For loop

 Do-while loop


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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


static ke ywo rd:

Whe n yo u say so me thing is static, it me ans that data o r 


me tho d is no t tie d to  any partic ular o bje c t instanc e  o f 
that c lass. 
So  e ve n if yo u’ ve  ne ve r c re ate d an o bje c t o f that c lass 
yo u c an c all a static me tho d o r ac c e ss a pie c e  o f static 
data
Example
Accessor(Getter) and Mutator(Setter) Method:
Class Test{
private String name;
public void setName(String temp){
name=temp;
}
public String getName(){
return name;
}
}
Nested Class
Syntax
class OuterClass {
...
static class StaticNestedClass {
...
}

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


class InnerClass {
...
}
}
The   Java  pro gramming  language   allo ws  yo u  to   de fine   a  c lass 
within ano the r c lass. Suc h a c lass is c alle d a ne ste d class
Classifie d as static  and no n­static . 

Ne ste d  c lasse s  that  are   de c lare d  static   are   simply  calle d  static 
ne ste d c lasse s. 
No n­static  ne ste d c lasse s are  c alle d inne r c lasse s.

No n­static   ne ste d  c lasse s  (inne r  c lasse s)  have   acc e ss  to   o the r 
me mbe rs  o f  the   e nc lo sing  c lass,  e ve n  if  the y  are   de clare d 
private  
Static nested classes do not have access to other members of the enclosing class.
Why Nested Class
Lo gic al gro uping o f c lasse s

 If a c lass is use ful to  o nly o ne  o the r c lass, the n it is lo gic al 
to   e mbe d  it  in  that  c lass  and  ke e p  the   two   to ge the r. 
Ne sting suc h "he lpe r c lasse s" make s the ir pac kage  mo re  
stre amline d. 
Inc re ase d e nc apsulatio n

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 Co nside r  two   to p­le ve l  c lasse s,  A  and  B,  whe re   B  ne e ds 
ac c e ss  to   me mbe rs  o f  A  that  wo uld  o the rwise   be  
de c lare d private . 
 By  hiding  c lass  B  within  c lass  A,  A's  me mbe rs  can  be  
de c lare d  private   and  B  c an  ac c e ss  the m.  In  additio n,  B 
itse lf c an be  hidde n fro m the  o utside  wo rld. 
Mo re  re adable , maintainable  c o de

 Ne sting  small  c lasse s  within  to p­le ve l  c lasse s  place s  the  


c o de  c lo se r to  whe re  it is use d.
Nested Class
Example
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");-->Error

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


System.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();-->error
NestedClass.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();}}
Constructor
Eve ry c lass must have  at le ast o ne  c o nstruc to r. 

If  the re   is  no   c o nstruc to rs  fo r  yo ur  c lass,  the   c o mpile r  will  supply 
a de fault c o nstruc to r(no ­arg c o nstruc to r). 
A c o nstruc to r is use d to  c o nstruc t an o bje c t. 

A  co nstruc to r  lo o ks  like   a  me tho d  and  is  so me time s  calle d  a 


c o nstruc to r me tho d. 

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


A c o nstruc to r ne ve r re turns a value  

A c o nstruc to r always has the  same  name  as the  c lass. 

A  c o nstruc to r  may  have   ze ro   argume nt,  in  whic h  c ase   it  is  c alle d 
a no ­argume nt c o nstruc to r. 
Co nstructo r  argume nts  c an  be   use d  to   initialize   the   fie lds  in  the  
o bje c t.

Example 1
class 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();
}}
Constructor
Example 2
class Rock2 {
Rock2(int i) {
System.out.println("Creating Rock number " + i);
}}

public class SimpleConstructor2 {


public static void main(String[] args) {

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


for (int i = 0; i < 10; i++)
new Rock2(i);
}}

Example 3: Constructor Overloading


public class MainClass {
double radius;
MainClass() {
}

// Class constructor
MainClass(double theRadius) {
radius = theRadius;
}
}
Polymorphism
 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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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.
Constructor
Example 4: this()
class Sphere {
int radius = 0;
Sphere() {
radius = 1;
}
Sphere(int radius) {
this.radius = radius;
}

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


}

Example 5: Calling a Constructor From a Constructor


class 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;
}}
Method Overloading
Example 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){

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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);
}
}
Access Modifiers
 You can define the scope of a variable or
method or class by using access modifiers.
 Public
 Protected

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 Default
 Private

Modifier Class Package Subclass World


public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
(default)
private Y N N N
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.

Inheritance
 Types of inheritance
 Simple Inheritance
 Multilevel Inheritance

Simple Ex1: Simple
class A {

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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");
}
}
Inheritance
Multilevel Ex2: Multilevel
class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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();
}
}
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


super class hidden by the sub class.
 Second: To call super class constructor in the
subclass
Inheritance
Ex1: super keyword
class A{
int a;
float b;
void Show(){
System.out.println("b in super class: " + b);
}
}

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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();
}
}
Inheritance
Ex2: Simple
class A{
int a;
int b;
int c;
A(int p, int q, int r){
a=p;
b=q;
c=r;

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


}
}
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();
}
}
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.
Inheritance - Overriding
Ex1:
class Animal{

public void move(){


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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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
}
}
Inheritance - Overriding
Ex2:
class Animal{

public void move(){


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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.
}
}
Inheritance - Overriding
Ex3:
class Animal{

public void move(){


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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.Jerome, Technical Consultant, CalydonTech, jerome@caly
Interfaces
R.Jerome, Technical Consultant, CalydonTech, jerome@caly
Abstract Classes
Exceptions
 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,

R.Jerome, Technical Consultant, CalydonTech, jerome@caly



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
Categories 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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.
Exception Hierarchy

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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
List 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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.
List of Checked or CompileTime Exceptions
 Following is the list of Java Checked Exceptions
Defined in java.lang.
Exception Description
ClassNotFoundException Class not found.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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

IllegalAccessException Access to a class is denied.


InstantiationException Attempt to create an object of an abstract class or
interface.

InterruptedException One thread has been interrupted by another thread.

NoSuchFieldException A requested field does not exist.


NoSuchMethodException A requested method does not exist.
Exception 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()

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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.
Catching 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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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
}
Catching 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);

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


j = numer1/denom2;
System.out.println("numer1/denom2 = " + j);
}
catch(ArithmeticException e) {
System.out.println("Arithmetic Exception!");
}
System.out.println("Done with test");
}
}
Catching Exceptions
Ex2:
public class exception_handling
{
public static void main (String args[])
{
int array[]={10,20,30};
int num1=15, num2=10;

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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 (ArrayIndexOutOfBoundsExceptione) {
System.out.println("Error.... Array is out of Bounds");
}
catch (ArithmeticExceptione) {
System.out.println ("Sorry.....Can't be divided by Zero"); }
}
}
Finally Block

 A finally block is always executed, regardless


of the cause of exit from the try block, or
whether any catch block was executed.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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>
}
Final Block Example
Ex3:
public class DivideException2 {
public static void main(String[] args) {
intresult = 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.");

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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;
}
}
Rules for try, catch and finally Blocks

 For each try block there can be zero or more


catch blocks, but only one finally block.  

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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
The 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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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
}
The 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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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}
Declaring 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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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 Exception
Ex4:
// File Name InsufficientFundsException.java
import java.io.*;
public class InsufficientFundsException

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


extends Exception{
private double amount;
public InsufficientFundsException(double
amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}
Declaring you own Exception
Ex4:
// File Name CheckingAccount.java
import java.io.*;
public class CheckingAccount{
private double balance;
private int number;
public CheckingAccount(intnumber) {
this.number = number;
}

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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 Exception
Ex4:
// File Name BankDemo.java
public 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...");

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsExceptione) {
System.out.println("Sorry, but you are short $"
+ e.getAmount());
e.printStackTrace();
}
}
}
Declaring you own Exception
Ex5:
class BadTemperature extends Exception{
BadTemperature( String reason ){
super ( reason );
}
}
class TooHot extends BadTemperature{
TooHot(){

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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 Exception
Ex5:
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");

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


}
}
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 Exceptions
Ex6:
public class ExceptionExample6 {
public static void main(String[] args) {
int x = 10, y = 2;
int counter = 0;
boolean flag = true;
while (flag) {
start:
try {

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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;
}}}
Java I/O
 Java I/O Operations are done by Standard
Streams.
 They read input from the keyboard and write
output to the display.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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.
Java 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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 System.in is a byte stream that has no
character stream features.
 The java.io package contains two classes,
InputStream and OutputStream
InputStream
 The InputStream class is an abstract base
class
 The InputStream class defines a methods for
 reading bytes or arrays of bytes,

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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.Jerome, Technical Consultant, CalydonTech, jerome@caly
InputStream
OutputStream
 The OutputStream class is an abstract base
class.
 OutputStream defines methods for writing
bytes or arrays of bytes to the stream and

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.Jerome, Technical Consultant, CalydonTech, jerome@caly
OutputStream
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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.
Overview of Filtered Streams
 DataInputStream and DataOutputStream
 Readsor writes primitive Java data types in a
machine independent format.
BufferedInputStream and

R.Jerome, Technical Consultant, CalydonTech, jerome@caly



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.
InputStream Methods
Method Summary

int available()
Returns the number of bytes that can be read (or skipped over) from this input stream without blocking by the

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


next caller of a method for this input stream.
void close()
Closes this input stream and releases any system resources associated with the stream.
void mark(int readlimit)
Marks the current position in this input stream.
boolean markSupported()
Tests if this input stream supports the mark and reset methods.
abstract int read()
Reads the next byte of data from the input stream.
int read(byte[] b)
Reads some number of bytes from the input stream and stores them into the buffer array b.
int read(byte[] b, int off, int len)
Reads up to len bytes of data from the input stream into an array of bytes.
void reset()
Repositions this stream to the position at the time the mark method was last called on this input stream.
long skip(long n)
Skips over and discards n bytes of data from this input stream.
OutputStream Methods

Method Summary
void close()
Closes this output stream and releases any system resources associated with this
stream.
void flush()

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.
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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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.
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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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)
InputStreamReader

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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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
InputStreamReader
Ex2:
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;

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.
}
}
}
InputStreamReader
Ex3:
import java.io.*;
public class TrivialApplication {
private static final int MAX = 10;

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


int i;

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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]);
}
}
}
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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 "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);
BufferedReader
Ex1:
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");

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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){}
}
}
Using 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");

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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);
}
}
}
Using Streams to Read and Write
Files
Ex2:
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")));

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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();
}
}
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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.
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   Me tho ds  o f  the   File   c lass  are   sho wn  in  the  

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.
Files
Ex1:
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()){

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


f.createNewFile();
System.out.println("New file sample_file.txt has been
created.");
}
}
}
Files
Ex2:
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);

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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");
}
}
}
Files
Ex3:
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");

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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");
}
}
Files
Ex4:
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");

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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();
}
}
}
Files
Ex5:
import java.io.*;

public class WriteFile{

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

File f=new File("C:/Program

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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");
}
}
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly



and the old one is disused.
 This causes extraneous garbage collection if string modifier
methods are used too often.
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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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.
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)

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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.
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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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.
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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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 Examples
Ex1:
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);

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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 Examples
Ex2:
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 expression
String name = "bob";
String str4 = "My name is " + name;

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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));
}
}
R.Jerome, Technical Consultant, CalydonTech, jerome@caly
String Examples

StringDemo3
Ex3:
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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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.
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()

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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 Examples
Ex1:
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{

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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 Examples
Ex1:
//insert()
strbuf.insert(5,"_Java ");
System.out.println(strbuf);

//reverse()
strbuf.reverse();

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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 Examples
Ex1:
//deleteCharAt()
strbuf.deleteCharAt(3);
System.out.println(strbuf);

//capacity()
System.out.print("Capacity of StringBuffer object : ");

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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());
}
}
}
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,

R.Jerome, Technical Consultant, CalydonTech, jerome@caly



g), getChars(i), setCharAt(iposn, c), substring(),
replace(i1,i2,gvalue), reverse(), trimToSize(g ), toString(g)

6 char StringBuilder nulString=new StringBuilder(6); // explicitly sets size StringBuilde
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly



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().
StringTokenizer Class
Ex1:
import java.util.*;
public class Test
{
public static void main(String args[])

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


{
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?
COLLECTIONS
ü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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.
Collections
ü A Collections Framework mainly contains the following 3 parts
ü Set of interfaces

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


ü 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.
Core Collection Interfaces
ü Collection
ü Set

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


ü List
ü SortedSet
ü Map
ü SortedMap

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


Collection Interfaces

Collection Map

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


List Set

Sorted Map

Sorted Set

perations are all there, but you work with a key-value pair instead of an isolated element. Map i
Hierarchical Relationships
vThe Collection interface is a group of objects, with
duplicates allowed.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


vThe Set interface extends Collection but forbids duplicates.
vThe List interface extends Collection, allows duplicates, and
introduces positional indexing.
vThe Map interface extends neither Set nor Collection.
R.Jerome, Technical Consultant, CalydonTech, jerome@caly
Collection Interfaces
R.Jerome, Technical Consultant, CalydonTech, jerome@caly
Concrete Classes
Operations
o boolean add(Object element)
o boolean remove(Object element)

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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

nterface returns an Iterator. An Iterator is similar to the Enumeration interface witch has the
Group Operations
 boolean containsAll(Collection collection)
 boolean addAll(Collection collection)
 void clear()
 void removeAll(Collection collection)

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 void retainAll(Collection collection)

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

method ensures all elements from another collection are added to the current collection

ethod removes all elements from the current collection


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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


ü 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 
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


Example :LinkedListExample.java 
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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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 
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


elements properly among the buckets.
 To prevent unsynchronized access to the Set: Set s =
Collections.synchronizedSet(new HashSet(…));

Example :HashSetExample.java 
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


Example :HashTableDemo.java 
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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 This implementation not synchronized provides guaranteed log(n) time cost
for the basic operations (add, remove and contains

Example :TreeSetExample.java 
Map Interface
 The Map interface is not an extension of the Collection
interface. Instead, the interface starts off its own interface

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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()
HashMap 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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.
Example:MapExample.java

import java.util.*;
public class MapExample {
public static void main(String args[]) {
Map map = new HashMap();
Integer ONE = new Integer(1);

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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);
}
}
Annotation
 Java, being a wonderful object-oriented
language provided support for Annotations
starting from 5.0.
 Annotations in Java is all about adding meta-

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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
Annotation
Employee.java
final class Employee{
private String name;
private String id;
// Getters and setters for Employee class.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly



}
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.
Annotation
TestAnnotation.java
public @interface TestAnnotation{
// Property Definition here.
}
 Don't get confused with the interface keyword.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.
Annotation
TestAnnotation.java
@Target(ElementType.METHOD)
public @interface TestAnnotation{
// Property Definitions here.
}
 Meta-Annotations (meta-data about meta-data)

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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.
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.
Annotation
TestAnnotation.java
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
public @interface TestAnnotation{
// Property Definitions here.
}
 Retention Annotation

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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.
Built-in Annotations in Java
 There are some pre-defined annotations
available in the Java Programming language.
They are,
1. Override

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


2. Deprecated
3. SuppressWarnings
Override 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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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

Annotation
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.RUNTIME)
public @interface Override{
}
Override Annotations
Employee.java
public class Employee {
protected void startWork() {
Manager.java
// Code
public class that willextends
Manager start toEmployee
do some work.
{
}@Override

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


} protected void startWork(){
// Code that will start to do some work.
}
}

 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.
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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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
The @Deprecated Annotation
Ex:
public class MyOldClass {
@Deprecated
public void myDeprecatedMethod(){
// Obsolete code here.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


}
public void myAlternativeMethod(){
// Revised code here.
}
 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.
The @SuppressWarnings Annotation
Ex:
public class SuppressWarningsExample{

@SuppressWarnings(value={"deprecation"}
)

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


public static void main(String[]
args) {
 These types ofDate
annotations
date=ensure
newthatDate(2008,
the compiler will9,
shield the
warning message in the annotated elements and also in all of its
30);
sub-elements.

System.out.println("date = " +
The @SuppressWarnings annotation tells the compiler to suppress
date);
the warning messages it normally show during compilation time.
 } level of suppression to be added to the code, these level
It has some
}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.

User-defined Annotations
Author.java
import java.lang.annotation.*;
public @interface Author{
String name();
}

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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


User-defined Annotations
AnnotatedClass.java (Using Annotation Author)
public class AnnotatedClass{
@Author(name = "Author1")
public void annotatedMethod1(){
}

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


} annotation member elements can be set to
 The
have default values. Here’s an example
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 here
public 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)

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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.
User-defined Annotations
Author.java
import java.lang.annotation.*;
@Target(value = {ElementType.CONSTRUCTOR, ElementType.METHOD,
ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Author{
Version.java
String name() default "unknown";
}

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


import java.lang.annotation.*;
@Target(value = {ElementType.CONSTRUCTOR, ElementType.METHOD,
ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Version{
double number();
}
User-defined Annotations
AnnotatedClass.java
@Author(name = "Johny")
@Version(number = 1.0)
public class AnnotatedClass{
@Author(name = "Author1")
@Version(number = 2.0f)
public void annotatedMethod1() {
}

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


@Author(name = "Author2")
@Version(number = 4.0)
public void annotatedMethod2() {
}
}
User-defined Annotations
See the Annotation details
AnnotationReader.java
Out Put
C:\caly\ano>java AnnotationReader

Finding annotations on java.lang.Class

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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
CarAnnotation.java
import java.lang.annotation.*;
@Target(ElementType.TYPE)
AbstractBMWCar.java
@Retention(RetentionPolicy.RUNTIME)
@CarAnnotation(maker="BMW")
@Inherited
public class AbstractBMWCar{
BMWRoadsterCar.java

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


public
public @interface
} CarAnnotation{
class BMWRoadsterCar extends
public String maker();
AbstractBMWCar{
}
}
Inherited Annotations
CarAnnotationTest.java
public class CarAnnotationsTest{
public static void main(String[] args) {
Output
Class[]with
classes@inherited annotation
= {AbstractBMWCar.class,
No. of annotations: 1
BMWRoadsterCar.class};
BMW for (Class classObj: classes) {
Output
No. of without @inherited
annotations: 1 annotation
Annotation[] annotations = classObj.getAnnotations();
BMW
No. of System.out.println("No.
annotations: 1 of annotations: " +
annotations.length);
BMW

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


No. of for
annotations: 0
(Annotation annotation: annotations) {
CarAnnotation carAnnotation = (CarAnnotation)annotation;
System.out.println(carAnnotation.maker());
}
}
}
}

 The annotation member elements can be set to


have default values. Here’s an example
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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
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.Jerome, Technical Consultant, CalydonTech, jerome@caly


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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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.
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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
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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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
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.

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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

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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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.
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:

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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.
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


 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
A List of JDBC Driver Vendors
Vendor 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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


DataRamp 3 ODBC supported databases
IBM 2/3 IBM DB2 Version 2
IDS Software 3 Oracle, 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 3 Oracle, Sybase, MS SQL Server, MS Access, Watcom,
ODBC supported databases
Visigenic 3 ODBC supported databases
WebLogic 2/3 Oracle, Sybase, MS SQL Server/ODBC supported
databases
List of JDBC Drivers
Database
IBMServer
JDBC-ODBC
Mcrosoft
Oracle
PointBase
Cloudscape
Firebird
IDS
Informix
DB2
Thin
(JCA/JDBC
Dynamic
SQL
Embedded
RMI
Bridge
Server
Server
Driver)
Server
Driver
jdbc:informix-
jdbc:db2://<HOST>:<PORT>/<DB>
jdbc:odbc:<DB>
jdbc:weblogic:mssqlserver4:<DB>@<HOST>:<PORT>
jdbc:oracle:thin:@<HOST>:<PORT>:<SID>
jdbc:pointbase://embedded[:<PORT>]/<DB>
jdbc:cloudscape:<DB>
jdbc:rmi://<HOST>:<PORT>/jdbc:cloudscape:<DB>
jdbc:firebirdsql:[//<HOST>[:<PORT>]/]<DB>
jdbc:ids://<HOST>:<PORT>/conn?dsn='<ODBC_DSN_NAME>'
COM.ibm.db2.jdbc.app.DB2Driver
sun.jdbc.odbc.JdbcOdbcDriver
weblogic.jdbc.mssqlserver4.Driver
oracle.jdbc.driver.OracleDriver
com.pointbase.jdbc.jdbcUniversalDriver
COM.cloudscape.core.JDBCDriver
RmiJdbc.RJDriver
org.firebirdsql.jdbc.FBDriver
ids.sql.IDSDriver
sqli://<HOST>:<PORT>/<DB>:INFORMIXSERVER=<SERVER_NAME>
com.informix.jdbc.IfxDriver

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


List of JDBC Drivers
Database
Hypersonic
Microsoft
MySQL
Oracle
PostgreSQL
Driver)
OCI
(MM.MySQL
SQL
SQL
8i
9i
(v6.5
(v7.0
Server
(v1.2
(v1.3
and later)
earlier)
(JTurbo
(Sprinta
2000
and
Driver)
earlier)
later)
(Microsoft
Driver)
Driver
jdbc:HypersonicSQL:<DB>
jdbc:JTurbo://<HOST>:<PORT>/<DB>
jdbc:inetdae:<HOST>:<PORT>?database=<DB>
jdbc:microsoft:sqlserver://<HOST>:<PORT>[;DatabaseName=<DB>]
jdbc:mysql://<HOST>:<PORT>/<DB>
jdbc:oracle:oci8:@<SID>
jdbc:oracle:oci:@<SID>
jdbc:postgresql://<HOST>:<PORT>/<DB>
hSql.hDriver
org.hsql.jdbcDriver
com.ashna.jturbo.driver.Driver
com.inet.tds.TdsDriver
com.microsoft.sqlserver.jdbc.SQLServerDriver
org.gjt.mm.mysql.Driver
oracle.jdbc.driver.OracleDriver
postgresql.Driver
org.postgresql.Driver

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


List of JDBC Drivers
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

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


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 Examples

JDBC Examples
MSAccess
JdbcMSAccess.java

R.Jerome, Technical Consultant, CalydonTech, jerome@caly


MSAccess
JdbcMsAccessControl.java
Oracle
JdbcOracle.java

Vous aimerez peut-être aussi