Sunteți pe pagina 1din 68

M.J.

JAVA Outline

Java
Comments:
Java has three types of comments:
// This is single line comment
/* This is multi line
comment */
/** This Java document comments: Special type of comments used in Java */
Java is case sensitive and strongly typed language which means you cant assign a
integer variable to float same for other types.

Java HelloMJS program:


class MJS
{
public static void main(String args[])
{ System.out.println("Hello M.J.S"); }
}

Data Types:
Java defines 8 simple data types. Java doesnt have unsigned types.

Integer Types
Type
Identifier

Width
Bits

long

64

int
short
byte

32
16
8

Range
9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
2,147,483,648 to 2,147,483,647
32,768 to 32,767
128 to 127

Float Point Types


Type Identifier Width Bits
Range
double
64
4.9e324 to 1.8e+308
float
32
1.4e045 to 3.4e+038

Character Type

Java uses Unicode to represent characters.


Type Identifier Width Bits
Range
char
16
0 to 65,536

M.J.S
Copyright 2007

Boolean Type
Type Identifier Width Bits
Range
boolean
JVM specific true or false

jasim.shah@yahoo.com

M.J.S

JAVA Outline

Variables Declarations:
Syntax: type identifier [ = value][, identifier [= value] ...] ;
e.g. int a = 5, b, c = 8;
e.g. char ch = M;
e.g. float area = 45.334;

Arrays:
In Java arrays are dynamically allocated. All array indexes starts from 0. Java has run
time array boundary check.
One Dimensional Array:
In Java Arrays are declared in two steps:
a. Declare a array. Syntax: type variableName[]; e.g. int rollNos[];
b. Allocate memory for the array. Syntax: variableName = new
type[size];
e.g. rollNos = new int[30];
Above two steps can be combined in one step as:
e.g. int rollNos[] = new int[30];

Initializing array:
Syntax: variableName[index] = value; e.g. rollNos[0] = 1;
Arrays can be initialized when they are declared as:
Syntax: type variableName[] = {initializer list};
e.g. int rollNos[] = {1,2,3,4,5};

Multi Dimensional Array:


Multidimensional arrays are actually arrays of arrays
e,g, int twoD[][] = new int[2][3];
e.g. int twoD[][] = { {2,3,4,5}, {2,2,1,4}, {3,2,4,5} };

Strings:
Java uses String type to create string object which can be assigned a quoted
string.
Syntax: String stringObjectName;
e.g. String name = MJS;

Operators
Arithmetic operators.
Java
operation

Arithmetic
operator

Algebraic
expression

Java
expression

Addition

f+7

f+7

Subtraction

p-c

p-c

Multiplication

bm

b*m

Division

x/y

x/y

Remainder

r mod s

r%s

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

Type Conversion, Casting and Promotions


Automatic Conversion:
When one type of data is assigned to another type of variable, an automatic type
conversion will take place if the following two conditions are met:
o When two types are compatible.
Like numeric types int, float, double, byte, types are compatible with each
others but these are not compatible with boolean or char.
o Destination type is larger than source type.
For example byte to int conversion, int to float conversion. These are called
widening conversions.
Type Casting:
For explicit type conversions casting is used for example assigning a larger value to
smaller destination this is called narrowing conversion. And for incompatible types
conversion casting is used.
Syntax: Result = (target-type) value;
e.g. If you convert float value into int value truncation is performed and fractional part
is lost. e.g. 35.043 is converted to in the result will be 35.
e.g. I you convert int into byte value. Result will be reduced modulo means int value
is divided by byte type's range which is 256. e.g. if you assign 257 int value to byte by
casting result will be 257/256 = 1.
Automatic Type Promotion in Expressions:
Consider :
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
The result of the intermediate term a * b easily exceeds the range of either of its byte
operands. To handle this kind of problem, Java automatically promotes each byte or
short operand to int when evaluating an expression. This means that the sub
expression a * b is performed using integersnot bytes. Thus, 2,000, the result of the
intermediate expression, 50 * 40, is legal even though a and b are both specified as
type byte.
Type Promotion Rules:
All byte and short values are promoted to int, as just described. Then, if one operand
is a long, the whole expression is promoted to long. If one operand is a float, the
entire expression is promoted to float. If any of the operands is double, the result is
double.

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

Special Arithmetic Operators


Java Operation
Increment
Decrement
Addition Assignment
Subtraction
Assignment
Multiplication
Assignment
Division Assignment
Modulus Assignment

Arithmetic
Operator
++
-+=

Algebraic
expression
a=a+1
a=a1
a=a+b

Java
expression
a++
a-a += b

-=

a=ab

a -= b

*=

a=a*b

a *= b

/=
%=

a=a/b
a = a mod b

a /= b
a %= b

Equality operators.
Standard algebraic
equality or relational
operator

Java equality or
relational
operator

Sample Java
condition

Meaning of
Java condition

Equality operators
=

==

x == y

x is equal to y

!=

x != y

x is not equal to
y

Relational operators
>

>

x>y

x is greater
than y

<

<

x<y

x is less than y

>=

x >= y

x is greater
than or equal to
y

<=

x <= y

x is less than or
equal to y

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

Boolean Logical Operators


Operator

Result

Operator

Result

Operator

Result

&

Logical AND
If left hand
side is false,
without
checking right
hand side it
results false.

Logical OR
If left hand
side is true,
without
verifying right
hand side it
returns true.

Unary NOT

&=

And
Assignment

|=

OR
Assignment

!=

Not Equal
To

==

Equal To

^=

XOR
Assignment

||

Short Circuit
OR
Checks both
sides and then
results.

&&

?:

Ternary ifthen-else

A^B
False
True
True
False

!A
True
False
True
False

XOR
(exclusive OR)
Short Circuit
AND
Checks both
sides and then
results.

Logical Operator Results


A
False
True
False
True

B
False
False
True
True

A|B
False
True
True
True

A&B
False
False
False
True

The ? Operator:
Syntax: Result = expression ? incase true : incase false;
If expression is true then true case is executed. When expression is false then false
case is executed.
e.g. stringResult = age < 12 ? child : adult;

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

Control Statements:
Selection Statements:
There are two selection statements in Java: if and switch:

a. if
Syntax : if (condition) statementsIfTrue
e.g. if (weight == 0) Sytem.out.println(Error: Weight cant be zero);
if_else
Syntax: if (condition) statementsIfTrue; else statementsIfFalse;

e.g. if (password == mjs)


{ System.out.println(Welcome);
Login(); }
else { System.out.println(Password not correct); exitSystem();
}
if_else_if
Syntax: if (condition1) statement1 else if(condition2) statement2 else
statement3
e.g.
if (gender == female)
if (age > 25)
Sytem.out.println(Woman);
else
System.out.println(Girl);
else if (gender == male)
System.out.println(Man);
else
System.out.println(Boy);

b. switch
The expression must be of type byte, short, int, or char; each of the values specified in
the case statements must be of a type compatible with the expression. Each case value
must be a unique literal (that is, it must be a constant, not a variable). Duplicate case
values are not allowed.
Syntax
Example
switch(expression) {
switch(choice) {
case value1: statements; break;
case o: open(); break;
case value2: statements; break;
case c: close(); break;
case valuen: statements; break;
case e: exit(); break;
default:
default:
default statements; }
system.out.println(not valid choice);
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

Switch Example:
switch(intM)
{
case 1: //If M is 1
case 2: //If M is 2
case 3:
case 4:
System.out.println(M is less than 5);
break;
case 5:
System.out.println(M is 5);
}

Iteration Statements
for
Syntax:
for(initialization; condition;
iteration) statements;
e.g.
int m;
for(m = 1; m<=10; m++)
System.out.println(m);
e.g.
for( ; ;) //infinite loop
e.g.
for(int m=0; m<5; m++)
//declaration in loop
e.g.
for(m=0,j=1;m<10; m++,j-)
//multiple initialization
// and multiple iteration

M.J.S
Copyright 2007

while

do_while

Syntax:
while(condition)
statements;

Syntax:
do {
e.g.
// body of loop.
int m = 1;
// In this loop body is
while(m<=10)
//executed at least
System.out.println(m); once //without
checking //condition.
e.g.
} while(condition);
while(++m < 5);
/*empty body, counting e.g. do {
m*/
//Print Menu
// choose e to exit
e.g. while(choice != e) } while(choice != e);
{ //menu. Press e to
exit }

jasim.shah@yahoo.com

M.J.S

JAVA Outline

Jump Statements:
Java supports three jump statements:
1. break; break statements has three basic uses:
a. In switch statement to terminate case.
b. Used to exit from loops
e.g. for(int m=1; m<=10; m++) {
if(m == 5) break; /*break loop when m is 5*/ System.out.println(m); }
c. Used as civilized form of goto.
By using this form of break, you can break out of one or more blocks of code. These
blocks need not be part of a loop or a switch. They can be any block. You can use a
labeled break statement to exit from a set of nested locks. But you cannot use break to
transfer control to a block of code that does not enclose the break statement.
Syntax : break label;
e.g. // Using break as a civilized form of goto.
class Break {
public static void main(String args[])
{
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
2. continue; continue statement has two uses:
a. In loops: In while and do-while loops, a continue statement causes control to be
transferred directly to the conditional expression that controls the loop. In a for
loop, control goes first to the iteration portion of the for statement and then to the
conditional expression. For all three loops, any intermediate code is bypassed.
e.g. for(int m = 1; m<=5; m++)
{ if(m==3) continue; /*Skip printing of 3*/ System.out.println(m); }
b. As with the break statement, continue may specify a label to describe which
enclosing loop to continue. Syntax: continue label;
3. return
The return statement is used to explicitly return from a method. And also used
to return any value or result to caller.

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

Classes And Objects:


Class is a template for an object, and an object is an instance of a class.

Syntax:

Example

class className
{
type instance-variable1;
type instance-variable2;
type instance-variableN;

class Rectangle
{
int height;
int width;
int Area()
{
return height*width;
}

type methodname1(parameter-list)
{ // body of method }
type methodname2(parameter-list)
{ // body of method }

type methodnameN(parameter-list)
{ // body of method }
}

Declaring Objects of Class:


Syntax: className objName = new classNameOrConstructor();
e.g. Rectangle myRec = new Rectangle();
OR
className objName; //declare reference to object
objName = new classNameOrConstructor(); //allocate a object
e.g. Rectangle myRec;
myRec = new Rectangle();
e.g. class Rectangle {
int height, width;
public static void main(String args[])
{
Rectangle myRec = new Rectangle();
myRec.height = 3;
myRec.width = 2;
System.out.println("Area of Rectangle :" +
myRec.height*myRec.width); } }
Assigning Object Reference Variables:
When you assign one object reference variable to another object reference variable,
you are not creating a copy of the object; you are only making a copy of the reference.
e.g. Rectangle myRec1 = new Rectangle();
Rectangle myRec2 = myRec1;
In above example both myRec1 and myRec2 are referring to a single object. myRec1
is not copied to myRec2 only its address.

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

10

Methods:
Syntax: type methodName(parameterList)
{ /* body of method */ }
type specifies the type of data returned by the method including class types that you
create. If method dont return any value then type must be void. The parameter-list is
a sequence of type and identifier pairs separated by commas. Parameters are
essentially variables that receive the value of the arguments passed to the method
when it is called. If the method has no parameters, then the parameter list will be
empty.

Method Returning Value


class Rectangle
{
int height;
int width;
int Area()
{
return height * width;
}
}
class rectangleTest
{
public static void main(String
args[])
{

Method With Parameters


class Rectangle
{
int height;
int width;
void getParameter(int recHeight,
int recWidth)
{
height = recHeight;
width = recWidth;
}

void showArea()
{
System.out.println("Area of
Rectangle : " + height*width);
}
Rectangle myRec = new Rectangle(); }
myRec.height = 3;
class rectangleTest
myRec.width = 5;
{
int Area = myRec.Area();
public static void main(String
System.out.println("Area of
args[])
Rectangle: " + Area);
{
}
Rectangle myRec = new
}
Rectangle();
myRec.getParameter(3,4);
myRec.showArea();
}
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

11

Method Overloading:
Method overloading is one of the ways that Java implements polymorphism. Java
uses the type and/or number of arguments as its guide to determine which version of
the overloaded method to actually call. Thus, overloaded methods must differ in the
type and/or number of their parameters.
Example:
class methodOverload {
void Sum() //No Parameter is defined
{ System.out.println("No Argument is given."); }
void Sum(int a) //One int Parameter is defined
{ System.out.println("Only One argument is given."); }
void Sum(int a, int b) //Two int Parameters for sum
{ System.out.println("Sum of two given integers : " + (a+b)); }
void Sum(int a, float b) //One int and one float parameter
{ System.out.println("Sum of int + float :" + (a+b)); }
void Sum(double a,double b) //Two double Parameters
{ System.out.println("Sum of two doubles :" + (a+b)); }
public static void main(String args[]) //Main
{
methodOverload test = new methodOverload();
test.Sum();
test.Sum(5);
test.Sum(5,5);
test.Sum(5,3.5f);
test.Sum(3.5,2.95);
}
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

12

Constructors and Destructors:


Constructors are methods having same name as the class in which it resides and is
syntactically similar to a method. Once defined, the constructor is automatically
called immediately after the object is created, before the new operator completes.
They have no return type, not even void. This is because the implicit return type of a
class constructor is the class type itself. Other properties of constructor are same as
simple methods like they can have parameters and overloading.
Destructors are methods, called when object is destroyed. For Destructor Java
provides a mechanism called finalization. It provides a finalize() method which acts
as destructor is only called just prior to garbage collection. It is not called when an
object goes out-of-scope, for example. This means that you cannot know whenor
even iffinalize( ) will be executed. So seldom used.

Example:
class Rectangle {
int height, width;
Rectangle(int recHeight, int recWidth) //Constructor to initilize
{
System.out.println("Constructor is called object is going to initialized");
height = recHeight;
width = recWidth;
}
protected void finalize()
{ System.out.println("Finalize is called object is going to destroy."); }
void showRec() //Simple Method
{ System.out.println("Height = " + height + " Width = " + width); }
public static void main(String args[])
{
Rectangle myRec = new Rectangle(4,5);
myRec.showRec();
}
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

13

Call_By_Value OR Call_By_Reference:
In general, there are two ways that a computer language can pass an argument to a
subroutine. The first way is call-by-value. This method copies the value of an
argument into the formal parameter of the subroutine. Therefore, changes made to the
parameter of the subroutine have no effect on the argument. The second way an
argument can be passed is call-by-reference. In this method, a reference to an
argument (not the value of the argument) is passed to the parameter. Inside the
subroutine, this reference is used to access the actual argument specified in the call.
This means that changes made to the parameter will affect the argument used to call
the subroutine. As you will see, Java uses both approaches, depending upon what is
passed.
When an object reference is passed to a method, the reference itself is passed by use
of call-by-value. However, since the value being passed refers to an object, the copy
of that value will still refer to the same object that its corresponding argument does.
When a simple type is passed to a method, it is done by use of call-by-value. Objects
are passed by use of call-by-reference.
Returning and Passing Objects to Methods:
class Box
{ int height, width;
Box(int boxHeight,int boxWidth)
{
height = boxHeight;
width = boxWidth;
}
void showboxHeightWidth()
{
System.out.println("Height = " + height);
System.out.println("Width = " + width);
}
Box changeBox(Box objBox) //Object as return type and as parameter
{
objBox.height = 7;
objBox.width = 9;
return objBox;
}
public static void main(String args[])
{
Box myBox = new Box(3,5); //Create myBox object
System.out.println("Before Change");
myBox.showboxHeightWidth(); //print myBox
myBox = myBox.changeBox(myBox); //myBox is given to method for
change
System.out.println("After Change");
myBox.showboxHeightWidth();
}
}
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

14

Instance Variable Hiding and use of this keyword:


When a local variable has the same name as an instance variable, the local variable
hides the instance variable. this is always a reference to the object on which the
method was invoked. Because this lets you refer directly to the object, you can use it
to resolve any name space collisions that might occur between instance variables and
local variables.
Example:
Without this
class Rectangle
{
int height, width;
Rectangle(int height,int width)
{ //Here is error
height = height;
width = width;
}

Using this
class Rectangle
{
int height, width;
Rectangle(int height,int width)
{ //this used here
this.height = height;
this.width = width;
}

void showRect()
{
System.out.println("Height = " +
height + "\nWidth = " + width);
}

void showRect()
{
System.out.println("Height = " +
height + "\nWidth = " + width);
}

public static void main(String args[])


{
Rectangle myRec = new
Rectangle(3,4);
myRec.showRect();
}
}

public static void main(String


args[])
{
Rectangle myRec = new
Rectangle(3,4);
myRec.showRect();
}
}
Output:
Height = 3
Width = 4

Output:
Height = 0
Width = 0

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

15

Access Control:
You can control what parts of a program can access the members of a class. Java
supplies a rich set of access specifiers to control this access. Javas access specifiers
are public, private, and protected.
private
When a member of a class is specified as private, then that member can only be
accessed by other members of its class.
public
When no access specifier is used, then by default the member of a class is public
within its own package, but cannot be accessed outside of its package. You can
understand why main( ) has always been preceded by the public specifier. It is called
by code that is outside the programthat is, by the Java run-time system.
Syntax
class className
{
access specifier type varName;
access specifier returnType
methodName(parameterList)
{ /* method Body */ }
}

Example
class Circle
{
private double radius;
Circle(double radius) //Constructor
{ this.radius = radius; }
private double calcArea() //private
method
{
return (radius * radius) * 3.142857;
}
void showArea() //public method
{
System.out.println("Area : " +
calcArea());
}
}
class circleTest
{
public static void main(String
args[])
{
Circle myCircle = new Circle(3.9);
myCircle.showArea();
//myCircle.calcArea(); //Error
calcArea is private to Circle class
}
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

16

What is static:
When a member is declared static, it can be accessed before any objects of its class
are created, and without reference to any object.
In Java static is used in 3 ways:
Instance variables declared as static:
Instance variables declared as static are, essentially, global variables. When objects of
its class are declared, no copy of a static variable is made. Instead, all instances of the
class share the same static variable.

class Student
{
int stuRollNo;
String stuName;
static int totalStudents = 0; //static variable
Student(int rollno, String name)
{
stuRollNo = rollno;
stuName = name;
totalStudents++;
}
void totalStudent()
{
System.out.println("Total Students Created :" + totalStudents);
}
}
class studentTest
{
public static void main(String args[])
{
Student st1 = new Student(1,"Ali");
Student st2 = new Student(2,"Junaid");
Student st3 = new Student(3,"M");
st1.totalStudent();
}
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

17

Methods declared as static:


Methods declared as static have several restrictions:
They can only call other static methods.
They must only access static data.
They cannot refer to this or super in any way.
It is illegal to refer to any instance variables inside of a static method.
The most common example of a static member is main( ). main( ) is declared as static
because it must be called before any objects exist.
Declare a static block:
You can declare a static block which gets executed exactly once, when the class is
first loaded.
// Demonstrate static variables, methods, and blocks.
class UseStatic
{
static int a = 3;
static int b;
static void meth(int x)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static { //static block
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
You can call a static method of any class1 form any class2 by:
class class2Name {
class1Name.staticMethodName(); }

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

18

Nested Classes
It is possible to define a class within another class; such classes are known as nested
classes. The scope of a nested class is bounded by the scope of its enclosing class.
Thus, if class B is defined within class A, then B is known to A, but not outside of A.
A nested class has access to the members, including private members, of the class in
which it is nested. However, the enclosing class does not have access to the members
of the nested class.
There are two types of nested classes: static and non-static.
static:
A static nested class is one which has the static modifier applied. Because it is static,
it must access the members of its enclosing class through an object. That is, it cannot
refer to members of its enclosing class directly. Because of this restriction, static
nested classes are seldom used.
Non-static:
The most important type of nested class is the inner class. An inner class is a nonstatic nested class. It has access to all of the variables and methods of its outer class
and may refer to them directly in the same way that other non-static members of the
outer class do. Thus, an inner class is fully within the scope of its enclosing class.
class Outer
{
private String msg;
Outer (String msg) //Constructor of Outer
{ this.msg = msg; }
void outerShow()
{
Inner objInner = new Inner();
objInner.show();
}
class Inner
{
void show()
{ System.out.println(msg); }
}
}
class Test
{
public static void main(String args[])
{
Outer testObj = new Outer("Hello M");
testObj.outerShow();
}
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

19

Recursion:
Recursion is the process of defining something in terms of itself. As it relates to Java
programming, recursion is the attribute that allows a method to call itself. A method
that calls itself is said to be recursive. When a method calls itself, new local variables
and parameters are allocated storage on the stack, and the method code is executed
with these new variables from the start. A recursive call does not make a new copy of
the method. Only the arguments are new. As each recursive call returns, the old local
variables and parameters are removed from the stack, and execution resumes at the
point of the call inside the method. Recursive versions of many routines may execute
a bit more slowly than the iterative equivalent because of the added overhead of the
additional function calls. Many recursive calls to a method could cause a stack
overrun. Because storage for parameters and local variables is on the stack and each
new call creates a new copy of these variables, it is possible that the stack could be
exhausted. If this occurs, the Java run-time system will cause an exception.

Example 1
class Factorial
{
static long calcFactorial(long value)
{
if(value == 0) return 1;
else
return calcFactorial(value - 1) *
value;
}
public static void main(String
args[])
{
System.out.println("Factorial of 4 :
" + calcFactorial(5));
}
}

Example 2
class Recursion
{
static void printOdd(int a)
{
System.out.println(a);
a++;
if(a <= 10)
printEven(a);
}
static void printEven(int b)
{
System.out.println(b);
b++;
if(b <= 10 )
printOdd(b);
}
public static void main(String
args[])
{
printOdd(1);
}
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

20

Introducing final:
A variable can be declared as final. Doing so prevents its contents from being
modified. This means that you must initialize a final variable when it is declared.
e.g. final double PI = 3.142857;

Command Line Arguments:


Sometimes you will want to pass information into a program when you run it. This is
accomplished by passing command-line arguments to main( ). A command-line
argument is the information that directly follows the programs name on the command
line when it is executed. To access the command-line arguments inside a Java
program is quite easythey are stored as strings in the String array passed to main( ).
Example:
// Display all command-line arguments.
class CommandLine
{
public static void main(String args[])
{
for(int m=0; mi<args.length; m++)
System.out.println("args[" + m + "]: " + args[m]);
}
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

21

Inheritance
A class that is inherited is called a super class. The class that does the inheriting is
called a subclass. To inherit a class, you simply incorporate the definition of one class
into another by using the extends keyword. Being a super class for a subclass does not
mean that the super class cannot be used by itself. You can only specify one super
class for any subclass that you create. Java does not support the inheritance of
multiple super classes into a single subclass. No class can be a super class of itself.
A class member that has been declared as private will remain private to its class. It is
not accessible by any code outside its class, including subclasses. Constructors are
called in order of derivation.
Syntax:
class subclass-name extends superclass-name {
// body of class
}
Example:
class Vehicle //super class
{
int Wheels;
}
class Car extends Vehicle //subclass of Vehicle
{
void showCarWheels()
{
System.out.println("Car has " + Wheels + " wheels.");
}
}
class MotorCycle extends Vehicle //subclass of Vehicle
{
void showMotorCycleWheels()
{
System.out.println("Motor Cycle has " + Wheels + " wheels.");
}
}
class VehicleTest
{
public static void main(String args[])
{
Car myCar = new Car();
myCar.Wheels = 4;
myCar.showCarWheels();
MotorCycle myMoto = new MotorCycle();
myMoto.Wheels = 2;
myMoto.showMotorCycleWheels();
}
}
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

22

A Superclass Variable Can Reference a Subclass Object


A reference variable of a superclass can be assigned a reference to any subclass
derived from that superclass. When a reference to a subclass object is assigned to a
superclass reference variable, you will have access only to those parts of the object
defined by the super class.
Example:
class Vehicle
{
int Wheels;
String color;
}
class Car extends Vehicle
{
String carName;
}
class VehicleTest
{
public static void main(String args[])
{
Vehicle myVehicle = new Vehicle(); //Reference of superclass
Car myCar = new Car(); //Reference of subclass
myCar.carName = "Honda"; //Sub class member
myCar.color = "Green"; //Super class member
myCar.Wheels = 4; //Super class member
myVehicle = myCar; //reference of subclass assigned to
// reference variable of super
myVehicle.color = "Red"; //Correct
myVehicle.carName = "Mistubishi"; //Generates an error
}
}
Using super
Whenever a subclass needs to refer to its immediate superclass, it can do so by use of
the keyword super.
Using super to Call Superclass Constructors:
A subclass can call a constructor method defined by its superclass by use of the
following form of super:
super(parameter-list);
Here, parameter-list specifies any parameters needed by the constructor in the
superclass. super( ) must always be the first statement executed inside a subclass
constructor. We can overload super() as other methods and constructors are
overloaded. When a subclass calls super( ), it is calling the constructor of its
immediate superclass. Thus, super( ) always refers to the superclass immediately
above the calling class. This is true even in a multileveled hierarchy. Also, super( )
must always be the first statement executed inside a subclass constructor.
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

Example:
Error Situation
class Vehicle
{
private int Wheels;
private String Name;
}
class Car extends Vehicle
{
private String Brand;
Car(int wheels,String name,String brand)
{
Wheels = wheels;
//Error bcz Wheel is priavate in superClass
Name = name;
//Error bcz Name is priavate in superClass
Brand = brand;
}
}
class VehicleTest
{
public static void main(String args[])
{

23

Solution
class Vehicle
{
private int Wheels;
private String Name;

Vehicle(int wheels,String name)


{
Wheels = wheels;
Name = name;
}
}
class Car extends Vehicle
{
private String Brand;
Car(int wheels,String name,String brand)
{
super(wheels,name);
Brand = brand;
}
}
class VehicleTest
{
Car myCar = new Car(4,"Car","Honda");
public static void main(String args[])
{
}
Car myCar = new
}
Car(4,"Car","Honda");
}
}
In error situation Wheels and Name is private to class Vehicle so they cant be accessed by
any code outside the Vehicle class so for the solution there must be a public method to give access
to its members it can be a constructor. So super is used in solution which calls the Vehicle class
constructor to initialize its members.
A Second Use for super
super acts somewhat like this, except that it always refers to the superclass of the
subclass in which it is used.
Syntax: super.memberOfsuperClass
member can be either a method or an instance variable.
For the example u can see instance variable hiding concept in this keyword example.

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

24

Method Overriding:
In a class hierarchy, when a method in a subclass has the same name and type
signature as a method in its superclass, then the method in the subclass is said to
override the method in the superclass. When an overridden method is called from
within a subclass, it will always refer to the version of that method defined by the
subclass. The version of the method defined by the superclass will be hidden. Method
overriding occurs only when the names and the type signatures of the two methods are
identical. If they are not, then the two methods are simply overloaded. If you wish to
access the superclass version of an overridden function, you can do so by using super.
Example:
class Vehicle
{ int Wheels;
String Name;
void show()//super class method
{ System.out.println("Vehicle :");
System.out.println("Wheels : " + Wheels);
System.out.println("Name : " + Name);
}
}
class Car extends Vehicle
{ String Brand;
void show() //overrides the superclass show()
{ System.out.println("Car :");
System.out.println("Wheels : " + Wheels);
System.out.println("Brand : " + Brand);
}
}
class MotorCycle extends Vehicle
{ String Brand;
void show(int wheels)//overloads the superclass show()
{ System.out.println("Motor Cycle has " + wheels + " wheels."); }
}
class VehicleTest
{
public static void main(String args[])
{
Car myCar = new Car();
myCar.Wheels = 4;
myCar.Brand = "Honda";
myCar.show();
MotorCycle myMoto = new MotorCycle();
myMoto.show(2);
}
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

25

Dynamic Method Dispatch


Dynamic method dispatch is the mechanism by which a call to an overridden method
is resolved at run time, rather than compile time. a superclass reference variable can
refer to a subclass object. Java uses this fact to resolve calls to overridden methods at
run time. Here is how. When an overridden method is called through a superclass
reference, Java determines which version of that method to execute based upon the
type of the object being referred to at the time the call occurs. Thus, this
determination is made at run time. When different types of objects are referred to,
different versions of an overridden method will be called. In other words, it is the type
of the object being referred to (not the type of the reference variable) that determines
which version of an overridden method will be executed. Therefore, if a superclass
contains a method that is overridden by a subclass, then when different types of
objects are referred to through a superclass reference variable, different versions of
the method are executed.
Example:
class superClass //create a superclass
{
void show()//method to be overridden
{ System.out.println("This is superClass method."); }
}
class subClassA extends superClass
{
void show()
{ System.out.println("This is subClassA method."); }
}
class subClassB extends superClass
{
void show()
{ System.out.println("This is subClassB method."); }
}
class DynamicMethodDispatch
{
public static void main(String args[])
{
superClass supObj = new superClass(); //creates a superclass object
subClassA subObjA = new subClassA(); //creates a subclassA object
subClassB subObjB = new subClassB();//creates a subclassB object
supObj.show(); //this will call a superclass method
supObj = subObjA; //subclass reference is assigned to superclass ref.
//Here Dynamic Method Dispatch occurred and will call a subClassA method.
supObj.show();
supObj = subObjB; //subclass reference is assigned to superclass ref.
//Here Dynamic Method Dispatch occurred and will call a subClassB method.
supObj.show();
}
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

26

Abstract Classes and Methods


That is, sometimes you will want to create a superclass that only defines a generalized
form that will be shared by all of its subclasses, leaving it to each subclass to fill in
the details. Such a class determines the nature of the methods that the subclasses must
implement. You can require that certain methods be overridden by subclasses by
specifying the abstract type modifier. These methods are sometimes referred to as
subclasser responsibility because they have no implementation specified in the
superclass. Thus, a subclass must override themit cannot simply use the version
defined in the superclass. Any class that contains one or more abstract methods must
also be declared abstract. To declare a class abstract, you simply use the abstract
keyword in front of the class keyword at the beginning of the class declaration. There
can be no objects of an abstract class. That is, an abstract class cannot be directly
instantiated with the new operator. you cannot declare abstract constructors, or
abstract static methods. Any subclass of an abstract class must either implement all of
the abstract methods in the superclass, or be itself declared abstract. Although abstract
classes cannot be used to instantiate objects, they can be used to create object
references, because Javas approach to run-time polymorphism is implemented
through the use of superclass references. Thus, it must be possible to create a
reference to an abstract class so that it can be used to point to a subclass object.
Example:
// Using abstract methods and classes.
class Triangle extends Figure
abstract class Figure
{
{
Triangle(double a, double b)
double dim1;
{ super(a, b); }
double dim2;
// override area for right triangle
Figure(double a, double b)
double area()
{ dim1 = a;
{
dim2 = b;
System.out.println("Area for Triangle.");
}
return dim1 * dim2 / 2;
}
// area is now an abstract method
}
abstract double area();
class AbstractAreas
}
{
public static void main(String args[])
class Rectangle extends Figure
{
{
// Figure f = new Figure(10, 10); // illegal now
Rectangle(double a, double b)
Rectangle r = new Rectangle(9, 5);
{ super(a, b); }
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object created
// override area for rectangle
figref = r;
double area()
System.out.println("Area is"+ figref.area());
{
figref = t;
System.out.println("Area for Rectangle."); System.out.println("Area is"+ figref.area());
return dim1 * dim2;
}
}
}
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

27

Using final with Inheritance


To Prevent Overriding
To disallow a method from being
overridden, specify final as a modifier at
the start of its declaration. Methods
declared as final cannot be overridden.
Methods declared as final can sometimes
provide a performance enhancement: The
compiler is free to inline calls to them
because it knows they will not be
overridden by a subclass. When a small
final method is called, often the Java
compiler can copy the bytecode for the
subroutine directly inline with the
compiled code of the calling method, thus
eliminating
the
costly
overhead
associated with a method call. Inlining is
only an option with final methods.
Normally, Java resolves calls to methods
dynamically, at run time. This is called
late binding. However, since final
methods cannot be overridden, a call to
one can be resolved at compile time. This
is called early binding.
class A
{
final void meth()
{
System.out.println("This is a final
method.");
}
}
class B extends A
{
void meth()
{
// ERROR! Can't override.
System.out.println("Illegal!");
}
}

M.J.S
Copyright 2007

To Prevent Inheritance

Sometimes you will want to prevent a


class from being inherited. To do this,
precede the class declaration with final.
Declaring a class as final implicitly
declares all of its methods as final, too.
As you might expect, it is illegal to
declare a class as both abstract and final
since an abstract class is incomplete by
itself and relies upon its subclasses to
provide complete implementations.

final class A
{
// ...
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
// ...
}

jasim.shah@yahoo.com

M.J.S

JAVA Outline

28

The Object Class


There is one special class, Object, defined by Java. All other classes are subclasses of
Object. That is, Object is a superclass of all other classes. This means that a
reference variable of type Object can refer to an object of any other class. Also, since
arrays are implemented as classes, a variable of type Object can also refer to any
array.
Object defines the following methods, which means that they are available in every
object.
Method
Object clone( )
boolean equals(Object object)
void finalize( )
Class getClass( )
int hashCode( )

void notify( )

void notifyAll( )
String toString( )
void wait( )
void wait(long milliseconds)
void wait(long milliseconds,int nanoseconds)

Purpose
Creates a new object that is
the same as the object being
cloned.
Determines
whether
one
object is equal to another.
Called before an unused object
is recycled.
Obtains the class of an object
at run time.
Returns the hash code
associated with the invoking
object.
Resumes execution of a thread
waiting on the invoking
object.
Resumes execution of all
threads waiting on the
invoking object.
Returns a string that describes
the object.
Waits on another thread of
execution.

The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final.
You may override the others.
The equals( ) method compares the contents of two objects. It returns true if the
objects are equivalent, and false otherwise.
The toString( ) method returns a string that contains a description of the object on
which it is called. Also, this method is automatically called when an object is output
using println( ). Many classes override this method.

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

29

Packages and Interfaces


Packages
The package is both a naming and a visibility control mechanism. You can define
classes inside a package that are not accessible by code outside that package. You can
also define class members that are only exposed to other members of the same
package. This allows your classes to have intimate knowledge of each other, but not
expose that knowledge to the rest of the world.
Defining a Package
To create a package is quite easy: simply include a package command as the first
statement in a Java source file. Any classes declared within that file will belong to the
specified package. The package statement defines a name space in which classes are
stored. If you omit the package statement, the class names are put into the default
package, which has no name.
Syntax: package myPackage;
File System Directories And Packages
Java uses file system directories to store packages. For example, the .class files for
any classes you declare to be part of MyPackage must be stored in a directory called
MyPackage. Remember that case is significant, and the directory name must match
the package name exactly.
Multiple files having same package statement
More than one file can include the same package statement. The package statement
simply specifies to which package the classes defined in a file belong. It does not
exclude other classes in other files from being part of that same package. Most realworld packages are spread across many files.
Packages Hierarchy
You can create a hierarchy of packages. To do so, simply separate each package name
from the one above it by use of a period. The general form of a multileveled package
statement is shown here:
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development
system. For example, a package declared as
package java.awt.image;
needs to be stored in java/awt/image, java\awt\image, or java:awt:image on your
UNIX, Windows, or Macintosh file system, respectively. Be sure to choose your
package names carefully. You cannot rename a package without renaming the
directory in which the classes are stored.
Finding Packages and CLASSPATH
How does the Java run-time system know where to look for packages that you create?
The answer has two parts. First, by default, the Java run-time system uses the current
working directory as its starting point. Thus, if your package is in the current
directory, or a subdirectory of the current directory, it will be found. Second, you can
specify a directory path or paths by setting the CLASSPATH environmental variable.
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

30

Package Example:
// myPackageTest.java
package myPackage;
class A
{
void test()
{
System.out.println("This is test method of class A");
}
}
class B
{
void test()
{
System.out.println("This is test method of class B");
}
}
class myPackageTest
{
public static void main(String args[])
{
A objA = new A();
objA.test();
B objB = new B();
objB.test();
}
}
Note:
Create a folder named as myPackage in yours current working folder save above
file named as myPackageTest.java in that folder. Then compile this file it will
creates a resulting myPackageTest.class in myPackage folder.
Then try executing the myPackageTest.class using the following command line:
java MyPack.myPackageTest
Remember, you will need to be in the directory above myPackage when you
execute this command, or to have your CLASSPATH environmental variable set
appropriately.
As explained, myPackageTest is now part of the package myPackage. This means
that it cannot be executed by itself. That is, you cannot use this command line:
java myPackageTest

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

31

Access Protection
Anything declared public can be accessed from anywhere. Anything declared private
cannot be seen outside of its class. When a member does not have an explicit access
specification, it is visible to subclasses as well as to other classes in the same package.
This is the default access.
protected
If you want to allow an element to be seen outside your current package, but only to
classes that subclass your class directly, then declare that element protected.
Class Access
A class has only two possible access levels: default and public. When a class is
declared as public, it is accessible by any other code. If a class has default access,
then it can only be accessed by other code within its same package.
Class Member Access : applies only to members of classes
Private No modifier Protected Public
Yes
Yes
Yes
Yes
Same class
No
Yes
Yes
Yes
Same package subclass
No
Yes
Yes
Yes
Same package non-subclass
No
No
Yes
Yes
Different package subclass
No
No
No
Yes
Different package non-subclass
Importing Packages
There are no core Java classes in the unnamed default package; all of the standard
classes are stored in some named package. Since classes within packages must be
fully qualified with their package name or names, it could become tedious to type in
the long dot-separated package path name for every class you want to use. For this
reason, Java includes the import statement to bring certain classes, or entire
packages, into visibility. Once imported, a class can be referred to directly, using only
its name.
In a Java source file, import statements occur immediately following the package
statement (if it exists) and before any class definitions. This is the general form of the
import statement: import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate
package inside the outer package separated by a dot (.). There is no practical limit on
the depth of a package hierarchy, except that imposed by the file system. Finally, you
specify either an explicit classname or a star (*), which indicates that the Java
compiler should import the entire package.
All of the standard Java classes included with Java are stored in a package called
java. The basic language functions are stored in a package inside of the java package
called java.lang. Normally, you have to import every package or class that you want
to use, but since Java is useless without much of the functionality in java.lang, it is
implicitly imported by the compiler for all programs.
If a class with the same name exists in two different packages that you import using
the star form, the compiler will remain silent, unless you try to use one of the classes.
In that case, you will get a compile-time error and have to explicitly name the class
specifying its package.
e.g import java.util.Date; OR
import java.io.*;
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

32

Interfaces
Interfaces are syntactically similar to classes, but they lack instance variables, and
their methods are declared without any body. In practice, this means that you can
define interfaces which dont make assumptions about how they are implemented.
Once it is defined, any number of classes can implement an interface. Also, one class
can implement any number of interfaces. To implement an interface, a class must
create the complete set of methods defined by the interface. However, each class is
free to determine the details of its own implementation. An interface is typically used
when disparate (i.e., unrelated) classes need to share common methods and constants.
This allows objects of unrelated classes to be processed polymorphically objects of
classes that implement the same interface can respond to the same method calls.
Programmers can create an interface that describes the desired functionality, then
implement this interface in any classes that require that functionality.
Defining an Interface
Syntax:
accessModifier interface nameofInterface
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
Here, access is either public or not used. When no access specifier is included, then
default access results, and the interface is only available to other members of the
package in which it is declared. When it is declared as public, the interface can be
used by any other code. name is the name of the interface, and can be any valid
identifier.
Notice that the methods which are declared have no bodies. They end with semicolon
after the parameter list. They are, essentially, abstract methods; there can be no
default implementation of any method specified within an interface. Each class that
includes an interface must implement all of the methods.
Variables can be declared inside of interface declarations. They are implicitly final
and static, meaning they cannot be changed by the implementing class. They must
also be initialized with a constant value. All methods and variables are implicitly
public if the interface, itself, is declared as public.
e.g.
interface Callback
{
void callback(int param);
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

33

Implementing Interfaces
To implement an interface, include the implements clause in a class definition, and
then create the methods defined by the interface.
Syntax:
access class classname [extends superclass]
[implements interface [,interface...]]
{
// class-body
}
access is either public or not used. If a class implements more than one interface, the
interfaces are separated with a comma. If a class implements two interfaces that
declare the same method, then the same method will be used by clients of either
interface. The methods that implement an interface must be declared public. Also, the
type signature of the implementing method must match exactly the type signature
specified in the interface definition. It is both permissible and common for classes that
implement interfaces to define additional members of their own.
Example:
interface myInterface
{
void test(String msg); //abstract method
}
class interfaceImplementClass implements myInterface
{
public void test(String msg)
{
System.out.println(msg);
}
}
class InterfaceTest
{
public static void main(String args[])
{
interfaceImplementClass testObj = new interfaceImplementClass();
testObj.test("Hello M");
}
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

34

Accessing Implementations Through Interface References


You can declare variables as object references that use an interface rather than a class
type. Any instance of any class that implements the declared interface can be referred
to by such a variable. When you call a method through one of these references, the
correct version will be called based on the actual instance of the interface being
referred to. This is one of the key features of interfaces. The method to be executed is
looked up dynamically at run time, allowing classes to be created later than the code
which calls methods on them. The calling code can dispatch through an interface
without having to know anything about the callee.
Example:
interface myInterface
{ void test(); }
class J implements myInterface
{
public void test()
{ System.out.println("Hello M! This is J"); }
}
class S implements myInterface
{
public void test()
{ System.out.println("Hello M! This is S"); }
}
class interfaceTest
{
public static void main(String args[])
{
myInterface interfaceVariable;
J object_of_J = new J();
interfaceVariable = object_of_J;
interfaceVariable.test();
interfaceVariable = new S();
interfaceVariable.test();
}
}
Partial Implementations
If a class includes an interface but does not fully implement the methods defined by
that interface, then that class must be declared as abstract.
Example:
abstract class Incomplete implements myInterface
{
void show()
{ System.out.println(Hello MJS); }
}
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

Variables in Interfaces
You can use interfaces to import shared
constants into multiple classes by simply
declaring an interface that contains variables
which are initialized to the desired values.
When you include that interface in a class (that
is, when you implement the interface), all of
those variable names will be in scope as
constants. This is similar to using a header file
in C/C++ to create a large number of #defined
constants or const declarations. If an interface
contains no methods, then any class that
includes such an interface doesnt actually
implement anything. It is as if that class were
importing the constant variables into the class
name space as final variables.
interface sharedConstants
{ final int VERYLOW = 1;
final int LOW = 2;
final int NORMAL = 3;
final int HIGH = 4;
final int VERYHIGH = 5;
}
class M implements sharedConstants
{
void test()
{
System.out.println("My priority is " +
NORMAL);
}
}

35

Interfaces Can Be Extended

One interface can inherit another by use of the


keyword extends. The syntax is the same as for
inheriting classes. When a class implements an
interface that inherits another interface, it must
provide implementations for all methods
defined within the interface inheritance chain.

interface M
{
void testM();
}
interface J extends M
{
void testJ();
}
class S implements J
{
public void testM()
{
System.out.println("This is M");
}

class J implements sharedConstants


public void testJ()
{
{
void test()
System.out.println("This is J");
{
}
System.out.println("My priority is " +
VERYHIGH); public static void main(String args[])
}
{
}
S obj = new S();
class testConst
obj.testJ();
{
obj.testM();
public static void main(String args[])
}
{
}
M objofM = new M();
objofM.test();
J objofJ = new J();
objofJ.test();
}
}
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

36

Exception Handling
An exception is an abnormal condition that arises in a code sequence at run time. In
other words, an exception is a run-time error. A Java exception is an object that
describes an exceptional (that is, error) condition that has occurred in a piece of code.
When an exceptional condition arises, an object representing that exception is created
and thrown in the method that caused the error. That method may choose to handle
the exception itself, or pass it on. Either way, at some point, the exception is caught
and processed. Exceptions can be generated by the Java run-time system, or they can
be manually generated by your code. Exceptions thrown by Java relate to fundamental
errors that violate the rules of the Java language or the constraints of the Java
execution environment. Manually generated exceptions are typically used to report
some error condition to the caller of a method.
How Java Handles Exceptions
Java exception handling is managed via five keywords: try, catch, throw, throws,
and finally. Briefly, here is how they work. Program statements that you want to
monitor for exceptions are contained within a try block. If an exception occurs within
the try block, it is thrown. Your code can catch this exception (using catch) and
handle it in some rational manner. System-generated exceptions are automatically
thrown by the Java run-time system. To manually throw an exception, use the
keyword throw. Any exception that is thrown out of a method must be specified as
such by a throws clause. Any code that absolutely must be executed before a method
returns is put in a finally block.
This is the general form of an exception-handling block:
try { // block of code to monitor for errors }
catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 }
catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 }
// ...
finally { // block of code to be executed before try block ends }
Exception Types
Throwable
All exception types are subclasses of the built-in class Throwable. Thus, Throwable
is at the top of the exception class hierarchy. Immediately below Throwable are two
subclasses that partition exceptions into two distinct branches.
Exception
One branch is headed by Exception. This class is used for exceptional conditions that
user programs should catch. This is also the class that you will subclass to create your
own custom exception types. There is an important subclass of Exception, called
RuntimeException. Exceptions of this type are automatically defined for the
programs that you write and include things such as division by zero and invalid array
indexing.
Error
The other branch is topped by Error, which defines exceptions that are not expected
to be caught under normal circumstances by your program. Exceptions of type Error
are used by the Java run-time system to indicate errors having to do with the run-time
environment, itself. Stack overflow is an example of such an error. These are typically
created in response to catastrophic failures that cannot usually be handled by your
program.
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

37

Using try and catch


Simply enclose the code that you want to monitor inside a try block. Immediately
following the try block, include a catch clause that specifies the exception type that
you wish to catch.
Example:
class exceptionTest
{
public static void main(String args[])
{
try
{
int var = 5/0; //Divided By zero generates exception
System.out.println("I\'m not executable statement.");
}
catch(ArithmeticException e)
{
System.out.println("Division by zero.");
}
System.out.println("I\'m after catch statement.");
}
}
Once an exception is thrown, program control transfers out of the try block into the
catch block. Execution never returns to the try block from a catch. Once the catch
statement has executed, program control continues with the next line in the program
following the entire try/catch mechanism. A try and its catch statement form a unit.
The scope of the catch clause is restricted to those statements specified by the
immediately preceding try statement. A catch statement cannot catch an exception
thrown by another try statement. The statements that are protected by try must be
surrounded by curly braces. You cannot use try on a single statement.
Displaying a Description of an Exception
Throwable overrides the toString( ) method (defined by Object) so that it returns a
string containing a description of the exception. You can display this description in a
println( ) statement by simply passing the exception as an argument.
Example:
class exceptionTest {
public static void main(String args[])
{
try
{
int var = 5/0; /*Divided By zero generates exception*/ }
catch(ArithmeticException e)
{
System.out.println(e); // e contains the description.
}
}
}
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

38

Multiple catch Clauses


More than one exception could be raised by a single piece of code. To handle this
type of situation, you can specify two or more catch clauses, each catching a different
type of exception. When an exception is thrown, each catch statement is inspected in
order, and the first one whose type matches that of the exception is executed. After
one catch statement executes, the others are bypassed, and execution continues after
the try/catch block.
Example:
This program has two types of exceptions when value of test variable is 0, Divided by
zero occurs. And when value of test is not zero Array index out of bounds occurs
because we provides index greater then bound.
class multiCatch
{
public static void main(String args[])
{
int Array[] = new int[1];
int test = 1;
try {
Array[3] = 5 / test;
}
catch (ArithmeticException e) {
System.out.println("Divided by zero");
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds");
}
System.out.println("After try/catch blocks.");
}
}
When you use multiple catch statements, it is important to remember that exception
subclasses must come before any of their superclasses. This is because a catch
statement that uses a superclass will catch exceptions of that type plus any of its
subclasses. Thus, a subclass would never be reached if it came after its superclass.
Example:
class multiCatchError {
public static void main(String args[])
{ try
{ int a = 5/0; }
catch(Exception e)
{ System.out.println("Generic Exception catch."); }
catch(ArithmeticException e)
{/* This catch is never reached because
ArithmeticException is a subclass of Exception. */
System.out.println("Divided by zero");
}
}
}
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

39

Nested try Statements


The try statement can be nested. That is, a try statement can be inside the block of
another try. Each time a try statement is entered, the context of that exception is
pushed on the stack. If an inner try statement does not have a catch handler for a
particular exception, the stack is unwound and the next try statements catch handlers
are inspected for a match. This continues until one of the catch statements succeeds,
or until all of the nested try statements are exhausted. If no catch statement matches,
then the Java run-time system will handle the exception.
Example:
class nestedTry {
public static void main(String args[])
{ int test = 2; int Array[] = new int[1];
try{
try {
int a = 5 / test;
Array[3] = test;
}
catch (ArithmeticException e) {
System.out.println("Divided by Zero");
}
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds.");
}
}
}
Nesting of try statements can occur in less obvious ways when method calls are
involved. For example, you can enclose a call to a method within a try block. Inside
that method is another try statement. In this case, the try within the method is still
nested inside the outer try block, which calls the method.
class nestedTry2 {
static int test = 5;
public static void nestedMethod() {
try {
int a = 5 / test;
int Array[] = new int[1];
Array[5] = test; }
catch (ArithmeticException e) { System.out.println("Divided by Zero"); }
}
public static void main(String args[])
{
try{
nestedTry2 obj = new nestedTry2();
obj.nestedMethod();
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out of bounds.");
}
}
}
In above both examples you can change value of test variable to see the effect.
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

40

throw
It is possible for your program to throw an exception explicitly, using the throw
statement. The general form of throw is shown here:
Syntax: throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable. There are two ways you can obtain a Throwable object: using a parameter
into a catch clause, or creating one with the new operator. The flow of execution stops
immediately after the throw statement; any subsequent statements are not executed.
The nearest enclosing try block is inspected to see if it has a catch statement that
matches the type of the exception. If it does find a match, control is transferred to that
statement. If not, then the next enclosing try statement is inspected, and so on. If no
matching catch is found, then the default exception handler halts the program and
prints the stack trace.
Example:
class throwTest
{
public static void Test()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside Test.");
throw e; /* rethrow the exception */
}
}
public static void main(String args[])
{
try { Test(); }
catch(NullPointerException e)
{ System.out.println("Recaught: " + e); }
}
}

Description

This program gets two


chances to deal with the
same error. First, main( )
sets up an exception
context and then calls
Test( ). The Test( )
method then sets up
another
exceptionhandling
context
and
immediately throws a new
instance
of
NullPointerException,
which is caught on the
next line. The exception is
then rethrown.

Here, new is used to construct an instance of NullPointerException. All of Javas


built-in run-time exceptions have at least two constructors: one with no parameter and
one that takes a string parameter. When the second form is used, the argument
specifies a string that describes the exception. This string is displayed when the object
is used as an argument to print( ) or println( ). It can also be obtained by a call to
getMessage( ), which is defined by Throwable.

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

41

throws
If a method is capable of causing an exception that it does not handle, it must specify
this behavior so that callers of the method can guard themselves against that
exception. You do this by including a throws clause in the methods declaration. A
throws clause lists the types of exceptions that a method might throw. This is
necessary for all exceptions, except those of type Error or RuntimeException, or
any of their subclasses. All other exceptions that a method can throw must be declared
in the throws clause. If they are not, a compile-time error will result. This is the
general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can
throw.
Example:
class throwsDemo
{
static int test = 2;
public static void Test()
throws ArithmeticException,ArrayIndexOutOfBoundsException
{
int a = 5/test;
int Array[] = new int[1];
Array[3] = test;
}
public static void main(String args[])
{
try
{
Test();
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index out of bound");
}
}
}
In above example you can change the value of test variable 0 or greater than zero to
generate exception.

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

42

finally
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear
path that alters the normal flow through the method. Depending upon how the method
is coded, it is even possible for an exception to cause the method to return
prematurely. This could be a problem in some methods.
For example, if a method opens a file upon entry and closes it upon exit, then you will
not want the code that closes the file to be bypassed by the exception-handling
mechanism.
The finally keyword is designed to address this contingency. finally creates a block of
code that will be executed after a try/catch block has completed and before the code
following the try/catch block. The finally block will execute whether or not an
exception is thrown. If an exception is thrown, the finally block will execute even if
no catch statement matches the exception. Any time a method is about to return to the
caller from inside a try/catch block, via an uncaught exception or an explicit return
statement, the finally clause is also executed just before the method returns. This can
be useful for closing file handles and freeing up any other resources that might have
been allocated at the beginning of a method with the intent of disposing of them
before returning. The finally clause is optional. However, each try statement requires
at least one catch or a finally clause.
In this example finally is used In this example finally is used
with try/catch and divided by with try/catch and finally is
zero exception is generated.
executed even no exception is
generated.
class finallyTest
class finallyTest
{
{
public static void
public static void
main(String args[])
main(String args[])
{
{
try
try
{
{
int a = 5/0;
int a = 5/1;
}
}
catch(ArithmeticException
e)
{

catch(ArithmeticException
e)
{

In this example finally is


used only with try. Finally
is executed even no
exception is generated
class finallyTest
{
public static void
main(String args[])
{
try
{
int a = 5/1;
}
finally
{

System.out.println("I\'m
executed after
System.out.println("Divided System.out.println("Divided try/catch");
by zero");
by zero");
}
}
}
finally
finally
}
{
{
}
System.out.println("I\'m
System.out.println("I\'m
executed after try/catch");
executed after try/catch");
}
}
}
}
M.J.S
Copyright 2007

}
}

jasim.shah@yahoo.com

M.J.S

JAVA Outline

43

Javas Built-in Exceptions


unchecked exceptions
Inside the standard package java.lang, Java defines several exception classes. The
most general of these exceptions are subclasses of the standard type
RuntimeException. Since java.lang is implicitly imported into all Java programs,
most exceptions derived from RuntimeException are automatically available.
Furthermore, they need not be included in any methods throws list. In the language
of Java, these are called unchecked exceptions because the compiler does not check to
see if a method handles or throws these exceptions.
Arithmetic error, such as divide-by-zero.
ArithmeticException
Array index is out-of-bounds.
ArrayIndexOutOfBoundsException
Assignment to an array element of an
ArrayStoreException
incompatible type.
Invalid cast.
ClassCastException
Illegal argument used to invoke a method.
IllegalArgumentException
Illegal monitor operation, such as waiting
IllegalMonitorStateException
on an unlocked thread.
Environment or application is in incorrect
IllegalStateException
state.
Requested operation not compatible with
IllegalThreadStateException
current thread state.
Some type of index is out-of-bounds.
IndexOutOfBoundsException
Array created with a negative size.
NegativeArraySizeException
Invalid use of a null reference.
NullPointerException
Invalid conversion of a string to a
NumberFormatException
numeric format.
Attempt to violate security.
SecurityException
Attempt to index outside the bounds of a
StringIndexOutOfBounds
string.
An unsupported operation was
UnsupportedOperationException
encountered.
checked exceptions
Exceptions defined by java.lang that must be included in a methods throws list if
that method can generate one of these exceptions and does not handle it itself. These
are called checked exceptions.
Class not found.
ClassNotFoundException
Attempt to clone an object that does not
CloneNotSupportedException
implement the Cloneable interface.
Access to a class is denied.
IllegalAccessException
Attempt to create an object of an abstract
InstantiationException
class or interface.
One thread has been interrupted by
InterruptedException
another thread.
A requested field does not exist.
NoSuchFieldException
A requested method does not exist.
NoSuchMethodException
Java defines several other types of exceptions that relate to its various class libraries.
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

44

Creating Your Own Exception Subclasses


To create your own exception types to handle situations specific to your applications.
Just define a subclass of Exception (which is, of course, a subclass of Throwable).
Your subclasses dont need to actually implement anythingit is their existence in
the type system that allows you to use them as exceptions. The Exception class does
not define any methods of its own. It inherits those methods provided by Throwable.
Thus, all exceptions, including those that you create, have the methods defined by
Throwable available to them. You may also wish to override one or more of these
methods in exception classes that you create.
Method

Description

Throwable fillInStackTrace( )

Throwable getCause( )

String getLocalizedMessage( )
String getMessage( )
StackTraceElement[ ]
getStackTrace( )

Throwable initCause(Throwable
causeExc)

void printStackTrace( )
void printStackTrace(PrintStream
stream)
void printStackTrace(PrintWriter
stream)
Void
setStackTrace(StackTraceElement
elements[ ])
String toString( )

M.J.S
Copyright 2007

Returns a Throwable object that contains


a completed stack trace. This object can
be rethrown.
Returns the exception that underlies the
current exception. If there is no
underlying exception, null is returned.
Added by Java 2, version 1.4.
Returns a localized description of the
exception.
Returns a description of the exception.
Returns an array that contains the stack
trace, one element at a time as an array of
StackTraceElement. The method at the
top of the stack is the last method called
before the exception was thrown. This
method is found in the first element of the
array. The StackTraceElement class gives
your program access to information about
each element in the trace, such as its
method name. Added by Java 2, version
1.4
Associates causeExc with the invoking
exception as a cause of the invoking
exception. Returns a reference to the
exception. Added by Java 2, version 1.4
Displays the stack trace.
Sends the stack trace to the specified
stream.
Sends the stack trace to the specified
stream.
Sets the stack trace to the elements passed
in elements. This method is for
specialized applications, not normal use.
Added by Java 2, version 1.4
Returns a String object containing a
description of the exception. This method
is called by println( ) when outputting a
Throwable object.

jasim.shah@yahoo.com

M.J.S

JAVA Outline

45

Multithreaded Programming
Thread class and Runnable interface makes JAVA multithreading system. Runnable
interface has only one abstract method run(); and Thread class has many methods to
perform multithreading.
Spawning a thread
There are two basic ways to create threads in JAVA.
1. Implementing Runnable Interface
In this way you have to create a class which implements Runnable interface,
and override the single method run() of Runnable. run() method is just like
main() method of main thread. In this method you can write code or
instructions for your new thread. After it you will instantiate an object of class
Thread from your newly created class. Thread class has several constructors
you can use any of them according to situation. Now thread is created but it
will not start until you call start() method of Thread class.
Example:
class newThread implements Runnable { class threadTest
/* class implementing Runnable interface */ {
Thread myThread;
public static void main(String args[])
/*Instance of Thread class*/
{
newThread() {
new newThread();
/*Constructor of newly created class*/
/*Instance of new Thread*/
myThread = new Thread(this,"Child
Thread");
try
myThread.start();
{
/*Thread class start method*/
for(int j=10; j>=1; j--)
}
{
System.out.println("Main Thread : "
public void run() {
+ j);
/*Overriding run() of Runnable interface*/
Thread.sleep(1000);
try
}
{
}
for(int m=1; m<=10; m++)
catch(InterruptedException e)
{
{
System.out.println("Thread Child : " + m);
System.out.println("Main Thread
myThread.sleep(1000);
Interrupted");
/*This method throws exception hence used
}
try/catch*/
}
System.out.println("Main going to
}
END");
catch(InterruptedException e)
}
{
}
System.out.println("Child Thread
interrupted");
}
System.out.println("Child Thread going to
end");
}
}
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

46

2. Inheriting Thread class


2nd method to create a new thread is to create a new class which inherits
Thread class. New class must override the run() method of Thread class. Call
the constructor of Thread class by using super() to create new Thread and then
start it by calling start() method of Thread class.
Example:
class newThread extends Thread
class threadTest
{ /*class inheriting Thread class*/
{
newThread()
public static void main(String args[])
{
{
/*Constructor of newly created class*/
new newThread();
super("Child Thread");
try
/*Constructor of Thread class is called to
{
create new Thread*/
for(int j=10; j>=1; j--)
start(); /*method of Thread class is
{
called to start Thread.*/
System.out.println("Main Thread : " +
}
j);
Thread.sleep(1000);
public void run() {
}
/*Overriding run() of Thread class*/
}
try
catch(InterruptedException e)
{
{ System.out.println("Main Thread
for(int m=1; m<=10; m++)
Interrupted."); }
{
System.out.println("Child Thread : "
System.out.println("Main Thread going
+ m);
to END.");
sleep(1000);
}
}
}
}
catch(InterruptedException e)
{ System.out.println("Child Thread
Interrupted."); }
System.out.println("Child Thread going
to END.");
}
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

47

Multiple Threads Creation


It is better to create a new class for each thread
because each thread has to perform its own task.
But you can create copies of any thread by
creating objects of class defining new thread.
Example:
class newThread implements Runnable
{
Thread myThread;
newThread(String threadName)
{
myThread = new Thread(this,threadName);
myThread.start();
}

The Main Thread


When JAVA program starts JVM creates this thread
and starts executing its main method. It is important
because you can spawn other threads from it which
are called child threads and secondly it may be the
last thread to finish program execution because it can
shut down other threads. Main thread is created
automatically by JVM but you can also control it by
using methods of Thread class. There is method
which returns the reference to thread in which it is
called.
Syntax: public static Thread currentThread();
Because it is public static method so it can be called
from main method and it give us the reference to
object of main thread. Now by using this reference
you can control main thread.
public void run()
{
Example:
System.out.println(myThread + " /*Prints my name character by character using
Created."); main thread.*/
}
class mainThread
}
{
class multiTest
public static void main(String args[]) {
{
Thread mainThread = Thread.currentThread();
public static void main(String args[])
char myName[] = {'J','a','s','i','m'};
{
try
new newThread("1");
{
new newThread("2");
for(int m=0; m<myName.length; m++)
new newThread("3");
{
}
System.out.println(myName[m]);
}
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{ System.out.println("Main Thread
Interrupted."); }
}}
Thread priorities
In JAVA each thread has a priority value which helps Operating System in scheduling
of threads. Priorities are defined in range MIN_PRIORITY (constant of 1) to
MAX_PRIORITY (constant of 10). By default each thread is given
NORM_PRIORITY (constant of 5). These constants are declared in Thread class.
Higher priority threads are more important to program and should be allocated
processor time before lower priority threads. But priorities cant guarantee order in
which threads execute. Two methods in Thread class gives us access to this property
of threads.
Syntax: final void setPriority(int level) // to set a priority of thread
Syntax: final int getPriority( ) // to get a priority of thread
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

Some Methods of Thread class


1. static Thread currentThread();
This method returns a reference to the thread in
which it is called.
2. static void sleep(long milliseconds)
throws InterruptedException
It is possible for a thread to suspend its own
execution for specific period of time by calling
sleep() method and providing milliseconds as
argument. This method has another form for
precise timing taking nanoseconds as arguments.
static void sleep(long milisec, int nanosec)
throws InterruptedException
3. final void setName(String threadName)
Used to change the name of thread providing new
name as argument.
4. final String getName( )
Used to obtain the name of thread.
5. final boolean isAlive( )
This method returns true if the thread upon which
it is called is still running.
6. final void suspend( )
A thread is told to pause its execution by this
method. It was used in JAVA 1.1 and earlier
versions but deprecated to use in JAVA 2.
7. final void resume( )
A thread is told to resume its execution from
where it was told to pause by suspend() method.
It was used in JAVA 1.1 and earlier versions but
deprecated to use in JAVA 2.
8. final void stop( )
This method is used to terminate a thread
permanently after this method thread cant be
resumed. It was used in JAVA 1.1 and earlier
versions but deprecated to use in JAVA 2.
9. static void yield()
Causes the current thread to yield the processor to
other threads. Generally only threads of equal
priority that were waiting to run get a chance.
Depending on the VM implementation, lowerpriority threads might or might not get a chance to
run.

48

10. final void join( )


throws InterruptedException
This method waits until the thread on which it is
called terminates. Its name comes from the
concept of the calling thread waiting until the
specified thread joins it. Additional forms of
join() allow you to specify a maximum amount of
time that you want to wait for the specified thread
to terminate. If the thread has already completed
its run() method, the join() method returns
immediately.
Example:
class newThread implements Runnable
{ /* class implementing Runnable interface */
Thread myThread;
newThread() {
myThread = new Thread(this,"Child
Thread");
myThread.start(); }
public void run() {
try {
for (int m = 1; m <= 10; m++)
{
System.out.println("Thread Child : " + m);
myThread.sleep(1000); }
}
catch(InterruptedException e)
{ System.out.println("Child Thread
Interrupted."); }
System.out.println("Child Thread ending");
}
}
class joinTest {
public static void main(String args[]) {
newThread child = new newThread();
System.out.println("Main Thread Started");
try
{ child.myThread.join();
/*here join() blocks child thread to
perform its complete execution.*/
}
catch(InterruptedException e)
{ System.out.println("Main Thread
Interrupted."); }
System.out.println("Main going to
END");
}
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

49

Synchronization
Defining threads in such a way when more than one thread need access to shared
resource one by one or resource will be used by only one thread at a time is called
synchronization. This technique is implemented by the concept of monitor (also called
a semaphore). Monitor is an object which is used as mutually exclusive lock, or
mutex. Only one thread can grab a mutex at a time when a thread acquires a lock, it is
said to have entered the monitor: if two threads try to grab a mutex, only one
succeeds. The other thread has to wait until the first thread releases the lock before it
can grab the lock and continue operation.
JAVA provides the synchronized keyword allows the programmer access to a
resource that is very similar to a mutex lock. It simply prevents two or more threads
from calling the methods of the same object at same time. When a method is declared
synchronized, the thread that wants to execute the method must acquire a token,
which we call a lock. Once the method has acquired (or checked out or grabbed) this
lock, it executes the method and releases (or returns) the lock. No matter how the
method returnsincluding via an exceptionthe lock is released. There is only one
lock per object, so if two separate threads try to call synchronized methods of the
same object, only one can execute the method immediately; the other has to wait until
the first thread releases the lock before it can execute the method.

In this example five threads are created and


each thread send a word to shared resource to
print it. Resource class prints it character by
character on screen. You can remove
synchronized key word from printWord()
method to see the effect of synchronization.
class Resource {
synchronized void printWord(String
word)
{
try {
for(int m=0; m<word.length(); m++)
{
System.out.print(word.charAt(m));
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{ System.out.println("Thread
Interrupted."); }
System.out.print(' ');
}
}
.

M.J.S
Copyright 2007

class newThread extends Thread {


Resource sharedResource;
String msg;
newThread(String msg,Resource receivedObj)
{
super("Child Thread");
this.msg = msg;
sharedResource = receivedObj;
start();
}
public void run()
{
sharedResource.printWord(msg);
}
}
class SyncTest
{
public static void main(String args[])
{
Resource sharedResource = new Resource();
new newThread("Jasim",sharedResource);
new newThread("is",sharedResource);
new newThread("a",sharedResource);
new newThread("nice",sharedResource);
new newThread("boy.",sharedResource);
}
}

jasim.shah@yahoo.com

M.J.S

JAVA Outline

50

synchronized block
Consider you have a class provided by third party but its methods are not
synchronized and you dont have access to its source code. Now in this situation how
it can be used in multithreaded environments. The solution is synchronized block.
Simply you have to call its methods from a synchronized block.
Syntax:
synchronized(object) { // statements to be synchronized }
object is a reference to the object being synchronized. A synchronized block ensures
that a call to a method that is a member of object occurs only after the current thread
has successfully entered objects monitor. For example see the Messenger example in
which setMsgLength() and getMsgLength() methods are called from synchronized
block.
Interthread Communication and producer consumer problem
Consider the situation one thread called producer is producing some information and
storing it in memory buffer. Another thread called consumer is consuming that
information from that memory buffer. There should be such a way while producer is
accessing memory buffer, consumer should not access it. And when consumer is
consuming information producer should not access memory buffer. It can be done by
synchronized statement. But implementing this situation by synchronized method is
not powerful because both threads are running concurrently when producer has
monitor consumer is wasting CPU cycles in checking monitor is free or not this is
called pooling. Same thing occurs when consumer has monitor and producer is
polling. To avoid this problem there must be messaging system between threads.
When producer takes monitor it should send message to consumer to wait and when
producer completes its tasks it should send message to consumer that it have released
monitor now you can take it. When consumer receives wait message it should go to
waiting state and should not waste CPU cycles by polling. Same system must exist for
consumer. This is called interthread communication. JAVA implements it by
providing methods wait( ), notify( ), and notifyAll( ). These methods are implemented
as final methods in Object, so all classes have them. All three methods can be called
only from within a synchronized context.

final void wait( ) throws InterruptedException


Tells the calling thread to give up the monitor and go to sleep until some other
thread enters the same monitor and calls notify( ). Additional forms of wait( )
exist that allow you to specify a period of time to wait.
final void notify( )
Wakes up the first thread that called wait( ) on the same object.
final void notifyAll( )
Wakes up all the threads that called wait( ) on the same object. The highest
priority thread will run first.

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

51

Messenger
class Resource {
//Shared Resource
char charMsg;
//Character Buffer
int msgLength;
//Message Length
boolean charSet = false;
/*Flag to check character is produced or not*/
boolean lengthSet = false;
/*Flag to check message length set or not*/
void setMsgLength(int n) {
/*Set Msg Length Used By Sender*/
if (lengthSet) {
try {
wait();
/*Go to wait if msg length already set*/
}
catch (InterruptedException e) {
System.out.println("Interrupted.");
}
}
msgLength = n;
/*set msg length if not already set*/
lengthSet = true; /*Raised flag*/
notify();
/* Notify Sender to produce Msg.*/
}
int getMsgLength() {
/*Returns Msg Length used by Receiver*/
if (!lengthSet) {
try {
wait();
/* If MsgLength still not Received so wait.*/
}
catch (InterruptedException e)
{ System.out.println("Interrupted."); }
}
notify();
/*If Msg Length received notify Receiver to
receive Msg.*/
return msgLength;
/*Return Msg Length to Receiver*/
}
M.J.S
Copyright 2007

synchronized void setChar(char ch) {


/*Puts character in Buffer used by Sender*/
if (charSet) {
try {
wait();
/*If character already sent go to wait*/
}
catch (InterruptedException e) {
System.out.println("Interrupted.");
}
}
charMsg = ch;
/*If character not yet sent, send it now.*/
charSet = true;
/*Raised flag to indicate character sent*/
notify();
/*Send Msg to Receiver to get character.*/
}
synchronized void getChar() {
/*Consumes character used by Receiver*/
if (!charSet) {
try {
wait();
/*If character not received yet, go for wait*/
}
catch (InterruptedException e) {
System.out.println("Interrupted.");
}
}
System.out.print(charMsg);
/*If character received print it.*/
charSet = false;
/*Raise Flag to indicate character
consumed.*/
notify();
/*Claim Sender for Next character.*/
}
} //End Of Resource class

jasim.shah@yahoo.com

M.J.S

JAVA Outline

52

Messenger Continued
class Sender
extends Thread {
Resource sharedResource;
/*to store resource object*/
String myMsg = "Jasim I Love You.";
/*Message to send.*/
Sender(Resource resourceObj) {
super("Sender");
/*Call to Thread class constructor to create
Sender Thread.*/
sharedResource = resourceObj;
/*Save received resource object.*/
start(); //Start Sender Thread
}

class Receiver
implements Runnable {
Thread receiver;
Resource sharedResource;
Receiver(Resource resourceObj) {
sharedResource = resourceObj;
receiver = new Thread(this, "Receiver");
receiver.start();
}

public void run() {


int Msg_Length;
synchronized (sharedResource) {
//Synchronized block used
Msg_Length =
public void run() {
sharedResource.getMsgLength();
synchronized (sharedResource) {
/*Msg Length Received.*/
/*Synchronized block used.*/
}
while (Msg_Length-- > 0) {
sharedResource.setMsgLength(myMsg.length());
sharedResource.getChar();
/*Send Msg Length*/
/*Receive Msg character by character upto
}
length.*/
for (int m = 0; m < myMsg.length(); m++) {
}
/*Send Msg character by character after 500 }
milliseconds.*/ } //End Of Reciver class
sharedResource.setChar(myMsg.charAt(m));
try {
sleep(500);
/*Sleep after sending each character.*/
class Messenger {
}
public static void main(String args[]) {
catch (InterruptedException e) {
Resource obj = new Resource();
System.out.println("Interrupted.");
/*Create Shared Resource.*/
}
new Receiver(obj); //Create Receiver
}
new Sender(obj); //Create Sender
}
}
} //End Of Sender class
}

In this example Sender plays the role of producer and Receiver plays the role of Consumer. Sender places
the message character by character and its length in Resource. Receiver first takes length of message to be
received and then takes actual message character by character from Resource and prints it.

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

53

Streams and Files


Streams:
JAVA performs I/O by using streams. A stream is an abstraction that either produces
or consumes information. A stream is linked to a physical device by the java I/O
System. All streams behave in the same manner, even if the actual physical devices to
which they are linked differ. Thus, the same I/O classes and methods can be applied
to any type of device. This means that an input stream can abstract many different
kinds of input: from a disk file, a keyboard, or a network socket. Likewise, an output
stream may refer to the console, a disk file, or a network connection.
To use these streams and to perform JAVA I/O you have to import java I/O package
in your program. e.g. import java.io.*;
Byte Stream Classes
Byte streams provide a convenient means for handling input and output of bytes. Byte
streams are used, for example, when reading or writing binary data. Byte streams are
defined by using two class hierarchies. At the top are two abstract classes:
InputStream and OutputStream. Each of these abstract classes has several concrete
subclasses, that handle the differences between various devices, such as disk files,
network connections, and even memory buffers. The abstract classes InputStream and
OutputStream define several key methods that the other stream classes implement.
Two of the most important are read( ) and write( ), which, respectively, read and write
bytes of data. Both methods are declared as abstract inside InputStream and
OutputStream. They are overridden by derived stream classes.
Character Stream Classes
Character streams provide a convenient means for handling input and output of
characters. They use Unicode and, therefore, can be internationalized. Also, in some
cases, character streams are more efficient than byte streams. Character streams are
defined by using two class hierarchies. At the top are two abstract classes, Reader and
Writer. These abstract classes handle Unicode character streams. Java has several
concrete subclasses of each of these streams. The abstract classes Reader and Writer
define several key methods that the other stream classes implement. Two of the most
important methods are read( ) and write( ), which read and write characters of data,
respectively. These methods are overridden by derived stream classes.
Predefined Streams
All Java programs automatically import the java.lang package. This package defines a
class called System, which encapsulates several aspects of the run-time environment.
System also contains three predefined stream variables, in, out, and err. These fields
are declared as public and static within System. This means that they can be used by
any other part of your program and without reference to a specific System object.
System.out refers to the standard output stream. By default, this is the console.
System.in refers to standard input, which is the keyboard by default. System.err refers
to the standard error stream, which also is the console by default. However, these
streams may be redirected to any compatible I/O device. System.in is an object of
type InputStream; System.out and System.err are objects of type PrintStream. These
are byte streams, even though they typically are used to read and write characters
from and to the console. You can wrap these within character-based streams, if
desired.

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

54

Console Input
Reading Character
Consider InputStream refers to console through its object System.in. Although
InputStream is byte stream class but we can use it for reading writing characters from
and to the console. Reader is character based reading stream but it is abstract class,
one of its concrete subclasses is InputStreamReader, which reads bytes from a given
InputStream and converts them to characters. So if we give System.in object of
InputStream to InputStreamReader it will connect us to console. Now we can use
read() method of InputStreamReader to read a character from console. read() method
returns a integer value of character we can use type casting to convert it to character
type. read() method returns -1 when end of stream occurs and it throws IOException
in case of error. Syntax : int read() throws IOException
Example:
import java.io.*;
class readChar
{
public static void main(String args[])
throws IOException //read() method throws it
{
InputStreamReader obj = new InputStreamReader(System.in);
/*Object of InputStreamReader is created by using its constructor
which takes object System.in of type InputStream.*/
char ch; //Character variable to store character
System.out.print("Type a character and press ENTER : ");
ch = (char) obj.read();
/*read() method of InputStreamReader is called, which returns Integer
value of character so type casting is also used to convert it to character.*/
System.out.println("You typed : " + ch);
}
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

55

Reading String using BufferedReader


Above method cant be used to read string from console because you have to press
ENTER key after typing each character. To avoid this problem BufferedReader input
character stream is used. BufferedReader is a subclass of Reader. It reads provided
stream of type Reader and stores it in memory buffer. Then you can call its read() or
readLine() methods to read from stored memory buffer. So if we provide it our
InputStreamReader which is already connected to Console through System.in, then it
will start buffering characters from console until we press ENTER which causes flush
to memory. After that we can use its read() method to read characters from memory
buffer those are stored by it from console into memory buffer.

Example:
import java.io.*;
class readString
{
public static void main(String args[])
throws IOException //readLine() method throws it
{
BufferedReader objBR;
objBR = new BufferedReader(new InputStreamReader(System.in));
/*Object of BufferedReader is created by using its constructor
which takes object of InputStreamReader(subclass of Reader)
that is already connected to console through System.in*/
System.out.println("Type String : "); //Prompt
String myString = objBR.readLine();
/* readLine() method of BufferedReader called
which returns line of string from Buffer */
System.out.println("You typed:");
System.out.println(myString);
}
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

56

Console Output
Writing to Console using PrintWriter
Writing to console through System.out is recommended mostly for debugging
purposes or for sample programs. For real-world programs, the recommended method
of writing to the console when using Java is through a PrintWriter stream. PrintWriter
is one of the character-based classes. Using a character-based class for console output
makes it easier to internationalize your program.
Consider OutputStream stream refers to console through its object System.out.
PrintWriter takes OutputStream and writes on it. So we can write to console by using
PrintWriter providing it System.out object of OutputStream. It will connect us to
console output. Now we can use its print() or println() methods output to console.
PrintWriter has several constructors one used here :
Syntax : PrintWriter(outputStreamObject,booleanValue)
If booleanValue is true, flushing automatically takes place, JAVA flushes the output
stream every time a println( ) method is called.. If false, flushing is not automatic you
can explicitly flush by using flush() method of PrintWriter.
PrintWriter supports the print( ) and println( ) methods for all types including Object.
Thus, you can use these methods in the same way as they have been used with
System.out. If an argument is not a simple type, the PrintWriter methods call the
objects toString( ) method and then print the result.
Example:
import java.io.*;
class printWriter
{
public static void main(String args[])
{
PrintWriter objPW;
objPW = new PrintWriter(System.out,true);
objPW.println("This is string."); //Sting printed.
int a = 5;
objPW.println("This is integer :" + a); //Integer printed.
float b = 3.534f;
objPW.println("This is float :" + b); //Float printed.
objPW.print(objPW);
/*Object printed which is not simple type so toString() method of Object
class is called which converts it to string then print() method prints it.*/
objPW.flush();
/*Because print() method not flushes automatically
therefore explicit flush() method is called.*/
}
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

57

More about byte Streams:


The byte stream classes provide a rich environment for handling byte-oriented I/O. A byte stream
can be used with any type of object, including binary data. Two top byte stream classes are:
1. InputStream:
InputStream is an abstract class that defines Javas model of streaming byte input. All of the
methods in this class will throw an IOException on error conditions.
Methods Of InputStream
Returns the number of bytes of input currently
int available( )
available for reading.
Closes the input source. Further read attempts will
void close( )
generate an IOException.
Places a mark at the current point in the input stream
void mark(int numBytes)
that will remain valid until numBytes bytes are read.
Returns true if mark( ) / reset( ) are supported by the
boolean markSupported( )
invoking stream.
Returns an integer representation of the next available
int read( )
byte of input. 1 is returned when the end of the file is
encountered.
Attempts to read up to buffer.length bytes into buffer
and returns the actual number of bytes that were
int read(byte buffer[ ])
successfully read. 1 is returned when the end of the
file is encountered.
Attempts to read up to numBytes bytes into buffer
starting at buffer[offset], returning the number of bytes
int read(byte buffer[ ], int offset, int numBytes)
successfully read. 1 is returned when the end of the
file is encountered.
void reset( )
Resets the input pointer to the previously set mark.
Ignores (that is, skips) numBytes bytes of input,
long skip(long numBytes)
returning the number of bytes actually ignored.
2. OutputStream
OutputStream is an abstract class that defines streaming byte output. All of the methods in this
class return a void value and throw an IOException in the case of errors.
Methods Of OutputStream
void close( )
Closes the output stream. Further write attempts
will generate an IOException.
void flush( )
Finalizes the output state so that any buffers are
cleared. That is, it flushes the output buffers.
void write(int b)
Writes a single byte to an output stream. Note that
the parameter is an int, which allows you to call
write( ) with expressions without having to cast
them back to byte.
void write(byte buffer[ ])
Writes a complete array of bytes to an output
stream.
void write(byte buffer[ ], int offset, int numBytes) Writes a subrange of numBytes bytes from the
array buffer, beginning at buffer[offset].
All methods of these classes are overridden by their subclasses but mark() and reset()
are specific to some classes.
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

58

File I/O through byte streams


JAVA provides a number of classes and methods that allow you to read and write
files. In Java, all files are byte-oriented, and Java provides methods to read and write
bytes from and to a file. However, Java allows you to wrap a byte-oriented file stream
within a character-based object.
File Reading using FileInputStream
The FileInputStream class creates an InputStream that you can use to read bytes from
a file. Its two most common constructors, both throws FileNotFoundException.
FileInputStream(String filenameORpath)
FileInputStream(File fileObj)
FileInputStream overrides six of the methods in the abstract class InputStream. The
mark( ) and reset( ) methods are not overridden, and any attempt to use reset( ) on a
FileInputStream will generate an IOException.
We use its constructor which takes file name as argument and opens that file to read.
If specified file not exists it throws FileNotFoundException. Then we can use its
read() method which reads a single byte from file and returns the byte as an integer
value. read() method returns -1 for end of file. In case of error it throws IOException.
When you have done reading file you should close it by close() method which also
throws IOException.
Example:
import java.io.*;
class fileReader
{
public static void main(String args[])
throws IOException //read() method throws it.
{
FileInputStream objFIN; //Object created.
try {
objFIN = new FileInputStream("MJS.txt");
//File stream opened with specified file
}
catch (FileNotFoundException e) {
System.out.println("File Not Found.");
return; //Incase of file not found exit
}
int intValue; //To store byte's integer value
do {
intValue = objFIN.read();
//reads file
System.out.print( (char) intValue);
}
while (intValue != -1); //check on EOF
}
}
Create text file MJS.txt first then read it by this example.
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

59

File Writing using FileOutputStream


FileOutputStream creates an OutputStream that you can use to write bytes to a file.
Its most commonly used constructors are shown here:
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)
They can throw a FileNotFoundException or a SecurityException. Here, filePath is
the full path name of a file, and fileObj is a File object that describes the file. If
append is true, the file is opened in append mode.
Creation of a FileOutputStream is not dependent on the file already existing.
FileOutputStream will create the file before opening it for output when you create the
object. In the case where you attempt to open a read-only file, an IOException will be
thrown.
We use its first constructor which takes file name as argument and opens that file to
write. If specified file cant be created it throws FileNotFoundException. If specified
file already exits and there is no append argument in constructor then it will be
replaced with new file. Then we can use its write() method which writes a byte value
to file. Although write() method takes int value as argument but it writes only low
order 8 bits to file. In case of error it throws IOException. When you have done
reading file you should close it by close() method which also throws IOException.
Example:
import java.io.*;
class fileWriter {
public static void main(String args[]) throws IOException //write() throws
{
FileOutputStream objFout;
try
{ objFout = new FileOutputStream("MJS.txt"); }
catch(FileNotFoundException e) {
System.out.println("File can't be created.");
return;
}
System.out.println("Enter text to file: enter \"Stop\" to stop writing file." );
BufferedReader objBR;
objBR = new BufferedReader(new InputStreamReader(System.in));
String myString;
do
{
myString = objBR.readLine();
for(int m=0; m<myString.length(); m++)
{
objFout.write(myString.charAt(m));
}
}
while(!myString.equals("Stop"));
}
}
In this example BufferedReader is used to input text from console and write it to file
character by character by write() method of FileOutputStream.
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

60

ByteArrayInputStream
ByteArrayInputStream is an implementation of
input stream that uses a byte array as the source.
This class has 2 constructors, each of which
requires a byte array to provide the data source:
ByteArrayInputStream(byte array[ ])
ByteArrayInputStream(byte array[ ], int start,
int numBytes)
array is the input source. The second constructor
creates an InputStream from a subset of your byte
array that begins with the character at the index
specified by start and is numBytes long. A
ByteArrayInputStream implements both mark( )
and reset( ). However, if mark( ) has not been
called, then reset( ) sets the stream pointer to the
start of the streamwhich in this case is the start
of the byte array passed to the constructor.

ByteArrayOutputStream
ByteArrayOutputStream is an implementation of an
output stream that uses a byte array as the
destination. ByteArrayOutputStream has two
constructors, shown here:
ByteArrayOutputStream( )
ByteArrayOutputStream(int numBytes)

import java.io.*;
class byteArrayInputStream
{
public static void main(String args[])
{
String myText = "Hello MJS, I hate you.";
byte byteArray[] = myText.getBytes();
/*byte array created, String method
getBytes() retuns byte representation of
whole string, is assigned to byte array*/
ByteArrayInputStream objBAInS = new
ByteArrayInputStream(byteArray);
/*ByteArrayInputStream created which will be
used to read bytes from byte array as input
stream source. */
int availableBytes = objBAInS.available();
//returns available bytes in stream
while(availableBytes-- > 0)
System.out.print((char) objBAInS.read());
/*reads all available bytes from
ByteArrayInputStream and prints them.*/
}
}

import java.io.*;
class byteArrayOutputStream
{
public static void main(String args[])
throws
FileNotFoundException,IOException
{
FileOutputStream objFout = new
FileOutputStream("TestFile.txt");
ByteArrayOutputStream objBAOutS =
new ByteArrayOutputStream();
String myText = "Hello MJS, I hate you.";
byte byteArray[] = myText.getBytes();
//convert string into byte array

M.J.S
Copyright 2007

In the first form, a buffer of 32 bytes is created. In


the second, a buffer is created with a size equal to
that specified by numBytes. The buffer is held in
the protected buf field of ByteArrayOutputStream.
The buffer size will be increased automatically, if
needed. The number of bytes held by the buffer is
contained in the protected count field of
ByteArrayOutputStream.

objBAOutS.write(byteArray);
/*byteArray is written to
ByteArrayOutputStream */
myText = " I hate you. I hate you.";
byteArray = myText.getBytes();
/*new text assigned and
converted to byteArray*/
objBAOutS.write(byteArray);
//new text written to ByteArrayOutputStream
objBAOutS.writeTo(objFout);
//ByteArrayOutputStream writes to file.
}
}

jasim.shah@yahoo.com

M.J.S

JAVA Outline

61

The File class


Although most of the classes defined by java.io operate on streams, the File class does
not. It deals directly with files and the file system. Objects of class File do not open
files or provide any file-processing capabilities. However, File objects are used
frequently with objects of other java.io classes to specify files or directories to
manipulate. A directory in Java is treated simply as a File with one additional
propertya list of filenames that can be examined by the list() method.
The following constructors can be used to create File objects:
a. File(String name)
The name can contain path information as well as a file or directory name. A file or
directory's path specifies its location on disk. The path includes some or all of the
directories leading to the file or directory. An absolute path contains all the
directories, starting with the root directory, that lead to a specific file or directory.
Every file or directory on a particular disk drive has the same root directory in its
path. A relative path normally starts from the directory in which the application
began executing, and is therefore a path that is "relative" to the current directory. Java
does the right thing with path separators between UNIX and Windows conventions. If
you use a forward slash (/) on a Windows version of Java, the path will still resolve
correctly. Remember, if you are using the Windows convention of a backslash
character (\), you will need to use its escape sequence (\\) within a string. The Java
convention is to use the UNIX- and URL-style forward slash for path separators.
b. File(String pathToName,String name)
Uses argument pathToName (an absolute or relative path) to locate the file or
directory specified by name.
c. File(File directory,String name)
Uses an existing File object directory (an absolute or relative path) to locate the file or
directory specified by name.
d. File(URI uri)
Uses the given URI object to locate the file. A Uniform Resource Identifier (URI) is a
more general form of the Uniform Resource Locators (URLs) that are used to locate
Web sites. For example, http://www.mjs.com/ is the URL for the MJS' Web site.
URIs for locating files vary across operating systems.
On Windows platforms, the URI
file:/C:/data.txt
Identifies the file data.txt stored in the root directory of the C: drive.
On UNIX/Linux platforms, the URI file:/home/student/data.txt
Identifies the file data.txt stored in the home directory of the user student.
Example:
import java.io.*;
class FileTest
{
public static void main(String args[])
{
File objFile = new File("c:\\");
String fileList[] = objFile.list();
for(int m=0; m<fileList.length; m++)
System.out.println(fileList[m]);
}
}
This program prints files and folders of drive c.
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

62

Some useful Methods of File


Method

Description

boolean canRead()

Returns true if a file is readable by the current application; false otherwise.

boolean canWrite()

Returns true if a file is writable by the current application; false otherwise.

boolean exists()

Returns True if the name specified as the argument to the File constructor is a file or
directory in the specified path; false otherwise.

boolean isFile()

Returns true if the name specified as the argument to the File constructor is a file; false
otherwise. Also, returns false for some special files, such as device drivers and named
pipes.

boolean isDirectory()

Returns true if the name specified as the argument to the File constructor is a directory;
false otherwise.

boolean isAbsolute()

Returns True if the arguments specified to the File constructor indicate an absolute path to
a file or directory; false otherwise.

String getAbsolutePath()

Returns a string with the absolute path of the file or directory.

String getName()

Returns a string with the name of the file or directory.

String getPath()

Returns a string with the path of the file or directory.

String getParent()

Returns a string with the parent directory of the file or directory (i.e., the directory in
which the file or directory can be found).

long length()

Returns the length of the file, in bytes. If the File object represents a directory, 0 is
returned.

long lastModified()

Returns a platform-dependent representation of the time at which the file or directory was
last modified. The value returned is useful only for comparison with other values returned
by this method.

String[] list()

Returns an array of strings representing the contents of a directory. Returns null if the File
object does not represent a directory.

File[ ] listFiles( )

Return the file list as an array of File objects instead of strings.

boolean renameTo(File newName)

File name specified by newName becomes the new name of the invoking File object.
Return true upon success and false if the file cannot be renamed.

boolean delete( )

Deletes the disk file represented by the path of the invoking File object. Also deletes a
directory if the directory is empty. Returns true if deleted and false if cannot be removed.

void deleteOnExit( )

Removes file associated with the invoking object when the JVM terminates.

boolean isHidden( )

Returns true if the invoking file is hidden. Returns false otherwise.

boolean setLastModified(long
millisec)
boolean setReadOnly( )

Sets the time stamp on the invoking file to that specified by millisec, which is the number
of milliseconds from January 1, 1970, Coordinated Universal Time (UTC).
Sets the invoking file to read-only.

boolean mkdir( )

Creates a directory, returning true on success and false on failure. Failure indicates that
the path specified in the File object already exists, or that the directory cannot be created
because the entire path does not exist yet.

boolean mkdirs( )

To create a directory for which no path exists, use the mkdirs( ) method. It creates both a
directory and all the parents of the directory.

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

63

More about character Streams:


Although byte stream classes can handle any type of I/O operation, they cannot work directly
with Unicode characters, so character streams are present. Its two top classes:
1. Reader:
Reader is an abstract class that defines Javas model of streaming character input. All of the methods in this
class will throw an IOException on error conditions.
Methods Of Reader
Closes the input source. Further read attempts will generate an
abstract void close( )
IOException.
Places a mark at the current point in the input stream that will remain
void mark(int numChars)
valid until numChars characters are read.
Places a mark at the current point in the input stream that will remain
void mark(int numBytes)
valid until numBytes bytes are read.
boolean markSupported( )
Returns true if mark( ) / reset( ) are supported by the invoking stream.
Returns an integer representation of the next available character from
int read( )
the invoking input stream. 1 is returned when the end of the file is
encountered.
Attempts to read up to buffer.length characters into buffer and returns
int read(char buffer[ ])
the actual number of characters that were successfully read. 1 is
returned when the end of the file is encountered.
Attempts to read up to numChars characters into buffer starting at
abstract int read(char buffer[ ],
buffer[offset], returning the number of characters successfully read. 1
int offset, int numChars)
is returned when the end of the file is encountered.
Returns true if the next input request will not wait. Otherwise, it returns
boolean ready( )
false.
void reset( )
Resets the input pointer to the previously set mark.
Skips over numChars characters of input, returning the number of
long skip(long numChars)
characters actually skipped.
2. Writer
Writer is an abstract class that defines streaming character output. All of the methods in this class return a
void value and throw an IOException in the case of errors.
Methods Of Writer
abstract void close( )
Closes the output stream. Further write attempts will
generate an IOException.
abstract void flush( )
Finalizes the output state so that any buffers are
cleared. That is, it flushes the output buffers.
void write(int ch)
Writes a single character to the invoking output stream.
Note that the parameter is an int, which allows you to
call write with expressions without having to cast them
back to char.
void write(char buffer[ ])
Writes a complete array of characters to the invoking
output stream.
abstract void write(char buffer[ ], int offset, int
Writes a subrange of numChars characters from the
numChars)
array buffer, beginning at buffer[offset] to the invoking
output stream.
void write(String str)
Writes str to the invoking output stream.
void write(String str, int offset, int numChars)
Writes a subrange of numChars characters from the
array str, beginning at the specified offset.
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

64

File I/O using character streams


File Reading using FileReader
The FileReader class creates a Reader that you can use to read the contents of a file.
Its two most commonly used constructors are shown here:
FileReader(String filePath)
FileReader(File fileObj)
Either can throw a FileNotFoundException. Here, filePath is the full path name of a
file, and fileObj is a File object that describes the file.
File Writing using FileWriter
FileWriter creates a Writer that you can use to write to a file. Its most commonly used
constructors are shown here:
FileWriter(String filePath)
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)
FileWriter(File fileObj, boolean append)
They can throw an IOException. Here, filePath is the full path name of a file, and
fileObj is a File object that describes the file. If append is true, then output is
appended to the end of the file. Creation of a FileWriter is not dependent on the file
already existing. FileWriter will create the file before opening it for output when you
create the object. In the case where you attempt to open a read-only file, an
IOException will be thrown.
Example:
import java.io.*;
class fileReader
{
public static void main(String args[]) throws Exception
{
File objFile = new File("MJS2.txt");
FileWriter objFW = new FileWriter(objFile);
String myText = "Hello MJS, I hate you.";
objFW.write(myText);
objFW.close();
FileReader objFR = new FileReader(objFile);
int ch = objFR.read();
while(ch != -1)
{
System.out.print((char) ch);
ch = objFR.read();
}
objFR.close();
}
}
This program creates a file using FileWriter writes a string in it. Then open this file by
FileReader and reads string from file and print it.

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

65

CharArrayReader
CharArrayReader is an implementation of an
input stream that uses a character array as the
source. This class has two constructors, each of
which requires a character array to provide the
data source:
CharArrayReader(char array[ ])
CharArrayReader(char array[ ], int start, int
numChars)

CharArrayWriter
CharArrayWriter is an implementation of an
output stream that uses an array as the
destination.
CharArrayWriter
has
two
constructors, shown here:
CharArrayWriter( )
CharArrayWriter(int numChars)
In the first form, a buffer with a default size is
created. In the second, a buffer is created with a
size equal to that specified by numChars. The
Here, array is the input source. The second buffer is held in the buf field of CharArrayWriter.
constructor creates a Reader from a subset of your The buffer size will be increased automatically, if
character array that begins with the character at needed. The number of characters held by the
the index specified by start and is numChars long. buffer is contained in the count field of
CharArrayWriter. Both buf and count are
protected fields.
import java.io.*;
class CAR
{
public static void main(String args[])
throws Exception
{
String myString;
myString = "Hello MJS, How are your.";
int length = myString.length();
char charBuf[] = new char[length];
myString.getChars(0,length,charBuf,0);
CharArrayReader objCAR;
objCAR = new CharArrayReader(charBuf);
int ch = objCAR.read();
while(ch != -1)
{
System.out.print((char) ch);
ch = objCAR.read();
}
}
}

import java.io.*;
class CAW
{
public static void main(String args[])
throws Exception
{
String myString = "Hello MJS, How are
your.";
CharArrayWriter objCAW =
new CharArrayWriter();
objCAW.write(myString);
char charArray[] = objCAW.toCharArray();
for(int m=0; m<charArray.length; m++)
System.out.print(charArray[m]);
}
}
In this program String is written to
CharArrayWriter and then CharArrayWriter
writes it to charArray, then program prints it from
charArray .

In this program string is converted to String class


method getChars() and assigned to charBuf
character array, then this array is read by
CharArrayReader.

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

66

Random Access Files


It is not derived from InputStream or OutputStream. Instead, it implements the
interfaces DataInput and DataOutput, which define the basic I/O methods. These
interfaces provide methods for reading and writing primitive-type values, byte arrays
and strings. When a program associates an object of class RandomAccessFile with a
file, the program reads or writes data, beginning at the location in the file specified by
the file-position pointer (the byte number of the next byte in the file to be read or
written to), and manipulates all the data as primitive types. When writing an int value,
four bytes are output to the file. When reading a double value, eight bytes are input
from the file. It also supports positioning requeststhat is, you can position the file
pointer within the file. It has these two constructors:
RandomAccessFile(File fileObj, String access)
throws FileNotFoundException
RandomAccessFile(String filename, String access)
throws FileNotFoundException
In the first form, fileObj specifies the name of the file to open as a File object. In the
second form, the name of the file is passed in filename.
In both cases, access determines what type of file access is permitted.
access Description
Open for reading only. If you try to write it throws IOException.
r
Open for reading and writing. If file not exist it will create it.
rw
Open for reading and writing and every change to the files data or metadata
rws
will be immediately (synchronously) written to the physical device.
Opened for read-write operations and every change to the files data will be
rwd
immediately (synchronously) written to the physical device.
Above access specifies can throw these Exceptions with invoking object.
IllegalArgumentException
If the mode argument is not equal to one of "r", "rw", "rws", or "rwd"
FileNotFoundException
If the file exists but is a directory rather than a regular file, or cannot be opened or
created for any other reason
SecurityException
If a security manager exists and its checkRead method denies read access to the file or
the mode is "rw" and the security manager's checkWrite method denies write access
to the file

The method seek( ), shown here, is used to set the current position of the file pointer
within the file:
void seek(long newPos) throws IOException
Here, newPos specifies the new position, in bytes, of the file pointer from the
beginning of the file. After a call to seek( ), the next read or write operation will occur
at the new file position.
void setLength(long len) throws IOException
This method sets the length of the invoking file to that specified by len. This method
can be used to lengthen or shorten a file. If the file is lengthened, the added portion is
undefined.
M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

67

Some Useful Methods of RandomAccessFile


Some methods to read write file
int read() : Reads byte of data from this file.
1
void write(int b) : Writes the specified byte to this file.
int read(byte[] b) : Reads up to b.length bytes of data from this file into an array of
bytes.
2
void write(byte[] b) : Writes b.length bytes from the specified byte array to this file,
starting at the current file pointer.
int read(byte[] b,int off,int len) : Reads up to len bytes of data from this file into an
array of bytes.
3
void write(byte[] b,int off, int len) : Writes len bytes from the specified byte array
starting at offset off to this file.
boolean readBoolean() : Reads a Boolean from this file.
4
void writeBoolean(boolean v) : Writes a boolean to the file as a one-byte value.
char readChar() : Reads a Unicode character from this file.
5
void writeChar(int v) : Writes a char to the file as a two-byte value, high byte first.
byte readByte() : Reads a signed eight bit value from this file.
6
void writeByte(int v) : Writes a byte to the file as a one-byte value.
short readShort() : Reads a signed 16-bit number from this file.
7
void writeShort(int v) : Writes a short to the file as two bytes, high byte first.
int readInt() : Reads a signed 32-bit integer from this file.
8
void writeInt(int v) : Writes an int to the file as four bytes, high byte first.
long readLong() : Reads a signed 64-bit integer from this file.
9
void writeLong(long v) : Writes a long to file as eight bytes, high byte first.
float readFloat() : Reads a float from this file.
void writeFloat(float v) : Converts the float argument to an int using the floatToIntBits
10
method in class Float, and then writes that int value to the file as a four-byte quantity,
high byte first.
double readDouble() : Reads a double from this file.
void writeDouble(double v) : Converts the double argument to a long using the
11
doubleToLongBits method in class Double, and then writes that long value to the file as
an eight-byte quantity, high byte first.
Some other methods
void close() : Closes this random access file stream and releases any system resources
associated with the stream.
long getFilePointer() : Returns the current offset in this file.
long length() : Returns the length of this file.
int skipBytes(int n) : Attempts to skip over n bytes of input discarding the skipped bytes.

M.J.S
Copyright 2007

jasim.shah@yahoo.com

M.J.S

JAVA Outline

68

Example:
import java.io.*;
class randomTest
{
public static void main(String args[]) throws Exception
{
RandomAccessFile objRAF;
objRAF = new RandomAccessFile("randomTest.mjs", "rw");
objRAF.writeInt(50); //Write Interger
objRAF.writeFloat(3.23f); //Write Float
objRAF.writeChar(65); //Write 'A'
objRAF.seek(0); //Takes FilePointer to Start of file.
System.out.println("Interger : " + objRAF.readInt());
System.out.println("Float : " + objRAF.readFloat());
System.out.println("Character : " + objRAF.readChar());
objRAF.seek(0); //Takes FilePointer to Start of file.
objRAF.skipBytes(4); //skip 4 bytes to skip integer value.
System.out.println("Float : " + objRAF.readFloat());
System.out.println("FilePointer is " + objRAF.getFilePointer() +
" Bytes away from start of file.");
//Prints where is file pointer .
System.out.println("Total File Size : " + objRAF.length() + " Bytes.");
}
}

M.J.S
Copyright 2007

jasim.shah@yahoo.com

S-ar putea să vă placă și