You are on page 1of 439

Programming in Java

Books
1. Java 2 - The Complete Reference, Herbert Schildt (Seventh Edition).
2. The Java Programming Language, Ken Arnold, James Gosling & David
Holmes (Third Edition).
3. Core Java Volume I – Fundamentals, Eigth Edition, C S Horstmann & G.
Cornell
4. Java.sun.com/docs/books/tutorial, javaworld.com
-------------------------------------------------------------------------------------------------------

JAVA
Just Another Vague Acronym

Initially called Oak

Originally designed by James Gosling


Research language vs. production language

A language is called research language if it has untested features (i.e. features that had
not been tested in its predecessor languages)

A language is called production language if it does not have any untested features.

Java is not a research language. It is a production language


C and C++ are examples of research languages.
Advantages of Java over C++
(i) Java syntax is similar to C++.
(ii) Java is more object-oriented than C++.
(iii) It is easier to write bug-free code in Java than in C++.

e.g. If you write the code


while (someIdentifier = 1) {
//do some thing
}
in C++, you will be caught in an infinite loop. But in Java this code will flagged be as compile
time error.

• You will find bound checking of arrays.


• There is no manual memory allocation and deallocation
• No pointer arithmetic and pointer syntax.
• There are no multiple inheritances.

Because of all these reasons, it is easier to write bug free code and
this reduces the program development time.

(iv) Java is architecture-neutral. Even if you upgrade the operating system and hardware,
the Java program written in the older operating system and previous hardware will continue
to run. This scenario is known as `Write Once Run Everywhere`.
Uses of Java

• Write application for establishing communication between client and server,


• Develop embedded systems,
• In new devices and applications.
Differences between Java and C++

1) C++ features not supported by Java


Operator overloading, multiple inheritance, header files, structures and unions, typedef,
virtual base class, default argument, goto, delete, destructor, automatic type conversion
that results in loss of precession, otherwise automatic type conversion is permitted,
primitive type can be passed by value only, object can be passed only by reference,.

2) Features of Java not found in C++


Multithreading, packages, interfaces, Application Programming Interface (API) classes,
enhanced `break` and `continue`, characters are unsigned 16 bits, unsigned right shift
(>>>) operator, built-in String class and documentation comments
(/** some comments */).

3) Features that are shared between C++ and Java


boolean variables, access specifiers and support for exception handling.
Java Buzzwords

Java is described by the by the following buzzwords.

Simple – Java has eliminated many rarely used, poorly understood and confusing features of C++. It is easy
to achieve fluency in Java.

Object-oriented – It is more object-oriented than C++.

Architecture-neutral – Java program written for a specific operating system and hardware can run in other
operating system and hardware. This is necessary because Java codes are downloaded from the Internet to
run on a variety of CPU and operating system.

Portable – All primitive types take the same amount of storage on all architectures.

Robust – Java provides early error checking facility and so it is easy to develop bug-free code.
Java Buzzwords

Multithreaded – Java has API classes that support multithreading.

Network-savvy – Java has support for TCP/IP protocols and remote method invocation (RMI).

Session management – There are API classes for session management and cookies.

High performance – In C++, you include files (header files e.g.) for using built-in functions and
after compilation, these functions find their place in the compiled code even if a few of them
only are actually used in the source code. This is not so with Java. Consequently, the size of
the java compiled code is small and so the space requirement and time of execution is low and
hence the performance is high.

Interpreted – Java compiler converts the Java source code into bytecodes and these are
interpreted by the Java interpreter also known as the Java Virtual Machine (JVM). The JVM
differs from architecture to architecture.

Dynamic – A Java program written using API classes need not be recompiled when the API
classes are modified and/or upgraded.
Coding Style

Java developers follow coding style in writing the name of an identifier depending upon
what it stands for.

The classes and interfaces are named using words in title case (e.g. Employee, String,
Thread, Runnable). If a class name need to consist of more than a single word then each
word is written in title case and words are concatenated without using underscore (e.g.
FinanceDepartment).

The method and variable names are written in lower case. If you need more than a single
word to construct such a name then the first word is written in title case and the rest of
the words are written in lower case and the words are concatenated (dailyTemperature).

The name of the constants are written in uppercase and if such a name need more than
one word then the words are joined using underscore (e.g.
GRAVITATIONAL_CONSTANT).
Basic (primitive) data types
char (unsigned and 16 bits),

short (for short integer, signed and 16 bits),

int (for integer, signed and 32 bits),

float (for floating point numbers, signed and 32 bits),

double (for floating point numbers, signed and 64 bits),

long (for long integers, signed and 64 bits),

byte (for signed 8 bit integer)

boolean having only two possible values true and false (unlike zero and non-zero) and it
requires no storage.
• The true and false are not converted into numeric representation.
• The true and false are known as boolean literals
• Can be assigned to boolean variables only
• Can be used in expressions with boolean operators.
Arithmetic operators

+ (addition), − (subtraction), * (multiplication), / (division), % (modulo operation

can be applied on integers as well as floating point numbers), ++(unit

increment), += (increment and assignment), -= (decrement and assignment),

*=(multiplication and assignment), /= (division and assignment), %= (modulo

and assignment) and -- (unit decrement).

Arithmetic operators can be applied only on numeric types and character type
not on boolean type
Bitwise operators

Perform bit operations on its operands and can be applied on long, int, short,
char and byte types only.

Operators
~ (negation), & (bitwise and), | (bitwise or), ^ (exclusive or), >>> (unsigned right

shift), << (left shift), >> (right shift), &= (bitwise and followed by assignment), ~= (bitwise

not followed by assignment, ^= (bitwise exclusive or followed by assignment), >>=

(bitwise right shift followed by assignment), >>>= (bitwise unsigned right shift

followed by assignment) and <<= (bitwise left shift followed by assignment)

N.B. Java uses 2`s complement form to store negative numbers.


Relational & Boolean logical operators

Relational operators
== (for testing equality of numbers or characters or object references returned
by an expression), <= (less than or equal to), >= (greater than or equal to), !=(
not equal to), < (less than), >(greater than)

Boolean logical operators (can be applied only on Boolean type)


& (and), | (or), ^ (exclusive or), || (short circuit or), && (short circuit and),
! (not), ^= (exclusive or followed by assignment), == (equality), != (not
equal to) and ?: ( conditional operator)

N.B. In short circuit or if the first expression is true than the second expression
will not be evaluated. In short circuit and if the first expression is false then
the second expression will not be evaluated.
Operator precedence
() []
++ -- ~ !
* / %
+ -

>> >>> <<

== !=

&

&&

||

?:

= operator=
Code example involving >>>

int a = -1; (111111…1)


(Java uses 2`s complement form to store negative number)
a = a>>> 24 (0…011111111 = 255).

Type casting

The type casting is performed using the syntax


(type) identifier.
Automatic type conversion

The automatic type conversion takes place in such a way that data
widening is permitted but shortening is not.

The conversion is performed in such a way that precision of data is not


lost.

char

byte → short → int → long (data widening)

float → double

Inversion of the arrows will lead to compile time error


Examples on type conversion rules and type casting.
int m = …;
short n = m; //compile time error- data shortening
n = (short) m; //this is okay. The result is m%512 when m is outside the range
of short integer
m = n;//this is okay – data widening
--------------------------------------------------------------------------------------------------------
float x = …;
double y = 2.798762;
x = y; //compile time error – data shortening
y = x; //this is okay
--------------------------------------------------------------------------------------------------------
int a = …;
byte b = …;
b = a; // compile time error.
---------------------------------------------------------------------------------------------------------
int a = …;
byte b = …;
b = (byte)a; The result is a%256 when a is outside the range of byte.
Automatic type promotion

Java is a strongly typed language.


Any type mismatch is flagged as compile time error.
e.g. Any mismatch between the type of formal and actual parameter(s)
In function call is flagged as compile time error.

Rules for automatic type promotion in arithmetic expression


• The bytes and shorts are promoted to integers
• If one of the operands is float or double or long then the other(s) is
(are) promoted to float or double or long and stored in float or
double or long.
Lexical elements (Building blocks of Java source code)
• White spaces
• Identifiers (name of a class, interface, method, variable, constant)
• Literals (true, false, numeric literals e.g. 1.2, 45; character literals e.g. ‘j’, string literals
“java”)
• Comments (// single line, /* */ multi-line, /** */ documentation comment)
• Separators
Parentheses ( )
Used to contain a list of parameters in method definition & invocation, defining
operator precedence, containing expressions in control statements,
surrounding cast types
Braces { }
Used to contain the values of automatically initialized arrays and to define a
block of code
Square brackets [ ]
Used to declare array types and also for dereferencing array values
Semicolon ;
Used to terminate a statement
Comma ,
Used to separates consecutive identifiers in variable declarations and to chain
statements together inside for loop
Period .
Used to separate package name from sub package and to separate a variable
or a method from a reference variable.(e.g. pkg1.pkg2, ob.f(), ob.m)
• Operators (Arithmetic operators, bitwise operators, relational operators, boolean
logical operators)
Lexical elements (Building blocks of Java source code)

• Keywords

char, short, int, float, long, double, byte, boolean, void – to


declare basic type or no type
for, if, else, do, while, switch, case, default, break, continue,
return – used to form control statements
try, catch, finally, throw, throws – used in exception handling
abstract, static, final – modifiers
public, private, protected – special kind of modifiers known as
access specifiers
class – to declare a class,
interface – to declare an interface
extends – to inherit a class
implements – to convert an interface into a class
new – for creating object.
this – refers to the current object
super – refers to the super class
Lexical elements (Building blocks of Java source code)

Keywords

synchronized – used in multithreaded programs


package – for declaring package (an umbrella)
import – to make package members available to a source file
transient – used in the context of serialization
volatile – used to maintain data consistency
instanceof – used to test whether an object is an instance of a specific
class e.g if (obj instanceof X)
native – refers to code written in native programming languages
namely, C, C++. Used as modifier in method declaration.
E.g. private native void method( );
assert – used to ensure whether the value of a boolean expression is
true.
e.g. assert expression;
Arrays
1-D Array

type[ ] arrayname = new type[size];

type arrayname [ ] = new type[size];

e.g. int [ ] m = new int[10];


The array is created and all elements are initialized by zero.

float [ ] x = new float[10];


The array is created and all elements are initialized by 0.0f.

char [ ] chrs = new char[20];


The array elements are initialized by blank space.

The elements of boolean arrays are initialized by false,


The elements of String arrays are initialized by null.

 The identifiers m, x and chrs are actually references.


 A reference is similar to a pointer except that it can`t point to an arbitrary
memory location and you can`t apply arithmetic on references.
1-D Arrays

type[ ] arrayname = new type[size];

type[ ] arrayname;

Array is not created, only a reference is declared and it points to nothing (null).

arrayname = new type[size];

The array is created i.e. the memory is allocated for the array and all the
elements of the array are initialized by their default values.

type[ ] arrayname = new type[size];


is equivalent to

type[ ] arrayname; and arrayname = new type[size];


1-D Array
• Every array name is a reference.

• You may initialize an array at the point of declaration.

type [ ] arrayname = { val1, val2, .., valn};


e.g. char [ ] chrs = {‘j’, ‘a’, ‘v’, ‘a’};
String [ ] strs = {“Java”, “ is”, “ a”, “ general-purpose”, “
concurrent”, “ class-based”, “ objected-oriented”, “
language”};

• To access an array element use arrayname[index];

• The index starts with zero.


1-D Arrays

• You can`t have negative index, or an index out of the bound of the
array. Java provides bound checking of arrays.

• You can use arrayName.length to access the length of the array

Example code:
int sum(int[ ] a) {
int result = 0;
for(int i =0; i < a.length; i++) result += a[i];
return result;
}
2D arrays

type[ ] [ ] arrayname = new type[size1][size2];

You may not mention the second dimension


type[ ] [ ] arrayname = new type[size1][ ];
for (i = 0; i<size1; i++) arrayname[i] = new type[size2];

Intialization at the point of declaration:


type[ ] [ ] arrayname = { { }, { } };
Arrays

 Java arrays, even of basic types, are objects. (Array names are
references)

 Java arrays are created dynamically on the heap.

 The array index may have type short, int, byte, char, but it cannot be
long, float, double or boolean

 Once an array is created its length cannot be altered


Control statements

while, do-while, for,

for-each version of for loop,

if-else, switch-case-default, break,

continue, labeled break; labeled continue,

return
for-each version of for loop

for (type iteration-var : array-name ) {


statements
}
Example code segment:
int sum(int[ ] a) {
int result = 0;
for(int i : a) result += i;
return result;
}
Using conventional for loop:
int sum(int[ ] a) {
int result = 0;
for(int i =0; i < a.length; i++) result += a[i];
return result;
}
Labeled break

A label is an identifier followed by a : (colon) e.g.


there:

Syntax: break label; e.g. break there;

Code example:
first: for(,,,) { //label is defined and can be referred to
//inside this block
//code
if( condition) break first; // label is used
//code
}
Labeled break

Nested labeled break


Code Example:

first: for (,,,) { //outer most loop


//code
second: for (,,,) { //inner loop
//code
if( condition) break first;
//code
third: for (,,,) { //inner most loop
//code
if( condition) break second;
else break third;
}//end of inner most loop
}//end of inner loop
}//end of outer loop
Labeled break
The following code will not compile.

first: for (,,,) {//outer loop


//code
second: for (,,,) {
//code
if( condition) break third;
//code
third:for (,,,) {
//code
if( condition) break second;
else break third;
}//end of inner most loop
}//end of inner loop
}//end of outer loop

You cannot break to a label which is not defined for the enclosing
block.
Labeled continue

Syntax: continue label;

Code example:

first: for(,,,) { //label is defined and can be referred to


//inside this block
//code
if( condition) continue first; // label is used
//code
}
Labeled break

Nested labeled continue


Code Example:

first: for (int i=0; i<m; i++) {//outer loop


//code
second: for (int j=0; j<n; j++) {//inner loop
//code
if( condition) continue first; //control transferred to i++
//code
third: for (int k=0; k<p; k++) {//inner most loop
//code
if( condition) continue second; //control transferred to j++
else continue third; //control transferred to k++
}//end of inner most loop
}//end of inner loop
}//end of outer loop
Labeled continue
The following code will not compile.

first: for (,,,) {//outer loop


//code
second: for (,,,) {//inner loop
//code
if( condition) continue third;
//code
third: for (,,,) {//inner most loop
//code
if( condition) continue second;
else continue third;
}//end of inner most loop
}//end of inner loop
}//end of outer loop

You cannot continue to a label which is not defined for the enclosing
block.
Usage of labeled break & labeled continue

When you want the program control to come out of a


deeply nested loop, use labeled break.

If you want to output ragged arrays (e.g. Pascal`s triangle),


use labeled continue.
Classes

A class is a reference type.

Partial syntax for class declaration:

[modifier] class ClassName {


//field declarations
//static initialization block
//initialization block
//constructor definition
//method definition
//class declarations
//interface declarations
}
Classes
• Fields can be static or non-static.

• Static fields are called class fields because they belong to the class
and do not belong to the object.

• The non-static fields are called instance fields.

• There exists only one (the original) copy of a class field. Each object
of a class has a copy of each of its instance field, but a class field is
shared by all the objects of a class.

• The class fields receive their share of memory when the class file is
loaded and instance fields receive their share of memory when an
object is created.

• Every Java source file is converted into a class file (.class file) by
the Java compiler
Classes

• Constructors can be overloaded (default / parameterized).

• If you do not provide any constructor, a default public constructor will be


synthesized by the compiler.

• Constructors cannot be declared static.

• Methods can be overloaded, but default arguments are not permitted.

• Overload resolution (which of the overloaded function is to be called) takes


place at the time of compilation.

• Automatic type promotion takes place at the time of overload resolution.

• The type and number of arguments of the function are considered for
overload resolution. Return type is not used for overload resolution
Classes
• Methods can be static or non-static.

• A static method can access only static fields, call only other static
methods and does not have `this` reference.

• While passing arguments to a method, the basic types are passed by


values and objects are passed by references.

• A method that changes the state of an object is called a mutator method


(e.g. set ( ) method)

• A method that only reads the state of an object is called an accessor


method (e.g. get ( ) method).

• The state of an object is determined by the value of its instance


fields.

• An object is an instance of a class.


Keyword final

• `final` is used as a modifier of a field, method, class.

e.g. final double PI = …; //a final field

final void method(…) { //a final method


body of the method
}

final class SomeClass { //a final class


body of the class
}
Keyword final

• If a field is declared final then its value cannot be changed.

• If a field is declared as final then it must be initialized at the point of


declaration. Blank finals are not permitted.

e.g. final double PI = 3.14;


final double PI; //compile time error

• So if you want to treat a field as a constant, use the modifier final.

• final fields are often declared static and public


e.g. public static final double PI = 3.14;
Keyword final

• If a method is declared final then it cannot be overridden.

• If a class is declared final then it cannot be extended (inherited).

• If a field is declared final then its value cannot be altered.


Classes
• Every field of a class except the final fields receives a default value
at the point of declaration.

 int, short, long, byte receives a value 0.

 char type receives blank space.

 float type receives 0.0f.

 double type receives 0.0,

 boolean type receives false.

 object references receive null value.


Local variables

• Variables declared inside a method or inside a block of code

e.g. void method(…) {


boolean flag = true; // flag is local to the method
int m = 10;
….
}

{//block of code starts


double x = 4.67; // x is local to this block

}//ends

• A block of code is defined by a pair of braces.

• Though field of class (if it is not final) has default value but local variables
do not have default values and they must be initialized at the point of
declaration.
The `this` reference

• The `this` reference refers to the current object (invoking object i.e.
object currently in use).
• Members of `this` are accessed by . (the period operator). i.e.
this.member

Example code
class X {
int m, n;
X(int m, int n) {
this.m = m;
this.n = n;
}
}
???
What operators are not found in Java but
found in C++???

::
->
What is the most unfortunate construct of
programming languages??
The `this` reference

• The `this` reference can also be used to call another constructor of


the same class.

Example code:
class X {
int m, n;
X(int m) {
this.m = m;
}
X(int m, int n) {
this(m); // must be the first non-comment statement in this definition.
this.n = n;
}
}
Object creation

X x1 = new X ( );

X x2 = new X(4);

X x3 = new X(10,20);

X x4;
Object not yet created, only a reference has been declared

x4 = x3;
No new object has been created, x4 points to the same object as x3
points to. If you test the return value of x3 == x4 you will get true
because the object pointed to by x3 and x4 are the same.

All objects are created on the heap at the run time. There is no compile
time object
Objects equality

• The state of an object is defined by the value of its instance fields.

• Two objects are said to be equal if they have the same state.

• The state of objects can be compared using (overriding, if


necessary) the equals method, originally defined in the Object
class
Object cloning
Making an exact copy of an object is called object cloning.

e.g. Inside a class:


class X {
//other code
X makeACopy( X x) {
this.m = x.m;
this.n = x.n;
return this;
}
}
X x = new X(10,20);
X x1 = x.makeACopy(x);

• x == x1 returns false because x and x1 points to object with the


same state but different location.
Object cloning

You may also use constructor for object cloning.

e.g. X (X ob) {
m = ob.m; n = ob.n;
}
X x1 = new X(5, 10); X x2 = new X(x1);

x2 is now a copy of x1.


main method

 The main method has the following form


public static void main(String[ ] args)

 The main method of a Java program must be declared


public and static.

 Its return type is void and its argument is an array of


strings.

 The main method is declared static because it starts its


execution before any object comes into existence

 It is public because it is to be accessed from outside the


class it is defined in.
Sending output to the standard output device (display screen)

Use System.out.println or System.out.print

 System (built-in class) is a class


 out is an object of PrintStream (built-in class) class
 print and println are methods defined inside the PrintStream class.
 print and println methods can take any argument except of type
void.
 print and println convert their arguments into string before sending
them to the console (display screen).

The built-in classes will be referred to as the API (Application


Programming Interface) classes.
Your first Java program

class HelloWorld {
public static void main(String[ ] args) {
System.out.println(“Welcome to the world of Computing”);
System.out.println(“Computing powered by Java”);
double x = 27;
System.out.print("The value of x is " + x);
} //main
} // HelloWorld

The name of the source file must be HelloWorld.java.


Your first Java program

 To compile this code use javac command.


javac HelloWorld.java

 You could also type javac helloworld.java or javac Helloworld.java.

 A class file is created by the java compiler, HelloWorld.class

 The name of the class file is exactly the same as the name of class
in the source code (no change of case).

 To execute the program, you need to type


java HelloWorld
at the command line.
Another program
class Box {
double l, b, h;
Box ( ) { l =10; b = 10; h = 10;}
Box (double l) {
this.l = l;
}
Box (double l, double b) {
this.l = l; this.b = b;
}
Box (double l, double b, double h) {
this(l, b); //calling the other constructor Box(double l, double b)
this.h = h;
}
Box (Box ob) { //object cloning
l = ob.l; b = ob.b; h = ob.h;
}
double volume ( ) {
return l*b*h;
}
Box modifyObject( ) { //a mutator method
this.l++; this.b++; this.h++; return this;
}
boolean equals(Box ob) { // tests equality of two objects
if( l == ob.l && b == ob.b && h == ob.h) return true; else return false;
}
}//Box class

class BoxTest {
public static void main(String[ ] args) {
Box b1 = new Box (12,14,17);
System.out.println(b1.volume( ));
Box b2 = new Box(b1);
Box b3 = b2;
System.out.println(b1.equals(b2));
System.out.println(b1 == b2);
}
}//BoxTest
Some observations

After compilation of this code two class files are created by the java
compiler,
Box.class & BoxTest.class.

To execute the program, you need to type


java BoxTest
at the command line.

You can`t use


java Box
because this class does not have the main method

If you incorporate a main method inside the Box class you can execute
it using the command java Box.
Comments

How many main methods you may have in a Java source file?

 You may have one main method in each of the classes that the
source file has.

 This is useful for unit testing (Developing and testing each class
separately).

 The argument of java command must be the name of the class


which you want the execution to start from.
Processing command line arguments

Code Example

class CommandLine {
public static void main(String[ ] args) {
for(int i=0; i<args.length; i++)
System.out.println(args[i]);

}
}
Remarks

 In C++ you may have variables and methods outside class, but in
Java everything & everything must be inside a class.

 You may write a C++ program without using classes, but you can`t
write a Java program without using classes.
Creating an array of objects

class BoxTest1 {
public static void main(String[ ] args) {
Box [ ] barray = new Box[10] ;
for(int i=0; i<5; i++) barray[i] = new Box( );
for(int i=5; i<10; i++) barray[i] = new Box(10,30,50);
}
}

Exercise: Create a 2D array of objects of the Box class


Initialization block

An initialization block is a block of statements that appears within a


class declaration, outside of any member or constructor declaration
and
which initialize instance fields.

• This is used for complex initialization.

• The initialization block gets executed, each time an object is


created.

• You may use `this` reference, you may use `super` inside
initialization block but you cannot use return statement.

• The initialization blocks are executed in order of text.


Code example

class Employee {
int id;

static int nextId = 1000;

{ // this is an initialization block


id = nextId++;
}
}
Static initialization block

A static initialization block is an initialization block declared as static.

e.g. static {
//code;
}

A static initialization block


• Can only refer to static members of the class
• Cannot have this reference, super and return.
• Block is executed when the class file is loaded.
Will this program run?

class X {
static {
System.out.println(“run”);
}
}
Answer

Program will compile.

When you try to execute it, it displays the string “run” and will terminate
with an error message saying that `main is not found`.

This error message can be overcome if you use System.exit(0), i.e.

class X {
static {
System.out.println(“run”);
System.exit(0);
}
}
Code example using initialization block
& static initialization block

class Employee {
int id;
static int nextId;
static { // this is a static IB
nextId = (int) (Math.random( )*1000);
}

{ // this is an IB
id = nextId++;
}
}
Generating prime numbers at the load time

class Primes {
static int [ ] knownPrimes = new int[10];
static {
knownPrimes[0] = 2;
for(int i=1; i<10; i++) knownPrime[i] = nextPrime( );
}
// code to define the nextPrime() method
}

Exercise: Complete this program


Some definitions
Top-level class & Nested class
A class is called a top-level class if it is not declared inside any other
class or interface, otherwise it is called a nested class.

Abstract class
An incomplete class is called an abstract class.

Incomplete class
A class is called incomplete if its specification either has not been
implemented completely or implementation is unknown.

Concrete class
A class that is complete is called a concrete class.
Abstract classes

To declare a class abstract, use the modifier `abstract`.

e.g.
abstract class X {
//code
}
Abstract classes

• Any class may be declared abstract and a class must be declared


abstract if one of its methods is abstract.

• An abstract class cannot be declared final.

• It is not possible to create an object of an abstract class but you can


declare a reference.

• If you do not declare a class abstract then you must give the
definition of all of its methods. This does not make the methods
inline.
• A class which is not declared abstract cannot have abstract
methods.
Abstract methods

• A method is called abstract if it does not have a body.

• A method with a body cannot be declared abstract.

• To declare a method abstract use the modifier abstract. e.g.


abstract rtype methodName (arglist );
abstract boolean f(X x);

• An abstract method cannot be declared final.

• An abstract method cannot be declared static


Interfaces

An interface is a reference type that does not describe how it is


implemented. An interface is a pure specification.

Partial syntax:
interface InterfaceName {
//field declarations
//method declarations
//classes
//interfaces
}
Interfaces

 The fields of an interface are implicitly public, static and final.


 The methods are public and abstract.
 The nested classes and interfaces are public.

Example of an interface

interface I {
int m = 10;
double x = 3.14;
}

To access the members of I use I.m; I.x;


Interfaces
 An empty interface is called a marker interface and it acts like a flag.
e.g. Serializable is a marker interface

 You cannot instantiate an interface, however you can declare a


reference.

e.g. You cannot write I x = new I( ); but you can write I x;

Since an interface is a pure specification so it is often necessary to give


an implementation of the interface.

To implement an interface use the clause

implements
Interfaces
A partial syntax for implementing an interface:

class ClassName implements I1 [, I2,I3,…] {


body of the class
}
A class can implement any number of interfaces
-----------------------------------------------------------------------------------------------
A class implementing a single interface I
class X implements I {
//definition of the methods of I
}

A class implementing two interfaces I1 & I2


class Y implements I1, I2 {
//definition of the methods of I1 & I2
}
An example of an Interface & its implementation

interface Shape {
double area( );
}

class Triangle implements Shape {


double d1, d2,d3;
Triangle( ) { }
Triangle (double d1, double d2, double d3) {
this.d1 = d1; this.d2 = d2; this.d3 = d3;
}
public double area ( ) {
return Math.sqrt(…) :
}
}
Interfaces

Any number of classes can implement an interface. You could write

class Rectangle implements Shape {


double d1, d2;
Rectangle( ) { }
Rectangle (double d1, double d2) {
this.d1 = d1; this.d2 = d2;
}
public double area ( ) {
return d1*d2;
}
}
Interfaces
A class that implements an interface may have its own methods.

e.g.
class Rectangle implements Shape {
double d1, d2;
Rectangle( ) { }
Rectangle (double d1, double d2) {
this.d1 = d1; this.d2 = d2;
}
public double area ( ) {
return d1*d2;
}
double perimeter( ) {
return d1*d2;
}
}
Interface reference can receive class object but
converse is not true
class ShapeTest {
public static void main(String[ ] args) {
Shape sh; //declare a reference of Shape. But cannot create object
Triangle ob = new Triangle(3,4,5);
Rectangle ob1 = new Rectangle (10,20);
sh = ob; //interface reference can receive object
System.out.println(sh.area( ));//calls area()@Triangle
sh = ob1;
System.out.print(sh.area( )); //calls area()@Rectangle
//but objects cannot receive interface reference
ob = sh; //compile time error
ob1 = sh; //compile time error
ob = (Triangle)sh; ob1 = (Rectangle)sh;

}
}
Interfaces

If you do not define a method of an interface then the class


implementing the interface must be declared abstract.

e.g.
abstract class Rectangle1 implements Shape {
double d1, d2;
Rectangle( ) { }
Rectangle (double d1, double d2) {
this.d1 = d1; this.d2 = d2;
}
}
An interface with data only

interface DataOnly {
int YES = 1; int NO = 0;
double DONT_KNOW = 0.5;
}
class Test {
public static void main(String[ ] args) {
System.out.println(DataOnly.YES);
}
}

class X implements DataOnly


public static void main(String[ ] args) {
System.out.println(YES);
System.out.println(DataOnly.YES); //this is also correct
}
}
Top-level & nested interface

• An interface is called a top-level interface if it is not declared inside


any other interface/class.

• Any interface declared inside any other interface/class is called a


nested interface.
Extending classes (Inheritance)

To inherit a class use the clause


extends
• A class can extend one and only one class (i.e. multiple inheritance
is not permitted),
• Any number of classes can extend a class.

A partial syntax for extending a class:


class SubClass extends SuperClass {
body of the class
}

• All inheritances are public inheritance.


• A sub class cannot access the private members of its super class.
Keyword `super`
`super` is used
• to the call the constructor of super class
• to access super class members (methods and fields).

• To call super class constructor use


super(arglist);
inside constructor of the subclass.
• This must be the first non-comment statement in the constructor
definition

• To call members of the super class use super.member


• `super` is available only to the non-static members of a class
Using `super` - An example

class BoxColor extends Box {


int c;
BoxColor( ) { }
BoxColor( double l, double w, double h, int c) {
super( l,w,h); //commenting this statement will call the
// default constructor of the super class
this.c = c;
}
double area ( ) {
//code
super.area( );
//code
}
}
Data hiding & method overriding
class X {
int m,n;
void f( ) {
//body of the method
}
void g( ) {
//body of the method
}
}//X
class Y extends X {
int m, n; //data hiding - these fields hide the m and n @X
void f( ) { //overriding f( )@X
//body of the method
}
void h( ) {
//code
super.m = 10; //accessing m of the super class
super.f( ); calling f( )@X
}
}//Y
Super class reference can receive subclass objects
but converse is not true

X x;

Y y = new Y( );

x = y; // Super class reference can receive subclass objects

y = x; //compile time error - subclass reference cannot receive super


//class object

y = (Y)x; //type casting is possible


Dynamic method dispatch

abstract class Shape {


abstract double area( );
}

class Triangle extends Shape {


double d1, d2,d3;
Triangle( ) { }
Triangle (double d1, double d2, double d3) {
this.d1 = d1; this.d2 = d2; this.d3 = d3;
}
double area ( ) {
return Math.sqrt(…) :
}
}
Dynamic method dispatch (contd.)

class Rectangle extends Shape {


double d1, d2;
Rectangle( ) { }
Rectangle (double d1, double d2) {
this.d1 = d1; this.d2 = d2;
}
double area ( ) {
return d1*d2;
}
}
Dynamic method dispatch (contd.)
class ShapeTest {
public static void main(String[ ] args) {
Shape sh; //you cannot create object of Shape
Triangle ob = new Triangle(3,4,5);
Rectangle ob1 = new Rectangle (10,20);
sh = ob; //super class reference receives sub class object
System.out.println(sh.area( )); //area()@Triangle
sh = ob1;
System.out.println(sh.area( ));//area()@Rectangle
//ob = sh; --compile time error
//ob1 = sh; --compile time error
ob1 = (Rectangle)sh;//This is okay because sh now holds Rectangle
ob = (Triangle)sh;
/*sh is now holding the type Rectangle, no compile time error here, but runtime
error(exception) occurs.
The name of this exception is ClassCastException . Rectangle sh cannot be
cast into Triangle, because they are independent classes. */
}
}
Announcement

JAVA QUIZ I
Scheduled on Jan. 22, 2010
(This FRIDAY)

PORTIONS
Up to Dynamic method dispatch
Object class

• The Object class is at the root of class hierarchy.


• Every class is an extension of the Object class and inherits the
methods of the Object class.

Constructor
public Object( )
Object class

Methods
public boolean equals (Object ob)

Assuming that x, y, z are not null the equals function is


• reflexive i.e. x.equals(x) always returns true,
• symmetric i.e. x.equals(y) and y.equals(x) always have the same
value
• transitive i.e. if x.equals(y) and y.equals(z) have the same value
then x.equals(z) has the same value as that of x.equals(y) and
y.equals(z).

To test whether two objects have the same state, override this method.
Object class
public String toString( )
Converts the current (invoking) object into its String representation.

The print and println methods call the toString( ) method to convert its
argument into string before sending it to the console.
e.g.
class X /* class X extends Object */ {
public String toString( ) {
return “Inside toString method”;
}
}
class Y {
public static void main(String[ ] args) {
X x = new X( );
System.out.println(x) //output: Inside toString method
}
}
Exercise :Do not override tooString. Create an object of Object class and pass it to println method
Exercise
Do not override toString. Create an
object of Object class and pass it to
println method
Object class

public final Class getClass( )


It returns the class the current object belongs to.
The Class class is an API class.

The following code establishes that every array name is an object.

class ArrayTest {
public static void main(String[ ] args) {
int [ ] m = new int[10];
System.out.println(m.getClass( )); //op: class [I
}
}
Exercise:Try with arrays of other type
Object class
protected Object clone( ) throws ClassNotSupportedException.
It makes an exact copy of an object.

protected void finalize( ).


This method is called just before the garbage collector is called.
Garbage collector is a piece of software that reclaims the memory occupied by
objects that are no longer in use.

public final void wait ( ) throws InterruptedException


public final void wait (long ms ) throws InterruptedException
public final void wait ( long ms, int ns) throws InterruptedException
public final void notify ( )
public final void notifyAll( )

public int hashcode( ).


Computes the hash code from current object

Object class has only declared methods and it has no inherited methods because it
is not inherited from any other class and so it is called the cosmic super class.
extends & implements

• A class that extends another class can also implement interface.

• extends clause appears before the implements clause.

e.g.
class Y extends X implements I1[,I2,I3,…] {
body of the class
}
Extending interfaces

Interfaces can be extended.

e.g. interface I extends I1 {


body of the interface
}

• Multiple inheritance is NOT possible.


• The interfaces are organized in a tree structure and there is no fixed
root in this tree. [The class hierarchy has a fixed root (Object class)]
• The interface hierarchy is different from the class hierarchy
Extending interfaces (example)
interface I1 {
int f(int n);
double g(double d);
}
interface I2 extends I1{
float h(Object ob);
}
class X implements I2 {
public int f(int n) { }
public double g(double d) { }
public float h(Object ob) { }
}
Extending interfaces

interface I1 {
int f(int n);
double g(double d);
}

interface I3 extends I1 {
// void f(int n); compile time error
int f(int n);
//void g(double d); compile time error
double g(double d);
}
Extending interfaces

interface A {
int f( );
String g ( );
}
interface C {
void f( );
void g( );
}

class X implements A,C {


//try to implement f( ) and g( )
//error because signature of f () and g() are the same but return type
//is different in both the interfaces
}
Extending interfaces

interface A {
int f( );
String g ( );
}

interface D extends A {
int f ( ); //overriding
String g ( ); //overriding
}
Extending interfaces
interface A {
int f( );
String g ( );
}
interface D extends A {
int f (); //overriding
String g (); //overriding
}
class X implements D {
public int f( ) { return 0;}
public String g() { return "" ; }
}

Will it compile??
YES
Inheriting constants

interface I1 {
double PI = 3.14;
}

interface I2 extends I1 {
double SPEED_OF_LIGHT = 3e10;
}
Inheriting and hiding constants

interface A {
int m = 1;
double x = 3.14;
}
interface B extends A {
int m = 10; //m@B. This value of m hides the value m = 1
int n = 20 + A.m; // accessing m@A
}
Number of class files

• Is equal to the number of interfaces and classes present in the


source code.

• For each class declared in the source code a class file is created.

• For each interface declared in the source code a class file is


created.
PROGRAMMING IN JAVA
QUIZ I
 ANSWER ALL QUESTIONS.
 A QUESTION MAY HAVE MULTIPLE CORRECT
ANSWERS.
 ENCIRCLE THE CORRECT ANSWER(S).
 DO NOT OVERWRITE ANYWHERE ON THE PAPER.
 TEST DURATION: 15 MINUTES
 MAXIMUM MARKS: 10
 WRITE YOU REGISTRATION NUMBER ON THE
QUESTION PAPER AS SOON AS YOU RECEIVE IT.
 DO NOT ANSWER QUESTIONS UNTIL YOU ARE
ASKED TO.
Nested classes

• A class declared inside any other class/interface is called a nested


class.

• You may have any number of levels of nesting (i.e. deep nesting is
possible) but nesting up to level two is recommended.

• A nested class can be declared static or non-static

• To declare a static nested class, use the modifier static

• A nested class can extend some other class and can itself be
extended.
Nested classes
class X { //A top level class - X is the enclosing (outer) class of Y and Z

//code

[static] class Y { // a nested class - is the enclosing (outer) class of Z

//code

[static] class Z { //a nested class

//code

}// Z

//code

}//Y

//code
}//X
Nested classes

• After compilation X.class, X$Y.class and X$Y$Z.class files are


created.

• JVM is not aware of the nesting of the classes.

• A nested class can be static or non-static.


Inner classes

• A non-static nested class is called an inner class.

• Inner classes cannot have static members. They cannot have final
fields.

• From the code of inner class it is possible to access directly (without


using object of the outer class) members of outer class, including
the private members.

• From the code of outer class direct access to the members of the
inner class is not possible, but it is possible to do so using an object
of the inner class.

• An inner class is a member of its enclosing class and so it can be


declared public, private or protected.
Inner class (an example)
class X { //an outer class
int m; double d;
X(int m, double d) {
this.m = m; this.d = d;
}
class Y { //an inner class
int mm; double dd;
Y(int mm, double dd) {
this.mm = mm; this.dd = dd;
}
void show( ) { // a method of Y
System.out.println(m); //direct access of m@X
display( );
}
}//Y
void display( ) { // a method of X
//System.out.println(mm);
//show( ); error – outer class cannot directly access members of inner class
Y y = new Y(10, 10.4);
y.show( );
}
}

After compilation the class files created are


X.class and X$Y.class
Local inner class
Definition
An inner class declared inside a block of code (e.g. inside method body, inside
initialization block, inside a loop, inside constructor) is called a local inner class.

Features
 A local inner class
 is a non-static nested class,
 is completely inaccessible outside the block it is declared,
 is not a member of the enclosing class and so it cannot be declared public,
private or protected.

 The only class modifier that can be used with a local inner class is final.

 A local inner class


 can directly access members of its enclosing class,
 can access parameters and local variables of the method/block inside
which it is declared, provided the parameters and local variables are final.
Local inner class (an example)
class X {
//code
int m = 10;
void show() {

}
int f(double d) {
int n = 6; double x = 4.5;
class Y { //a local inner class
//body of Y
void display() {
System.out.println(m); show( ); //you can directly access members of X
// System.out.println(x); -- error x is not final
}
}// local inner class Y ends here
return 0;
}//f
}//X

 If d,n, x are declared final then they can be accessed from within Y.
 After compilation, the class files that are created are
X.class &
X$1Y.class
Anonymous inner class

Definition
An Anonymous Inner class (AIC) is an inner class that does not have a
name.

Feature
Since it does not have a name so it cannot have a constructor.

Usage
 If you want to create object of a class only once during an execution
of a program then use AIC.
 The AICs are extensively used in event handling.
Anonymous inner class (an example)
class X {
X(int n, double d) {
this.n = n; this.d = d;
}
X( ) { }
}
class Y {
//X x = new X( );
X x = new X( ) { //AIC starts here
//code of AIC
}/*AIC ends here*/;
X x = new X( 10, 9.8) { //AIC starts here
//code of AIC
}/*AIC ends here*/;
//other code of Y
}//Y
The class files created after compilation of this code are
X.class, Y.class,
Y$1.class & Y$2.class.
Anonymous inner class

 The AIC, mentioned in the above example, is a subclass of X, i.e. is


related to X by inheritance.

 X is a super class of the AIC

 An AIC can access arguments of the super class constructor if they


are final.

 The numbers of lines of code within an AIC should not be too many
(i.e. at the most six statements are recommended). If there are too
many statements, readability becomes a problem.
Anonymous Inner class (another example)

class A {
Object ob = new Object( ) { //AIC starts
//body of AIC
}/* AIC ends here */ ;
//other code
}

In this example, the AIC is an extension of the Object class.


Anonymous inner class
You may also use an interface to declare an AIC.
e.g.
interface I {

}
class Y {
I i = new I( ) { //AIC starts here
//code of AIC
}/*AIC ends here*/;
}//Y
The class files created after compilation are
I.class, Y.class &
Y$1.class.

The AIC declared here implements the interface I.


Syntax for declaration of AIC

SuperType identifier = new SuperType( ) {


//code of AIC
};

 The super type may be either a class or an interface.


 If the super type is a class then the AIC extends the class.
 If the super type is an interface then the AIC implements the
interface.
Class Modifiers of inner class

Modifiers of inner class


public/private/protected, final/abstract & strictfp

Modifier of local inner class


final

Modifiers of AIC
None
Modifier strictfp

Though Java is platform independent,


but the floating point arithmetic may produce different results on
different platform.

strictfp guarantees common behavior across platforms in the results


of floating point arithmetic i.e.
the floating-point arithmetic behaves the same when the application
program is moved to a different platform.
Modifiers of top-level class

 The only modifiers that can be used for a top level class are public,
final/abstract and strictfp.

 The class modifiers can be used in any order but the above order is
recommended.
Modifiers of top-level interface

 The modifiers that can be used for a top-level interface


are public, abstract & strictfp.

 They can be used in any order but the mentioned order


is recommended.
String class
public final class String
extends Object implements Serializable, Comparable, CharSequence

• The String class represents character strings. All string literals in


Java programs, such as “Java Language", are instances of this
class.
• Strings are immutable (constant).

Constructors
• public String ( ) -- creates an empty string.

• public String(String str) -- makes an exact copy of str.

• public String(char[ ] value) -- constructs a new String from a


character array
e.g. char [ ] value = {‘J’, ‘a’, ‘v’, ‘a’};
String str = new String(value);
String class

Constructors
• public String(char[ ] value, int offset, int count)
Constructs a new String that contains characters, picking up count number
of characters from the position offset of the array value.

• public String(byte[ ] bytes)


Constructs a new String by decoding the specified array of bytes using the
platform's default charset. The length of the new String is a function of the
charset, and hence may not be equal to the length of the byte array.

• public String(byte[ ] bytes, int offset, int length, String charsetName)


throws UnsupportedEncodingException
Constructs a new String by decoding the specified subarray of bytes using
the specified charset. The length of the new String is a function of the
charset, and hence may not be equal to the length of the subarray.
Character sets

A character set (charset) is a character encoding scheme,


i.e. how the characters are mapped into integers and visa-versa.

Some of the character sets (character encoding schemes) are


ASCII, UTF-7, UTF-8, UTF-16, UTF-32
UTF (Unicode Transformation Format)

e.g.
byte [ ] bytes = {67, 68, 69, 70};
String str = new String(bytes, 0, 4, "ASCII");
System.out.println(str + " " + str.length( )); //output: ABCD 4
String class

• public String(byte[ ] bytes, int offset, int length)


Constructs a new String by decoding the byte array from the
position
offset, picking up exactly length number of bytes. The decoding
scheme uses platform's default charset. The length of the new
String is a function of the charset, and hence may not be equal to
the length of the subarray.

• public String(StringBuffer buffer)
Constructs a new string that contains the sequence of characters
currently contained in the string buffer argument.
String class
Methods
• public int length()
Returns the length of this string. The length is equal to the number of
16-bit Unicode characters in the string.

• public char charAt(int index)


Returns the character at the specified index. An index ranges from 0 to
length() - 1.

• public void getChars(int srcBegin, int srcEnd, char[ ] dst, int dstBegin)


Copies characters from this string into the character array dst. The first
character to be copied is at the index srcBegin; the last character to be
copied is at the index srcEnd-1 (thus the total number of characters to be
copied is srcEnd - srcBegin).
String class

• public byte[ ] getBytes( )


Encodes this String into a sequence of bytes using the platform's
default charset, storing the result into a new byte array.

• public byte[ ] getBytes(String charsetName) throws


UnsupportedEncodingException

Encodes this String into a sequence of bytes using the named


charset, storing the result into a new byte array.

• public boolean equals(Object ob)


Compares this string to the specified object.
String class

• public boolean contentEquals(StringBuffer sb)


Returns true if and only if this String represents the same sequence
of characters as the specified StringBuffer.

• public boolean equalsIgnoreCase(String anotherString)


Compares this String to another String, ignoring case
considerations.
String class

• public int indexOf(char ch)


returns the position of the first occurrence of the character ch in this
string object. If there is no such character then -1 is returned.
e.g. String str = “java language”;
str.indexOf(‘a’) returns 1.

• public int lastIndexOf(int ch)


Returns the position of the last occurrence of the character ch in this
string.
String class

• public int indexOf(char ch, int fromIndex)


returns for position of the first occurrence of the character ch
starting from the position fromIndex.

• public int lastIndexOf(int ch, int fromIndex)


returns for position of the last occurrence of the character ch starting
from the position fromIndex.
String class

• public int indexOf(String str)


returns the position of the first occurrence of the substring str in the
current string.
e.g. String str1 = “java language and java virtual machine”;
str1.indexOf(“java”) returns 0;

• public int lastIndexOf(String str)


returns the position of the last occurrence of the substring str in the
current string.
String class

• public int indexOf(String str, int fromIndex)


returns the position of the first occurrence of the substring str in the
current string starting from the position fromIndex.
e.g. str1.indexOf(“java”, 1) returns 18.

• public int lastIndexOf(String str, int fromIndex)


returns the position of the last occurrence of the substring str in the
current string starting from the position fromIndex.
String class

• public int compareTo(String anotherString)


e.g. “Programming”.compareTo(“Java”); o/p +ve int
“Java”.compareTo(“Programming”); o/p –ve int
Compares two strings lexicographically. The comparison is based
on the Unicode value of each character in the strings.
If this string object precedes the argument string then –ve value is
returned,
if this string object follows the argument string then +ve value is
returned,
if they are equal then 0 is returned.

• public int compareToIgnoreCase(String str)


Similar to compareTo method except that case is ignored.
String class

• public String substring(int beginIndex)


e.g. "unhappy".substring(2) returns "happy“
Returns a new string that is a substring of this string. The substring
begins with the character at the specified index and extends to the
end of this string.

• public String substring(int beginIndex, int endIndex)


e.g. "unhappy".substring(2, 7) returns "happy“
Returns a new string that is a substring of this string. The substring
begins at the specified beginIndex and extends to the character at
index endIndex - 1. Thus the length of the substring is
endIndex-beginIndex.
String class

• public String concat(String str)


Concatenates the specified string to the end of this string.
e.g. “Java”.concat(“ language”); returns Java language.

• public String replace(char oldChar, char newChar)


e.g. “Java”.replace(‘a’,’e’);
Returns a new string resulting from replacing all occurrences of
oldChar in this string with newChar. If the oldChar is not found then
this string is returned.

• public String replaceFirst(String str, String replacement)


Replaces the first substring of this string that matches the given
string str by the given replacement.
String class

• public String replaceAll(String str, String replacement)


Replaces each substring of this string that matches the given str
with the given replacement.

• public String toLowerCase()


Converts all of the characters in this String to lower case using the
platform`s default locale.
The default locale of windows is English(US)

• public String toUpperCase()


Locale

In computing, locale is defined by the user`s language, country and any


special variant (e.g. the name of the OS).

You will find Locale class in Java.


The constructors of this class are
Locale (String language)
Locale (String language, String country).
Locale (String language, String country, String variant).
e.g. Locale(“english”);
Locale(“english”, “Singapore”);
Locale(“english”, “Singapore”, “MAC”);
String class

• public String toLowerCase(Locale locale)


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

• public String toUpperCase(Locale locale)


String class

• public String trim()


Returns a copy of the string, with leading and trailing whitespace
omitted.

• public String toString( )


Returns this object
String class
• public char[ ] toCharArray( )
Converts this string to a new character array.

• public boolean regionMatches(int toffset, String other, int ooffset,


int len)
Tests if two string regions are equal.
toffset - the starting offset of the subregion in this string.
other - the string argument.
ooffset - the starting offset of the subregion in the string argument.
len - the number of characters to compare.
e.g. "java language".regionMatches(0, "java", 0, 4) returns true.

• public boolean regionMatches(boolean ignoreCase, int toffset,


String other, int ooffset, int len)
String class

 public String[ ] split(String str)


Splits this string around matches of the given string str.
e.g. String [ ] strs = “Programming in Java”.split(“ “);
for(int i=0; i<strs.length;i++) System.out.println(strs[i]);

 public int hashCode( )


Returns a hash code for this string. The hash code for a String
object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
using int arithmetic, where s[i] is the ith character of the string, n is
the length of the string, and ^ indicates exponentiation.
String class

• public boolean startsWith(String prefix)


Tests if this string starts with the specified prefix.
e.g. “Java language”.startsWith(“Java”); o/p: true

• public boolean endsWith(String suffix)


Tests if this string ends with the specified suffix.

• public boolean startsWith(String prefix, int toffset)


Tests if this string starts with the specified prefix beginning a
specified index.
String class

• public static String valueOf(Object obj)


Returns the string representation of the Object argument.

• public static String valueOf(char[ ] data)

• public static String valueOf(char[ ] data, int offset, int count)

• public static String valueOf(boolean b)


String class

• public static String valueOf(char c)


Returns the string representation of the char argument.
e.g. String.valueOf(‘a’);

• public static String valueOf(int i)

• public static String valueOf(long l)

• public static String valueOf(float f)

• public static String valueOf(double d)


Exercise

Write a program to demonstrate the


functionality of the constructors and the
methods of the String class.
Portions for CAT I

Up to String class
StringBuffer class

public final class StringBuffer


extends Object
implements Serializable, CharSequence

 The objects of StringBuffer class are mutable.


 Capacity of a SB object is defined by the maximum number of
characters that it can accommodate.
 Length of a SB object is defined as the number of characters in the
buffer.

Constructors
 public StringBuffer( )
Constructs a string buffer with no characters in it and an initial
capacity of 16 characters.
StringBuffer class

 public StringBuffer(int capacity)
Constructs a string buffer with no characters in it and an initial
capacity specified by the capacity argument.
If the capacity argument is less than 0,
NegativeArraySizeException is thrown.

 public StringBuffer(String str)
Constructs a string buffer so that it represents the same sequence
of characters as the string argument. The initial capacity of the
string buffer is
length of the string argument + 16.
If you pass null as argument, NullPointerException is thrown
StringBuffer class
Methods

• public int length( )


Returns the length (character count) of this string buffer.

• public int capacity( )


Returns the current capacity of the String buffer.

• public void ensureCapacity(int minimumCapacity)


Explicitly allocating rooms.
Ensures that the capacity of the buffer is at least equal to the
specified minimum.
If the current capacity of this string buffer is less than the argument,
then a new internal buffer is allocated with greater capacity.
New capacity = max(minimumCapacity, 2*oldCapacity + 2).
If the current capacity > minimumCapacity, method returns.
StringBuffer class

StringBuffer sb = new StringBuffer( );//capacity = 16

sb.ensureCapacity(20);
System.out.print(sb.capacity( )); //output capacity = max(20, 2*16 + 2);
StringBuffer class

• public void setLength(int newLength)


Sets the length of this String buffer. If the newLength is less than the
current length then excess characters are truncated, otherwise new
rooms are filled with null.
If the newLength is negative then IndexOutOfBoundsException is
thrown.

• public char charAt(int index)


Returns the character at the location index of this StringBuffer
object.
If the index is negative then IndexOutOfBoundsException is thrown.
StringBuffer class

• public void getChars(int srcBegin, int srcEnd, char[ ] dst,


int dstBegin)
Similar to the getChars method of String class.

• public void setCharAt(int index, char ch)


Replaces the character at the location index by the character ch.

• public StringBuffer append(Object obj)


Appends the string representation of the Object argument to this
string buffer.
StringBuffer class

• public StringBuffer append(String str)


Appends the string to this string buffer.

• public StringBuffer append(StringBuffer sb)


Appends the specified StringBuffer to this StringBuffer.

• public StringBuffer append(char[ ] chrs)


Appends the string representation of the char array argument to this
string buffer.

• public StringBuffer append(char[ ] chrs, int offset, int len)


Appends the string representation of a subarray of the char array
argument to this string buffer. The subarray starts at offset and
has len characters
StringBuffer class

• public StringBuffer append(boolean b)


Appends the string representation of the boolean argument to the
string buffer.

• public StringBuffer append(char c)


• public StringBuffer append(int i)
• public StringBuffer append(long l)
• public StringBuffer append(float f)
• public StringBuffer append(double d)
StringBuffer class

• public StringBuffer delete(int start, int end)


Removes the characters in a substring of this StringBuffer. The substring
begins at the specified start and extends to the character at index end – 1.

• public StringBuffer deleteCharAt(int index)


Removes the character at the specified position in this StringBuffer.

• public StringBuffer replace(int start, int end, String str)


Replaces the characters in a substring of this StringBuffer with
characters in the specified String. The substring begins at the
specified start and extends to the character at index end – 1.
StringBuffer class

• public String substring(int start)


Similar to the substring method of String class.

• public String substring(int start, int end)


Similar to the substring method of String class.
StringBuffer class

• public StringBuffer insert(int where, char[ ] chrs, int offset, int len)


Inserts the string representation of a subarray of the chrs array
argument into this string buffer. The subarray begins at the specified
offset and extends len characters.

• public StringBuffer insert(int where, Object obj)


Inserts the string representation of the Object argument into this
string buffer.

• public StringBuffer insert(int where, String str)


Inserts the string into this string buffer.
StringBuffer class

• public StringBuffer insert(int where, char[ ] chrs)


Inserts the string representation of the char array argument into this
string buffer.

• public StringBuffer insert(int where, boolean b)


• public StringBuffer insert(int where, char c)
• public StringBuffer insert(int where, int i)
• public StringBuffer insert(int where, long l)
• public StringBuffer insert(int where, float f)
• public StringBuffer insert(int where, double d)
StringBuffer class

• public int indexOf(String str)


• public int indexOf(String str, int fromIndex)
• public int lastIndexOf(String str)
• public int lastIndexOf(String str, int fromIndex)

Similar to the String class methods.


StringBuffer class

• public StringBuffer reverse( )


The character sequence contained in this string buffer is replaced
by the reverse of the sequence.

• public String toString( )


Converts to a string representing the data in this string buffer.
Exercise
Develop a program to demonstrate the functionality of the constructors
and the methods of the StringBuffer class.

Memory management is more involved in StringBuffer objects than in


String objects and so run time overhead for managing StringBuffer
objects is higher than String objects.
package

 A source file is called a compilation unit or translation unit.

 A compilation unit may have at the most one top-level public class
or interface. You may have other classes and interfaces in the
same compilation unit, but they cannot be declared public. These
other classes and interfaces present in the compilation unit act as
helper classes and interfaces.

 There is no restriction on the number of classes and interfaces that


a compilation unit may have.
package

 Definition of package
A package is a software unit that can be distributed independently
and be combined with other packages to form application.

 Members
Classes, interfaces, other packages and resource files (e.g. image,
audio, video).
package

 There is no restriction on the number of members that a package


may have. A package is a container that can expand automatically
to accommodate as many members as it is required.

 Every compilation unit (Java source file) belongs to a package. This


package may have a name, it may not have name.

 A package without a name is called a default package. To develop a


named package, use package statement inside the source file.

 A package statement consists of the keyword package followed


by a package name terminated by a semi colon. A package
name is an identifier.
e.g.
package pkg1;
package pkg1.pkg2;
package

 The significance of the package statement is that the classes and


interfaces declared inside the source file are members of the
package.

 The package statement is optional. But, if present, then it must be


the first non-comment statement of the source file.

 In absence of package statement, the compilation unit belongs to an


unnamed package, called default package.
package

 You may have at the most one package statement in a compilation


unit.

 Any number of compilation units may belong to a single package.

 The classes and interfaces declared inside a package can talk to


each other, even if they are declared inside a different compilation
unit.

 The classes and interfaces declared inside a package can talk to


only public classes and interfaces declared in other packages
each other.
Developing package (example)

package pkg1;
public class Example {

}
//other classes and interfaces

 Suppose the name of this Java source file (compilation unit) is


Example.java
 This source code needs to be stored inside a subdirectory \pkg1
under some directory.
 Note that the name of the sub directory is the same as the name of
the package.
 The sub directory \pkg1 can be under any directory.
e.g. e:\java\08mca\pkg1
Developing package

 The directory under which the sub directory \pkg1 is created is


called a base directory/development directory.

 A base directory can be any directory.


e.g. e:\java\08mca
is a base directory.

 So Example.java is stored inside e:\java\08mca\pkg1\

 To compile Example.java go to the sub directory


e:\java\08mca\pkg1 & type javac Example.java
Developing package

 You may also compile this file from some other directory specifying
the full path e:\java\08mca\pkg1\Example.java

 To execute the class file you need to go to the base directory


(i.e. e:\java\08mca) and type java pkg1.Example

 If you want to develop a package with name pkg1.pkg2 then you


need to create a subdirectory \pkg1\pkg2 under some base directory
& store the source file the subdirectory …\pkg1\pkg2
Including more classes and interfaces into a package
 Any number of compilation units may belong to a package.

 At present the only source file which is inside the package pkg1 is
Example.java.

 How to add more classes and interfaces to the package pkg1?

 Create another Java source file say, Example1.java with the package
statement package pkg1; as the first non-comment statement of the
file and store it inside the sub directory …\pkg1
and compile.

 In this way you may add more classes and interfaces to the package
pkg1.
Base directory & class path

 Definition of base directory


A base directory is any directory whose sub directory may contain
Java class files.

 Any directory can be a base directory.

 You may have any number of base directories in your file system.

 The collection of all base directories is called class path.

 In order that members of different packages can talk to each other,


you must tell the run time environment where the class files are
stored.
Base directory & class path

 Telling the run time environment where the class files are stored, is
referred to as setting the classpath.
 How to set classpath?
 Setting the classpath depends on the environment you are working
in.
 On UNIX/Linux,
 if you use C shell, add the following line to the .cshrc file:
setenv CLASSPATH name of base dirs separated by ;
 If you use BASH shell, add the following line to the .bashrc file or
in the bash-profile file:
export CLASSPATH = name of base dirs separated by ;
Base directory & class path

 On windows environment except win 95/98


 Control Panel → System → Advanced → Environment variables
→ New.
 A frame appears.
 Type classpath inside the text box labeled variable name.
 Type the name of the base directories separated by semi-colons
inside the text box labeled variable value.

 On windows 95/98, add the following line in the autoexec.bat file


set classpath = name of the base directories separated by ;
package

 By convention, package names are written in lower case. A sub


package name is separated from a package name by . (dot).
e.g. if the name of a package is pkg1.pkg2 then
pkg2 is a sub package of pkg1

 Every . in a package name is mapped to a \ in windows and to a / in


UNIX/Linux.
e.g. the name pkg1.pkg2 is mapped to
baseDirectory\pkg1\pkg2
package
 The packages are organized in the form of hierarchy.

 The Java standard library is distributed among a large number of


packages and the roots of these packages are
java and javax

 Some of the standard library packages are


java.lang, java.util, java.awt, java.awt.event, java.math,
javax.swing, javax.servlet.http

 java.awt is a sub package of the package java.


java.awt.event is a sub package of the package java.awt.
package

 Some of the library classes declared inside the


java.lang package are String, Math, System.

 The interface Serializable is declared inside the package java.lang

 Some of the library classes declared inside the java.util package are
Date, Calendar, GregorianCalendar

 The fully qualified name of the String class is java.lang.String.

 The fully qualified name of a class is defined by


packagename.ClassName

 Package name is case sensitive.


Why package?

 To guarantee uniqueness of class and interface name.

 The class pkg1.Example is different from the class


pkg1.pkg2.Example and pkg2.Example.

 To absolutely guarantee the uniqueness of class and interface


name, Sun Microsystems recommends that you use the internet
domain name of your organization written in reverse as the root of
the packages and then use sub packages for different projects.
e.g. in.ac.vit may be the root of the all packages being developed at
VIT
import statement

An import statement appears inside a source file.

An import statement may have one of the following forms:


import packagename.*; (called import on demand)
import packagename.ClassName; (single type import)
import packagename1[.packagename2…].*; (called import on demand)
e.g. import java.awt.*; ---import on demand
import java.util.Date; --- single type import
The import statement
import packagename.*;
implies that
the members of the package named `packagename` are available to
this source file.
import statement

The import statement


import packagename.ClassName;
implies that the class ClassName is available to this source file.

The import statement


import packagename1.packagename2.*;
implies that the members of the package named
packagename1.packagename2 are available to this source file.

 The import statement is about availability only,


 not about actual inclusion of the classes & interfaces (of the
package) into the compiled code
 Only those members of the package that are actually used in the
source file are included into the compile code.
import statement

e.g. if a package pkg1 has a number of public classes and interfaces

say, X, Y, Z, I1, I2 and if you use the import statement import pkg1.*;

and use only the class X inside the source file then the class file of the

class X only is included into the compiled code.


import statement

 The import statement is optional.

 If import statement is present then (in absence of package


statement) it must the first non-comment statement of the source
code.
e.g.
package pkg1;
import pkg2.*;

 A compilation unit may have any number of import statements.


import statement

 One import statement can make available the members of one


package only.
 A single import statement cannot make members of multiple
packages available.

e.g. you can write


import java.util.*;

But you cannot write


import java.*.*;

Because this statement makes an attempt to import all the sub


packages of the package java

i.e. you may use wild card (*) for members of a package, but not for the
package name.
import statement
 You can import types (classes and interfaces) but you cannot import
objects.

 Two different packages may contain the same class/interface.


e.g. you find the Date class inside the package java.util and java.sql;

 You may use the import statements


import java.util.*; import java.sql.*;
inside the same source file.

 But you cannot access the Date class without qualifying it by its
package name
i.e. you can write either java.util.Date or java.sql.Date
import statement

Alternatively, you may use one of the following code segments.

import java.util.*;
import java.sql.Date;
OR
import java.util.Date;
import java.sql.*;
import statement

 An import statement of the form


import pkg1.*;
is called import on demand
 An import statement of the form
import pkg1.ClassName;
is called single type import

 Using import on demand is easier than single type import. This is


why it is preferable to use import on demand to single type import.

 Using import on demand has no effect on the size of the compiled


code.
A note

The System class is declared in the package java.lang

Though you use the System class in the code


System.out.println

but you need not import java.lang because

java.lang is automatically imported into every Java source file.


Difference between #include and import

 import is about availability of the members of a package. Only those


classes and interface that are actually referred to in the source code
are included into the compiled code.

 #include incorporates the entire content of the header file into the
compiled code.

 This is the reason why the size of a Java compiled code is smaller
than that of C++ code.

 It is possible to completely dispense with import statements (using


fully qualified name of the classes and interfaces), but it is not
possible to completely dispense with #include.
Access protection

 Access to a class/interface member is protected by access modifier.

 There are four different levels of access namely,


private (modifier used is private) – least access
package (no modifier is used. This is the default access),
protected (modifier used is protected)
public (modifier used is public) – most access
Access protection

 If a class member is declared as public then it is visible everywhere


(most access).

 If it is declared protected then it is visible in the package it is


declared and also in the sub class declared in other packages.

 If it is declared without any access modifier then it is visible


throughout the package.

 If it is declared private then it is visible only inside the class (least


access).
Access protection (Example)
package pkg1;
public class X { // class X is visible everywhere
private int m; //visible only inside this class
protected double d; //visible inside this package & in a sub class in
//other package
void f( ) {//visible anywhere inside the package pkg1.
//no access modifier used
//member is said have package scope
}
protected double g( ) { //visible inside this package & in a sub class in
//other package

}
public double h( ) { //visible everywhere

}
}//X
Access protection (Example)

package pkg2;
import pkg1.*;
public class Y {
//can access public members of X
//cannot access protected members of X, members without modifier
// & the private members
}
class Z extends X {
//can access public and protected members of X
//cannot access members without modifier & private members of X
}
Class modifier access
private No modifier protected public

Same class Yes Yes Yes Yes

Same package sub class No Yes Yes Yes

Same package non-sub class No Yes Yes Yes

Different package sub class No No Yes Yes

Different package non- sub class No No No Yes


Access protection

 In order that the public and protected members of a class may be


accessed in other packages, the class must be declared public.

 The members of a C++ class are by default private.

 The members of a Java class are by default not private. The default
scope is package.
i.e. by default (in absence of any access modifier), the members of
a Java class are visible everywhere inside the package the class is
declared.
Exception handling

 Exceptions are run-time errors.

 Every exception is an object of built-in exception class or user-


defined exception class.

 Every user-defined exception class must be a sub class of a built-in


exception class.

 The built-in exception classes are organized in hierarchy.

 The class Throwable is at the root of the exception class hierarchy.


Built-in Exception class hierarchy

Object

Throwable

Error Exception

IOException RuntimeExeption
Exception class hierarchy

Error

LinkageError VirtualMachineError ThreadDeath

NoClassDefFoundError -- OutOfMemoryError
--StackOverflowError
--UnknownError
--InternalError
Exception class hierarchy

RuntimeException

---- ArithmethicException ( divide by zero)


---- ArrayStoreException (storing object of wrong type)
---- EmptyStackException (a pop was attempted on an empty stack)
---- IndexOutOfBoundsException

---- StringIndexOutOfBoundsException
---- ArrayIndexOutOfBoundsException
---- IllegalArgumentException

---- IllegalThreadStateException
---- NumberFormatException
---- ConcurrentThreadException
Exception class hierarchy

IOException

---- InterruptedException
---- FileNotFoundException
---- EOFException
Exception handling
Exception handling is performed using the keywords try, catch, finally, throw
and throws.
Format of try-catch-finally:

try {
//code to be monitored for exception
}catch(ExceptionType1 ob) {
// code to be executed when exception occurs (known as exception handler)
}catch(ExceptionType2 ob) {
// code to be executed when exception occurs (known as exception handler)
}
.
.
.
finally{
//code that must be executed before try block ends
}
Exception handling
 If there is no catch block then there has to be a finally block

 You may have any number of catch blocks (even zero)

 In presence of catch block, finally is optional.

 If finally block is present then it will be executed even if no exception


is thrown.

 If you need to release some resources (e.g. disconnecting from the


database, closing files, releasing locks) even in the face of runtime
errors then use finally block & write this code inside finally block.

 The exception types in different catch blocks associated with a try


block must be different.
Exception handling

public class ExceptionTest {


public static void main(String[ ] args) {
int a=10, b=0, c;
System.out.println(“hello there”); //will be printed
c = a/b;
System.out.println(“hello”); //will not be printed
}
}

It will compile
On execution you will find the following output:
hello there
Exception in thread “main” java.lang.ArithmeticException: / by zero
at ExceptionTest.main (ExceptionTest.java:5)
The string in italic is called stack trace
Exception handling
If exception is handled then it is possible to recover from error and resume
execution.

public class ExceptionTest {


public static void main(String[ ] args) {
int a=10, b=0, c;
System.out.println(“hello there”);
try {
c = a/b; //code to be monitored for exception
}catch(ArithmeticException e) {
System.out.println(e); //exception handler
}
System.out.println("hello");
}
}
Output:
hello there
java.lang.ArithmeticException: / by zero
hello
Exception handling

public class ExceptionTest {


public static void main(String[ ] args) {
int a=10, b=0, c;
System.out.println("hello there");
try {
c = a/b;
}catch(ArithmeticException e) {
e.printStackTrace( ); //printStackTrace is a method of Throwable
}
System.out.println("hello");
}
}

Output:
hello there
Exception in thread “main” java.lang.ArithmeticException: / by zero
at ExceptionTest.main (ExceptionTest.java:5)
hello
Exception handling

It is possible to recover from exception and resume execution–another example

public class HandleError {


public static void main(String[ ] args) {
int a=0, b=0, c=0;
java.util.Random r = new java.util.Random( );
for (int i = 0; i< 100; i++) {
b = r.nextInt( );
c = r.nextInt( );
try {
a = 10/(b/c);
}catch(ArithmeticException e) {
a = 0;
}
System.out.println(“a = “+ a);
}//for
}//main
}//HandleError
Exception handling

Multiple catch blocks and finally block

public class MultiCatch {


public static void main(String[ ] args) {
int a= -10, b=0;
a = args.length;
try {
b = 10/a;
int [ ] c = {15};
c[5] = 43;
}catch(ArithmeticException e) {
e.printStackTrace( );
}catch(ArrayIndexOutOfBoundsException e) {
e.printStackTrace( );
}finally {
System.out.println(“this will always be printed”);
}
}//main
}//MultiCatch
Exception handling
public class CatchFinally {
public static void main(String[ ] args) {
int a= -10, b=0;
a = args.length;
try {
b = 10/a;
int [ ] c = {15};
c[5] = 43;
}catch(Exception e) {
e.printStackTrace( );
}finally {
System.out.println(“this will always be printed”);
}
}//main
}// CatchFinally

The Exception block can handle ArithmeticException &


ArrayIndexOutOfBoundsException, because both are sub class of the class
Exception. (Super class reference can receive sub class objects)
Exception handling

public class MultiCatch1 {


public static void main(String[ ] args) {
int a= -10, b=0;
a = args.length;
try {
b = 10/a;
int [ ] c = {15};
c[5] = 43;
}catch(Exception e) {
e.printStackTrace( );
}catch(ArithmeticException e) {
e.printStackTrace( );
}finally {
System.out.println(“this will always be printed”);
}
}//main
}//MultiCatch1
Will it compile?
Exception handling

The above code will not compile.

Reason
Super class reference can receive sub class object. The
ArithmeticException and ArrayIndexOutOfBoundsException being a
subclass of Exception, all exception objects will be caught at the catch
block that handles Exception object and control never reaches the
ArithmeticException block leading to unreachable code which is a
compile time error.

In order that the code compiles, you need to catch ArithmeticException


object before catching Exception object.
See the next slide.
Exception handling

public class MultiCatch2 {


public static void main(String[ ] args) {
int a=0, b=0;
a = args.length;
try {
b = 10/a;
int [ ] c = {15};
c[5] = 43;
}catch(ArithmeticException e) {
e.printStackTrace( );
}catch(Exception e) {
e.printStackTrace( );
}finally {
System.out.println(“this will always be printed”);
}
}//main
}//MultiCatch2
Exception handling
Nested try
Try blocks can be nested i.e. you may have one try block inside another try
block.
try { //outer try block
//code
try { //inner try block

}catch(ExceptionType1 ob) {
//exception handler
} catch(ExceptionType2 ob) {
//exception handler
}//inner try ends
} catch(ExceptionType3 ob) {
//exception handler
} catch(ExceptionType4 ob) {
//exception handler
}//outer try ends

Any number of levels of nesting is possible, but is nesting up to level two is


recommended.
Exception handling

The nested try block may be implicit also.


class X {
static void f( ) {
//code
try {
//code
}catch(Exception e) {
//exception handler
}
}
public static void main( String [ ] args ) {
try {
f( );//implicit nested try
}catch(Exception e) {
//code
}
}//main
}//X
Exception handling

Throw statement
The throw statement has the following form:
throw expression;

 The expression must return an object of Throwable or any of its sub


class.
 It may also be an object of a user-defined exception class.
 It cannot be of primitive type.
 It cannot be an object of arbitrary class.

The throw statement facilitates throwing an exception forcibly.


e.g. if(condition) throw new NullPointerException( );
if(condition) throw new ArithmeticException(“Division by zero” );
Exception handling

public class ThrowTest {


public static void main(String[ ] args) {
int a=0, b=0;
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
try {
if (b == 0) throw new ArithmeticException("Do not perform division");
else System.out.println((double)a/b);
}catch(ArithmeticException e) {
e.printStackTrace( );
}
}//main
}//ThrowTest
Exception handling
Rethrowing an exception
class X {
static void f ( ) {
//code
try {
//code
if(condition) throw new NullPointerException( );
else
//do something else
}catch(NullPointerException e) {
e.printStackTrace( );
throw e; //rethrowing an exception
}
}//f
public static void main(String[ ] args) {
try {
f ( );
}catch(NullPointerException e ) {
//exception handler
}
}//main
}//X
Exception handling
NullPointerException Thrown when an application
attempts to use null in a case where an object is required.
These include:

 Calling the instance method of a null object.


 Accessing or modifying the field of a null object.

Constructor
NullPointerException()
          Constructs a NullPointerException with no detail message.
NullPointerException(String s)
          Constructs a NullPointerException with the specified detail
message.
Announcement
Quiz II
March 8, 2010 (Monday)

Portions
Nested classes, String class, StringBuffer
class, interfaces, packages, exception
handling.
Exception handling

throws clause

 The throws clause has the following form


throws exception_list
The exception_list is a list of exceptions separated by comma.

 Used with a method declaration.


[modifier] rtype methodname(arg-list) throws exception_list

 The throws clause is an announcement.


Exception handling
class ThrowsTest {
static void f( ) {
//code
throw new Exception( );
}//f
public static void main(String[ ] args) {
try {
f( );
}catch(Exception e) {
e.printStackTrace( );
}
System.out.println("hello");
}//main
} //ThrowsTest
Exception handling

class ThrowsTest1 {
static void f( ) {
//code
throw new RuntimeException( );
}//f
public static void main(String[ ] args) {
try {
f( );
}catch(RuntimeException e) {
e.printStackTrace( );
}
System.out.println("hello");
}//main
} //ThrowsTest1
Exception handling
class ThrowsTest {
static void f( ) {
//code
try {
throw new Exception( );
}catch(Exception e) {
e.printStackTrace( );
}
}
public static void main(String[ ] args) {
try {
f( );
}catch(Exception e) {
e.printStackTrace( );
}
System.out.println("hello");
}
}
Exception handling

class ThrowsTest {
static void f( ) throws Exception {
//code
throw new Exception( );
}
public static void main(String[ ] args) {
try {
f( );
}catch(Exception e) {
e.printStackTrace( );
}
System.out.println("hello");
}
}
Exception handling

 An exception is called checked exception if the compiler checks to


find out whether the exception thrown by the method but not
handled is declared.

 An exception is called unchecked exception if the compiler does


not check to find out whether the exception thrown by the method
but not handled is declared.

 The exception classes Error and RuntimeException and any of their


sub classes are unchecked exceptions.

 All other exception classes are checked exception classes


Exception handling

When to use throws clause?


If not used in the following case, a compile time error occurs.
If a method throws checked exception and the exception is not
processed within the body of the method then this exception must be
declared in the exception list of the throws clause.

e.g. [modifier] rtype f(arglist) throws E1, E2 {


//exceptions E1 and E2 are checked exceptions thrown but not
//processed inside the body of the method
}
Exception handling

The following code will not compile.


class X {
static void f( ) {
//code
throw new IllegalAccessException( );
}
public static void main(String[ ] args) {
try {
f( );
}catch(IllegalAccessException e) {
e.printStackTrace( );
}
}
}
Exception handling

In order to compile the last code successfully make the following


change:

class X {
static void f( ) throws IllegalAccessException {
//code
throw new IllegalAccessException( );
}
public static void main(String[ ] args) {
try {
f( );
}catch(IllegalAccessException e) {
e.printStackTrace( );
}
}
}
Exception handling

Chained exception

If one exception is the cause of the other then they are said to form a
chain of exceptions.

If an exception E1 is the cause of another exception E2 which in turn is


the cause of another exception E3 then E1, E2 and E3 are said to form
a chain of exceptions.

A chain of exceptions may have at least two exceptions involved in it.


Exception handling

Throwable class

Constructors
public Throwable( )
public Throwable(String msg)
public Throwable(Throwable cause)
public Throwable(String msg, Throwable cause)
Exception handling

Some Methods

public Throwable getCause( )


returns the underlying exception object (i.e. the cause of the
exception).
If there is no cause then null is returned.

public Throwable initCause(Throwable cause)


Associates cause with the current object.

public void printStackTrace( )


displays the stack trace.
Exception handling

Demonstration of chained exception

public class ChainedException {


public static void main(String[ ] args) {
NullPointerException e = new NullPointerException(“You are using
null reference”);
e.initCause(new ArithmeticException(“this is the cause”);
try {
throw e;
}catch(NullPointerException e1) {
e1.printStackTrace( );
e1.getCause( ).printStackTrace( );
}
}//main
}//ChainedException
Exception handling

Creating user-defined exception

 Every user-defined exception must be a sub class of built-in


exception class
e.g. class MyException extends Throwable {
//body of the class
}

 By convention, Exception class is extended to develop user-defined


exception class
e.g. class MyException extends Exception {
//body of the class
}

 Since Exception class is a checked exception, hence all user-


defined exceptions are checked exceptions.
Exception handling

Example code

class TemperatureException extends Exception {


int temperature;
TemperatureException(int t) {
temperature = t;
}
int getTemperature( ) {
return temperature;
}
}
class TooColdException extends TemperatureException {
//code
}
Exception handling

Synchronous & asynchronous exception

 When the instructions of the developer’s program execute, the


instruction of the JVM also execute concurrently.

 An exception is called synchronous exception if it is thrown while


executing instruction of the developers program.

 An exception is called asynchronous exception if it is thrown while


executing instruction of the JVM.
Multithreaded programming

A thread is a sub program that can execute independently sharing the


same address space as the program.

Inter-thread communication is cheaper than inter-process


communication.

Processing critical section of a thread is cheaper than processing


critical section of a process.

When multiple threads share the same CPU among themselves they
are said to execute concurrently (i.e. in an inter leaving fashion).
Multithreaded programming

Thread models
 Cooperative thread model
A running thread relinquishes the CPU. It is under the control of the
JVM (and hence under the control of the Java application
developer).

 Preemptive thread model


A running thread is forced to leave the CPU. This model is under the
control of the OS.
Multithreaded programming

State transition diagram

New Ready Suspended

Running Terminated
Multithreaded programming

To develop a multi threaded program either


(i) implement the Runnable interface
(ii) use the Thread class or a sub class of the thread class

If you implement Runnable interface then you must give the definition
of the run( ) method of Runnable interface.

This method has following form


public void run( ).

The definition of the run method describes the work done by the thread.
Multithreaded programming

Thread class (package java.lang)

public class Thread extends Object


implements Runnable

Constructors
public Thread ( )
public Thread(String name)
public Thread(Runnable work)
public Thread(Runnable work, String name)
public Thread(ThreadGroup group, Runnable work)
public Thread(ThreadGroup group, String name)
public Thread(ThreadGroup group, Runnable work, String name)
Multithreaded programming

A thread group is a data structure that controls the behavior of a


collection of threads.

Constants defined inside the Thread class


public static final int MIN_PRIORITY
The minimum priority that a thread can have. Value 1

public static final int NORM_PRIORITY


The default priority that is assigned to a thread. Value 5

public static final int MAX_PRIORITY


The maximum priority that a thread can have. Value 10
Multithreaded programming

Priority of a thread refers to its relative importance with respect to other


threads.

A thread with higher priority executes more often than a thread with lower
priority.

If a single thread is in execution then its priority makes no sense.

Priority of a child thread is the same as that of its parent.

It is possible to modify the priority of thread.

A thread also has a name that can be changed.

Changing the priority and name of a thread is called configuring the thread.
Multithreaded programming

Static methods
public static Thread currentThread( ) returns a reference to the running
thread. e.g. Thread.currentThread( )

public static void yield( ) Causes the currently executing thread object
to temporarily pause and allow other threads to execute.

public static void sleep (long ms) throws InterruptedException


Suspends execution of the currently running thread for ms milliseconds. The
thread does not lose ownership of any monitors (locks).

public static void sleep (long ms, int ns) throws InterruptedException

public static boolean interrupted( )


Returns true if the current thread has been suspended.
Multithreaded programming

Final methods

public final boolean isAlive( ) returns true if this thread has not been
terminated.

public final void setPriority(int newPriority) changes the priority of this


thread object.

public final int getPriority( ) returns the priority of this thread.

public final void setName(String name) alters the name of this thread
object.

public final String getName( ) returns the name of this thread object.
Multithreaded programming

Final methods

 public final ThreadGroup getThreadGroup( )


Returns the group this thread belongs to.

 public final void join( ) throws InterruptedException


Waits for this thread to terminate
e.g. if you use t.join( ) then the method that contains this code will
not terminate until t terminates, t being a thread object.

 public final void join(long ms) throws InterruptedException


waits for at most ms milliseconds before terminating.
Multithreaded programming

Methods that are neither final nor static

public void start( ) spawns a new thread.

public void run( ) Thread goes to ready state. Start method


automatically calls run( ) method.

public void interrupt( ) interrupts a thread.

public boolean isInterrupted( ) returns true if this thread has been


interrupted.
Multithreaded programming

 A thread object is an abstraction of a worker

 A Runnable object (i.e. the class that implements Runnable


interface) is an abstraction of a work.

 If you are implementing Runnable interface to create thread object


then wrap the Runnable object inside the Thread class constructor
i.e. associate a work with a worker.

 To associate a work with a worker, use one of the following


constructors
public Thread(Runnable work)
public Thread(Runnable work, String name)
public Thread(ThreadGroup group, Runnable work, String name)
Multithreaded programming
Example code

public class ThreadTest {


public static void main(String[ ] agrs) {
Thread t = Thread.currentThread( );
System.out.println(t);
System.out.println(t.getName( ) + “ “ + t.getPriority());
t.setName(“Main Thread”) ;
t.setPriority(9);
Thread t1 = new Thread( );
System.out.println(t1);
Thread t2 = new Thread( );
System.out.println(t2);

}
}
Multithreaded programming
Extending Thread class
public class Thread11 extends Thread {
private String word;
private int delay;
public Thread11(String str, int d) {
word = str; delay = d;
}
public void run( ) {
for(; ;) {
System.out.print(word+ " ");
try {
Thread.sleep(delay);
}catch(InterruptedException e) {

}
}//for
}//run
public static void main(String[ ] args) {
Thread11 t1 = new Thread11("Java", 50);
Thread11 t2 = new Thread11("Programming", 50)
t1.start( ); t2.start( )
/* new Thread11("Java", 50).start( );
new Thread11(“Programming", 50).start( ); */
}
}
Multithreaded programming
Using Runnable interface

public class Thread12 implements Runnable {


private String word;
private int delay;
public Thread12(String str, int d) {
word = str; delay = d;
}
public void run( ) {
for(; ;) {
System.out.print(word+ “ “);
try {
Thread.sleep(delay);
}catch(InterruptedException e) {
}
}//for
}//run
public static void main(String[ ] args) {
new Thread(new Thread12(“Java”, 50)).start( );
new Thread(new Thread12(“Programming”, 100)).start( );
}
}
Multithreaded programming
Dropping Thread object inside constructor and using start method inside constructor

public class Thread13 implements Runnable {


private String word;
private int delay; private Thread t;
public Thread13(String str, int d) {
word = str; delay = d;
t = new Thread(this);
t.start();
}
public void run( ) {
for(; ;) {
System.out.print(word+ " ");
try {
Thread.sleep(delay);
}catch(InterruptedException e) {

}
}
}
public static void main(String[ ] agrs) {
new Thread13("Java", 50);
new Thread13("Programming", 100);
}
}
Multithreaded programming
using start method inside constructor
public class Thread13 extends Thread {
private String word;
private int delay;
public Thread13(String str, int d) {
word = str; delay = d;

start();
}
public void run( ) {
for(; ;) {
System.out.print(word+ " ");
try {
Thread.sleep(delay);
}catch(InterruptedException e) {

}
}
}
Multithreaded programming

public static void main(String[ ] agrs) {


new Thread13("Java", 50);
new Thread13("Programming", 100);
}
}
Multithreaded programming
Using Anonymous inner class
public class Thread14 {
private String word;
private int delay;
public Thread14(String str, int d) {
word = str; delay = d;
Runnable work = new Runnable( ) {
public void run( ) {
for(; ;) {
System.out.println(word+ " ");
try {
Thread.sleep(delay);
}catch(InterruptedException e) {
}
}//for
}//run
};
new Thread(work).start( );
}//constructor ends

public static void main(String[ ] agrs) {


new Thread14("Java", 50);
new Thread14("Programming", 100);
}
}
Multithreaded programming

Thread synchronization

When multiple threads interfere with each other in executing a code


segment then this execution of the code segment is called
asynchronous execution and when they do not interfere then it is called
synchronous execution.

There are two different ways of implementing synchronous execution of


code segment
 Synchronized method
 Synchronized block
Multithreaded programming

synchronized method

use synchronized method and use the code segment to be


synchronized inside this method. A method is declared synchronized
using the modifier synchronized.

e.g. synchronized void drop( ) {


/*code whose execution must not be interfered by multiple
threads */
}

A synchronized method may be declared static. Constructors cannot be


synchronized.
Multithreaded programming
Use synchronized block

A synchronized block is declared as

synchronized(expr) { //expr must evaluate to an object reference


//code to be synchronized
}
e.g. X x = new X( );
synchronized(x) {
x.f( ); //doing something on the object x one at a time by
different //threads
}

synchronized(this) {
//doing something on the current object one at a time by different
//threads
}
Multithreaded programming
 Synchronized method and synchronized block are called
synchronized codes.

 Synchronized block is also called synchronized statement

 Associated with every object (e.g. bank account object) there exists
a lock. In order to execute synchronized code on the object, a thread
must acquire the lock of the object. Before entering into
synchronized code a thread requests the OS for the lock. If the lock
of the object is already held by some other thread then this thread
has to wait. If the lock is available then the thread acquires the lock,
enters into the synchronized code, and after it returns from the
synchronized code it releases the lock.

 e.g. A particular bank account is an object. At a time only one teller


(one thread) can alter the balance of the account.
Multithreaded programming

Banking example
class BankAccount {
private double balance;
public BankAccount(double d) { balance = d; }
public synchronized void setBalance(double d) {
balance = balance + d;
}
public synchronized void getBalance( ) {
return balance;
}
}
Multithreaded programming
public class Teller implements Runnable {
private BankAccount ba; private double d;
public Teller(BankAccount ba, double d) {
this.ba = ba; this.d = d;
}
public void run( ) {
ba.setBalance(d);
}
public static void main(String[ ] agrs) {
BankAccount ba = new BankAccount(1000);
Thread t1 = new Thread (new Teller(ba, 2000);
Thread t2 = new Thread (new Teller(ba, 3000);
t1.start( ); t2.start( );
try {
t1.join( ); t2.join( );
}catch(InterruptedException e) { }
System.out.println(ba.getBalance( )); // o/p should be 6000
}//main
}Teller
Portions
CAT II
 Interfaces
 StringBuffer class
 Package
 Access protection
 Exception handling
 Multithreaded programming (up to thread
synchronization)
Multithreaded programming

wait, notify and notifyAll method

These are the declared methods of the Object class, inherited by the
Thread class.
These methods are useful in establishing communication
among threads (called inter-thread communication).

 final void wait( ) throws InterruptedException


Suspends execution of this thread until some other thread wakes it
up invoking notify or notifyAll method. If a thread goes to wait then it
will first release any lock held by it before going to wait state (but it is
not so with the sleep method i.e. it does not release the lock before
going to sleep).
Multithreaded programming

 final void wait(long ms) throws InterruptedException


Causes current thread to wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.

 final void wait(long ms, int ns) throws InterruptedException


Multithreaded programming

 final void notify( )


It wakes up a single thread that was waiting for this object`s lock to
be released. It two threads t1 and t2 were waiting for the object`s
lock then only one of them receives the notification
and the selection of t1 or t2 is arbitrary and platform dependent.

 final void notifyAll( )


All the waiting threads gets notification but only one of them gets the
lock and the selection is arbitrary and platform dependent.
PROGRAMMING IN JAVA
QUIZ II
 WRITE YOU REGISTRATION NUMBER ON THE
QUESTION PAPER AS SOON AS YOU RECEIVE IT.
 DO NOT ANSWER QUESTIONS UNTIL YOU ARE
ASKED TO.
 ALL QUESTIONS ARE COMPULSORY.
 A QUESTION MAY HAVE MULTIPLE CORRECT
ANSWERS.
 ENCIRCLE THE CORRECT ANSWER(S).
 DO NOT OVERWRITE ANYWHERE ON THE PAPER.
 TEST DURATION: 15 MINUTES
 MAXIMUM MARKS: 10
Multithreaded programming

Inter-thread communication
 Can be achieved using wait, notify and notifyAll methods.
 Producer-consumer problem is an example of inter-thread
communication where producer and consumer are threads.
 Producer produces items and keep the items in a buffer whereas
the consumer picks up the items one at a time from the buffer.
 As long as the buffer is full the producer thread cannot produce
items (i.e. it waits indefinitely until the buffer is empty)
 The consumer too waits until there is at least one item in the buffer.
 For simplicity we assume that the buffer size is one i.e. the producer
has to wait after producing an item until the consumer picks up the
item.
Multithreaded programming

 The consumer is in indefinite wait until an item is produced.

 How will the consumer know that the item has been produced?

 The producer after producing the item issues notification to the


consumer using notify method.

 After producing the item the producer has to wait until the item is
picked
up (assuming that the buffer size is one).

 How will the producer know that the item has been picked up?

 After picking up the item the consumer issues notification using the
notify method.
Implementation of producer-consumer problem (buffer size = 1)

class Data {
private int data; //this can be an array when the buffer size > 1
private boolean found = false; //no item found in the buffer
synchronized int pickup( ) { //executed by the consumer thread
while(!found) {
try {
wait( );
}catch(InterruptedException e) { }
}//while
found = false;
notify( );
return data;
}
Implementation of producer-consumer problem (buffer size = 1)

synchronized void drop (int m /*item to be dropped*/) { //executed by


//the producer thread
while(found) {
try {
wait( );
}catch(InterruptedException e) { }
}//while
data = m;
found = true;
notify( );

}//drop
}//Data
Implementation of producer-consumer problem (buffer size = 1)

class Producer implements Runnable {


private Data d;
private java.util.Random r = new java.util.Random( );
Producer(Data d) {
this.d = d;
}
public void run( ) {
d.drop(r.nextInt( ));
}
}//Producer
Implementation of producer-consumer problem (buffer size = 1)

class Consumer implements Runnable {


private Data dd;
Consumer (Data dd) {
this.dd = dd;
}
public void run( ) {
System.out.println(dd.pickup( ));
}
}//Consumer
Implementation of producer-consumer problem (buffer size = 1)

class InterThreadCommunication {
public static void main(String [ ] args) {
Data dt = new Data( );
new Thread(new Producer(dt)).start( );
new Thread(new Consumer(dt)).start( );
}
}
Deadlock

It is difficult to develop a program that can deadlock.

If you have two threads


And two objects with lock
Then you may have deadlock.
Deadlock

Code example

class A {
synchronized void h( ) { //h( ) @ A
//code
}
synchronized void f(B b) {
try {
Thread.sleep(1000);
}catch(InterruptedException e) { }
b.h( ); //h( ) @ B
}
}
Deadlock

class B {
synchronized void h( ) { //h( ) @ B
//code
}
synchronized void g(A a) {
try {
Thread.sleep(1000);
}catch(InterruptedException e) { }
a.h( ); //h( ) @A
}
}//B
Deadlock
class X implements Runnable {
A a = new A( );
B b = new B( );
Thread t;
X(){
t = new Thread(this);
t.start( );
a.f(b);
}
public void run( ) {
b.g(a);
}
public static void main(String[ ] args) {
new X( );
}
}
Deadlock

Trace
1. Main thread comes into existence and calls X( ) using new X( );
2. Thread t (a child thread of the main thread) is created using t =
new Thread(this) and started using t.start( )
3. start calls run method which in turn execute (child thread is
executing) b.f(a). Since f is a synchronized method, the lock of b
is required and so it is allocated to the child thread t.
4. After entering into the method f, since it contains sleep so the
child thread t is suspended and CPU is switched to the main
thread.
5. When the main thread was suspended last it had already
executed t.start( ) and so now it executes a.g(b).
Deadlock

6. Since g is a synchronized method so its execution requires the lock


of the object a and so the lock is allocated to the main thread
(because it is not held by any other thread).
7. After entering into method g the main thread is suspended again
because of Thread.sleep(1000) inside g. So the CPU is now
switched to the child thread t.
8. The child thread was suspended last and now gets the CPU. It now
requires the lock of b to execute b.h ( ). But the lock of b is already
held by the main thread.
9. When CPU is again switched to the main thread it requires the lock
of a which is now held by the child thread t.

So the main thread and the child thread are in a deadlock situation.
Modifier ‘volatile`

When two or more threads share the same instance field, a private
copy of the field is given to each thread and the threads modify this
private copy.

Apart from these private copies there is also maintained a master copy.
If you want to keep the values of the master copy always updated
whenever the private copy is updated then use the modifier volatile.

e.g. volatile double x;


Garbage collection

Any object that is no longer being referenced by the program is called a


dead object (garbage), the other objects are called live objects.

To declare an object x as dead you may use the code x = null.

Though there is no reference any more, it still occupies memory.

To reclaim memory occupied by the dead objects, the garbage


collector
is used.
Garbage collection

 A garbage collector is a piece of software that reclaims the memory


occupied by dead objects.
 The garbage collector is called sporadically (irregularly) by the JVM.
 The application program and the GC run concurrently. When the GC
executes the application program is halted.
 There are various algorithms for implementing garbage collection.
One of them is called mark-and-sweep (mark the live object and
remove the dead object).
 An application developer can call the GC using System.gc( )

ACM Transactions on Programming Languages & Systems


finalize method

protected void finalize( ) @ Object class

This method is called automatically just before the garbage collector is


called.
If you want to release any non-memory resources before the GC is
called then override this method.
e.g. class X {
//code
protected void finalize( ) {
//code that de-allocates non-memory resources
super.finalize( );
}
}
Java I/O
Java stream classes perform I/O in Java

Stream classes are defined in the package java.io

A stream is an ordered sequence of data (bits).

When bits are interpreted as bytes the stream is called byte stream.

When bits are interpreted as characters the stream is called character


stream.

An input stream allows a program to read data.

An output stream allows a program to write data.

Every input stream has a source and it reads data from the source.

Every output stream has a destination and it writes data to the destination
Stream classes

InputStream class (java.io) abstract class.


Byte oriented input stream class.

Methods
 public abstract int read( ) throws IOException
Reads the next byte of data from this input stream.
The value of byte is returned as an integer in the range 0 to 255.
If no byte is available because the end of the stream has been
reached, the value -1 is returned.
The method blocks until input data is available, the end of the
stream is detected, or an exception is thrown.
A subclass must provide an implementation of this method.
InputStream class

 public int read(byte[ ] b) throws IOException


Reads some number of bytes from the input stream and stores them
into the buffer array b.
The number of bytes actually read is returned as an integer.
This method blocks until input data is available, end of file is
detected, or an exception is thrown.
If the length of b is zero, then no bytes are read and 0 is returned;
otherwise, there is an attempt to read at least one byte.
If no byte is available because the stream is at the end of the file,
the value -1 is returned.
InputStream class

 public int read(byte[ ] b, int off, int len) throws IOException


Reads up to len bytes of data from the input stream into an array of
bytes. An attempt is made to read as many as len bytes, but a
smaller number may be read. The number of bytes actually read is
returned as an integer. This method blocks until input data is
available, end of file is detected, or an exception is thrown.
If len is zero, then no bytes are read and 0 is returned; otherwise,
there is an attempt to read at least one byte. If no byte is available
because the stream is at end of file, the value -1 is returned;
InputStream class

 public long skip(long n) throws IOException


Skips over and discards n bytes of data from this input stream.
The skip method may, for a variety of reasons, end up skipping over
some smaller number of bytes, possibly 0. This may result from any
of a number of conditions; reaching end of file before n bytes have
been skipped is only one possibility.
The actual number of bytes skipped is returned. If n is negative, no
bytes are skipped.
InputStream class

 public int available( ) throws IOException


Returns the number of bytes still lying in this stream.

 public void close( ) throws IOException


Closes this input stream and releases any system resources
associated with the stream.
The close method of InputStream does nothing.
InputStream class

 public void mark(int readlimit)


Remembers readLimit number of bytes starting from the current
position (where you call mark method) and may read these bytes
again when reset is called.
For this to happen the method markSupported should return true.
Marking a closed stream should not have any effect on the stream.
The mark method of InputStream does nothing.

 public void reset( ) throws IOException


Repositions this stream to the position at the time the mark method
was last called on this input stream.
InputStream class

 public boolean markSupported( )


Tests if this input stream supports the mark and reset methods.
The markSupported method of InputStream returns false.
OutputStream class

public abstract class OutputStream (java.io)


Byte-oriented output stream class.

Methods
 public abstract void write(int b) throws IOException
Writes the specified byte to this output stream. The byte to be
written is the eight low-order bits of the argument b.

 public void write(byte[ ] b) throws IOException


Writes b.length bytes from the specified byte array to this output
stream.
OutputStream class

 public void write(byte[ ] b, int off, int len) throws IOException


Writes len bytes from the specified byte array starting at offset off to
this output stream.
If b is null, a NullPointerException is thrown.

 public void flush( ) throws IOException


Forces any buffered output bytes to be written out.
OutputStream class

 public void close( ) throws IOException


Closes this output stream and releases any system resources
associated with this stream. A closed stream cannot perform output
operations and cannot be reopened.
The close method of OutputStream does nothing.

N.B. There is no print or println method in this class


Reader class

public abstract class Reader (java.io)

Character-oriented input stream.

Methods
 public int read( ) throws IOException
Read a single character and returns it as an integer between 0 to
65535 and returns -1 when there is no character to read.
This method will block until a character is available, an I/O error
occurs, or the end of the stream is reached.
Reader class

 public int read(char[ ] cbuf) throws IOException


Read characters into an array. The number of characters read is
returned as an integer. If there is nothing to read -1 is returned.
The method will block until some input is available, an I/O error
occurs, or the end of the stream is reached.

 public abstract int read(char[ ] cbuf, int off, int len) throws


IOException
Read characters into a portion of an array. The number of
characters read is returned as an integer. If there is nothing to read
-1 is returned.
The method will block until some input is available, an I/O error
occurs, or the end of the stream is reached.
Reader class

 public long skip(long n) throws IOException


Skip the next n characters. May end up skipping less than n
characters.
The method will block until some characters are available, an I/O
error occurs, or the end of the stream is reached.

 public boolean ready( ) throws IOException


Tell whether this stream is ready to be read.

 public boolean markSupported( )


Similar to the markSupported method of InputStream class
Reader class

 public void mark(int readAheadLimit) throws IOException

 public void reset( ) throws IOException

 public abstract void close( ) throws IOException


Close the stream.
Once a stream has been closed, further read( ), ready( ), mark( ), or
reset( ) invocations will throw an IOException.
Closing a previously-closed stream, however, has no effect.
Writer class

public abstract class Writer


Character-oriented output stream

Methods
 public void write(int c) throws IOException
Write a single character.
The character to be written is contained in the 16 low-order bits of
the given integer value; the 16 high-order bits are ignored.

 public void write(char[ ] cbuf) throws IOException


Write an array of characters.
Writer class
 public abstract void write(char[ ] cbuf, int off, int len)
throws IOException
Write a portion of an array of characters.

 public void write(String str) throws IOException


Write a string.

 public void write(String str, int off, int len)


throws IOException
Write a portion of a string.
Parameters:
str - A String,
off - Offset from which to start writing characters
len - Number of characters to write
Writer class

 public abstract void flush( ) throws IOException


Flush the stream i.e. forces any buffered output characters to be
written out.

 public abstract void close( ) throws IOException


Close the stream, flushing it first.
Once a stream has been closed, further write( ) or flush( )
invocations will cause an IOException to be thrown.
Closing a previously-closed stream, however, has no effect.
Pre-defined streams

Inside the System class there are declared public static final stream
objects called
in, out and err
in is of type InputSteam
out and err are of type PrintStream.

These objects can be accessed using


System.in System.out System.err
e.g. System.out.print System.out.println
System.err.print Syste.err.println
As a matter of convention, use System.err when you want send error
message.
Pre-defined streams

 System.in points to standard input device and the default standard


input device is keyboard.

 System.out as well as System.err point to standard output device


and the default standard output device is the display device.

System.in may be used as


System.in.read( )
reads the next byte available in the stream and reruns an integer
between 0 to 255.
e.g. Syste.out.println(System.in.read( ));
When to use byte stream class &
when to use character stream class

If you want to perform I/O on byte data (e.g. image, audio, video), use
byte stream class.

If you want to perform I/O on character data (text based), use character
stream class.
InputStreamReader class

public class InputStreamReader extends Reader


An InputStreamReader is a bridge from byte streams to character
streams: It reads bytes and decodes them into characters using a
specified charset.
To enable the efficient conversion of bytes to characters, more bytes
may be read ahead from the underlying stream than are necessary to
satisfy the current read operation. For top efficiency, consider wrapping
an InputStreamReader within a BufferedReader.
For example:
BufferedReader in =
new BufferedReader(new InputStreamReader(System.in));
System.out.print(in.readLine( ));
InputStreamReader class

Constructors

 public InputStreamReader(InputStream in)
Creates an InputStreamReader that uses the default charset.

 public InputStreamReader(InputStream in, String charsetName)


throws UnsupportedEncodingException
Creates an InputStreamReader that uses the named charset.
InputStreamReader class

Methods

 public String getEncoding( )


Returns the name of the character encoding being used by this
stream.

 public int read( ) throws IOException


Reads a single character.

 public int read(char[ ] cbuf, int offset, int length)


throws IOException
Reads characters into a portion of an array.
InputStreamReader class

 public boolean ready( ) throws IOException


Tells whether this stream is ready to be read. An
InputStreamReader is ready if its input buffer is not empty, or if
bytes are available to be read from the underlying byte stream.

 public void close( ) throws IOException


BufferedReader class

 public class BufferedReader extends Reader


Reads text from a character-input stream, buffering characters so as
to provide for the efficient reading of characters, arrays, and lines.
The buffer size may be specified, or the default size may be used.
The default is large enough for most purposes.

 public BufferedReader(Reader in, int sz)


Creates a buffering character-input stream that uses an input buffer
of the specified size.
BufferedReader class

 public int read( ) throws IOException


Reads a single character.
Overrides read method of Reader class.

 public int read(char[ ] cbuf, int off, int len) throws IOException


Reads characters into a portion of an array.
Overrides read method of Reader class.

 public String readLine( ) throws IOException


Reads a line of text.
BufferedReader class

 public long skip(long n) throws IOException

 public boolean ready( ) throws IOException

 public boolean markSupported( )

 public void mark(int readAheadLimit) throws IOException

 public void reset( ) throws IOException

 public void close( ) throws IOException


PrintStream class

public class PrintStream extends FilterOutputStream

Constructor
 public PrintStream(OutputStream out)
Create a new print stream. This stream will not flush automatically.
 public PrintStream(OutputStream out, boolean autoFlush)
Create a new print stream.
Parameters:
out - The output stream to which values and objects will be printed
autoFlush - A boolean; if true, the output buffer will be flushed
whenever a byte array is written, one of the println methods is
invoked, or a newline character or byte ('\n') is written
PrintStream class

 public PrintStream(OutputStream out, boolean autoFlush, String charset)


throws UnsupportedEncodingException
Create a new print stream.
Parameters:
out - The output stream to which values and objects will be printed
autoFlush - A boolean; if true, the output buffer will be flushed whenever a
byte array is written, one of the println methods is invoked, or a newline
character or byte ('\n') is written
encoding - The name of a supported character encoding

 public PrintStream(String fileName) throws FileNotFoundException

 public PrintStream(String fileName, String charset)


throws FileNotFoundException, UnsupportedEncodingException
PrintStream class
 public PrintStream(File file) throws FileNotFoundException

 public PrintStream(File file, String charset)


throws FileNotFoundException, UnsupportedEncodingException

Methods
 public void flush( ) Flush the stream.
 public void close( ) Close the stream.
 public void write(int b) Write the specified byte to this stream.
 public void write(byte[ ] buf, int off, int len)
 public void print(boolean b) Print a boolean value.
 public void print(char c) Print a character.
PrintStream class

 public void print(int i) Print an integer.

 public void print(long l) Print a long integer.

 public void print(float f) Print a floating-point number.

 public void print(double d)


Print a double-precision floating-point number.

 public void print(char[ ] s) Print an array of characters.

 public void print(String s) Print a string.

 public void print(Object obj) Print an object.


PrintStream class
 public void println( ) Terminate the current line by writing the line separator
string.

 public void println(boolean x) Print a boolean and then terminate the line.

 public void println(char x) Print a character and then terminate the line.

 public void println(int x) Print an integer and then terminate the line.

 public void println(long x) Print a long and then terminate the line.
 public void println(float x) Print a float and then terminate the line.
 public void println(double x) Print a double and then terminate the line.
 public void println(char[ ] x) Print an array of characters and then terminate
the line.
 public void println(String x) Print a String and then terminate the line.

 public void println(Object x)Print an Object and then terminate the line.


PrintStream class

 public PrintStream printf(String format, Object... args)


A convenience method to write a formatted string to this output
stream using the specified format string and arguments.

 public PrintStream append(char c)


Appends the specified character to this output stream.
PrintWriter class

public class PrintWriter extends Writer

Constructors

PrintWriter(File file)
PrintWriter(File file, String csn)
PrintWriter(OutputStream out)
PrintWriter(OutputStream out, boolean autoFlush)
PrintWriter(String fileName)   
PrintWriter(String fileName, String csn)
PrintWriter(Writer out)
PrintWriter(Writer out, boolean autoFlush)

Methods
Overloaded print and println similar to PrintStream class, printf method
and append method
BufferedWriter class

public class BufferedWriter extends Writer


Write text to a character-output stream.

PrintWriter out = new PrintWriter(new BufferedWriter(new


FileWriter("foo.out")));

Constructor
BufferedWriter(Writer out)
BufferedWriter(Writer out, int sz)
BufferedWriter class

public void write(int c) throws IOException


public void write(char[ ] cbuf, int off, int len) throws IOException
public void write(String s, int off, int len) throws IOException

public void newLine() throws IOException


Write a line separator.

public void flush() throws IOException


public void close() throws IOException
OutputStreamWriter class

public class OutputStreamWriter extends Writer


An OutputStreamWriter is a bridge from character streams to byte
streams: Characters written to it are encoded into bytes using a
specified charset.

e.g.
Writer out = new BufferedWriter(new OutputStreamWriter(System.out));
OutputStreamWriter class

Constructors

OutputStreamWriter(OutputStream out)
         
OutputStreamWriter(OutputStream out, Charset cs)
         
OutputStreamWriter(OutputStream out, CharsetEncoder enc)
         
OutputStreamWriter(OutputStream out, String charsetName)
         
OutputStreamWriter class

Methods

void close()
           
void flush()
           
String getEncoding()
           
void write(char[ ] cbuf, int off, int len)
          
void write(int c)
           
void write(String str, int off, int len)
          
ByteArrayInputStream class

public class ByteArrayInputStream extends InputStream

ByteArrayInputStream(byte[ ] buf)
 
ByteArrayInputStream(byte[] buf, int offset, int length)

Methods of the InputStream class are defined here. 


ByteArrayOutputStream class

public class ByteArrayOutputStream extends OutputStream

The data is written into a byte array.


ByteArrayOutputStream( )           
ByteArrayOutputStream(int size)

Methods from OutputStream class are defined here.


          
CharArrayReader class

CharArrayReader(char[ ] buf)
          
CharArrayReader(char[ ] buf, int offset, int length)

Methods of Reader class defined here.


          
CharArrayWriter class

CharArrayWriter( )
CharArrayWriter(int initialSize)

Methods of Writer class are defined here


FileInputStream class

public class FileInputStream extends InputStream


A FileInputStream obtains input bytes from a file in a file system.
Constructor
public FileInputStream(String name) throws FileNotFoundException
public FileInputStream(File file) throws FileNotFoundException
Methods
public int read() throws IOException
public int read(byte[ ] b) throws IOException
public int read(byte[ ] b, int off, int len) throws IOException
public long skip(long n) throws IOException
public int available() throws IOException
public void close( ) throws IOException
FileOutputStream class

FileOutputStream(File file)
          
FileOutputStream(File file, boolean append)
                    
FileOutputStream(String name)
          
FileOutputStream(String name, boolean append)

You will find write methods, close


method.           
FileReader class

public class FileReader extends InputStreamReader

public FileReader(String fileName) throws FileNotFoundException


public FileReader(File file) throws FileNotFoundException

Methods are inherited from super class


FileWriter class

class FileWriter extends OutputStreamWriter

public FileWriter(String fileName) throws IOException


public FileWriter(String fileName, boolean append) throws IOException
public FileWriter(File file) throws IOException
public FileWriter(File file, boolean append) throws IOException

Methods are inherited from super class.


Code examples

BufferredReader br = new BufferredReader(new


InputStreamReader(new FileInputStream(“filepath”);
String str;
while((str=br.readLine( )) !=null) System.out.println(str);

FileInputStream fis = new FileInputStream(“filepath”)


int b;
while( (b=fis.read( )) != -1) System.out.print((char)b);
Code examples

FileInputStream fos = new FileInputStream(“filepath”);


int m = fis.available( );
byte[ ] bytes = new byte[m];
fis.read(bytes);
FileOutputStream fos = new FileOutputStream(“output.dat”);
fos.write(bytes);
Code examples

If you want read characters from a file and write these characters to
another file then use the following code.
FileReader fr = new FileReader(“Inputfile”);
FileWriter fw = new FileWriter(“outputfile”);
int ch;
while((ch = fr.read( )) != -1) fw.write((char)ch);

If you want to read lines from a file and write to another file then??

Try it out
File class

public class File extends Object

File(String path)
File(String name, String relativePath)
File(URI uri)
e.g. File f = new File(“e:\dir1\dir2\prog.java”);

String getName( ) String getParent( ) boolean exists( )


boolean canRead( ), boolean canWrite( ),
boolean renameTo(File newName) returns true if renaming succeeds
String getPath( ), String getAbsolutePath( ), boolean isFile( )
boolean isDirectory( ) String[ ] list( ) displays the files & directories in
this File object
e.g. File f = new File(“e:\”);
String [ ] files = f.list( );
File class

File [ ] listFiles( )
boolean mkdir( )
boolean mkdirs( )
e.g.
File f = new File(“e:\dir1”);
f.mkdir( );

File f = new File(“e:\dir1\dir2\dir3\dir4”);


f.mkdirs( );
RandomAccessFile class
public class RandomAccessFile extends Object

Instances of this class support both reading and writing to a random access file.
There is a kind of cursor, called the file pointer; input operations read bytes
starting at the file pointer and advance the file pointer past the bytes read. If the
random access file is created in read/write mode, then output operations are also
available; output operations write bytes starting at the file pointer and advance the
file pointer past the bytes written.

public RandomAccessFile(String name, String mode) throws


FileNotFoundException

public RandomAccessFile(File file, String mode) throws


FileNotFoundException
RandomAccessFile class

Mode
"r“
Open for reading only. Invoking any of the write methods of the resulting object
will cause an IOException to be thrown.
"rw“
Open for reading and writing. If the file does not already exist then an attempt
will be made to create it.
"rws“
Open for reading and writing, as with "rw", and also require that every update to
the file's content or metadata be written synchronously to the underlying
storage device.
"rwd"  
Open for reading and writing, as with "rw", and also require that every update to
the file's content be written synchronously to the underlying storage device.
Java Networking

java.net package provides the necessary API for writing networking


program in Java.

A server is an entity that has sharable resource.


A client is an entity that wants to access a server.
Associated with every service there exists a port number.
e.g. HTTP 80, FTP 21, Telnet 23, email 25, netnews 119.

Every computer has an IP address. IP address comes in two forms


namely, domain name (www.myDomain.com) & numeric IP address
(xxx.xxx.xxx.xxx)
Java Networking

DNS maps the domain name to the IP address.

A computer that has resource to share is called a host. The host name
can be expressed by its domain name or by numeric IP address.

If a domain name can be mapped to multiple numeric addresses then


the host is called multi-homed host.
Java Networking

TCP Connection
A socket is an abstraction of the end point of a connection.

In Java a socket is an object that encapsulates this abstraction.

A socket object is created using Socket class constructor

Socket(String ipaddrr, int portno) throws UnkownHostException,


IOException
e.g. Socket s = new Socket(www.vit.ac.in, 80);
Java Networking

Associated with every socket there exists an input stream and an


output stream.

These are the streams to read data from and write data to the socket.

To obtain the input stream execute the code


InputStream in = s.getInputStream( );

To obtain the output stream execute the code


OutputStream out = s.getOutputStream( );
Socket class

public class Socket extends Object

This class implements client sockets (also called just "sockets").


A socket is an endpoint for communication between two machines.

public Socket(String host, int port) throws UnknownHostException,


IOException

public Socket(InetAddress address, int port) throws IOException


Socket class

Methods
public InetAddress getInetAddress()
Returns the address to which the socket is connected.

public InetAddress getLocalAddress()


Gets the local address to which the socket is bound.

public int getPort()


Returns the remote port to which this socket is connected.

public InputStream getInputStream() throws IOException


Returns an input stream for this socket.
Socket class

public OutputStream getOutputStream() throws IOException


Returns an output stream for this socket.

public void close() throws IOException


Closes this socket.
Any thread currently blocked in an I/O operation upon this socket will
throw a SocketException.
Once a socket has been closed, it is not available for further networking
use (i.e. can't be reconnected or rebound). A new socket needs to be
created.
If this socket has an associated channel then the channel is closed as
well.
Java Networking

Inside the server program you create a server socket using constructor
of ServerSocket class

ServerSocket(int portno);

e.g. ServerSocket ss = new ServerSocket(8189);

Socket s = ss.accept( ); //waits until a connection request comes in.


InetAddress class

It encapsulates IP address

Methods
public String getHostName()
Gets the host name for this IP address

public String getHostAddress()


Returns the IP address string in textual presentation.

public static InetAddress getByName(String host) throws


UnknownHostException
Determines the IP address of a host, given the host's
name.
InetAddress class

public static InetAddress[ ] getAllByName(String host) throws


UnknownHostException
Given the name of a host, returns an array of its IP
addresses

public static InetAddress getLocalHost() throws


UnknownHostException
Returns the local host.
HTTP connection

To establish HTTP connection with a host, use URL class constructor


URL(String url) throws MalformedURLException

Class URL represents a Uniform Resource Locator, a pointer to a


"resource" on the World Wide Web. A resource can be something as
simple as a file or a directory, or it can be a reference to a more
complicated object, such as a query to a database or to a search
engine.

An URL has the following form


protocolname://hostname:portno/filepath
In absence of the port no. it is assumed to be 8080
e.g. http://www.osborne.com/index.html
Some of the methods of URL class are
URLConnection openConnection( )
String getHost( )
String getProtocol( )
String getPort( )
HTTP connection

The following code segment creates a URL object, opens a URL


connection and reads data from this connection.

URL url = new URL(http://www.osborne.com/index.html);


URLConnection urlcon = url.openConnection( );
InputStream is = urlcon.getInputStream( );
int ch;
while( (ch = is.read( )) != -1) System.out.println((char)ch);
UDP Connection

A datagram is an independent packet.

DatagramPacket class encapsulates a datagram.

DatagramPacket(byte[ ] data, int sz)


DatagramPacket(byte[ ] data, int off, int sz)
DatagramPacket(byte[ ] data, int sz, InetAddress iaddrr, int portno)
DatagramPacket(byte[ ] data, int off, int sz, InetAddress iaddrr, int portno)
The first two constructors are used for receiving data and the other two are
used for sending data.
byte[ ] getData( )
UDP connection
DatagramSocket class

DatagramSocket(int portno) throws SocketException


Constructs a datagram socket and binds it to the specified port on the
local host machine.

DatagramSocket(int port, InetAddress laddr)
Creates a datagram socket, bound to the specified local address.

void send(DatagramPacket dp)


Writes datagram packet to datagram socket

void receive(DatagramPacket dp)


Reads datagram packet from datagram socket
Remote Method Invocation

Remote Method Invocation (RMI) facilitates object function calls


between machines running JVM.
Naming class(java.rmi)

public final class Naming extends Object

public static Remote lookup(String url) throws NotBoundException,


MalformedURLException, RemoteException
Returns a reference for the remote object associated with the specified
url. (rmi://host:port/name)

public static void bind(String url, Remote obj) throws


AlreadyBoundException, MalformedURLException, RemoteException
Binds the specified name to a remote object.
Naming class

 public static void rebind(String url, Remote obj) throws


RemoteException, MalformedURLException
Rebinds the specified name to a new remote object. Any existing
binding for the url is replaced.

 public static void unbind(String url) throws RemoteException,


NotBoundException, MalformedURLException
Destroys the binding for the specified url that is associated with a
remote object.

 public static String[ ] list(String name) throws RemoteException,


MalformedURLException
Returns an array of the urls bound in the registry.
What should you do to develop and test RMI application?

 Develop an interface containing the method(s) to be invoked. This


interface must be an extension of the API interface Remote
(java.rmi). The interface should be developed in the local as well as
in the remote machine.

 Develop a class that implements this interface and extends the API
class UnicastRemoteObject (java.rmi.server) in the remote
machine. This class facilitates export of object from the remote
machine to the local machine. A public default constructor in this
class is mandatory.

 Develop a class in the remote machine that creates an object of the


class that implements the method interface and registers this object
with the rmi registry using bind method or rebind method of the
Naming class.
RMI application

 Develop a class inside the local machine that looks for the desired
service using lookup method of the Naming class.

 Create the class files from the source files in the local & remote
machine.

 Create the stub and skeleton using at the command prompt:


rmic –v1.1 ClassName_That_Implements_Interface

 start rmiregistry

 start java ClassName_That_Registers_Object_With_RMIRegistry

 java Addition
References

 Thinking in Java, Bruce Eckel

 java.sun.com

 Core Java Volume II by Horstmann & Cornell


Java Database Connectivity (JDBC)

JDBC is a collection of classes & interfaces (java.sql) for accessing SQL


database from Java program.

In 1995, Sun tried to expand the Java library for accessing SQL
database.

In 1996, they came out with two group of interfaces namely, JDBC API
and JDBC driver API.

A database driver allows a program to talk to a database.

The JDBC driver manager (written in pure Java) manages the database
drivers.
JDBC

For connecting to different database management systems you need


different drivers. e.g the driver for connecting to Oracle database has
the name
com.oracle.jdbc.OracleDriver
For connecting to Microsoft access database use the driver
jdbc.odbc.JdbcOdbcDriver

For connecting to MySQL database use the driver com.mysql.jdbc.Driver

Each new connection needs the driver to be loaded.

For loading the driver use the following code


Class.forName(“driver class file”);

public static Class forName(String className) throws


ClassNotFoundException @Class class
JDBC

For connecting to database use the following code

Connection conn =
DriverManager.getConnection(“protocol:subprotocol:data source
name”, “user”, “pwd”);

 public static Connection getConnection(String url, String user,


String password) throws SQLException
@DriverManager class
Attempts to establish a connection to the given database URL.

url = protocol:subprotocol:dsn
DriverManager class is declared in java.sql
Connection is an interface declared in java.sql
JDBC

For connecting to MySQL database use


Connection conn =
DriverManager.getConnection(“jdbc:mysql://host/dbname”, “user”,
“pwd”);
For connecting to Oracle database use
Connection conn =
DriverManager.getConnection(“jdbc:oracle://host/dbname”, “user”,
“pwd”);
For connecting to access database use
Connection conn =
DriverManager.getConnection(“jdbc:odbc://host/dbname”, “user”,
“pwd”);
JDBC

For executing query on the database use the following code

Statement stmt = conn.createStatement( );


ResultSet rs = stmt.executeQuery(“select ename, sal from emp where
sal > 30000”);
while( rs.next( ))
System.out.println(rs.getString( “ename”) + “ “ + rs.getDouble(“sal” ) );

Statement is an interface (java.sql), so also ResultSet.


The next( ) method of ResultSet returns false when there is no more
row in the cursor rs.
The getXXX method of ResultSet is used to retrieve the value at the
column. You may use column name or column number.
JDBC

Statement interface

 public ResultSet executeQuery(String sql) throws SQLException


Executes the given SQL statement, which returns a single ResultSet
object.

 public int executeUpdate(String sql) throws SQLException


Executes the given SQL statement, which may be an INSERT,
UPDATE, or DELETE statement or an SQL DDL statement.
 boolean execute(String sql) throws SQLException
Executes the given SQL statement (SQL query/ DDL /DML
statement)
JDBC

Connection interface

 public Statement createStatement() throws SQLException


Creates a Statement object for sending SQL statements to the
database.
 public PreparedStatement prepareStatement(String sql) throws
SQLException
Creates a PreparedStatement object for sending parameterized
SQL statements to the database.
 public void commit() throws SQLException
 public void rollback() throws SQLException
 public void close() throws SQLException
JDBC

PreparedStatement interface (A sub interface of Statement interface)


 public ResultSet executeQuery() throws SQLException
Executes the SQL query in this PreparedStatement object and
returns the ResultSet object generated by the query.

 public int executeUpdate() throws SQLException


Executes the SQL statement in this PreparedStatement object,
which must be an SQL INSERT, UPDATE or DELETE statement;
or a DDL statement.
JDBC

 public boolean execute() throws SQLException


• Executes the SQL statement in this PreparedStatement
object, which may be any kind of SQL statement.

You will find setXxx(int index, Xxx value) methods that assign a
value to a parameter.
If the parameter is of type int then use
setInt method, if it is of type double then use setDouble method.
JDBC

ResultSet interface
 public boolean next() throws SQLException
 public String getString(int colindex) throws SQLException
 public String getString(String colName) throws SQLException
 public int getInt(int colindex) throws SQLException
 public int getInt(String colName) throws SQLException
 public double getDouble(int colindex) throws SQLException
 public double getDouble(String colName) throws SQLException
 public float getFloat(int colindex) throws SQLException
 public float getFloat(String colName) throws SQLException
JDBC

If the query is of the form


Select ename, sal from emp where sal > ? and deptno = ?
then use PreparedStatement object as shown below:

Class.forName(“driver class file”); //load driver


Connection conn = //connect to database
DriverManager.getConnection(“protocol:subprotocol:data source
name”, “user”, “pwd”);
PreparedStatement pstmt = conn.prepareStatement(“Select ename, sal
from emp where sal > ? and deptno = ?”);
pstmt.setDouble(1, user_input);
pstmt.setInt(2, user_input);
ResultSet rs = pstmt.executeQuery( );
//iterate through rs
JDBC

DML statement

Load the driver, connect to database,


Statement stmt = conn.createStatement( );
stmt.executeUpdate(“update emp set…”);
//stmt.execute(“update emp set…”); you could also write this

For parameterized SQL statement use PreparedStatement object:


PreparedStatement pstmt = conn.prepareStatement(“DML
statement” );
pstmt.setXXX(1, value1); pstmt.setXXX(2, value2);
pstmt.executeUpdate( );
JDBC

DDL statement

Load the driver, connect to database,


Statement stmt = conn.createStatement( );
stmt.executeUpdate(“create table …”);
//stmt.execute(“create table …”); you could also write this

For parameterized SQL statement use PreparedStatement object:


PreparedStatement pstmt = conn.prepareStatement(“DDL statement” );
pstmt.setXXX(1, value1); pstmt.setXXX(2, value2);
pstmt.executeUpdate( );
JDBC

 You may create & execute stored procedure & functions


 You may create triggers in the database
 You may manipulate meta data (result set meta data & database
meta data)
References

 Thinking in Java, Bruce Eckel

 java.sun.com

 Core Java Volume II by Horstmann & Cornell


QUIZ III
Scheduled on
April 12, 2010

Portions
Multithreaded programming
Java I/O
QUIZ IV
Scheduled on
April 19, 2010

Portions
Java Networking
JDBC
RMI
Console-based program vs. Window-based program

A console-based program can prompt its user for input but a window-
based program cannot. All window-based programs are event-driven.
When there is no event it waits for an event to occur. Whenever an
event occurs, the program catches the event, takes necessary actions
and immediately returns control to the runtime system. It cannot keep
control with itself for a prolonged interval. This is why if you want a
window-based program to do a job repeatedly (e.g. animation) then
you
need to run an additional thread of execution.
Applets

Definition
An applet is a window-based small program that can run inside a
browser / appletviewer.

 Applets cannot run independently.


 They do not require main methods.
 They are downloaded from the Internet onto client machine,
automatically installed and execute in the client machine.
Applets

Applets are safe and secure because


(i) they cannot access the file system of the client machine and
(ii) cannot establish network connection with any host other than the
one they are downloaded from.
Applets

Applets are event driven. Whenever an event occurs, applet catches


the event, take necessary actions and immediately return control to the
runtime system. It cannot keep control with itself for a prolonged
interval. This is why if you want an applet to do a job repeatedly (e.g.
animation) then you need to run an additional thread of execution.
Applets

Every applet that you develop must a sub class of Applet class
(java.applet) and this class must be declared public

e.g.
pubic class Applet1 extends Applet {
Body of the class

}.
Applets

Object

Component

Container

Panel

Applet

A panel is a surface without border and title bar


Component class

 Component class (java.awt)

 public void setBackground(Color c)


This method changes the back ground color of this component.

 public void setForeground(Color c)


This method changes the fore ground color of this component.

 public Color getBackground( ), public Color getForeground( )

The Color class is in the package java.awt.

The default back ground color of a component is light grey and fore
ground color is black.
Component class

 public void paint(Graphics g)


Draws this component.
The Graphics class is in the package java.awt & it provides
graphical context.

 public void update(Graphics g)


Redraws this component. In its default implementation it calls paint
method.
Component class

 public void repaint( )


redraws this component, calls update which in turn calls paint
method.

 public void repaint(int top, int left, int w, int h)


draws a portion of this component defined by the top left corner and
the width and height.

 public void repaint(long ms)


ms is the delay that can be tolerated before update is called and if
update is not called by ms milliseconds then it is not called at all this
time.

 public void repaint(long ms, int top, int left, int w, int h)
Component class

 public void setFont(Font f)


Changes the font of text displayed on this component.

e.g. Font f = new Font(“Verdana”, Font.BOLD | Font.ITALIC, 16);


this.setFont(f);
Applet class

 public Applet( )

 public void init( )


initialize the applet, method is called by the browser or the
appletviewer only once when the applet class file is loaded.

 public void start( ) starts or resumes execution of the applet

 public void stop( ) suspends the execution of the applet.

Start and stop may be called more than once.


If you minimize the applet window then the stop method is called and
when you maximize the applet window the start method is called.
Applet class

 public void destroy( )


removes the applet from the client`s memory. Before destroy is
called stop is called.

 public void showStatus(String msg)


displays the msg in the status bar of the browser/appletviewer.

 URL getCodeBase( )
returns the base directory of the applet class file.

 URL getDocumentBase( )
returns the URL of the document in which this applet is embedded.
Applet class

 String getAppletInfo( )
returns the author`s name, version etc. of the applet. The
default implementation returns null.

 String getParameter(“param name”)

 void showDocument(URL url)


requests the browser to display the document whose URL is
passed as an object.
This method does not work with applet viewer.
If it cannot show the document then no exception is thrown.
Applet class

AppletContext getAppletContext( )
returns the context the applet is running.

Image getImage(URL url)
Returns an Image object that can then be painted on the screen. The
url that is passed as an argument must specify an absolute URL.

• AudioClip getAudioClip(URL url)
– Returns the AudioClip object specified by the URL argument.
• void play(URL url)
– Plays the audio clip at the specified absolute URL
Applet tag

In its simplest form


<applet code = appletClassFile width = … height = … > </applet>

Detail of applet tag


<applet code = appletClassFile width = … height = …
codebase = baseDirectory hspace = no of pixels vspace = no of pixels
align = MIDDLE| LEFT | RIGHT | TOP | BOTTOM | TEXTTOP
alt =”text” name = “appletname” >
<param name = name1 value = value1>
<param name = name2 value = value2>

<param name = namen value = valuen>

</applet>
Applet tag

In case the browser is Java enabled but currently cannot display the
applet then the alternate text (alt) is displayed.

The attribute name is used for communication among applets running


in the same context.
Abstract Window Toolkit (AWT)

AWT is a collection of classes and interfaces for developing GUI.

Component

Container

Panel Window

Applet Frame Dialog

A window is a surface without title bar and without border.


One window cannot be attached to another window.
AWT

Component

Label Button Checkbox List Choice Scrollbar TextComponent

TextField TextArea
Label class

Label( )
Label(String text)
Label(String text, int align)
Value of align may be Label.LEFT, Label.RIGHT, Label.CENTER

String getText( )
void setText(String newText)
int getAlignment( )
void setAlignment(int align)
Button class

Button( )
Button(String caption)

String getLabel( )
void setLabel(String caption)
Checkbox class

Checkbox(String label)
Checkbox(String label, boolean checked)
Checkbox(String label, boolean checked, CheckboxGroup cbg)
Checkbox(String label, CheckboxGroup cbg, boolean checked)

boolean getState( )
void setState(boolean checked)
String getLabel( )
void setLabel(String label)
Choice class

Represents a pop-up menu


Choice( ) creates an empty list of items.
To add item to the list
void add(String item) void add(String item, int index)
Other methods
String getSelectedItem( ) int getSelectedIndex( )
String getItem(int index) int getItemCount( )
void select(int pos) void select(String item)
void insert(String item, int index) void remove(String item)
void remove(int index) void removeAll( )
Choice class

The following code example produces a pop-up menu:


Choice colorChooser = new Choice();
colorChooser.add("Green");
colorChooser.add("Red");
colorChooser.add("Blue");
List class

List class
The List component presents the user with a scrolling list of text items.
The list can be set up so that the user can choose either one item or
multiple items.
List( )
List(int numRows) no. of rows visible at any time.
List(int numRows, boolean multiselect)
e.g.
List lst = new List(2, false);
lst.add("Mercury");
lst.add("Venus");
lst.add("Earth");
lst.add("JavaSoft");
List class

void add(String item)


void add(String item, int index)
String getSelectedItem( )
String getSelectedIndex( )
String [ ] getSelectedItems( )
String [ ] getSelectedIndexes( )
int getItemCount( )

And other methods similar to the methods of Choice class


TextField class

An object of this class is a single-line edit control.


TextField( ) blank field of 20 columns
TextField(int numChars)
TextField(String text)
TextField(String text, int numChars)

String getText( ) void setText(String text)


void setEditable(boolean editable)
boolean isEditable( ) returns true if you can write text in the text field.
void setEchoChar(char ch) boolean echoCharIsSet( )
char getEchoChar( ) retrieves the echo character.
String getSelectedText( )
TextArea class

An object of this class is a multi line edit control.

TextArea( )
TextArea(String text)
TextArea(int numlines, int numChars)
TextArea(String text, int numlines, int numChars, int sbars)
sbars = TextArea.SCROLLBARS_BOTH
= TextArea.SCROLLBARS_NONE(default)
= TextArea.SCROLLBARS_HORIZONTAL_ONLY
= TextArea.SCROLLBARS_VERTICAL_ONLY
TextArea class

String getText( ) void setText(String text)


void append(String) void insert(String text, int pos)
void replace(String str, int si, int ei);
Scrollbar class
HORIZONTAL, VERTICAL
Scrollbar( )
Scrollbar(int style) Scrollbar.HORIZONTAL, ScrollBar.VERTICAL
Scrollbar(int style int initValue, int thumbSize, int min, int max)

int getMinimum() int getMaximum( ) int getValue( ) void setValue( )


void setUnitIncrement( int newValue)
void setBlockIncrement(int newValue)

e.g.Scrollbar sb = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 300);


Frame class

A Frame object is a surface with border and title bar.

Frame( ) Frame(String title)

A Frame object is a container and so it can hold components.

A code example:
Window class

A window is a surface without border and title bar.

Window(Frame owner)

A code example:
Panel class

An object of this class is a surface without border and without title bar.

Panel( )

Panel(LayoutManager lm)
creates a panel with the specified layout manager.
Layout Managers

Layout Managers lay out the components inside a container using


algorithms.

There are different types of layout namely, flow layout, border layout,
grid layout, card layout and these are implemented in
FlowLayout, BorderLayout, GridLayout, CardLayout classes
respectively.

Each of these classes is an implementation of LayoutManager


interface.
FlowLayout class

The flow layout manager lays out components from left to right and top
to bottom.
The default spacing between components is 5 pixels (both horizontal
and vertical direction).

FlowLayout( )

FlowLayout(int how)
how = FlowLayout.CENTER, FlowLayout.LEFT, FlowLayout.RIGHT

FlowLayout(int how, int hgap, int vgap)


– hgap - the horizontal gap between components and between the
components and the borders of the Container
– vgap - the vertical gap between components and between the
components and the borders of the Container
BorderLayout class

This layout manager lays out components at 5 different regions – one


large area at the center and four narrow fixed-width regions at the
edges of the container.
BorderLayout class

BorderLayout( )
BorderLayout(int hgap, int vgap)
GridLayout class

This layout manager lays out components in an invisible grid inside the
container.

GridLayout( )
GridLayout(int numRows, int numCols)
GridLayout(int numRows, int numCols, int hgap int vgap)
Changing layout of a container

The default layout of a frame and window is border layout.


The default layout of an applet and a panel is flow layout.

To alter the layout manager of a container, use


public void setLayout(LayoutManager lm) @ Container class.
Adding component to a container

To add component to a container use one of the methods:

public Component add(Component cmp) @ Container class.

public Component add(Component cmp, int pos)


@ Container class
A case study
Event handling

An event is an object that describes change of state of a source.


A source is an object that can fire an event.
A listener is an object that can receive event.

In order that a listener can receive an event fired by a source it must


registers itself with the source. After receiving event notification the
event handler handles the event and returns control to the runtime
system.

The event handling facilities are found in the package java.awt.event.


Delegation event model

In this model, a source fires an event and sends it to one or more


listeners.
The listener waits until it receives an event.
Once received, the listener processes the event and then returns.
The advantage of this design is that the application logic that
processes
the event is cleanly separated from the user interface logic that
fires the event.
A user interface element is able to delegate the processing of event to
a separate piece of code.
A listener must registers with a source in order to receive an event
notification and thus notifications are sent only to listeners that want to
receive them.
Event handling

When you click on a button an ActionEvent is fired.


The event handler (method that processes the event) is

public void actionPerformed(ActionEvent ae)


@ ActionListener interface.

To register a listener with a button use the method


public void addActionListener(ActionListener al)

e.g. b1. addActionListener(al);


Event handling

If you click on a check box an ItemEvent is fired.

The method that can handle the event is


public void itemStateChanged(ItemEvent ie)
@ ItemListener interface

The registration method is


public void addItemListener(ItemListener il).
Event handling

 If you click (single) on a choice item an ItemEvent is fired

 If you double click on a list item an ActionEvent is fired.

 If a text field has input focus and if you press the enter key then
ActionEvent is fired.
Event handling

When you edit a text field or a text area then TextEvent is fired.

The method that handles the event is


public void textValueChanged(TextEvent te)
@ TextListener interface

The method that performs the registration is


public void addTextListener(TextListener tl).
Event handling

When you manipulate a scroll bar an AdjustmentEvent is fired

The event handler is


public void adjustmentValueChanged(AdjustmentEvent ae)

The registration method is


public void addAdjustmentListener(AdjustmentListener al).
Handling key events

A KeyEvent is fired when you press/release/type a key.

The event handlers are


public void keyPressed(KeyEvent ke)
public void keyReleased(KeyEvent ke)
public void keyTyped(KeyEvent ke)
@KeyListener interface.

The registration method is


public void addKeyListener(KeyListener kl)
KeyEvent class

Some of the useful methods declared in the KeyEvent class are

int getKeyCode( ) returns an integer associated with the key

char getKeyChar( ) returns the character associated with the key


(character echoed) . If there is no character associated with the key
then CHAR_UNDEFINED us returned.

For each key there is defined a public static final identifier in the
KeyEvent class and name of these identifiers starts with VK (virtual
key) e.g. VK_A, VK_B, VK_SHIFT
Adapter class

If a listener interface has multiple methods (e.g. KeyListener interface


has 3 methods – keyPressed, keyReleased, keyTyped) then you find
an adapter class for the interface.

An adapter class is a default implementation of listener interface.

If you are implementing the KeyListener interface then you need to give
the definition of all the methods (even an empty definition is
mandatory).

If you use adapter class you don`t have to define all the methods of the
interface.
Adapter class

The adapter class for the KeyListener interface is KeyAdapter.

Code example:

//listener registration
addKeyListener(new KeyAdapter( ) {
public void keyTyped(KeyEvent ke) {
//code
}
}
);
Mouse event

A MouseEvent is fired when a mouse is


clicked/pressed/released/enters a component/exits from a
component/moved/dragged.
The event handling methods are
public void mouseClicked(MouseEvent me)
public void mousePressed(MouseEvent me)
public void mouseReleased(MouseEvent me)
public void mouseEntered(MouseEvent me)
public void mouseExited(MouseEvent me)

@MouseListener interface
Mouse event

Two other event handling methods are


public void mouseMoved(MouseEvent me)
public void mouseDragged(MouseEvent me)

@MouseMotionListener interface

The methods that registers a listener to receive mouse event are


public void addMouseListener(MouseListener ml)
public void addMouseMotionListener(MouseMotionListener ml)
Adapter class

The adapter class

for MouseListener is MouseAdapter


for MouseMotionListener is MouseMotionAdapter
Window event

A window event is fired when a window is


iconified/deiconified/opened/cloded/closing/activated/deactivated/
gain focus/lost focus.
The WindowEvent class encapsulates window event. The event
handling methods are

public void windowIconified(WindowEvent we)


public void windowDeiconified(WindowEvent we)
public void windowOpened(WindowEvent we)
public void windowClosed(WindowEvent we)
public void windowClosing(WindowEvent we)
@ WindowListener interface
Window event

public void windowGainedFocus(WindowEvent we)


public void windowLostFocus(WindowEvent we)
@ WindowFocusListener interface

To find the order in which the event handling methods are called
include an output message in each of the event handling methods.

The registration methods are


addWindowListener(WindowListener wl)
addWindowFocusListener(WindowFocusListener wfl)
Adapter classes

WindowAdapter for WindowListener


WindowFocusAdapter for WindowFocusListener
Dismissing a frame using closing button

//registration
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose( );
}
}
);
Menu bar, menus, menu items & check box menu items

MenuCompnent

MenuBar MenuItem

Menu CheckboxMenuItem

Since Menu class is a sub class of MenuItem class so a hierarchy of


nested sub menus can be created.
Menu bar, menus, menu items & check box menu items

MenuBar( )
e.g.MenuBar mbar = new MenuBar( );

Menu( )
Menu(String label)
Menu(String label, boolean tearOff)
e.g. Menu menu = new Menu(“Draw’);

MenuItem( )
MenuItem(String label)
MenuItem(String label, MenuShortcut keyAccel)
Menu bar, menus, menu items & check box menu items

MenuShortCut(int key)
MenuShortCut(int key, boolean shiftRequired)
e.g. MenuItem item =
new MenuItem(“Line”, new MenuShortcut(KeyEvent.VK_L, true)

CheckboxMenuItem( )
CheckboxMenuItem(String label)
CheckboxMenuItem(String label, boolean checked)

For adding a MenuItem object to a Menu object use


MenuItem add(MenuItem item) @ Menu class
Adds the item to this Menu object.
e.g.menu.add(item1)
Menu bar, menus, menu items & check box menu items

For adding Menu object to the menu bar object use


Menu add(Menu menu) @ MenuBar class
Appends menu to this MenuBar object.
e.g. mbar.add(menu);

For adding menu bar to the container use


void setMenuBar(MenuBar mbar) @ Frame class
e.g. setMenuBar(mbar); adds mbar to this object
Menu bar, menus, menu items & check box menu items

Create menu items (and check box menu items).


Add these items to the menu object.
Add menu object to menu bar object.
Add men u bar object to the container.

When user clicks on a menu item an ActionEvent is fired.


When user clicks on a check box menu item an ItemEvent is fired.

You might also like