Sunteți pe pagina 1din 384

Arrays

Arrays in Java
Arrays in java are objects which belongs to class Array.
Array objects implements only static arrays. i.e once you
create an array, its length is fixed. User can not change the
length after array creation.
Java follows strict bound checking for referencing array
elements. If an attempt is made to reference the elements
outside the bounds then
ArrayIndexOutOfBoundsException will be thrown at run
time.
Array elements can be referenced from 0 as LB to length-1
as UB.
Java also follows strict type checking for Array elements. If
an attempt is made to store the elements of another type
then ArrayStoreException will be thrown at run time.
Length is the attribute of each array which can be
referenced by
<arrayreference> . <length>

Arrays in Java continued.


Syntax : One-Dimensional Arrays :
type[ ] arrayname = new type[size];
or
type arrayname[ ] = new type[size];
Examples :
1. int[ ] marks = new int[10];
marks is an int array, length = 10 LB index =0 , UB index = 9
2. float[ ] values = new float[20];
values is an float array, length = 20 LB index =0 , UB index =1 9
3. double cgpa[ ] = new double[5];
cgpa is double array, length = 5 LB index =0 , UB index = 4
4. box[ ] b = new box[20];
Array of Objects
b is a box array, length = 20 LB index =0 , UB index = 19
5. point points[ ] = new point[20];
points is a point array, length = 20 LB index =0 , UB index =19

Arrays in Java continued.


Syntax : Two-Dimensional Arrays :
type[ ][ ] arrayname = new type[row_size][col_size];
or
type arrayname[ ][ ] = new type[row_Size][col_Size];
row index varies from 0 to row_size 1
column index varies from 0 to col_size 1

Examples
(Two Dimensional Arrays)
1. int[ ][ ] data = new int[3][3];
data is 2-D int an array, row index 0 to 2 , col index 0 to 2

2. float values[][] = new float[10][4];


values is 2-D float array, row index 0 to 9 , col index 0 to 3

3. int table[][] = {{ 0,0,0},{1,1,1}};


// 2 by 3 Array. Initializes first row to 0 & second to 1
4. Variable Size Array:
int x[][] = new int[3][];
x[0] = new int[2];
x[1] = new int[4];
x[2] = new int[3];

Examples
int a[] = { 10,8,6};
for(int
i=0;i<a.length;i++)
System.out.println(a[i
int a[3] = { 10,8,6};
]);
for(int
i=0;i<a.length;i++)
System.out.println(a[i]
//int
); table[][]={0,0,0,1,1,1};
//int table[2][3]={0,0,0,1,1,1};
int table[ ][ ]={{0,0,0},{1,1,1}};
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(table[i][j]);}
System.out.println();
}

10
8
6

WRONG

']' expected
int a[3] = { 10,8,6};
^
1 error

000
111

A Brief Look at the Arrays class


1. Arrays class in java.util package is defined as follows
public class Arrays extends Object
2. This class contains all the methods required for manipulating arrays such
as sorting and seraching
3. The methods in this class all throw a NullPointerException if the specified
array reference is null.

4. This class is member of Javas Collection Framework.

Important Methods of Arrays class


static int binarySearch(byte[] a, byte key)
static int binarySearch(char[] a, char key)
static int binarySearch(double[] a, double key)
static int binarySearch(float[] a, float key)
static int binarySearch(int[] a, int key)
static int binarySearch(long[] a, long key)
static int binarySearch(Object[] a, Object key)
static int binarySearch(Object[] a, Object key, Comparator c)
static int binarySearch(short[] a, short key)

Important Methods of Arrays class cont


static boolean

equals(boolean[] a, boolean[] a2)

static boolean

equals(byte[] a, byte[] a2)

static boolean

equals(char[] a, char[] a2)

static boolean

equals(double[] a, double[] a2)

static boolean

equals(float[] a, float[] a2)

static boolean

equals(int[] a, int[] a2)

static boolean

equals(long[] a, long[] a2)

static boolean

equals(Object[] a, Object[] a2)

static boolean

equals(short[] a, short[] a2)

Important Methods of Arrays class cont..


static void
static void
static void
static void
static void
static void
static void
static void
static void

fill(boolean[] a, boolean val)


fill(boolean[] a, int fromIndex, int toIndex,
boolean val)
fill(byte[] a, byte val)
fill(byte[] a, int fromIndex, int toIndex, byte val)
fill(char[] a, char val)
fill(char[] a, int fromIndex, int toIndex,
char val)
fill(double[] a, double val)
fill(double[] a, int fromIndex, int toIndex,
double val)
fill(float[] a, float val)

Important Methods of Arrays class cont


static void
static void
static void

static void
static void
static void

static void
static void
static void

fill(float[] a, int fromIndex, int toIndex,


float val)
fill(int[] a, int val)
fill(int[] a, int fromIndex, int toIndex,
int val)
fill(long[] a, int fromIndex, int toIndex,
long val)
fill(long[] a, long val)
fill(Object[] a, int fromIndex, int toIndex,
Object val)
fill(Object[] a, Object val)
fill(short[] a, int fromIndex, int toIndex,
short val)
fill(short[] a, short val)

Important Methods of Arrays class cont..


static void
static void
static void
static void
static void
static void
static void
static void
static void
static void

sort(byte[] a)
sort(byte[] a, int fromIndex, int toIndex)
sort(char[] a)
sort(char[] a, int fromIndex, int toIndex)
sort(double[] a)
sort(double[] a, int fromIndex,
int toIndex)
sort(float[] a)
sort(float[] a, int fromIndex,
int toIndex)
sort(int[] a)
sort(int[] a, int fromIndex,
int toIndex)

Important Methods of Arrays class


static void

sort(long[] a)

static void

sort(long[] a, int fromIndex, int toIndex)

static void

sort(Object[] a)

static void

sort(Object[] a, Comparator c)

static void

sort(Object[] a, int fromIndex, int toIndex)

static void

sort(Object[] a, int fromIndex, int toIndex, Comparator c)

static void

sort(short[] a)

static void

sort(short[] a, int fromIndex, int toIndex)

Array Method Examples


import java.util.*;

Import java.util package to use


Arrays class

class ArrayExample
{
public static void main(String args[])
{
int x[] = {10,6,8,20};
int array Size = 4 LB=0 UB =3
double data[] = { 12.5,34.6,90.56,12.34,12.56};
double array Size = 5 LB=0 UB =4
float values[] = { 10.45f,23.56f,12.67f};
float arrays Size = 3 LB=0 UB =2
double data1[] = new double[10];
double array Size = 10 LB=0
UB =9
boolean flags[] = new boolean[5];
boolean array Size = 5 LB=0 UB =4
int x1[] = {10,6,8,20}; int array Size = 4 LB=0 UB =3

System.out.println(Arrays.binarySearch(x,20));
Arrays.sort(x);
for(int i=0;i<x.length;i++)
System.out.print(x[i]+" ");
System.out.println();

Prints index of 20 in x
Sorts elements of x
Prints Elements of x
6 8 10 20

Arrays.fill(data1,12.56);
for(int i=0;i<data1.length;i++)
System.out.print(data1[i]+" ");
System.out.println();

Fills a single value


12.56 in all indexes of
data1
Prints Elements of
data1

12.56 12.56 12.56 12.56 12.56 12.56 12.56 12.56 12.56 12.56

Arrays.fill(flags,2,5,true);
//Arrays.fill(flags,2,6,true);
for(int i=0;i<flags.length;i++)
System.out.print(flags[i]+" ");
System.out.println();

Fills true value in boolean


array flags from index 2 to
4
ArrayIndexOutOfBoundsEx
ception
false false true true true

System.out.println(Arrays.equals(x,x1));

Arrays.sort(values);
for(int i=0;i<values.length;i++)
System.out.print(values[i]+" ");
System.out.println();
}
} // End of class

Prints true or false whether


x and x1 equals false
10.45 12.67 23.56

OUTPUT

D:\java\bin>java ArrayExample
3
6 8 10 20
12.56 12.56 12.56 12.56 12.56 12.56 12.56 12.56 12.56 12.56
false false true true true
false
10.45 12.67 23.56

Exercise 1:
class Matrix
{
private int ROWS;
private int COLS;
double values[][];
Matrix(int r,int c) { . }
// Provide Accessor Marks for getting a element, all elements of a
a given row, all elements of a given column
// Provide Mutator methods for the same
Matrix add(Matrix other) { .. }
static Matrix add(Matrix first, Matrix second) { }
// Supply operations for multiplication as well as subtraction
// Methods for matrix equality (static flavor also)
// Transpose of a matrix
// boolean isTranspose(Matrix other) returns true if other is transpose
of this matrix
}

class Matrix {
private int ROWS;
private int COLS;
double values[][];
Matrix(int r,int c) {
values = new double[r][c];
ROWS=r;
COLS=c;
}
double getElement(int r, int c)
{
return values[r][c];
}
double [] getRow(int r)
{
return values[r];
}
double[] getColumn(int c)
{ double arr[]= new
double[ROWS];
for(int i=0;i<ROWS;i++)
arr[i]=values[i][c];
return arr;
}

void setElement(int r,int


c,double d)
{
values[r][c]= d;
}
void setRows(int r,
double row[])
{
for(int
i=0;i<row.length;i++)
values[r][i]=row[i];
}
void setColumn(int c,
double column[])
{
for(int
i=0;i<column.length;i++)
values[i][c]=column[i];
}

Matrix add(Matrix other)


{ Matrix extra= new Matrix(2,3);

for(int r=0;r<ROWS;r++)
for(int c=0;c<COLS;c++)
extra.values[r][c]=
other.values[r][c]+values[r][c];
return extra;
}
static Matrix add(Matrix first, Matrix
second)
{Matrix extra= new Matrix(2,3);
for(int r=0;r<first.ROWS;r++)
for(int c=0;c<first.COLS;c++)
extra.values[r][c]= first.values[r][c]+
second.values[r][c];
return extra;
}

boolean isEquals(Matrix other)


{
for(int r=0;r<ROWS;r++)
for(int c=0;c<COLS;c++)
if(other.values[r][c] != values[r][c])
return false;
return true;
}
static boolean isEquals(Matrix first,
Matrix second)
{
for(int r=0;r<first.ROWS;r++)
for(int c=0;c<first.COLS;c++)
if(first.values[r][c] !=
second.values[r][c])
return false;
return true;
}

double [][] transponse()


{ double tran[][]= new double[ROWS][COLS];
for(int r=0;r<ROWS;r++)
for(int c=0;c<COLS;c++)
tran[c][r] = values[r][c];
return tran;
}
boolean isTransponse(double tran[][],int row,int col)
{
for(int r=0;r<ROWS;r++)
for(int c=0;c<COLS;c++)
if(tran[c][r] != values[r][c])
return false;
return true;
}
void print()
{
for(int r=0;r<ROWS;r++)
for(int c=0;c<COLS;c++)
System.out.println(values[r][c]);
}

public static void main(String args[])


{
Matrix obj = new Matrix(2,3);
int i=0;
//obj.value[][]={1,2,3,4,5,6};
for(int r=0;r<obj.ROWS;r++)
for(int c=0;c<obj.COLS;c++)
obj.values[r][c]=i++;
obj.print();
double d[];
d=obj.getColumn(2);
System.out.println("Get Column");
for(i=0;i<d.length;i++)
System.out.println(d[i]);
}
} // end of class

Predict OutPut
int x[] = new int[10];
for(int i=0;i<x.length;i++)
System.out.print(x[i]+" ");

0000000000

boolean flags[] = new boolean[10];


for(int i=0;i<flags.length;i++)
System.out.print(flags[i]+" ");
false false false false false false false false false false
boolean flags[] = new boolean[10];
Arrays.fill(flags,2,8,true);
for(int i=0;i<flags.length;i++)
System.out.print(flags[i]+" ");
false false true true true true true true false false

boolean flags[] = new boolean[10];


Arrays.fill(flags,2,11,true);
for(int i=0;i<flags.length;i++)
System.out.print(flags[i]+" ");

Exception in thread "main"


java.lang.ArrayIndexOutOfBoundsException: Array index
out of range: 11
at java.util.Arrays.rangeCheck(Arrays.java:1325)
at java.util.Arrays.fill(Arrays.java:2213)
at ArrayExample2.main(ArrayExample2.java:7)

What is the output???


int a[]={1,2,3};
int b[]=a;
for(int c=0;c<a.length;c++)
System.out.println("A array
for(int c=0;c<a.length;c++)
System.out.println("b array
b[0]=2; b[1]=4; b[2]=6;
for(int c=0;c<a.length;c++)
System.out.println("A array
for(int c=0;c<a.length;c++)
System.out.println("A array

"+ a[c]);

"+ b[c]);

"+ a[c]);
"+ a[c]);

Exercise2:
class Student
{
private String name;
private String idno;
private double marks[ ][ ];
// Assume all accessor and mutator methods defined earlier

// Define a method which returns a Student with


highest total in all subjects
Student getStudentWithHighestScore(Student[] students)
{
.
}

// Define a method which returns a Student with highest total in


a given subject
Student getStudentwithSubjectHighest(Student[] students , int subject)
{
.
}

Todays Lecture

String

Strings in Java
1. strings in java are handled by two classes String &

StringBuffer

2. String -- Immutable class, StringBuffer - Mutable class


3. Constructors :
1. String()

<< Creates an Empty String >>

2. String(char chars[]) << Creates a String frorm char Array>>


3. String(char chars[],int start, int numChars)
<< Creates a String frorm char Array from start to start+numChars -1 >>

4. String(String x)
<< Creates a String frorm another String >>
5. String(byte bytes[]) << Creates a String frorm byte Array>>

6. String(byte bytes[],int start, int numChars)


<< Creates a String frorm byte Array from start to start+numChars -1 >>

String Examples
1. String s1 = Object OR String s1 = new String(Object);
2. String s1 = new String();
<< Empty String Created>>
3.
char[ ] names ={ O,B, J,E, C,T, ,O,R, I,E, N,T, E,D};
String s1 = new String(names); << s1 will be OBJECT ORIENTED>>
String s2 = new String(names,2,4); << s2 will be JECT>>
String s3 = new String(names,6,10);
<< StringIndexOutOfBoundsException>>
String s4 = new String(names,6,-4);
4.

<< s1 will be space byte[ ] values = { 10,45,67,34,68,66 };


C"DB>>
String s1 = new String(values);
String s2 = new String(values, 2,3); << s2 will be C"D>>
String s3 = new String(values,2,6);
<< StringIndexOutOfBoundsException>>
5.
String s1 = Object;
String s2 = new String(s1);
<< Creating String from another String>>

String Examples cont..


6. String s1 =OOP;
String s2 =OOP;
String s3 =OOP;

String:
s1

OOP

s2
s3

String Length
int length() << Returns the length of
String>>
Usage :
<string>.length();
Examples :
S.O.P(Object.length()); 6
s1.length();
name.length();

String Concatenation
Adding Strings together <<Concatenation>>
+ operator can be used to concatenate two strings

String concat(String other) method can also be used


Examples :
1. String s1 = Hello+How are You+20+20;
// s1 will be HelloHowareYou2020

2. String s2 = Object
String s3 = Programming
String s4 = s2 + s3 OR String s4 = s2.concat(s3);
3. System.out.println(xyz.concat(oop));
4. String s1 = 20+20+Hello+How are You;

// s1 will be 40HelloHowareYou

Extracting a Single Character from a String


char charAt(int where)

charAt() method extracts a character from a string at


a given index
<<where>> parameter should be within range (0 to
stringlength-1).
Otherwise StringIndexOutOfBoundsException will be thrown

Examples :
char ch = xyz.charAt(1); // ch will be y
char ch = xyz.charAt(3);
//StringIndexOutOfBoundsException

Extracting More than one character


getChars()
To Extract more than one character we can use getChars() method
Syntax:
void getChars (int sourceStart, int sourceEnd, char target[ ], int targetStart)

Start index in
End index in
char Array where
Invoking String Invoking String characters from
string are to be
Start index in char
stored
Array from where
the characters are
1. characters will be extracted from sourceStart
to be stored
to sourceEnd-1
2. Extracted Characters will be stored in target[]
char array from index targetStart
3. Every index either in invoking or target string
should be within specified limits

getChars() Example 1

class StringExamples
{
public static void main(String args[])
{
String s1="object oriented";
char[] name = new char[10];

s1.getChars(2,6,name,0);
for(int i=0;i<name.length;i++)
System.out.print(name[i]+" ");
System.out.println(" ");

char[] name1 = new char[10];

s1.getChars(5,8,name1,3);
for(int i=0;i<name.length;i++)
System.out.print(name1[i]+" ");
}
}

D:\java\bin>java StringExamples
ject
t o

getChars() Example 2
class StringExamples
{
public static void main(String args[])
{
String s1="object oriented";
char[] name = new char[10];

s1.getChars(6,2,name,0);
for(int i=0;i<name.length;i++)
System.out.print(name[i]+" ");
System.out.println(" ");
char[] name1 = new char[10];

s1.getChars(8,5,name1,3);
for(int i=0;i<name.length;i++)
System.out.print(name1[i]+" ");
}
}

D:\java\bin>java StringExamples
Exception in thread "main"
java.lang.StringIndexOutOfBoundsExce
ption: String in
ex out of range: -4
at
java.lang.String.getChars(String.java:72
4)
at
StringExamples.main(StringExamples.ja
va:8)

getChars() Example 3
class StringExamples
{
public static void main(String args[])
{
String s1="object oriented";
char[] name = new char[10];

s1.getChars(0,13,name,0);
for(int i=0;i<name.length;i++)
System.out.print(name[i]+" ");
System.out.println(" ");
char[] name1 = new char[10];

s1.getChars(0,5,name1,3);
for(int i=0;i<name.length;i++)
System.out.print(name1[i]+" ");
}
}

D:\java\bin>java StringExamples
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsE
xception
at
java.lang.System.arraycopy(Native
Method)
at
java.lang.String.getChars(String.jav
a:726)
at
StringExamples.main(StringExampl
es.java:8)

String to byte Arrays

getBytes[]

Useful when exporting a String values to


8-bit ASCII code.
class StringExamples
{
public static void main(String args[])
{

String s1="object oriented";


byte[] values = s1.getBytes();
for(int i=0;i<values.length;i++)
System.out.print(values[i]+" ");
}
}
D:\java\bin>java StringExamples
111 98 106 101 99 116 32 111 114 105 101 110 116 101 100

String to character Arrays

toCharArray[ ]

Coverts a string to an character array


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

String s1="object oriented";


char[ ] values = s1.toCharArray();
for(int i=0;i<values.length;i++)
System.out.print(values[i]+" ");
}
}
D:\java\bin>java StringExamples
object oriented

String Comparisons
boolean equals(Object str)
boolean equalsIgnoreCase(String str)
Examples :
(i) xyz.equals(abc); << false>>
(ii) xyz.equalsIgnoreCase(XYZ) << true>
(iii) s1.equals(s2) << returns if s1 and s2 are equal>>
(iv) s1.equalsIgnoreCase(s2)
<< returns if s1 and s2 are equal by ignoring case>>

equals Vs ==
String s1 = new String(OOP);
String s2 = new String(OOP);
if (s1 == s2)
S.O.P(Hello);
else
S.O.P(Hi);

How Many Objects are created?


TWO
What will be output?
Hi

= = checks whether two string references are pointing to same


string object or not.

if (s1.equals(s2))
What will be output?
S.O.P(Hello);
Hello
else
S.O.P(Hi);
equals( ) checks whether contents of two strings.

equlas Vs == cont..
String s1 = new String(OOP);
String s2 = s1

How Many Objects are created?


ONE

if (s1 == s2)
S.O.P(Hello);
else
S.O.P(Hi);

What will be output?

if (s1.equals(s2))
S.O.P(Hello);
else
S.O.P(Hi);

What will be output?

Hello

Hello

int compareTo(String str)


int compareToIgnoreCase(String str)

Used for String comparisons. Returns one


of the three possible values:
<0 invoking string is less than str
>0 invoking string is greater than str
=0 if both strings are equal
Used for ordering/sorting strings

String Comparison Examples

String s1 = "OOP";
String s2 = "OOP";
String s3 = "java";

How Many Objects are created here?.


ONE

if( s1 == s2)
System.out.println("Hello");
else
System.out.println("Hi");
System.out.println(s1.compareTo(s3));
System.out.println(s3.compareTo(s1));

Hello
-27
27

Searching Strings

indexOf()
lastIndexOf()
Used searching first/last occurences of a character / substring
Return the index of character or substring if found otherwise -1
These two methods are overloaded in several different ways

1. int indexOf(int ch) / int lastIndexOf(int ch)


2. int indexOf(String str) / int lastIndexOf(String str)
3. int indexOf(int ch, int startIndex) / int lastIndexOf(int ch,
int startIndex)
4. int indexOf(String str,startIndex) / int lastIndexOf(String
str, int startIndex)

Example
String s1 = "Now is the time for all good men to come forward to aid their country";

System.out.println(s1.indexOf('t'));
System.out.println(s1.lastIndexOf('t'));

7
66

System.out.println(s1.indexOf("to"));
System.out.println(s1.lastIndexOf("to"));

33
49

System.out.println(s1.indexOf("to",35));
System.out.println(s1.lastIndexOf("to",35));

49
33

Extracting a SubString From String


1.
2.
3.

1.
2.
3.

String substring(int startIndex)


Returns a substring from invoking string starting form
startIndex up to last of the invoking string
I Love India.substring(7);
startIndex <= invoking string length 1.

String substring(int startIndex, int endIndex)


Returns a substring from invoking string starting form
startIndex up to endIndex-1
endIndex > startIndex and both should be within permitted
range.
I Love India.substring(2,6);

Complete the Constructor


class Course
{
private String courseNo;
private int compCode;
private String courseName;
Course(String courseString)
{
// courseString has first 10 places for courseNo
// Next 4 places for comp code
// Next 30 places for courseName
courseNo = courseString.substring(0,10);
compcode = Integer.parseInt(courseString.substring(10,14));
courseName = courseString.substring(14);
}
}

Character Replacement in a String

1.
2.

1.
2.
3.

String replace(char original, char replacement)


Replaces all occurences of one character with
replacement character in the invoking string
Hello.replace(l,w); << l with w>>
String trim()
Removes any leading and trailing whitespaces
Hello World .trim();
<< returns Hello World>>
Useful for processing user commands

Home Exercise

void sort(String[] arr, boolean isAscending)


void sort(String[] arr, int fromIndex, int toIndex, boolean
isAscending)

Changing Case of Characters Within a String

1.
2.

String toLowerCase()
String toUpperCase()
Examples :
S.O.P(object.toUpperCase());
S.O.P(OBJECT.toLowerCase());

boolean startsWith(String str)


boolean endsWith(String str)
Can be used to check whether a string starts/ends with a
string str or not
Examples :
object.startsWith(obj) << true>>
Indians love cricket.endsWith(cricket); << true>>
Second Form of startsWith allows to specify the starting
point:
boolean startsWith(String str, int startIndex);
Indians love cricket.startsWith(love,8); << true>>
endsWith has only one form and is not available in
boolean endsWith(String str, int startIndex);
It is case sensitive

Comparing Regions For matching


Used for comparing selected regions within strings.
Two Methods can be used:
1. boolean regionMatches(int startIndex, String str2,int str2StartIndex, int numChars)

Start index within invoking


String

Start index within str2 String

String with whom invoking string


will be matched

No of characters to be
matched

Comparing Regions For matching


2. boolean regionMatches(boolean ignorecase, int startIndex, String str2,int str2StartIndex, int
numChars)

<< Used When matching is to be done by ignoring case>>


True means case is ignored
False means case is not ignored. Same as previous
method

Region matches Examples


String s1 = It is time to start preparation for the incoming exams;
String s2 = Indian team will start preparation for the match;
String s3 = INDIAN TEAM WILL START PREPARATION FOR THE MATCH;

S1.regionMatches(4,s2,6,10); false
S1.regionMatches(14,s2,17,17); true
S1.regionMatches(14,s3,17,17); false
S1.regionMatches(true,14,s2,17,17); true

Substring Example
String s1 = "Now is the time for all good men to come forward to aid their country";

Index 20 to end

System.out.println(s1.substring(20));

all good men to come forward to aid their country


System.out.println(s1.substring(20,40));

Index 20 to 39

all good men to come


System.out.println("object oriented".substring(6));

oriented

Index 6 to end

System.out.println("object oriented".substring(5,10));

t ori

Index 5 to 9

StringTokenizer Class
This class is defined in
java.util.StringTokenizer;
It is used to extract token(words) from string.
Default delimiters are Space , Tab, newline and
carriage return.

StringTokenizer st = new StringTokenizer("this is a test");

this
is
a
test
BITS Pilani, Pilani Campus

StringTokennizer
Constructors
StringTokennizer(String str)
StringTokennizer(String str, String delimiters)

Each character in delimiter String is treated as a separate


delimiter.
StringTokennizer(String str, String delimiters, boolean
delimAsToken)
A provision is provided by which you can treat individual
delimiters as tokens.

BITS Pilani, Pilani Campus

Examples
String str = "BITS C342,83,Object Oriented Programming,Lecture Section
3;MWF 9,Sunita;Bansal,3160;

If Only Comma (,) is taken as delimiter:


NO OF TOKENS = 6
Tokens : { BITS C342} {83} {Object Oriented Programming} {Lecture
Section 3; MWF 9} {Sunita;Bansal} {3160}

If Only Semicolon (;) is taken as delimiter


NO OF TOKENS = 3
Tokens : ?

If Both Comma(,) and Semicolon (;) are taken as delimiters:


NO OF TOKENS = 8
Tokens : ?

Delimiters themselves are not taken as


Tokens
BITS Pilani, Pilani Campus

StringTokenizer
Methods
1. int countTokens()
Counts the number of tokens in StringTokennizer based upon
delimiters

2. boolean hasMoreTokens() / boolean hasMoreElements()


Helpful in parsing a String.
Returns true if there are one or more tokens left otherwise false.

3. String nextToken()
Returns the next token in String form

Used in conjunction with hasMoreTokens() method

4. Object nextElement()
Same as nextToken() but returns next Token in Object Form not in
String Form

BITS Pilani, Pilani Campus

Example-1
String str = "BITS C342,83,Object Oriented Programming,Lecture Section
3;MWF 9,Sunita;Bansal,3160";
StringTokenizer strT1 = new StringTokenizer(str);
// No Delimiters Specified
System.out.println("Number Of Tokens :"+strT1.countTokens());
System.out.println("Individual Tokens");
while(strT1.hasMoreTokens())
System.out.println(strT1.nextToken());

Number Of Tokens :7
Individual Tokens
BITS
C342,83,Object
Oriented
Programming,Lecture
Section
3;MWF
9,Sunita;Bansal,3160
BITS Pilani, Pilani Campus

Example-2
String str = "BITS C342,83,Object Oriented Programming,Lecture Section
3;MWF 9,Sunita;Bansal,3160";
StringTokenizer strT1 = new StringTokenizer(str,;);
// Semicolon (;) is Specified as delimiter

System.out.println("Number Of Tokens :"+strT1.countTokens());


System.out.println("Individual Tokens");
while(strT1.hasMoreTokens())
System.out.println(strT1.nextToken());
Number Of Tokens :3
Individual Tokens
BITS C342,83,Object Oriented Programming,Lecture Section 3
MWF 9,Sunita
Bansal,3160
BITS Pilani, Pilani Campus

Example-3
String str = "BITS C342,83,Object Oriented Programming,Lecture Section
3;MWF 9,Sunita;Bansal,3160";
StringTokenizer strT1 = new StringTokenizer(str,,);
// Comma (,) is Specified as delimiter

System.out.println("Number Of Tokens :"+strT1.countTokens());


System.out.println("Individual Tokens");
while(strT1.hasMoreTokens())
System.out.println(strT1.nextToken());

Number Of Tokens :6
Individual Tokens
BITS C342
83
Object Oriented Programming
Lecture Section 3;MWF 9
Sunita;Bansal
3160
BITS Pilani, Pilani Campus

Example-4
String str = "BITS C342,83,Object Oriented Programming,Lecture Section
3;MWF 9,Sunita;Bansal,3160";
StringTokenizer strT1 = new StringTokenizer(str,;,);
// Both Semicolon (;) and Comma (,) are Specified as delimiters

System.out.println("Number Of Tokens :"+strT1.countTokens());


System.out.println("Individual Tokens");
while(strT1.hasMoreTokens())
System.out.println(strT1.nextToken());

Number Of Tokens :8
Individual Tokens
BITS C342
83
Object Oriented Programming
Lecture Section 3
MWF 9
Sunita
Bansal
3160
BITS Pilani, Pilani Campus

Example-5
String str = "BITS C342,83,Object Oriented Programming,Lecture Section 3;MWF
9,Sunita;Bansal,3160";
StringTokenizer strT1 = new StringTokenizer(str,;,, true);
// Both Semicolon (;) and Comma (,) are Specified as delimiters
// Delimiters then selves are tokens now
System.out.println("Number Of Tokens :"+strT1.countTokens());

System.out.println("Individual Tokens");
while(strT1.hasMoreTokens())
System.out.println(strT1.nextToken());

BITS Pilani, Pilani Campus

Output-5
Number Of Tokens :15
Individual Tokens
BITS C342
,
83
,
Object Oriented Programming
,
Lecture Section 3
;
MWF 9
,
Sunita
;
Bansal
,
3160
BITS Pilani, Pilani Campus

String Buffer Class

BITS Pilani, Pilani Campus

StringBuffer
Peer class of String, stringbuilder
String represents fixed length and immutable
character sequence
StringBuffer allows growable and writable character
sequence
Characters in StringBuffer can be
inserted/appended/added/deleted any where and the
size of the StringBuffer will automatically
grow/shrink to make room

StringBuffer Constructors

StringBuffer()

<< Reserves room for 16 characters >>

StringBuffer(int size)

<< Explicitly sets the size of buffer >>

StringBuffer(String str)

<< Sets the initial content of the string


Buffer and allocates room for 16 more
characters>>
Note : At the time of creation if no size is specified then
length will be 0 but capacity will be 16

StringBuffer Methods
int length() returns the current length of string buffer
int capacity() returns the allocated capacity
Example :
StringBuffer strbuf = new StringBuffer(); No size Mentioned
System.out.println(strbuf.length()); 0
System.out.println(strbuf.capacity()); 16
StringBuffer strbuf1 = new StringBuffer("Object"); No size Mentioned
System.out.println(strbuf1.length()); 6
System.out.println(strbuf1.capacity()); 22
StringBuffer st = new StringBuffer(5);
System.out.println(st.length());
System.out.println(st.capacity()); 5

Size is Mentioned
0

StringBuffer Methods
void ensureCapacity(int capacity)
Useful if you know in advance the size of buffer
<<capacity>> specifies the size of buffer
StringBuffer strbuf = new StringBuffer();
System.out.println(strbuf.length()); 0
System.out.println(strbuf.capacity()); 16
strbuf.ensureCapacity(10);
System.out.println(strbuf.capacity());

16

StringBuffer strbuf1 = new StringBuffer("Object");


System.out.println(strbuf1.length()); 6
System.out.println(strbuf1.capacity()); 22
strbuf1.ensureCapacity(20);
System.out.println(strbuf1.capacity()); 22

Examples
StringBuffer strbuf = new StringBuffer();
System.out.println(strbuf.length());
System.out.println(strbuf.capacity());
strbuf.ensureCapacity(20);
System.out.println(strbuf.capacity()); 34

0
16

StringBuffer strbuf1 = new StringBuffer("Object");


System.out.println(strbuf1.length());
System.out.println(strbuf1.capacity()); 22
strbuf1.ensureCapacity(30);
System.out.println(strbuf1.capacity()); 46

What will happen for the following statements


strbuf.ensureCapacity(-20);
strbuf1.ensureCapacity(-30);

NO EFFECT ON
CAPACITY

Examples
StringBuffer s1 = new StringBuffer("Java");
4
System.out.println(s1.length());
System.out.println(s1.capacity()); 20

s1.ensureCapacity(50);

System.out.println(s1.length());
System.out.println(s1.capacity());

4
50

??
class Driver{
public static void main(String args[])
{
StringBuffer b=new StringBuffer("hello"); //5
System.out.println(b.capacity());
b.append("hello how are u mr"); //23
System.out.println(b.length());
System.out.println(b.capacity());
}
}

21
23
44

Reverse the String Buffer


Syntax:
StringBuffer reverse();
Examples :
StringBuffer s1 = new
StringBuffer(Object);
System.out.println(s1.reverse());

Appending [Adding at the End] String


Buffer

1.
2.
3.

append() method can be used for adding at the end of


StringBuffer.
Append() is overloaded with following foms:
StringBuffer append(String str)
Updates this
StringBuffer append(int num)
parameter
StringBuffer append(Object obj)
First Method adds String str in the end.
Second converts num into string and then adds in the end.
Third method calls toString() on obj and then String form of
obj will be inserted in the end. [ In this case obj must supply
a suitable toString() method otherwise it will be taken from
Object].

Append Example
class Circle
{
private double radius;
Circle(double radius)
{
this.radius = radius;
}
}
class CircleTest
{
public static void main(String args[])
{
StringBuffer strbuf = new StringBuffer("Object");

strbuf.append(" oriented");
System.out.println(strbuf);

Object oriented

strbuf.append(6.1);
System.out.println(strbuf);

Object oriented6.1

Append Example Cont.


strbuf.append(6.1);
System.out.println(strbuf);
Circle c1 = new Circle(10.56);

strbuf.append(c1);
System.out.println(strbuf);
}
}

Object oriented6.16.1
Object oriented6.16.1Circle@82ba41

Hashcode of Circle

Append Example
Cont.

class Circle
{
private double radius;
Circle(double radius)
{
this.radius = radius;
}
public String toString()
{
return "Circle with Radius:"+radius;
}
}
class CircleTest
{
public static void main(String args[])
{
StringBuffer strbuf = new StringBuffer("Java");
Circle c1 = new Circle(10.56);

strbuf.append(c1);

System.out.println(strbuf);
}
}

OUTPUT
JavaCircle with Radius:10.56

INTERFACES IN JAVA
1. Java Does not support Multiple Inheritance directly. Multiple inheritance
can be achieved in java by the use of interfaces.
2. We need interfaces when we want functionality to be included but does
not want to impose implementation.

3. Implementation issue is left to the individual classes implementing the


interfaces.
4. Interfaces can have only abstract methods and final fields.
5. You can declare a variable to be of type interface. But you can not create
an object belonging to type interface.
6. Interface variable can point to objects of any class implementing the
interface.

7. Another way of implementing Run Time Polymorphism.

Similarities between Interfaces and


classes
is compiled into byte code file.
can be either public, protected, private or
package accessibility.
can not be public unless defined in the file
having same name as interface name.
serve as a type for declaring variables and
parameters .

Differences between Interfaces and


classes
Declares only method headers and public
constants.
Has no constructors.
Can be implemented by a class.
Can not extend a class.
Can extend several other interfaces .

General Form
Syntax :
<access specifier> interface <interface name> extends [
<interface1> , <interface 2> ]
{
[public][final] variablename 1 = value;
.
[public][final] variablename N = value;
[public][abstract] <return type> methodname 1(<parameter lis>);
[public][abstract] <return type> methodname 2(<parameter lis>);

[public][abstract] <return type> methodname N(<parameter lis>);


}

Example
public interface A
{
double PI = 3.14156;
void show();
void display();
}

class XYZ implements A


{
public void show() { .. }
public void display() { .. }
}

Should be typed in file A.java


By Default public final Should
be initialized. In case of
interface
double PI; Wrong
Can have only abstract
methods. Each method is by
default public abstract

Interfaces Can Extend Multiple Interfaces


interface A
{
int a=10;
void show();
}
interface B
{
int b=10;
void print();
}
interface C extends A,B
{
void display();
}

<<interface>> <<interface>>
A

<<interface>>

Interface Can not Extend a Class

Interface Example
interface Area
{
double PI = 3.1456;

Area

double area();
double perimeter();
}
interface Volume extends Area

{
double volume();
}

Volume

class Circle implements Area


{
private double radius;
Circle(double radius)
{
this.radius = radius;
}
double getRadius() { return radius;}
public double area()
{
return PI * radius * radius;
}
public double perimeter()
{
return 2 * PI * radius;
}
}

<<interface>>
Area

Circle

<<class>>

public double area()

class BOX implements Volume


{
private double length;
private double width;
private double height;
BOX(double l, double b, double h)
{
length = l;
width = b;
height = h;
}
double getLength() { return length ;}
double getWidth() { return width ;}
double getHeight() { return height ;}

{
return 2 * (length * width + width *
height + height * length);
}
public double volume()
{
return length * width * height ;
}
public double perimeter()
{
return 4*(length + width + height);
}
<<interface>>
}

Volume

BOX
<<class>>

Iterable
Interfaces from Javas Collection Framework

<<interface>>
Collection

<<class>>Abstractcollection

List

Set

<<interface>>
<<class>>

Sorted Set

AbstractList

<<interface>>
ArrayList

AbstractSequentialList

LinkedList
Either a class should fully implement an interface or it should be declared as abstract

The Collection
Interface
public interface Collection<E> extends Iterable<E> {
// Basic operations

int size();
boolean isEmpty();
boolean contains(Object element);

boolean add(E element);


boolean remove(Object element);

Iterator<E> iterator();
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean removeAll(Collection<?> c);
boolean retainAll(Collection<?> c);
void clear();
// Array operations

Object[] toArray();
}

The List Interface


A List is an ordered Collection (sometimes called a
sequence). Lists may contain duplicate elements. In
addition to the operations inherited from Collection, the
List interface includes operations for the following:
Positional access: manipulates elements based on their
numerical position in the list
Search: searches for a specified object in the list and
returns its numerical position
Iteration: extends Iterator semantics to take advantage of
the list's sequential nature
Range-view: performs arbitrary range operations on the list.

The List Interface


public interface List<E> extends Collection<E> {
// Positional access
E get(int index);
E set(int index, E element);
add(E element); //optional
void add(int index, E element);
E remove(int index);
boolean addAll(int index, Collection<? extends E> c);
// Search
int indexOf(Object o);
int lastIndexOf(Object o);
// Iteration
ListIterator<E> listIterator();
ListIterator<E> listIterator(int index);
// Range-view List<E>
subList(int from, int to);
}

Comparable Interface
1. Provides an interface for comparing any two objects of
same class.
2. General Form :
public interface Comparable<T>
public interface Comparable
{
{
int compareTo(<T> other );
int compareTo(Object other );
}
}
Note : other parameter should be type casted to the class type
implementing Comparable interface
3. Collections. sort method can sort objects of any class that implements
comparable interface.
4. By implementing this interface , programmers can implement the logic
for comparing two objects of same class for less than, greater than or
equal to.

Examples for Implementation


class BOX Implements Comparable class Student Implements Comparable

public int compareTo(Object other) public int compareTo(Object other)


{

BOX box = (BOX) other;

Student std = (Student) other;

......Logic for comparison .

......Logic for comparison .

.
}

.
}

Examples for Implementation


class BOX Implements Comparable<BOX>
{

class Student Implements Comparable<Student>

public int compareTo(BOX other)

......Logic for comparison .

public int compareTo(Student other)

.
}

{
......Logic for comparison .
}
.
}

Example
class BOX implements Comparable
Unparametrized Comparable
{
private double length;
private double width;
private double height;
BOX(double l,double b,double h)
{
length=l;width=b;height=h;
}
public double getLength() { return length;}
public double getWidth() { return width;}
public double getHeight() { return height;}
public double getArea()
{
return 2*(length*width + width*height+height*length);
}
public double getVolume()
{
return length*width*height;
}

Example
public int compareTo(Object other)
{
BOX b1 = (BOX) other;
if(this.getVolume() > b1.getVolume())
return 1;
if(this.getVolume() < b1.getVolume())
return -1;
return 0;
}
public String toString()
{
return Length:+length+ Width :+width + Height :+height;
}
} // End of BOX class

Example

Import java.util.*;
class ComparableTest
{
public static void main(String[] args)
import java.util.*;
{
class ComparableTest
ArrayList box = new ArrayList();
{
public static void main(String[] args) box.add( new BOX(10,8,6));
box.add( new BOX(5,10,5));
{
box.add( new BOX(8,8,8));
BOX[] box = new BOX[5];
box.add( new BOX(10,20,30));
box[0] = new BOX(10,8,6);
box.add( new BOX(1,2,3));
box[1] = new BOX(5,10,5);
Collections.sort(box);
box[2] = new BOX(8,8,8);
Iterator itr = ar.iterator();
box[3] = new BOX(10,20,30);
while(itr.hasNext())
box[4] = new BOX(1,2,3);
{
Arrays.sort(box);
System.out.println(itr.next());
for(int i=0;i<box.length;i++)
}
System.out.println(box[i]);
}
}
}// End of class
} // End of class

Problems With Comparable Interface


Method int compareTo(Object obj) needs to
be included in the base class itself.(because it
compares with specified object and this
reference)
We can include only single ordering logic.
Different order requires logic to be included
and requires changes in the base class itself.
Each type we need different order we need to
change the code itself.

Comparator Interface
Allows two objects to compare explicitly.
Syntax :
public interface Comparator Unparametrized Comparator
{
int compare(Object O1, Object O2);
}
Parametrized Comparator
public interface Comparator<T>
{
int compare(T O1, T O2);
}
Does not require change in the base class.
We can define as many comparator classes for the base class.
Each Comparator class implements Comparator interface and
provides different logic for comparisons of objects.
But as we are passing both parameters explicitly, we have to
type cast both Object types to their base type before
implementing the logic OR Use the second form

Example
Comparator

Student
class Student
{
private String name;
private String idno;

studentbyname

studentbyidno

studentbyage

private int age;


private String city;
..
..
}

studentbynameidno

studentbynameage

Example cont.
class studentbyname implements comparator
{
public int compare(Object o1,Object o2)
{
Student s1 = (Student) o1;
Student s2 = (Student) o2;
return s1.getName().compareTo(s2.getName());
}
}
class studentbyidno implements comparator
{
public int compare(Object o1,Object o2)
{
Student s1 = (Student) o1;
Student s2 = (Student) o2;
return s1.getIdNo().compareTo(s2.getIdNo());
}
}

class studentbyage implements comparator


{
public int compare(Object o1,Object o2)
{
Student s1 = (Student) o1;
Student s2 = (Student) o2;
if( s1.getAge() > s2.getAge() ) return 1;
if( s1.getAge() < s2.getAge() ) return -1;
return 0;
}
}
class studentbynameidno implements comparator
{
public int compare(Object o1,Object o2)
{
Student s1 = (Student) o1;
Student s2 = (Student) o2;
if( s1.getName().compareTo(s2.getName()) == 0)
return s1.getIdNo().compareTo(s2.getIdNo());
else
return s1.getName().compareTo(s2.getName());
}}

Example cont.
class studentbynameage implements comparator
{
public int compare(Object o1,Object o2)
{
Student s1 = (Student) o1;
Student s2 = (Student) o2;
if( s1.getName().compareTo(s2.getName()) == 0)
return s1.getAge() s2.getAge();
else
return s1.getName().compareTo(s2.getName());
}
}

Example cont.
Import java.util.*;
class comparatorTest
{
public static void main(String args[])
{
Student[] students = new Student[5];
Student[0] = new Student(John,2000A1Ps234,23,Pilani);
Student[1] = new Student(Meera,2001A1Ps234,23,Pilani);
Student[2] = new Student(Kamal,2001A1Ps344,23,Pilani);
Student[3] = new Student(Ram,2000A2Ps644,23,Pilani);
Student[4] = new Student(Sham,2000A7Ps543,23,Pilani);
// Sort By Name
Comparator c1 = new studentbyname();
Arrays.sort(students,c1);
for(int i=0;i<students.length;i++)
System.out.println(students[i]);

Example cont.
// Sort By Idno
c1 = new studentbyidno();
Arrays.sort(students,c1);
for(int i=0;i<students.length;i++)
System.out.println(students[i]);

// Sort By Age
c1 = new studentbyage();
Arrays.sort(students,c1);
for(int i=0;i<students.length;i++)
System.out.println(students[i]);
// Sort by Name & Idno
c1 = new studentbynameidno();
Arrays.sort(students,c1);
for(int i=0;i<students.length;i++)
System.out.println(students[i]);

// Sort by Name & Age


c1 = new studentbynameage();
Arrays.sort(students,c1);
for(int i=0;i<students.length;i++)
System.out.println(students[i]);
} // End of Main
} // End of test class.

Example
import java.util.*;
class BOX implements
Comparable
{
double length;
private double width;
private double
height;
BOX(double l,double
b,double h)
{
length=l;width=b;heig
ht=h;
}
BOX()
{}

public double getArea()


{
return 2*(length*width +
width*height+height*length);
}
public double getVolume()
{
return length*width*height;
}
public int compareTo(Object
other)
{
BOX b1 = (BOX) other;
if(this.getVolume() >
b1.getVolume())
return 1;
if(this.getVolume() <
b1.getVolume())

Example
class ComparableTest
{
public static void main(String[]
args)
{
ArrayList <BOX> box = new ArrayList
();
box.add( new BOX(10,8,6));
box.add( new BOX(5,10,5));
box.add( new BOX(8,8,8));
box.add( new BOX(10,20,30));
box.add( new BOX(1,2,3));
Iterator itr = box.iterator();
Collections.sort(box);
while(itr.hasNext())
System.out.println(itr.next(););
}} // end of class

Volume:6.0
Volume:250.0
Volume:480.0
Volume:512.0
Volume:6000.0

class box1 extends BOX


implements Comparable
{
box1(double l,double
b,double h)
{
super(l,b,h);
}
public int compareTo(Object
other)
{
box1 b1 = (box1) other;
if(length > b1.length)
return 1;
if(length < b1.length)
return -1;
else return 0;
}
public String toString()
{return "Length:"+length;
}
}

ArrayList <BOX> box = new


ArrayList ();
box.add( new box1(10,8,6));
box.add( new box1(5,10,5));
box.add( new box1(8,8,8));
box.add( new box1(10,20,30));
box.add( new box1(1,2,3));
Collections.sort(box);
Iterator itr = box.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}

Length:1.0
Length:5.0
Length:8.0
Length:10.0
Length:10.0

ArrayList Class

Supports Dynamic Arrays that can grow as needed.


Variable length array of object references.
ArrayList can increase or decrease in size.
Earlier versions of java supports dynamic arrays by a legacy
class Vector.

Types of ArraysList
Unparametrized ArrayLists
Supported in earlier versions (before 1.5) of
Java
Can store/handle objects of any type.

Parametrized ArrayLists
Supported in later versions
Can handle objects of only mentioned type

ArrayList Constructors
ArrayList()
Unparametrized
Creates an empty ArrayList() of size() =0 Type
Examples :
parametrized
ArrayList lst = new ArrayList();
Type
ArrayList<Box> boxes = new ArrayList<Box>();
ArrayList<Student> students = new
ArrayList<Student>();
ArrayList(Collection c)
Creates an ArrayList which is initialized with elements from other
collection
ArrayList(int capacity)
Creates an arraylist with initial capacity.
Examples
ArrayList lst = new ArrayList(10);
ArrayList<Box> lstBox = new ArrayList<Box>(10);
ArrayList<Student> lstStud = new ArrayList<Student>(20);

Example Unparametrized
ArrayLists
To Use ArrayList import java.util.*

import java.util.*;
class ArrayListTest
{
public static void main(String
args[]){
ArrayList lst1 = new
ArrayList();
ArrayList lst2 = new
ArrayList(20);

Empty ArrayList size() == 0,


Type is unparametrized

System.out.println(lst1.size()

);

Both ArrayList s size() = 0

System.out.println(lst2.size()
);
// Adding Elements

Cont.
lst1.add(new Integer(10));

//Adds integer 10 at
index 0
//Adds String A at
lst1.add("A");
index 1
//Adds 12.56 at
index 2
lst1.add(new Double(12.56));
//Adds boolean true at
index 3
lst1.add(new Boolean(true));
//Adds integer 30 at
index 2
//5

lst1.add(2,new Integer(30)); //Adds all elements of lst1 to end


of lst2

System.out.println(lst1.size());
lst2.addAll(lst1);
}

Example Parametrized
ArrayLists
To Use ArrayList import
java.util.*

Parametrized ArrayList of
import java.util.*;
type <String> Can Hold
class ParamListTest
Only String Type Data
{
public static void main(String args[]){
ArrayList<String> lstStr = new
ArrayList<String>();
//ArrayList<Box> lstBox = new
ArrayList<Box>(20);

Parametrized ArrayList of
type <Box>. Can Hold
System.out.println(lstStr.size());
Only Box Type Data

//System.out.println(lstBox.size());
// Adding Elements

Cont.
Wont work lst1 can hold only
String Data

// lstStr.add(10);
// lstStr.add(new Integer(10));

// Adds String A at
lstStr.add("A");
index 0
Wont Work. lst1 can hold
only String Data // Adds B at
//lstStr.add(new Double(12.56));
index 1
// Adds OOP at
lstStr.add(B);
index 2
//3
lstStr.add(new String(OOP));
System.out.println(lstStr.size());
//lstBox.addAll(lstStr);
}
}

Wont work Elements of


different types

Traversing ArrayLists
Traversing means visiting/cycle through the
arrayList and retrieving individual elements.
Traversal can be forward or backward
There can be following ways of traversal
Use for() loop along
Use for each loop.
Use of Iterator interface [ For Forward Traversing
Only]
Use of ListInterator interface [For Both Way
Traversing]

For Loop
import java.util.*;
class ArrayListWithLoop
{
public static void main(String args[])
{
ArrayList arrStr = new ArrayList(20);
arrStr.add("A");
arrStr.add("B");
arrStr.add("X");
arrStr.add("Y");
arrStr.add("Z");
// For Forward Traversing
System.out.println("Forward");
for(int i=0;i<arrStr.size();i++){
String str = (String) arrStr.get(i);
System.out.println("Hello "+str);
}
}
}

For Loop
import java.util.*;
class ArrayListWithLoop
{
public static void main(String args[])
{
ArrayList <String>arrStr = new ArrayList<String>(20);
arrStr.add("A");
arrStr.add("B");
arrStr.add("X");
arrStr.add("Y");
arrStr.add("z");
System.out.println("Forward");
for(int i=0;i<arrStr.size();i++)
{
String str = arrStr.get(i);
System.out.println("Hello "+str);
}
}
}

For Each Loop


Other form of for loop known as
for each in collection

/* For Forward Traversing using for


each
for(String str : arrStr){
System.out.println("Hello "+str);
}
*/

// For Backward Traversal


System.out.println("Backward");
for(int i= arrStr.size()-1;i>=0;i--){
String str = (String) arrStr.get(i);
System.out.println("Hello "+str);
}
}
}

Iterator
import java.util.*;
class IteratorExample{
public static void main(String args[])
{
ArrayList arrStr = new ArrayList(20);
arrStr.add("A");
arrStr.add("B");
arrStr.add("X");
arrStr.add("Y");
arrStr.add("Z");
// How to get an iterator for any
collection
Iterator itr = arrStr.iterator();
while(itr.hasNext()){
String str = (String) itr.next();
System.out.println("Hello "+str);
}
}
}

List Iterator

It allows modify during iteration.


It allows to traverse in both direction.
It has N+1 possible position of cursor.
Remove method removes the element that had returned
by the last call of previous() or next() method.
Methods:
void add(element)
void set(element)
void remove(element)
boolean hasPrevious()
Object Previous()

Listiterator
import java.util.*;
class ListIterExample
{
public static void main(String args[])
{
ArrayList arrStr = new ArrayList(20);
arrStr.add("A");
arrStr.add("B");
arrStr.add("X");
arrStr.add("Y");
arrStr.add("Z");
// How to get an ListIterator for any
collection
for forward Traversal
System.out.println("Forward");
ListIterator lstIter =
arrStr.listIterator();
while(lstIter.hasNext()){
String str = (String)
lstIter.next();
System.out.println("Hello "+str);
}

Listiterator
Unparameterized
//
//

How to get an ListIterator for


any collection for Backward Traversal
System.out.println("Backward");
ListIterator lstIter =
arrStr.listIterator(arrStr.size());
while(lstIter.hasPrevious()){
String str = (String)
lstIter.previous();
System.out.println("Hello "+str);
}
}
}

Listiterator
Parametrized

import java.util.*;
class ParamListIteratorExample
{
public static void main(String args[])
{
ArrayList<String> arrStr = new ArrayList(20);
arrStr.add("A");
arrStr.add("B");
arrStr.add("X");
Parametrized Iterator
arrStr.add("Y");
at the start of list
arrStr.add("Z");
// For Forward Traversing
System.out.println("Forward");
ListIterator<String> lstIter = arrStr.listIterator();
while(lstIter.hasNext()){
String str = lstIter.next(); // No Need of type
casting
System.out.println("Hello "+str);

Listiterator
Parametrized
List Itearator sets at the end of the list

// For Backward Traversing


System.out.println("Backward");
ListIterator<String> lstIter = arrStr.listIterator(arrStr.size());
while(lstIter.hasPrevious())
{
String str = lstIter.previous();
System.out.println("Hello "+str);
}
}
System.out.println(srrStr);
}

Listiterator
class Driver
{
public static void main(String args[])
{
ArrayList arrStr = new ArrayList(20);
arrStr.add("A");
arrStr.add("B");
arrStr.add("X");
arrStr.add("Y");
arrStr.add("Z");
ListIterator itr = arrStr.listIterator();
String str;
while(itr.hasNext())
{str = (String) itr.next();
itr.add(str+ "+");
}
System.out.println(arrStr);
while(itr.hasPrevious())
{ System.out.println(itr.previous()); }}}

LinkedList
class Driver
{
public static void main(String args[] {
LinkedList lstStr = new LinkedList();
lstStr.add("C");
lstStr.add("D");
lstStr.add("E");
System.out.println(lstStr);
lstStr.addFirst("A"); // at zero index
lstStr.addLast("X");
System.out.println(lstStr);
lstStr.add(1,"B"); // at first position
System.out.println(lstStr);
lstStr.remove("d");
System.out.println(lstStr);
lstStr.removeFirst();
System.out.println(lstStr);
lstStr.add(0,"A");
for(int i=0;i<lstStr.size();i++)
System.out.print(lstStr.get(i))} }

import java.util.*;
class Driver
{
public static void main(String args[])
{
ArrayList arrStr = new ArrayList(20);
arrStr.add("A");
arrStr.add("B");
arrStr.add("X");
arrStr.add("Y");
arrStr.add("Z");
Iterator itr = arrStr.iterator();
//itr.remove();
//arrStr.add(1,"s");
arrStr.set(1,"S");
while(itr.hasNext())
{if(itr.next().equals("B"))
itr.remove();
}
System.out.println(arrStr); }}

Illegal Monitor Exception


Concurrent Exception

Nested Classes
Non-static nested class(inner class)
Member inner class
Anonymous inner class
Local inner class

Static nested class

Nested Class
Java programming language allows you to define a class
within another class
class OuterClass
{ ...

Enclosing Class
OR Outer Class

class NestedClass { ... }

A nested class is a member


of its enclosing class

}
Nested Class
1. Nested class can access to other members of the enclosing
class, even if they are declared private
2. Nested class can be private, public, protected or friendly
access

Non-Static nested classes


1. These nested classes do not have static keyword applied
2. Non-Static nested class can use the instance fields/methods of
the outer class directly.
3. Its object can be created in:
Enclosing class
Outside the enclosing class
OuterClass.NestedClass nestedObject = Outerobjectreference. new innerclass();
4.

Enclosing class can access members of nested class through


creating an object only.

Member class object is


created outside the
enclosing class

Example 1 [Non-static
Nested
Class]
class B
class A
{
private int a;
Outer Class
A(int a)
{
this.a =a;
}
void print()
{
System.out.println("a="+a);
}

Call to print() of
outer class

{
int b;
Nested class
B(int b)
with friendly
{
access
int c = b+10;
this.b = c;
}
void show()
{
print();
System.out.println("b="+b);
}
} // End of class B
} // End of class A

Example 1 [Non-static
Nested Class]
class innertest1
{
public static void main(String args[])
{
A a1 = new A(10);
A.B b1 = a1.new B(100);
b1.show();
}
}

Inner class Name


Outer class Reference

To create an inner class instance


for non-static classes you need an
outer class reference.
Inner class Reference
Outer class Name

If class B is Private then it is not visible in main().


A.B b1 = a1.new B(100); is WRONG/INVALID

Enclosing class access


member of nested class

class A
{
private int a;
private int b=10;

Outer class

A(int a)
{
this.a=a;
}

Local b
Bs instance Field b

As instance Field b
void show()
{
B b1 = new B(30); /* inner class
b1.show();
}
} // End of Outer class A

Nested Inner class [Nonstatic Type]

class B
{
private int b;
Instance Field of B
B(int b)
{
this.b =b;
}
Outer Class As a
void show()
{
int b=20;
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("this.b="+this.b);
System.out.println("Outer b="+A.this.b);
/* if we write A.b it assumes its static
and give an error*/
}
} // End of B inner class
object is created inside the outer class */

Example cont.
class innerTest
{
public static void main(String args[])
{

A a1 = new A(20);
A.B b1 = a1.new B(-30);
b1.show();

a=20
b=20
this.b=-30
Outer b=10

// inner class object instantiation thru anonymous outer reference

A.B b2 = new A(30).new B(-40);


b2.show();
}
}

a=30
b=20
this.b=-40
Outer b=10

Anonymous Inner
classes

Anonymous classes enable you to make your


code more concise.
They enable you to declare and instantiate a
class at the same time.
They are like local classes except that they do
not have a name
Can either implements an interface or extends a
class.
Whole body of the class is declared in a single
statement ending with ;

Cont
Syntax [ If extending a class]
[variable_type_superclass =] new superclass_name() {
// properties and
methods
} [;]
Syntax [ If implementing an interface]
[variable_type_reference =] new interface_name() {
// properties and
methods
} [;]

Anonymous Inner Class


Example
class A
{
private int a;
A(int a)
{
this.a =a;
}
void show()
{
System.out.println("a="+a);
} // End of show()
}// End of class A

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

Anonymous inner class extending super class A

A a1 = new A(20){
public void show()
{
super.show();
System.out.println("Hello");
}
public void display()
{
System.out.println("Hi");
}
};
a1.show();
// a1.display(); ??
Calling show from inner
}
class
}

interface X
{
int sum(int a,int b);
int mul(int x,int y);
}
class innertest2
{
public static void main(String args[])
{
Anonymous inner class implementing an interface

X x1 = new X()
{
public int sum(int a,int b)
{
return a+b;
}
public int mul(int a,int b)
{
return a*b;
}
};
System.out.println(x1.sum(10,20));
System.out.println(x1.mul(10,20));
}// End of main
}// End of innertest2

Example
interface movable
{ void moveLeft();
void moveRight();
String toString();
}
class movablePoint implements movable,Comparable
{// code here}
class movableCircle implements movable,Comparable
{// code here}
Class test
{write the code that shows dynamic polymorphism}

Example cont.
import java.util.*;
interface movable
{ void moveLeft();
void moveRight();
String toString();
}
class movablePoint implements
movable,Comparable
{ int x, y, xSpeed;
movablePoint(int x,int y, int xSpeed)
{this.x=x;
this.y=y;
this.xSpeed=xSpeed;
}

public void moveLeft()


{x=x-xSpeed;}
public void moveRight()
{ x=x+xSpeed;
}
public String toString()
{ return "x= "+x+" y= "+y+ " xSpeed=
"+xSpeed;}
public int compareTo(Object o1)
{
movablePoint m2 = (movablePoint)
o1;
return this.x - m2.x;
}
}

class movableCircle implements


movable,Comparable
{ int radius;
movablePoint center;
movableCircle(int x,int y, int xSpeed, int radius)
{ center = new movablePoint(x,y,xSpeed);
this.radius=radius;}
public int getRadius()
{return radius;}
public void moveLeft()
{ center.x-=center.xSpeed;}
public void moveRight()
{center.x+=center.xSpeed;}
public String toString()
{ return center.toString()+ "radius =" + radius;}
public int compareTo(Object o1)
{ movableCircle m2 = (movableCircle) o1;
return this.center.x-m2.center.x;
} }

Example cont.
class Test
{ public static void main(String args[])
{ ArrayList al = new ArrayList ();
al.add(new movableCircle(1,2,3,5));
al.add(new movableCircle(3,4,5,10));
al.add(new movableCircle(2,4,5,2));
Collections.sort(al);
Collections.sort(al, new Comparator<movableCircle>(){
public int compare(movableCircle o1, movableCircle o2)
{ return o1.radius - o2.radius;}
});
Comparator c = new Comparator()
{ public int compare(Object o1, Object o2)
{ movableCircle c1 = (movableCircle) o1;
movableCircle c2 = (movableCircle) o2;
return c1.center.y - c2.center.y;
}
};

Example cont.
Collections.sort(al,c);
Iterator it = al.iterator();
while(it.hasNext())
{
System.out.println((movableCircle) it.next());
}
}
}

class xyz implements Comparator


<movableCircle>
{ int order;
xyz(int o)
{order =o;}
public int compare(movableCircle o1,
movableCircle o2)
{ if(order == 0)
return o1.radius - o2.radius;
else
return ((o1.radius - o2.radius ) *order);
} Collections.sort(al,new xyz(0)); // sort in ascending
} order
Collections.sort(al,new xyz(1)); // sort in descending
order

ArrayList into Array


Object objArray[] =
al.toArray();
movableCircle cirArray[] = new
movableCircle[objArray.length];
for(int i=0;i<objArray.length;i++)
cirArray[i]= (movableCircle)objArray[i];
Arrays.sort(cirArray, new
Comparator<movableCircle>()
{
public int compare(movableCircle o1,
movableCircle o2)
{return o1.radius-o2.radius;
}});
for(int i=0;i<cirArray.length;i++)
System.out.println(cirArray[i]);

ArrayList into Array


movableCircle cirArray1[] =
al.toArray(new
movableCircle[al.size()]);
Arrays.sort(cirArray1, new
Comparator<movableCircle>()
{
public int compare(movableCircle o1,
movableCircle o2)
{return o1.radius-o2.radius;}
}
);
Arrays.sort(cirArray1, new xyz(-1));
for(int i=0;i<cirArray1.length;i++)
System.out.println(cirArray1[i]);

Local Inner Class

Local Inner classes [ Classes


Within method body]
Class declared within a

class A
{
private int a;
protected static int b=10;
A(int a)
{
this.a=a;
}
void show()
{
class B
{}
}
}

method body.
Here method is show()
Local inner classes Can
not be declared as
public,private or protected
1. Class B is visible only in method
show().
2. It can be used within this show()
method only
3. Local inner classes can only use final
variables from its enclosing method.
4. However inner classes can refer to its
fields of enclosing class.

class A
{
private int a;
protected static int b=10;
A(int a)
{
this.a=a;
}
void show()
{
int x=10;
class B
{
private int b;
B(int b)
{
this.b=b;
}
void display()
{

System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("x="+x);

}
} // End of class B
} // End of show() method
} // End of A class

D:\jdk1.3\bin>javac
innerTest2.java
innerTest2.java:23: local
variable x is accessed from
within inner class;
to be declared final
System.out.println("x="+x);
^
1 error

Reference for As a
Reference for Bs b
Reference is wrong /
errorneous
x is local variable inside the
local method. Local classes
can use only final fields from
enclosing method

class innertest
{
public static void main(String
args[])
{
final int a1=10;

new A(20).show();
print();
}// End of main
static void print()
{

/*
A a1 = new A(30);
a1.show();
*/

System.out.println("Hello");
}
}

class A
{
private int a;
private int b;
int c;
A(int a)
{
this.a =a;
b = a+20;
c = a+40;
}
void show()
{
System.out.println("a1="+a1)
;
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
}
} //End of A

OUTPUT
E:\oop>java innertest
a1=10
a=20
b=40
c=60
Hello

Autoboxing / Unboxing
Assignment statements
Method call
Expression

Autoboxing/unboxing in
method call
class AutoBox2 {
static int m(Integer v)
{
return v ; // auto-unbox to int
}
public static void main(String args[])
{
Integer iOb = m(100);
System.out.println(iOb);
}
}

Autoboxing/unboxing in
expression
class AutoBox3 {
public static void main(String args[]) {
Integer iOb, iOb2;
int i;
iOb = 100;
System.out.println("Original value of iOb: " + iOb);
++iOb;
System.out.println("After ++iOb: " + iOb);
iOb2 = iOb + (iOb / 3);
System.out.println("iOb2 after expression: " + iOb2);
i = iOb + (iOb / 3);
System.out.println("i after expression: " + i);
}
}

Non-Generic type
class gen
{
Object obj;
gen(Object o)
{obj=o;}
Object getObj()
{return obj;}
}
class testgen
{public static void main(String args[])
{ gen intObj = new gen(10);
int i =(Integer) intObj.getObj();
System.out.println(i);
gen strObj = new gen ("java program");
String s = (String)strObj.getObj();
System.out.println(s);
intObj=strObj;
i=(Integer) intObj.getObj();
System.out.println(i);
} }

Generic type
class gen<T>
{T obj;
gen(T o)
{obj=o;}
T getObj()
{return obj;}
}
class testgen
{public static void main(String args[])
{ gen <Integer>intObj = new gen<Integer>(10);
int i = intObj.getObj();
System.out.println(i);
gen <String>strObj = new gen<String> ("java program");
String s =strObj.getObj();
System.out.println(s);
}
}

Random Number
import java.util.Random;
/** Generate 10 random integers in the range 0..99. */
class RandomInteger {
public static final void main(String... aArgs){
//note a single Random object is reused here
Random randomGenerator = new Random();
for (int idx = 1; idx <= 10; ++idx)
System.out.println(randomGenerator.nextInt(100));
}
}

Exception
class DemoException
{
public static void main(String args[])
{ int i=1;
Scanner obj = new Scanner(System.in);
while(i<5)
try
{
System.out.println("enter i th number" +i);
System.out.println("result is" + i/obj.nextInt());
i++;
}
catch(RuntimeException e)
{
System.out.println("do not enter 0");
i--;
} } // end of main
} // end of class

Static nested classes


1. Static keyword can be applied for class declaration
2. Static nested class can use the instance fields/methods of the outer
class only through object reference.
3. Static class can access static member of enclosing class without
creating a reference.
4. Static class can have static member and non static member. Static
member can access only static member of that class. Non static
member can access both non static and static.
5. If static nested class static method than no need to create an
instance otherwise instance is created as :
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

Static Inner class / Static Nested


class
Example
static class B
class A
{
private int a;
A(int a)
{
this.a =a;
}
void print()
{
System.out.println("a="+a);
}

Static nested class can


refer to non static outer
members only through
outer reference

{
int b;
B(int b)
{
Static inner
int c = b+10;
class
this.b = c;
}
void show()
{
// print(); INVALID
A a1 = new A(10);
a1.print();
System.out.println("b="+b);

//from non static context non static variable

}
} // End of class B
} // End of class A

Example (continued)
class innertest10
{
public static void main(String args[])
{
A.B b1 = new A.B(100);
b1.show();
Instance of static Inner class
}
}

Static Nested class


Example 2

class A
{
private int a;
protected static int b=10;
A(int a)
{
this.a=a;
}
public void show()
{
System.out.println("a="+a);
display();
}
public static void display()
{
System.out.println("b="+b);
}

static class B
{
private int a;
protected static int b=100;
B(int a)
{
this.a=a;
}
void show() //non static
{
// A.this.show(); // Won't work show() is non-static in outer
display(); // Will work as method is static in outer
System.out.println("a="+a); // from nonstatic method nonstatic variable
// System.out.println("a="+A.this.a); // Won't work a is non-static in
outer
System.out.println("b="+b); // Will refer to its own b
System.out.println("A'sb="+A.b); // will refer to outer class static B
new A(40).show();
// This is how you can call non static methods of outer
}
} // End of inner class B
} // End of class A

Example 2 cont.
class innerTest1
{
public static void main(String args[])
{
A.B b1 = new A.B(-30);
b1.show();
D:\jdk1.3\bin>java innerTest1
}
}
b=10
a=-30

b=100
A'sb=10
a=40
b=10

Lect-17
EXCEPTIONS IN JAVA

Whats Exception
An exception is an abnormal condition that occurs run time.
E.g divide by 0.
During execution of a method if any exceptional conditions
occurs, Java run time environment i.e java interpreter creates
a suitable Exception object and throws it.
Every Exception is basically an object belonging to Javas
Exception class Hierarchy.
Exceptions needs to be handled so that appropriate actions can
be taken.
Programmer can also provide exception handling code. However
if there is no exception handling code present during runtime,
then java interpreter provides default exception handler.
Default Exception Handler Simply displays the name of the
exception object in string form and stops the execution of the
program.
However, programmer can provide exception handling code and
programs execution can continue even after the occurrence of
exception.

Exception class Hierarchy


Every Exception type is basically an object belonging to class Exception
Throwable class is the root class of Exceptions.
Throwable class has two direct subclasses named Exception, Error
Errors are neither checked nor catch.

Error in Java are


java.lang.OutOfMemoryError
Java.lang.NoClassDefFoundErr
or
java.lang.UnSupportedClassVe
rsionError.

Types of Exceptions
A.

Unchecked Exceptions

All Exceptions that extend the RuntimeException or any one of its


subclass are unchecked exceptions

Unchecked Exceptions are unchecked by compiler.

Whether you catch the exception or not compiler will pass the
compilation process.

If Unchecked exception is caught then exception handling code


will be executed and programs execution continues.

If Unchecked exception is not caught then java interpreter will


provide the default handler. But in this case execution of the
program will be stopped by displaying the name of the exceptions
object.

Unchecked Exceptions
Some Common Unchecked Exceptions
1.
ArithmaticException (Divide By 0)
2.
ArrayIndexOutOfBoundsException
3.
ArrayStoreException
4.
NullPointerException
5.
NumberFormatException
6.
IllegalArumentsException

Throwable

Exception

Error

RunTimeException
All Unchecked
Exceptions
directly or
indirectly are sub
classes of
RunTimeException

Any Class belonging to RunTimeException

UncheckedExceptions Example
class Exceptiondemo1
{
public static void main(String arhs[]) throws ArithmeticException
{
int a=10;
int b= 5;
int c =5;
No Need to mention for
int x = a/(b-c); // Dynamic Initilization
Unchecked Exceptions
System.out.println("c="+c);
int y = a/(b+c);
System.out.println("y="+y);
Can Throw an
Exception
}
} D:\java\bin>javac Exceptiondemo1.java << Compilation Step Pass>>
D:\java\bin>java Exceptiondemo1
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at Exceptiondemo1.main(Exceptiondemo1.java:8)

Example 2 (Unchecked
class Exceptiondemo2Exceptions)
{
public static void main(String args[])
{
double a= Double.parseDouble(args[0]);
}
}

Can throw either


ArrayIndexOutOfBoundsException
OR
NumberFormatException

D:\java\bin>javac Exceptiondemo2.java
D:\java\bin>java Exceptiondemo2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Exceptiondemo2.main(Exceptiondemo2.java:5)
D:\java\bin>java Exceptiondemo2 pankaj
Exception in thread "main" java.lang.NumberFormatException: For input
string: "pankaj at
sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1
2 24) at java.lang.Double.parseDouble(Double.java:482)
at Exceptiondemo2.main(Exceptiondemo2.java:5)

Put the Related/Dependent Statements in try


block

class extest
{
public static void main(String args[])
{
try
{
E:\oop>javac extest.java
int a = Integer.parseInt(args[0]);
extest.java:10: cannot find
}
symbol
catch(Exception e) {}
symbol : variable a
int b = a+10;
location: class extest
System.out.println("b="+b);
int b = a+10;
}
^
extest.java:10: incompatible types
}
found : <nulltype>
required: int
int b = a+10;
^
2 errors

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

try
{
int a = Integer.parseInt(args[0]);
int b = a+10;
System.out.println("b="+b);
}
catch(Exception e) {}
}
}

Types of Exceptions
B Checked Exceptions
All Exceptions that extends the Exception or any one its subclass
except RunTimeException class are checked exceptions

Checked Exceptions are checked by the


Java compiler.

There are two approaches that a user can


follow to deal with checked exceptions

Handling Checked Exceptions

Inform the compiler that a method can throw


an Exception.

Catch
block

If Checked exception is caught then exception


handling code will be executed and programs
execution continues.

If Checked exception is not caught then java


interpreter will provide the default handler.
But in this case execution of
the program
will be stopped by displaying the name of the
exceptions object.

the

checked

exception

in

try

catch

Checked Exceptions Examples


Some Common Checked Exceptions
1.
IOException
2.
ClassNotFoundExceptions
3.
InterruptedException
4.
NoSuchMethodException

Throwable

Exception

Error

Any Sub Class belonging to Exception

EXCEPT
RuntimeException

Checked Exceptions
/* Program to read two integers Display their sum */
import java.io.*;
WILL THIS CODE
class Exceptiondemo3
COMPILE
{
SUCCESSFULLY
public static void main(String args[])
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int a = Integer.parseInt(br.readLine());
int b = Integer.parseInt(br.readLine());
System.out.println("Sum is :"+(a+b));
}
Exceptiondemo3.java:9: unreported exception
}
java.io.IOException; must be caught or declared to be thrown
int a = Integer.parseInt(br.readLine());

Exceptiondemo3.java:10: unreported exception


java.io.IOException; must be caugh or declared to be thrown
int b = Integer.parseInt(br.readLine());
^

Ways To Handle Checked


Exceptions
Method 1: << Mention thru throws clause>>
import java.io.*;
class Exceptiondemo3
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new inputStreamReader(System.in));

int a = Integer.parseInt(br.readLine());
int b = Integer.parseInt(br.readLine());
System.out.println("Sum is :"+(a+b));
}
}

1. throws clause is used with methods to indicate type of Exception a


method can throw
2. Specifically required for Checked Exceptions [ To Pass Compilation
process]. It can/may be used for unchecked exceptions also.
3. A method can throw as many exceptions.

Ways To Handle Checked


Exceptions
Method 2 << Put
the statements in (cont.)
try catch block and catch >>
import java.io.*;
class Exceptiondemo3
{
public static void main(String args[])
{

BufferedReader br = new BufferedReader(new inputStreamReader(System.in));

try {
int a = Integer.parseInt(br.readLine());
int b = Integer.parseInt(br.readLine());
System.out.println("Sum is :"+(a+b));
}
catch(IOException e) { }
}
}

Exception Handling
Exception Handling Requires the following steps
1. Finding the problem (Identify the statements whose
execution may result in Exception. Put all those
statements in a try{..} block)
2. Receive the exception ( Catch the exception using
catch{..} block)
Provide exception handling code in
catch block.
3. Otherwise throws the exception.

Exception Hadling Syntax


try
{
<statements that can throw exceptions>
}
catch(ExceptionType<1> e1) {.}
catch(ExceptionType<2> e2) {.}
catch(ExceptionType<3> e3) {.}

..
catch(ExceptionType<N> e4) {.}

Important Points :
1. try {} block may have one or
multiple statements.
2. try{} block may throw a single
type of Exception or multiple
exceptions. But at a time it can
throw only single type of
exception.
3. There can be multiple catch() {
.. } blocks associated with
single try{} block.
4. If try{} block can throw multiple
exceptions then user should
catch all exceptions. (one catch
block for each type of
exception)

Catching an Exception
class Exceptiondemo1
{
public static void main(String arhs[])
{
int a=10;
int b= 5;
int c =5;
try
{
int x = a/(b-c);
System.out.println("c="+c);
}
catch(ArithmeticException e)
{
System.out.println(e.toString());
}
int y = a/(b+c);
System.out.println("y="+y);
} }

D:\java\bin>java Exceptiondemo1
java.lang.ArithmeticException: / by zer
y=1

Catching Multiple Exceptions

class Exceptiondemo4
{
public static void main(String args[])
{
int a[]= {5,10};
try
{
int b= Integer.parseInt(args[0]);
int x = a[b]/(b-a[1]);
System.out.println("x="+x);
}

This Statement is outside catch block


and will be executed in any case

catch(ArithmeticException e)
{
System.out.println(e.toString());
}
catch(NumberFormatException e)
{
System.out.println(e.toString());
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.toString());
}

System.out.println("Hello This is Exception Test");


}
}

OUTPUT
What will be o/p if you execute it like
1. Java Exceptiondemo4
2. java Exceptiondemo4 1
3. java exceptiondemo4 oop

NO COMMAND LINE ARGUMENTS


COMMAND LINE ARGUMENTS
PASSED AS 1

COMMAND LINE ARGUMENT


PASSED oop

Nested Try Statements

Nested try blocks


A typical Syntax
try
{
Statement A;
Statement B;
try
{
Statement C;
Statement D;
}
catch(CException e) {
catch(DException e) {
}
catch(AException e) { .
catch(BException e) { .

. }
. }
}
}

try
{
Statement A;
Statement B;
try
{
Statement C;
Statement D;
}
}
catch(AException e) {
catch(BException e) {
catch(CException e) {
catch(DException e) {

.
.
.
.

}
}
}
}

Nested try blocks cont

try
{
Statement A;
Statement B;
try
{
Statement C;
Statement D;
}
catch(CException e)
catch(DException e)
}
catch(AException e) { .
catch(BException e) { .
catch(CException e) { .
catch(DException e) { .

{
{
}
}
}
}

.
.

}
}

Nested try statements Example


class nestedtry
{
public static void main(String args[])
{
int a[] = { 2,5,6};
try // outer try
{
int b = Integer.parseInt(args[0]);
try // inner try
{
int c[] = { 4,5,6};
int d = c[b]/(c[b]-4);
} // End of inner try
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception : "+ e.toString());
System.out.println("By Inner try");
}
catch(ArithmeticException e)
{
System.out.println("Exception : "+ e.toString());
System.out.println("By Inner try");
}
} // End of outer try

// Catch Blocks for outer try


catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception : "+ e.toString());
System.out.println("By Outr try");
}
catch(NumberFormatException e)
{
System.out.println("Exception : "+ e.toString());
System.out.println("By Outer try");
}
} // End of main
} // End of class
D:\java\bin>java nestedtry
Exception : java.lang.ArrayIndexOutOfBoundsException: 0
By Outer try

D:\java\bin>java nestedtry 4
Exception : java.lang.ArrayIndexOutOfBoundsException: 4
By Inner try
D:\java\bin>java nestedtry 0
Exception : java.lang.ArithmeticException: / by zero
By Inner try

Writing Your Own Exceptions


Programmers Can write their own Exception classes apart from javas
library Exceptions.
Programmer can write either checked Exception OR Unchecked
Exception.
To make a checked exception , make your exception class a subclass
of Exception OR any one of its subclass EXCEPT RunTimeException.
class AException extends Exception { }
Checked Exception
class BException extends IOException { ..} Checked Exception

To make a Unchecked exception , make your exception class a


subclass of RunTimeException OR any one of its subclass .
class
class
class
class

XException
YException
ZException
ZException

extends
extends
extends
extends

RunTimeException { }
AritmeticException { }
ArrayIndexOutOfException { }
IndexOutOfBoundsException { }

Creating Unchecked Exception


1. Create an InvalidBOXException which will be
thrown by the constructor of the BOX class
whenever an attempt will be made to create an
invalid BOX object. (Any Dimension = 0 or < 0).

EXAMPLE 1:
class InvalidBOXException extends RuntimeException
{
InvalidBOXException(String msg)
{
super(msg);
System.out.println("An attempt is made to create an Invalid BOx object ");
}
}
class BOX
No Need to mention in throws
{
clause as Exception is Unchecked
private double length;
private double width;
private double height;
BOX(double l, double w, double h) throws InvalidBOXException
{
if( l <=0 || w <= 0 || h <= 0)
throw new InvalidBOXException("Invalid BOX Object creation");
length = l;
width = w;
height = h;
}

double getLength() { return length; }


double getWidth() { return width; }
double getHeight() { return height; }
double Area() { return 2*(length*width + width*height + height*length); }
double Volume() { return length*width*height ; }
}
class exceptiontest1
{
public static void main(String args[])
{

BOX b1 = new BOX(0,0,0);


BOX b2 = new BOX(10,4,5);

System.out.println(Area of b2:+b2.Area());
}
}
D:\java\bin>java exceptiontest1
An attempt is made to create an Invalid BOx object
Exception in thread "main" InvalidBOXException: Inavlid BOX Object
creation
at BOX.<init>(exceptiontest1.java:18)
at exceptiontest1.main(exceptiontest1.java:35)

Change of main method No 1


class exceptiontest1
{
public static void main(String args[])
{
try {
BOX b1 = new BOX(0,0,0);
System.out.println("Area of b1"+b1.Area());
}
// catch(InvalidBOXException e) { }
If these statements are out
catch(Exception e) { };
side try block?
try {
BOX b2 = new BOX(10,4,5);
System.out.println("Area of b2:"+b2.Area());
}
D:\java\bin>java exceptiontest1
// catch(InvalidBOXException e) { }
An attempt is made to create an
catch(Exception e) {};
Invalid BOx object
}}
Area of b2:220.0

Change of Main Method No 2


class exceptiontest1
{
public static void main(String args[])
{
BOX b1;
System.out.println(b1.Area());
}
}
class exceptiontest1
{
public static void main(String args[])
{
BOX b1 = null;
System.out.println(b1.Area());
}
}

<Compile Time Error>


D:\java\bin>javac exceptiontest1.java
exceptiontest1.java:36: variable b1 might
not have been initialized
System.out.println(b1.Area());
^
1 error

<RUNTIME Error>
D:\java\bin>java exceptiontest1
Exception in thread "main"
java.lang.NullPointerException
at
exceptiontest1.main(exceptiontest1.java:3
6)

Checked Exceptions
Make your exception class extends Exception class or any one
of its subclass except RumtimeException.
Checked Exceptions needs to either caught or informed by use
of throws clause
Note down that throw clause is used to throw the exception
where as throws clause is used to inform that an exception is
thrown by the method.
Throw clause is used inside method body where as throws
clause is used with first line of the method.
Throws clause can be used to inform both type of exceptions.
But in case a method is throwing a unchecked exception then it
is not compulsory to inform.
In case a method is throwing a checked Exception, then it has
either to caught the exception or informs by using throws
clause or it can do both.

EXAMPLE 1:
class InvalidBOXException extends Exception
Checked
{
Exception
InvalidBOXException(String msg)
{
super(msg);
System.out.println("An attempt is made to create an Invalid BOx object ");
}
}
class BOX
{
Any Method or constructor which throws an
private double length;
checked Type Exception must inform it thru
private double width;
throws clause
private double height;
BOX(double l, double w, double h)
{
if( l <=0 || w <= 0 || h <= 0)
throw new InvalidBOXException("Inavlid BOX Object creation");
length = l;
width = w;
height = h;
}

double getLength() { return length; }


double getWidth() { return width; }
double getHeight() { return height; }
double Area() { return 2*(length*width + width*height + height*length); }
double Volume() { return length*width*height ; }
}
class exceptiontest1
{
public static void main(String args[])
{
BOX b1 = new BOX(0,0,0);
BOX b2 = new BOX(10,4,5);
System.out.println(Area of b2:+b2.Area());
}
}

D:\java\bin>javac exceptiontest1.java < Compile Time Error>


exceptiontest1.java:18: unreported exception InvalidBOXException; must be
caught or declared to be thrown throw new InvalidBOXException("Inavlid
BOX Object creation");
^
1 error

EXAMPLE 1:
class InvalidBOXException extends Exception
{
InvalidBOXException(String msg)
{
super(msg);
System.out.println("An attempt is made to create an Invalid BOx object ");
}
}
class BOX
{
private double length;
private double width;
private double height;
BOX(double l, double w, double h) throws InvalidBOXException
{
if( l <=0 || w <= 0 || h <= 0)
throw new InvalidBOXException("Inavlid BOX Object creation");
length = l;
width = w;
height = h;
}

double getLength() { return length; }


double getWidth() { return width; }
double getHeight() { return height; }
double Area() { return 2*(length*width + width*height + height*length); }
double Volume() { return length*width*height ; }
}
class exceptiontest1
{
public static void main(String args[]) throws InvalidBOXException
{
BOX b1 = new BOX(0,0,0);
BOX b2 = new BOX(10,4,5);
System.out.println(Area of b2:+b2.Area());
}
}

D:\java\bin>java exceptiontest1
An attempt is made to create an Invalid BOx object
Exception in thread "main" InvalidBOXException: Inavlid BOX Object creation
at BOX.<init>(exceptiontest1.java:18)
at exceptiontest1.main(exceptiontest1.java:36)

Use of finally Clause


finally block may be added immediately after try block or after the last catch
block.
finally block in general used to perform house keeping operations such as
closing files or releasing system resources.
Finally block when present is guaranteed to execute regardless of whether
an exception is thrown or not.
If you want then finally block can be used to handle any exception generated
within a try block.
A method/block can have at most one finally block and multiple catch blocks
exists.
The finally block will not be executed if program exits(either by calling
System.exit() or by causing a fatal error that causes the process to abort).

finally clause Syntax


try
{
..
..
.
}
finally
{
..
..
.
}

try
{
..
..
.
}
catch(.)
{ . }
catch(..)
{ . }
..
..
finally
{
..
..
}

class ex10
{
Example(finally clause)
public static void main(String args[])
{
int a=10;
int b = 20;
try
{
int b1=Integer.parseInt(args[0]);
int x = a/(a-b1);
try
{
int y = b/(b-b1);
}
finally
{
System.out.println("Inner Block executed");
finally
}
{
}
System.out.println("Outer Block executed");
}
}
}

Output
D:\java\bin>java ex10
Outer Block executed
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at ex10.main(ex10.java:9)
D:\java\bin>java ex10 45
Inner Block executed
Outer Block executed
D:\java\bin>java ex10 10
Outer Block executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ex10.main(ex10.java:10)
D:\java\bin>java ex10 20
Inner Block executed
Outer Block executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ex10.main(ex10.java:13)

Example
class AException extends RuntimeException{}
class BException extends AException{}
class CException extends AException{}
class ex11
{
public static void main(String args[])
{
try
{
D:\java\bin>javac ex11.java
int a=10;
ex11.java:14: exception BException has already been caught
}
catch(BException e) {}
catch(AException e) {}
^
catch(BException e) {}
ex11.java:15: exception CException has already been caught
catch(CException e) {}
catch(CException e) {}
}
^
}
2 errors

Creating Hierarchy of Exceptions


1. We can create our own tree of exception classes.
2. All Exceptions classes in tree are either checked or unchecked depending
upon whether the super class is checked or unchecked.
InvalidStudentException
InvalidIdNOException

InvalidIdNoYearException

InvalidNameException

InvalidIdNoDesciplineException

class StudentException extends Exception


{
StudentException(String msg)
{
super(msg);
System.out.println(msg);
}
}
class InvalidNameException extends StudentException
{
InvalidNameException(String msg)
{
super(msg);
System.out.println(msg);
}
}
class InvalidIdException extends StudentException
{
InvalidIdException(String msg)
{
super(msg);
System.out.println(msg);
}}

class InvalidYearException extends InvalidIdException{


InvalidYearException(String msg)
{
super(msg);
System.out.println(msg);
}
}
class InvalidNumberException extends InvalidIdException{
InvalidNumberException(String msg)
{
super(msg);
System.out.println(msg);
}
}

class Student
{
private String name;
private String idno;
private boolean containsAlphabetsOnly(String str)
{
for(int i=0;i<str.length();i++)
{
int j = str.charAt(i);
if(j < 65) return false;
if(j > 125) return false;
if(j > 91 && j < 96) return false;
}
return true;
}

Student(String name,String idno) throws StudentException


{
if(!containsAlphabetsOnly(name))
throw new InvalidNameException("Invalid Name");
int a = Integer.parseInt(idno.substring(0,4));
if( a < 1995 || a > 2007)
throw new InvalidYearException("Invalid Id Year");
int b = Integer.parseInt(idno.substring(8));
if( b <= 0 || b > 999)
throw new InvalidNumberException("Invalid Student Number");
this.name = name;
this.idno = idno;
}
}// End of student class

class exceptiontest
{
public static void main(String args[]) throws StudentException
{
Student std1 = new Student("123","sttts");
}
}

Invalid Name
Invalid Name
Exception in thread "main" InvalidNameException: Invalid Name
at Student.<init>(NewClass2.java:58)
at exceptiontest.main(NewClass2.java:76)
Java Result: 1

??
import java.io.*;
class Sample
{
public static void main(String args[])
{
try
{
int a = 10;
Sample.java:10: exception
}
java.io.IOException is never thrown in body
of corresponding try statement
catch(IOException e) {}
catch(IOException e) {}
}
^
}//End of class
1 error

??
import java.io.*;
class Sample
{
public static void main(String args[])
{
try
{
int a = 10;
}
catch(Exception e) {}
catch(RuntimeException e) {}
}
}//End of class

D:\java\bin>javac Sample.java
Sample.java:11: exception
java.lang.RuntimeException has already been
caught
catch(RuntimeException e) {}
^
1 error

??
class a
{}
class b extends a
{}
class c extends a
{}
class Exceptiondemo2
{
public static void main(String args[])
{
a ex = new b();
c ex1 = (c)ex;
}
}

??
import java.util.*;
class Exceptiondemo2
{
public static void main(String args[])
{
ArrayList al = new ArrayList();
al.add("sunita");
Iterator it = al.iterator();
System.out.println((Integer)it.next());
}
}

??
class Example {
private String key = null;
private Integer value;
public Example(String key, Integer value) {
this.key = key;
this.value = value;
}
public String getKey() {
return this.key;
}
public Integer getValue() {
return this.value;
}
}

??

class Driver
{
static void method() throws Exception
test
{
inside method
try
main
{
throw new Exception();
}
catch(Exception e)
{System.out.println("test");}
System.out.println("inside method");
} // end of method
public static void main(String args[])
throws Exception

class Driver
{
void show()
{try
{ int a = 10/0; }
catch(NullPointerException o)
{}
System.out.println("method");
java.lang.ArithmeticException:
} // end of method
/ by
zero
public static void
main(String
at
args[])
pankaj.Driver.show(st.java:7)
{
at
try
pankaj.Driver.main(st.java:18)
{
java.lang.ArithmeticException:
new Driver().show();
/ by zero
}
catch(Exception e)Main method

??
class Driver
{
void show() throws
ArithmeticException
{int a = 10/0;}
public static void main(String
Exception in thread "main"
args[])
java.lang.ArithmeticExceptio
{
n: / by zero
new Driver().show();
at
}
pankaj.Driver.show(st.java:5
)
at
pankaj.Driver.main(st.java:8
)

??
class Driver
{
public static void main(String...
args) {
{
Object[] s = new String[4];
s[0] = 4.4;
}
}}

Exception in thread "main"


java.lang.ArrayStoreException:
java.lang.Double
at pankaj.Driver.main(st.java:11)

Object Model & Java Type System

Type Inquiry
1. instanceof operator tests whether the type of an object reference is a
subtype of given type or not.

2. Syntax :
if(

instanceof S) { . }

Object
reference

Type [may be a class or


interface]

3. The above statement tests whether e is a instance of type S or not.


4. This statement returns true if e is a direct instance of S or e belongs to
one of the sub classes of S.
5. Instanceof operator can test whether the type of a value is subtype of a
given type or not. But it does not give the exact type to which e
belongs.
6. If e is null then instanceof does not throw an Exception but simply
returns false.

class Class
A Class object is a type descriptor. It contains information
about a given type such as type name and super class.
:Employee

name = Jack
Salary = 50000

:Class

:Class

name = Employee
superclass =

name =java.lang.Object
superclass = null

class Class

Given a object reference we can know the exact type of the object by
using getClass() method

Class c = e.getClass();

getClass() method returns a Class Object. Once you have a class


object its name can be printed as follows

System.out.println(e.getClass().getName());

Adding the suffix .class to a type also yields the Class object.

Rectangle.class, Employee.class , Student.class

Knowing Exact class of


Reference
1. Adding a suffix .class to a class name always yields a Class Object.
2. To test whether std is a reference belonging to class Student or not
use
if (std.getClass() == Student.class)
3. To test whether emp is a refrence for Employee class object or not
if(emp.getClass() == Emplyoee.class)
4. What about Arrays ?

BOX[ ] box = new BOX[5];


Class c = box.getClass();
if( c.isArray())

S.O.P ( Component Type :+ c.getComponentType());

class TypeTest
{
public static void main(String
args[]){
String str = new String("Object");
System.out.println(str.getClass().getNa
me());
// Checking whether str belongs to
Object
if(str instanceof Object)
System.out.println("YES IT
E:\oop>java
IS");
TypeTest
else
java.lang.Strin
System.out.println("NO ITS
g
NOT");

Instance of operator

class aclass
{}
class bclass extends aclass
{ }
class cclass extends aclass
{}
class ch1
{
public static void main(String
args[])
{
aclass aobj = new cclass();
Class cast exception throw
bclass bobj;
if ( aobj instanceof aclass)

Class descriptor
class aclass
{}
class bclass extends aclass
{ }
class cclass extends aclass
{}
class ch1
{
public static void main(String args[])
{
aclass aobj = new cclass();
bclass bobj;
if ( aobj.getClass() == bclass.class )
{
bobj = (bclass) aobj;

class aaa
{}
class bbb extends aaa
{ }
class ddd extends aaa
{}
class ch
{
public static void main(String
args[])
C:\Users\Dell\test.java:12: error: incompatible
{
types: aaa cannot be converted to bbb
aaa aobj = new ddd();
bbb bobj = aobj;
bbb bobj = aobj;
^
}
1 error

Object class
Common super class for all other java classes.
A class which is defined without extends clause is a direct sub
class of Object class.
Methods of Object class applies to all Java Objects.
Important Methods:
1.
2.
3.
4.

String toString()
boolean equals(Object other)
int hashCode()
Object clone()

public String toString()

Returns a string representation of the object


Useful for debugging
toString used by concatenation operator
aString + anObject means aString +
anObject.toString()
User can override the toString() method.

class BOX {

public String
toString() {

}
}

class Student {

public String
toString() {

}
}

toString() continued
toString() is automatically called when you
1. concatenate an object with a string
2. print an object with print or println method
Default implementation of toString() method returns the name
of the class and the hash code of the object.

class Student
{
private String name, idno;
Student(String name, String idno){
this.name = name; this.idno = idno;
}
public String toString(){
return name+" "+idno;
}
}
class HostlerStudent extends Student {
private int hostelCode;
private String hostelName;
private int roomNo;
HostlerStudent(String name, String idno,
int hcode, String hname, int rno){
Super(name,idno);
hostelCode = hcode;
hostelName = hname ;
roomNo = rno;
}
public String toString(){
return super.toString()+" " +hostelName+" " + roomNo;
}
}

public boolean equals(Object


other)
equals method tests whether two objects have equal
contents or not.
Equals method must be reflexive, symmetric and
transitive.
x.equals(x) should return true. (Reflexive)
x.equals(y) returns true iff y.equals(x) returns true
If x.equals(y) returns true and y.equals(z) returns true then
x.equals(z) should also return true.

For any null reference, x.equals(null) should return


false.
For x == y return true
Users can either overload or override equals()
method.

equals() overloading examples


class BOX {
BOX Parameter

public boolean
equals(BOX other) {
<< Implement equals OVERLOADING
logic>>

class
Student {
Student Parameter
}
}
public boolean equals(Student
other) {
<< Implement equals logic>>

equals() overloading examples

class BOX {
Object Type Paramete
..
..
public boolean equals(Object other)
{
BOX other = (BOX) other;
<< Implementclass
equals
logic>>
Student
{
..
}
public boolean equals(Object
}OVERRIDING other) {
Student other = (Student)
other;
<< Implement equals

class Student {
private String name;
private String idno;
.....................
.....................
// Assume Accessor Methods
public boolean equals(Object other) {
if(other == null) return false;
if(this.getClass() != other.getClass())
return false;
if(this == other) return true;
Student std = (Student) other;
boolean b1 = name.equals(other.getName())
boolean b2 = idno.equals(other.getIdno())
if(b1 && b2) return true;
return false;
}
}

Cont

class HostlerStudent extends Student {


private int hostelCode;
private String hostelName;
private int roomNo;
....................
// Assume Accessor Methods
public boolean equals(Object other){
if(other == null) return false;
if(this.getClass() != other.getClass())
return false;
if(this == other) return true;
Student std = (Student) other;
if(!super.equals(std)) return false;
HostlerStudent hstd
= (HostlerStudent) other;
boolean b1 =
hostelCode == other.getHostelCode();
boolean b2 = roomNo == other.getRoomNo();
boolean b3 = hostelName.compareTo(other.hosteName);
if(b1 && b2&&b3) return true;
return false;
} }

Shallow and Deep copy


clone() method is used to make the clone or deep of the object.
Example :
Employee e = new Employee(..);

Employee cloned = (Employee)


e.clone();

Assumption :

Employee class supplies a suitable clone() method

Cloning Conditions
x.clone() != x return true
x.clone().equals(x) return true
x.clone().getClass() == x.getClass() return
true
clone should be a new object but it
should be equals to its original

clone requirements
Any class willing to be cloned must
1.
Declare the clone() method to be public
2.
Implement Cloneable interface and catch
CloneNotSupportedException
class Employee implements Cloneable {
public Object clone() {
try { super.clone() }
catch(CloneNotSupportedException e){ .. }
}
}

Shallow Copy
Clone() method makes a new object of the same type as the
original and copies all fields.
But if the fields are object references then original and clone
can share common sub objects.

Shallow Cloning

Deep Cloning
public class Employee implements Cloneable {
public Object clone() {
try {
Employee cloned = (Employee)super.clone();
cloned.hireDate = (Date)hiredate.clone();
return cloned;
}
catch(CloneNotSupportedException e) {
return null; // won't happen
}
}
}

Java Type System


Set of Values with a set of
Operations that can be applied to the
values.
Example :
int type
Set of values { [-2^31] to
[+2^31-1])}
Operations : All Arithmetic
Operations
1.Java
is Strongly Typed Language because
BOX
typevariable
Set
of all
BOX object
every
must
be declared
with a data
references
type. A variable cannot start off life
area()
, it can
without knowingOperations
the range: of
values
volume()
, toString()
hold, and
once it is declared, the data type
of the variable cannot change.
Type checking is done both at Compile and Run

Values in Java
1.
2.
3.
4.

A Value of Primitive type


A reference to an object
reference to an array
null

Examples :
10 , 10.35 , true
new BOX(10,6,8);
new int[] { 10,6,8}
null

Primitive Type Values


Reference to an object
Reference to array

Note : You can not have a value of type interface.

Sub Types
Sub type specifies the inheritance relationship
either by extending a class or implementing an
interface
A
X
A is super type
of B
B is sub type
of A

Similarly X is super type for Y and Y is sub type for X.


You can substitute a value of subtype whenever
supertype value is expected

Example
Whats Expected

x1

x1 is reference variable of type X?


If X is an interface
RHS can be an instance of any class implementing X.
If X is abstract class
RHS can be an instance of any concrete subclass of X
If X is a concrete class
RHS can be either an instance of X or any of its subclasses

Rules for Subtype Relationships


S is a subtype of T if
1. S and T are the same type
2. S and T are both class types, and T is a direct
or indirect superclass of S
3.S is a class type, T is an interface type,
and S or one of its superclasses implements T
4. S and T are both interface types, and T is a
direct or indirect superinterface of S
5. S and T are both array types, and the component
type of S is a subtype of the component type of T

Examples

LayoutManager super type for JButton


Object is super type for all types
JButton is sub type of Container

FlowLayout is sub type of


LayoutManager
ListIterator is sub type of Iterator

Examples continued
1. Is Container is a subtype of Component ?
2. Is JButton is a subtype of Component ?
3. Is FlowLayout is a subtype of LayoutManager?
4. Is ListIterator is a subtype of Iterator ?
5. Is Rectangle[ ] is a subtype of Shape[ ] ?
6. Is int[ ] is a subtype of Object ?
7. Is int is subtype of long ?
8. Is long is a subtype of int ?

TRUE
TRUE
TRUE
TRUE
TRUE
TRUE
NO
NO

Primitive Types are not implemented as Objects

The ArrayStoreException
Rectangle[] is a subtype of Shape[] ?.

TRUE

Can assign Rectangle[] value to Shape[]


variable:
Rectangle[] r = new Rectangle[10];
Shape[] s = r;
Both r and s are references to the same
array
The assignment
s[0] = new Polygon(); compiles
But Throws an ArrayStoreException at runtime
Each array remembers its component type

Array References

GUI

1.
2.

Mostly the classes graphics category are in two


packages
java.awt.*
javax.swing.*; [ All classes in this package starts
with letter J]
Graphics Programming in Java is Component
oriented.

Partial View of Graphics class


Object
Hierarchy
Color
Graphics
Component

Graphics2D
Button
Canvas
Checkbox
Container
JComponent

Window

AbstractButton
JPanel
JButton

Frame
GridBagLayout
BorderLayout
FlowLayout
BoxLayout
GridLayout
CardLayout

JFrame

Panel
Applet

JApplet
Layout managers for
containers

JFrame in Java
An actual Window having Title Bar, Menu Bar, Borders and resizing corners.
Imporatant Constructors :
1.

JFrame()
Constructs a new frame that is initially invisible.

2. JFrame(String title)
Creates a new, initially invisible Frame with the specified title.

JFrame in Java
Important Methods :
1. Container getContentPane()
Returns the contentPane object for this frame.

2. void setLayout(LayoutManager manager)


Sets the LayoutManager.

3. void setDefaultCloseOperation(int operation)


4. void setSize(FRAME_WIDTH,FRAME_HEIGHT)
5. setVisible(true/false); // Actual Method Java 2 for displaying Frames.

JFrame Examples
JFrame f1 = new JFrame(); // Creates a Frame with no
title

JFrame f2 = new JFrame(My Frame); // Frame with


Title MY Frame
f1.setSize(400,600); // sets size to 400 by 600 pixels
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
;

(Program Terminates when Frame Window is closed)

f1.setVisible(true);

JPanel class
Is just
like a Frame window without Borders and
in Java
a Title.
Flat panel window acts a light weight container
Constructors
JPanel()
Creates a new JPanel with a double buffer and a flow layout.

JPanel(LayoutManager layout)
Create a new buffered JPanel with the specified layout manager

Label

GUI Components

A Label object is a component for placing text in a container.

Button
This class creates a labeled button.

Check Box
A check box is a graphical component that can be in either an on true or off false state.

Text Field
A TextField object is a text component that allows for the editing of a single line of text.

Text Area
A TextArea object is a text component that allows for the editing of a multiple lines of
text.

Component Class Methods


void setBackground(Color c)
void setForeground(Color c)
void setBounds(int x,int y,int width,int
height)
Moves and resizes this component.

void setEnabled(boolean b)
void setVisible(boolean b)
Shows/enable or hides this component depending on the value of parameter b

JLabel Objects in Java


1. Display text or image or both in Java Graphics

2. Constructors :
JLabel()
JLabel(Icon image)

JLabel(String text)
3. Important Methods :
setIcon(Icon icon);

setText(String text);
setSize(width,height);
setForeground(Color.red);

JTextField class
A text field is a text component that displays editable text.
Standard mechanism for input into graphics program.
Constructors :
JTextField()
JTextField(String text)
JTextField(int columns)
JTextField(String text, int columns)

Java.awt.Color class

Every Component can set foreground and background colors.


1. public void setBackground(java.awt.Color c)
2. public void setForeground(java.awt.Color c)
Colors can be set by passing arguments as :
Color.red
Color.black
Color.green

Color(float r, float g, float b)

Layout Managers
Arrangements of several components within a container is called
layout.
Conatiners layout can be set by passing LayoutManager object to
setLayout() method.
Some basic Layouts :
1. FlowLayout :
Lays out components left to right and then starts
from new row when there is not enough room in the current one.
2. BOXLayout :
Lays out components horizontally or vertically
3. BorderLayout :
This layout has five areas for laying out.
NORTH,SOUTH,EAST,WEST and CENTER.

Layout Managers continued


GridLayout :
Arraganges Components in a rectangular grid. All
Components are resized to an identical size.
GridBagLayout:
Also Arraganges Components in a grid but rows
and columns can have different sizes and components can
span multiple rows and columns.

Icon Interface
Used to create and define icons.
public interface Icon
{
public int getIconHeight();
public int getIconWidth();
public void paintIcon(Component c, Graphics g, int x, int y)
}
Paint icon draws Icon on specified location.
Graphics Parameter carries out the Drawing operation.
To use more powerful 2D drawing operations we have to type cast to
Graphics2D
Component is used to get the properties of component.

Icon interface .
paintIcon method receives graphics context of
type Graphics
Actually a Graphics2D object in modern Java
versions
public void paintIcon(Component c, Graphics g, int x, int y)
{
Graphics2D g2 = (Graphics2D)g;
...
}

Drawing Shapes

We can draw objects of any class that implements shape interface


java.lang.Object
java.awt.geom.RectangularShape
java.awt.geom.Rectangle2D implements Shape, Serializable, Cloneable
java.awt.Rectangle

Drawing shapes .
Shape s = .
g2.draw(s);
Shape s = new Rectangle2D.Double(x,y,width,height);
g2.draw(s); // Rectangle will be drawn
Shape s = new Ellipse2D.Double(x,y,width,height);
g2.draw(s); // Ellipse will be drawn
Shape s = new Rectangle2D.Double(x,y,width,width);
g2.drawRect(x,y,width,height); // Rectangle will be drawn

Drawing shapes cont.


Point2D.Double start = new Point2D.Double(x1,y1);
Point2D.Double end = new Point2D.Double(x1,y1);
Shape s1 = new Line2D.Double(start,end);
g2.draw(s1);

Example 1 Circle Icon


import java.awt.geom.*;
import java.awt.*;
import javax.swing.*;
class circleicon implements Icon
{
private int size; // radius
circleicon(int radius) { size = radius;}
public int getIconHeight() { return size;}
public int getIconWidth() { return size;}
public void paintIcon(Component c, Graphics g, int x,int y)
{
Graphics2D g2 = (Graphics2D) g;
Ellipse2D.Double circle = new Ellipse2D.Double(x,y,size,size);
g2.draw(circle);
}

public static void main(String args[])


{
JFrame f = new JFrame("testing");
JButton b = new JButton(new circleicon(50));
f.add(b);
f.setSize(100,100);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Example 2 RectangleIcon
class recticon implements Icon
{
private int height;
private int width;
recticon(int height,int witdh)
{
this.height = height;
this.width = width;
}
public int getIconHeight() { return height;}
public int getIconWidth() { return width;}
public void paintIcon(Component c, Graphics g, int x,int y)
{
Graphics2D g2 = (Graphics2D) g;
Rectangle2D.Double r1 = new Rectangle2D.Double(5,5,x-width,y-height);
g2.draw(r1);
}
}

Adding a Rectangle to Frame


METHOD 1 : Make a Rectangle a Componenet
// A simple Frame with Rectangle Inside
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;

// For Shapes

class rectComponent extends JComponent


{
public void paint(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Rectangle2D.Double rect = new Rectangle2D.Double(0,0,20,30);
g2.draw(rect);
g2.setColor(Color.red);
}
}

class FrameTest
{
public static void main(String args[])
{
JFrame f1 =new JFrame("My Frame");
f1.setLayout(new BorderLayout());
rectComponent r1 = new rectComponent();
f1.setSize(300,400);
f1.add(r1,BorderLayout.CENTER);
//f1.show();
f1.setVisible(true);
}
}

Adding a Rectangle to Frame


METHOD 2 : Make a class implemeting Icon interface
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
class rectComponent implements Icon
{
private int height; private int width;
rectComponent(int h,int w)
{ height = h; width = w; }
public int getIconHeight() { return height; }
public int getIconWidth() { return width; }
public void paintIcon(Component c,Graphics g,int x,int y)
{
Graphics2D g2 = (Graphics2D) g;
Rectangle2D.Double rect = new Rectangle2D.Double(x,y,width,height); // document
//Rectangle rect = new Rectangle(0,0,50,100); // integer
g2.draw(rect);
g2.setColor(Color.red);
g2.fill(rect);
}
}

class FrameTest1
{
public static void main(String args[])
{
JFrame f1 =new JFrame("My Frame");
f1.setLayout(new BorderLayout());
rectComponent r1 = new rectComponent(50,100);

JLabel l1 = new JLabel(r1);


f1.setSize(300,400);
f1.add(l1,BorderLayout.CENTER);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//f1.show(); // Deprecated.
f1.setVisible(true);
}
}

EVENT HANDLING

Event

1.
2.
3.
4.
5.
6.

Object that describes a state change in source


e.g Pressing a Button generates Action Event [
Button is source of Event, Name of the event is
Action]
Every event has a source whose state change causes
the event
Some of the activities that may result in event
generation:
Pressing a Button
Entering a Character from keyboard
Selecting an item in a list
Clicking the mouse
Timer expires
Counter Exceeds

Event Source

Source is an object that generates an event

Internal state of the source changes in some way

When ever source generates an event it is notified to one or more

listeners

Source must register one or more listeners via following methods:

1.

public void addTypeListener(TypeListener el)

2.

public void addTypeListener(TypeListener el) throws


java.util.TooManyListnersException

Second Form allows only single listener to attached to the source.

<<Type>> is the type of the Event

Event Listeners

Object That is notified whenever source


generates a particular type of event
Responsibilities
1. Must register with the source
2. Must implement desired Listener interface

Delegation Event Model

1.
2.
3.

Modern Approach for event handling


Three components
Source [Object which generates the vent]
Event [ Object that indicates state change in Source]
Listener [ Notified Object which carries out some
action whenever event is generated]
Source generates a particular type of event and it
notifies the listener
On receiving notification from source listener carries
out the desired task

Event Sources Examples

1.
2.
3.
4.
5.
6.
7.
8.

User interface components that can generate events


Button
(ActionEvent)
Checkbox
(ItemEvent)
Choice
(ItemEvent)
List
(ActionEvent, ItemEvent)
MenuItem
(ActionEvent, ItemEvent)
Scrollbar
(AdjustmentEvent)
Window
(WindowEvent)
TextBox
(Key event) getKeyChar()

Event Classes
EventObject (Super Class for for all events,
java.util.*)
Object getSource()
String toString()

AWTEvent (Subclass of EventObject, Part of


java.awt.event)
int getID();

ActionEvent (sub class of AWTEvent)


String getActionCommand();

Event Listener Interfaces

1.
2.

Listener must implement suitable event listener interface


in order to execute the code whenever that type of event
is generated
What happens when an event occurs?
Suitable Event object is created
Source invokes the appropriate method provided by the
listener by passing the object created in step1 as
parameter
Examples : ActionListener, MouseListner,
MouseMotionListener

ActionListener Interface
public interface ActionListener
{
public void actionPerformed(ActionEvent ae);
}

MouseListener
public interface MouseListener
{
public void mouseClicked(MouseEvent me);
public void mouseEntered(MouseEvent me);
public void mouseExited(MouseEvent me);
public void mousePressed(MouseEvent me);
public void mouseReleased(MouseEvent me);
}

MouseMotionListener extends MouseListener


public interface MouseListener extends MouseMotionListener
{
public void mouseMoved(MouseEvent me);
public void mouseDragged(MouseEvent me);
}

Design and Implement a Frame


as follows
RED

<< A Label String Here>>


GREEN

Hello

Hi

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class buttonlistener implements ActionListener
{
JLabel l1 ;
Without Inner Classes
buttonlistener(JLabel l1)
{
this.l1 = l1;
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
if(str.equals("Hello"))
l1.setText("Hello How are you");
if(str.equals("Hi"))
l1.setText("Hi How are you");
if(str.equals("RED"))
l1.setForeground(Color.red);
if(str.equals("GREEN"))
l1.setForeground(Color.green);
}
} // End of class

class mainframetest
{
public static void main(String args[])
{
JFrame f1 = new JFrame("Main Frame");
JPanel pnlColor = new JPanel();
pnlColor.setLayout(new BoxLayout(pnlColor,BoxLayout.Y_AXIS));

JPanel pnlGrt = new JPanel(); // panel for greeting buttons


pnlGrt.setLayout(new BoxLayout(pnlGrt,BoxLayout.X_AXIS));
JPanel pnlMsg = new JPanel(); // for label
JButton btnRed = new JButton("RED");
JButton btnGreen = new JButton("GREEN");
JButton btnHello = new JButton("Hello");
JButton btnHi = new JButton("Hi");
pnlColor.add(btnRed);
pnlColor.add(btnGreen);
pnlGrt.add(btnHello);
pnlGrt.add(btnHi);
JLabel l1 =new JLabel("Hello How are you");
pnlMsg.add(l1,BorderLayout.CENTER);

btnRed.addActionListener(new buttonlistener(l1));
btnGreen.addActionListener(new buttonlistener(l1));
btnHello.addActionListener(new buttonlistener(l1));
btnHi.addActionListener(new buttonlistener(l1));
f1.add(pnlColor,BorderLayout.EAST);
f1.add(pnlMsg,BorderLayout.CENTER);
f1.add(pnlGrt,BorderLayout.SOUTH);
f1.setSize(400,600);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

Use anonymous classes


class mainframetest
{
public static void main(String args[])
{
JFrame f1 = new JFrame("Main Frame");
JPanel pnlColor = new JPanel();
pnlColor.setLayout(new BoxLayout(pnlColor,BoxLayout.Y_AXIS));
JPanel pnlGrt = new JPanel(); // panel for greeting buttons
pnlGrt.setLayout(new BoxLayout(pnlGrt,BoxLayout.X_AXIS));
JPanel pnlMsg = new JPanel(); // for label
pnlGrt.setLayout(new BorderLayout());
JButton btnRed = new JButton("RED");
JButton btnGreen = new JButton("GREEN");
JButton btnHello = new JButton("Hello");
JButton btnHi = new JButton("Hi");

pnlColor.add(btnRed);
pnlColor.add(btnGreen);
pnlGrt.add(btnHello);
pnlGrt.add(btnHi);
JLabel l1 =new JLabel("Hello How are you");
pnlMsg.add(l1,BorderLayout.CENTER);
btnRed.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
l1.setForeground(Color.red);
}
});
btnGreen.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
l1.setForeground(Color.green);
}
});

btnHello.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
l1.setText("Hello How are you");
}
});
btnHi.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
l1.setText("Hi How are you");
}
});
f1.add(pnlColor,BorderLayout.EAST);
f1.add(pnlMsg,BorderLayout.CENTER);
f1.add(pnlGrt,BorderLayout.SOUTH);
f1.setSize(400,600);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Icon Frames
RED

<< A Icon Shpae Here>>


GREEN

Circle

Rectangle

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.event.*;

Using Inner classes

class circleicon implements Icon


{
private int size;
circleicon(int radius) { size = radius;}
public int getIconHeight() { return size;}
public int getIconWidth() { return size;}
public void paintIcon(Component c, Graphics g, int x,int y)
{
Graphics2D g2 = (Graphics2D) g;
Ellipse2D.Double circle = new Ellipse2D.Double(x,y,size,size);
g2.draw(circle);
}
}

class recticon implements Icon


{
private int height;
private int width;
recticon(int height,int witdh)
{
this.height = height;
this.width = width;
}
public int getIconHeight() { return height;}
public int getIconWidth() { return width;}
public void paintIcon(Component c, Graphics g, int x,int y)
{
Graphics2D g2 = (Graphics2D) g;
Rectangle2D.Double r1 = new
Rectangle2D.Double(5,5,width,height);
g2.draw(r1);
}
}

class maintest
{
public static void main(String args[])
{
JFrame f1 = new JFrame("Main Frame");
JPanel pnlColor = new JPanel();
pnlColor.setLayout(new BoxLayout(pnlColor,BoxLayout.Y_AXIS));
JPanel pnlGrt = new JPanel(); // panel for greeting buttons

JPanel pnlMsg = new JPanel(); // for label


pnlGrt.setLayout(new BorderLayout());
pnlGrt.setLayout(new BoxLayout(pnlGrt,BoxLayout.X_AXIS));

JButton btnRed = new JButton("RED");


JButton btnGreen = new JButton("GREEN");
JButton btnRec = new JButton(Rectangle");
JButton btnCir = new JButton(Circle");
pnlColor.add(btnRed);
pnlColor.add(btnGreen);
pnlGrt.add(btnRec);
pnlGrt.add(btnCir);
pnlMsg.add(l1,BorderLayout.CENTER);

circleicon cir = new circleicon(50);


recticon rect = new recticon(10,20);
JLabel l1 =new JLabel();
pnlMsg.add(l1);

class demo implements ActionListener


{
public void actionPerformed(ActionEvent e)
{ if(e.getSource().equals(btnRed))
l1.setForeground(Color.red);
if(e.getSource().equals(btnGreen))
l1.setForeground(Color.green);
if(e.getSource().equals(btnCir))
l1.setIcon(cir);
if(e.getSource().equals(btnRec))
l1.setIcon(rect);
}}
demo obj = new demo();
btnRed.addActionListener(obj);
btnGreen.addActionListener(obj);
btnRec.addActionListener(obj);
btnCir.addActionListener(obj);
f1.add(pnlColor,BorderLayout.EAST);

Example TextField Demo


Enter Temperature in Fahrenhiet

<<

OK

Out Put

>>

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class textfielddemo
{
public static void main(String args[])
{
JFrame f1 = new JFrame("Temprature Converiosn Demo");
f1.setLayout(new BorderLayout());
JLabel l1 = new JLabel("Enter Temprature: ");

JLabel l2 = new JLabel();


JTextField txt = new JTextField(10);
JButton btn = new JButton("OK");
JPanel p1 =new JPanel();
p1.add(l1);
p1.add(txt);
p1.add(btn);
f1.add(p1,BorderLayout.NORTH);
f1.add(l2,BorderLayout.CENTER);

btn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
double f = Double.parseDouble(txt.getText());
int c = (int) Math.round(5*(f-32)/9);
txt.setText("");
l2.setText("Temprature in Centigrade is :"+c);
}
});
f1.setSize(400,400);
f1.setLocation(100,200);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Timer class in Java


Used for Animation Pupose
Defined in javax.swing. Package
Generates action events spaced at equal
intervals.
Syntax :
Action Listener
in successive
action
Timer T1 Delay
= new
Time(100,L1);
events [ In this case 100 ms]

T1.start(); //starts generating events


T1.stop(); // stops generating events

Example
Show a Frame which displays texts Hello and Hi
alternatively after 10 ms interval.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class TimerTest
{
static boolean isHello = false;
public static void main(String args[])
{
JFrame f1 = new JFrame();
f1.setSize(400,600);
JLabel label = new JLabel("Hi");
f1.add(label,BorderLayout.CENTER);

ActionListener l1 =new ActionListener()


{
public void actionPerformed(ActionEvent ae)
{
if(isHello)
{
label.setText("Hi");
isHello = false;
}
else
{
label.setText("Hello");
isHello = true;
}
}
};
Timer t1 = new Timer(100,l1);
t1.start();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Animation Effects using Threads

Start

Stop

<< Start>> will display displaying texts Hello and Hi alternatively


<<Stop>> will stop alternating the text.

USING suspend and resume (Java 1.1)


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class LabelThread extends Thread
{
JLabel lbl;
boolean helloFlag;
LabelThread(JLabel lbl)
{
this.lbl = lbl;
helloFlag = true;
}
public void run()
{
try
{
if(helloFlag)
{
lbl.setText("Hi");
helloFlag = false;
}

else
{
lbl.setText("Hello");
helloFlag = true;
}
Thread.sleep(10);
run();
}
catch(InterruptedException ae){}
}
}

class MYFRAME
{
static boolean started =false;
public static void main(String args[])
{
JFrame f1 = new JFrame();
final JLabel lbl = new JLabel("Hello");
final LabelThread T1 = new LabelThread(lbl);
JButton b1 = new JButton("Start");
JButton b2 = new JButton("Stop");
JPanel btnPanel = new JPanel();
btnPanel.add(b1);
btnPanel.add(b2);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.add(lbl,BorderLayout.CENTER);
f1.add(btnPanel,BorderLayout.SOUTH);

b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if(!started)
{
T1.start();
started = true;
return;
}
T1.resume();
}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
T1.suspend();
}
});
f1.setSize(400,600);
f1.show(); } }

Suspend and Resume in Java 2


(Page 308 complete reference)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class LabelThread extends Thread


{
JLabel lbl;
boolean helloFlag;

boolean suspendflag =false;


LabelThread(JLabel lbl)
{
this.lbl = lbl;
helloFlag = true;
}

public void run()


{
try
{
synchronized(this)
{
while(suspendflag)
wait();
}
if(helloFlag)
{
lbl.setText("Hi");
helloFlag = false;
}
else
{
lbl.setText("Hello");
helloFlag = true;
}
Thread.sleep(10);
run();
}
catch(InterruptedException ae){}
}

void mysuspend() { suspendflag = true;}


synchronized void myresume()
{
suspendflag = false;
notify();
}
}

class MYFRAME15
{
static boolean started =false;
public static void main(String args[])
{
JFrame f1 = new JFrame();
final JLabel lbl = new JLabel("Hello");
final LabelThread T1 = new LabelThread(lbl);
JButton btnStart = new JButton("Start");
JButton btnStop = new JButton("Stop");
JPanel btnPanel = new JPanel();
btnPanel.add(btnStart);
btnPanel.add(btnStop);
f1.add(lbl,BorderLayout.CENTER);
f1.add(btnPanel,BorderLayout.SOUTH);

btnStart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if(!started)
{
T1.start();
started = true;
return;
}
T1.myresume();
}
});
btnStop.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
T1.mysuspend();
}
});
f1.setSize(400,600);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.show();
}}

Multi Threading

Thread Class In Java

Defined in java.lang package


Constructors :
1. Thread()
2. Thread(String name)
3. Thread(Runnable r)
4. Thread(Runnable r, String name)
Important Methods : (Next Slide)

Thread Class Methods


1.
2.
3.
4.
5.

public static Thread currentThread()


public string getName() returns name of the thread
public int getPriority() returns priority of the thread
public Boolean isAlive() checks if thread is alive or not
public getState() -> return state of thread

6. public void run()


entry point for the thread
7. static void sleep(long millis) causes the current thread to
sleep for mentioned no of milliseconds
8. static void sleep(long millis, long nano)
9. public void start() to start a thread
10. public stop() to stop a thread (deprecated method)
11. interrupt() interrupt a thread
12. boolean isInterrupted() checks whether the thread is
interrupted or not.

Various Method of Thread


Class

class MainThread {

public static void main(String[] args) {


long id = Thread.currentThread().getId();
String name = Thread.currentThread().getName();
int priority = Thread.currentThread().getPriority();
Thread.State state = Thread.currentThread().getState();
String threadGroupName = Thread.currentThread().getThreadGroup().getName();

System.out.println("id="+id+"; name="+name+"; priority="+priority);


System.out.println("state="+state+";
threadGroupName="+threadGroupName);

System.out.println(Thread.currentThread().isAlive());
id=1; name=main; priority=5
} }
state=RUNNABLE; threadGroupName=main
true

Java Thread Basics


1. Thread Priority

1. Java assigns a thread priority that determines how


that thread should
be treated with respect to other
threads
2. Thread priorities are integers ( 1 to 10) MIN_PRIORITY
=1, MAX_ PRIORITY = 10, NORM_ PRIORITY =5

Thread Basics
2. Thread States :

1. New
2. Runnable
3. Blocked

4. Dead

How To Create a Thread


Two Ways of Creating a
Thread
1. By Extending a Thread
class
2. By Implementing a
Runnable interface

Runnable interface
public interface Runnable
{
public void run();
}
static void sleep(long millis)throws InterruptedException
// pause the execution or give the chance to other
static void sleep(long millis, int nanos)throws InterruptedException

Main Thread
class thread1
{
public static void main(String args[])
{ for(int i=0;i<5;i++)
{ try
{
Thread.sleep(1000);
System.out.println(i);

Output:0
1
2
3

}
catch(InterruptedException e)
{}
System.out.println();
}
Thread t = new Thread();
System.out.println(t.getPriority());
System.out.println(t.isAlive());
System.out.println(t.isInterrupted());
}
}

4
Priority 5
Alive=false
Interrupted= false

To create a new thread either


1. Your class should extend Thread class
OR
2. Your class should implement Runnable
interface
class MyThread extends Threadclass MyThread implements Runnable
{
{
public void run()
public void run()
{
{

}
}
}

Which
is
better
??
Thread or runnable

Using Thread class


class thread2 extends Thread
{ int k;
public void run()
{ for(int i=0;i<5;i++)
System.out.println(this.getName()+" " +k++);
}
public static void main(String args[])
{ thread2 obj1 = new thread2();
thread2 obj2 = new thread2();
obj1.start();
obj2.start();
}
}

Sample Output:
Thread-0 0
Thread-1 0
Thread-0 1
Thread-1 1
Thread-1 2
Thread-1 3
Thread-1 4
Thread-0 2
Thread-0 3
Thread-0 4

Output

class ThreadTest implements Runnable


{
Thread t;
ThreadTest(String t1)
{
t= new Thread(this);
t.start();
//System.out.println(t.getState() + " " + t.getName());
}
public void run()
{
for(int i=0;i<2;i++)
System.out.println(t.getState() + " " + t.getName());
} // end of run
public static void main(String args[])
{
ThreadTest obj = new ThreadTest("Test");
for(int i=0;i<2;i++)
System.out.println(Thread.currentThread().getState() + "
Thread.currentThread().getName());
}
}

" +

Using Runnable interface


class thread3 implements Runnable
{ int k;
Thread t;
String name;
thread3(String s)
{
t= new Thread(this); // passing the reference of runnable
name=s;
t.start();
}
public void run()
{
for(int i=0;i<5;i++)
System.out.println(this.name+" " +k++);
}
public static void main(String args[])
{
thread3 obj = new thread3("th1");
thread3 obj1 = new thread3("th2");
for(int i=0;i<5;i++)
{
System.out.println("Main"+i);
} //thread3 obj2 = new thread3("ss2");
} }

Sample output:
th1 0
th1 1
th1 2
Main0
th1 3
Main1
Main2
th2 0
Main3
th1 4
Main4

Example

class TH1 extends Thread


{
Thread printing Three
public void run()
digit
{
try
Odd Numbers
{
for(int i=101;i<120;i=i+2)
{
System.out.println(i+"By Thread TH1");
Thread.sleep(10);
}
}// End of try
catch(InterruptedException e){}
}// End of run
} //end of TH1

class TH2 extends Thread


{
public void run()
{
int i,j;
try
{
Thread printing Three Digit
for(i=100;i<=120;i++)
{
prime Numbers
for(j=2;j<i/2;j++)
{
if(i % j != 0) continue;
else
break;
}
if( j >= i/2)
{
System.out.println(i+"By Thread TH2");
Thread.sleep(100);
}
} // end of for
}// end of try
catch(InterruptedException e){}
}// End of run
} //end of TH1

class THtest
{
public static void main(String args[])
{
Thread t1 = new TH1();
Thread t2 = new TH1();
Thread t3 = new TH2();
Thread t4 = new TH2();
t1.start();
t4.start();
System.out.println(Main Method Exited);
}
}

Sample output
101By Thread TH1
Main Method Exited
101By Thread TH2
103By Thread TH1
105By Thread TH1
107By Thread TH1
109By Thread TH1
111By Thread TH1
113By Thread TH1
115By Thread TH1
117By Thread TH1
119By Thread TH1
103By Thread TH2
107By Thread TH2
109By Thread TH2
113By Thread TH2

Join methods
void join() throws
interruptedException
void Join(ms) throws
interruptedException
// wait at most millisecond for this
thread to die.
This method waits for the thread on which it is called. Wait for termination of that thread ( a thread
on which it's been called ).
It is useful to manage co-related / inter- dependant tasks and functionalities implementation with
multiple threads.

Join method
class TestJoinMethod1 extends Thread{
public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(this.getName()+ +i);
}
}
public static void main(String args[]){
TestJoinMethod1 t1=new TestJoinMethod1();
TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1();

System.out.println("Thread 1 is
started");
t1.start();
try{
t1.join();
}catch(Exception
e){System.out.println(e);}
System.out.println("Thread 2 is
started");
t2.start();
System.out.println("Thread 3 is
started");
t3.start();
System.out.println(Main thread is
existed);
}
}

Join method
Thread 1 is started
Thread-0 1
Thread-0 2
Thread-0 3
Thread-0 4
Thread-0 5
Thread 2 is started
Thread 3 is started
Main thread is existed
Thread-2 1
Thread-1 1
Thread-2 2
Thread-1 2
Thread-2 3
Thread-1 3
Thread-2 4
Thread-1 4
Thread-2 5
Thread-1 5

Join Example

class TestJoinMethod2 extends Thread{


public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(this.getName()+ " " + i);
}
}
public static void main(String args[]){
TestJoinMethod2 t1=new TestJoinMethod2();
TestJoinMethod2 t2=new TestJoinMethod2();
TestJoinMethod2 t3=new TestJoinMethod2();
t1.start();
try{
t1.join(1500);
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}

Thread-0 1
Thread-0 2
Thread-0 3
Thread-1 1
Thread-0 4
Thread-2 1
Thread-1 2
Thread-2 2
Thread-0 5
Thread-1 3
Thread-2 3
Thread-1 4
Thread-2 4
Thread-1 5
Thread-2 5

Daemon Method

public void setDaemon(boolean status)


//is used to mark the current thread as daemon thread or user thread.

public boolean isDaemon()


//is used to check that current is daemon.

Demon Example
class JavaDaemonThread {
public static void main(String[] args) throws
InterruptedException {
Thread dt = new Thread(new DaemonThread(), "dt");
dt.setDaemon(true);
dt.start();
Thread.sleep(30000);
System.out.println("Finishing program");
} }
class DaemonThread implements Runnable
{
public void run() {
while(true){ processSomething();
}
}
private void processSomething() {
try {
System.out.println("Processing daemon thread");
Thread.sleep(5000);
}
catch (InterruptedException e) {
e.printStackTrace() }
} }

Yield
Method
static void Yield()
This method causes the currently executing thread object to temporarily
pause and allow other threads to execute. It does not guaranteed to have
any effect at all.

class ThreadDemo implements Runnable {


Thread t;
ThreadDemo(String str) {
t = new Thread(this, str);
// this will call run() function
t.start();
}
public void run() {
for (int i = 1; i < 6; i++) {
System.out.println(t.getName() + " " + i);
// yields control to another thread every 5
iterations
if ((i % 5) == 0) {
System.out.println(Thread.currentThread().getNam
e() + " yielding control...");
/* causes the currently executing thread
object to temporarily
pause and allow other threads to execute */
Thread.yield();

public static void main(String[]


args) {
new ThreadDemo("Thread 1");
new ThreadDemo("Thread 2");
new ThreadDemo("Thread 3");
} }

Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread

1 1
3 1
2 1
3 2
1 2
1 3
3 3
2 2
3 4
3 5
1 4
1 5
1 yielding control...
3 yielding control...
2 3
2 4
2 5
2 yielding control...
1 has
finished executing.
3 has
finished executing.
2 has
finished executing.

Corruption of Data
class callMe
{
public void call(String msg)
{ System.out.println("[" + msg);
try{
Thread.sleep(1000);
}
catch(Exception e) {}
System.out.println("]");
}
}
class caller implements Runnable
{ String msg;
callMe target; //shared object
Thread th;
caller(String s, callMe t)
{ msg=s;
target=t;
th = new Thread();
th.start();
}

public void run()


{
target.call(msg);
}
}

class Sync
{
public static void main(String args[])
{ callMe obj = new callMe();
caller th1 = new caller("one",obj);
caller th2 = new caller("two",obj);
caller th3 = new caller("three",obj);
System.out.println(main Thread);
}
}

Corrupting a Shared Data


Structure

Threads share access to common objects and hence can conflict with
each other and corrupt data structure.
Race Condition may occur
Race

Condition occurs if the effect of multiple threads


on shared data depends on the order in which threads are
scheduled.


1.
2.
3.
4.

1.
2.

Synchronization

Key for synchronization is monitor or semaphore.


Monitor is an object that is used as mutually exclusive lock
Only one thread can own a monitor at a given time.
Acquiring a lock or monitor is said to have entered the monitor.
All other threads attempting to acquire the lock or enter the
monitor are blocked.
Java implements synchronization thru
Synchronized methods (Object Locks)
Synchronize Statement

Synchronized Block
Example

class callMe
{
public void call(String msg)
{ System.out.println("[" + msg);
try{
Thread.sleep(1000);
}
catch(Exception e) {}
System.out.println("]");
}
}
class caller implements Runnable
{ String msg;
callMe target;
Thread th;
caller(String s, callMe t)
{ msg=s;
target=t;
th = new Thread();
th.start();
}

public void run()


{ synchronized(target)
target.call(msg);
}
}

class Sync
{
public static void main(String args[])
{ callMe obj = new callMe();
caller th1 = new caller("one",obj);
caller th2 = new caller("two",obj);
caller th3 = new caller("three",obj);
System.out.println(main Thread);
}
}

Synchronized Method
Example

class callMe
{
synchronized public void call(String msg)
{ System.out.println("[" + msg);
try{
Thread.sleep(1000);
}
catch(Exception e) {}
System.out.println("]");
}
}
class caller implements Runnable
{ String msg;
callMe target; //shared object
Thread th;
caller(String s, callMe t)
{ msg=s;
target=t;
th = new Thread();
th.start();
}

public void run()


{
target.call(msg);
}
}

class Sync
{
public static void main(String args[])
{ callMe obj = new callMe();
caller th1 = new caller("one",obj);
caller th2 = new caller("two",obj);
caller th3 = new caller("three",obj);
System.out.println(main Thread);
}
}

SINGLE BUFFER
PRODUCER CONSUMER

class Q
{
int n;
synchronized int get()
{
return n;
}
synchronized void put(int n)
{
this.n=n;
}
} // end of class Q

class producer implements Runnable


{ Q q;
Thread t;
producer(String name, Q q)
{
this.q = q;
t= new Thread(this,name);
t.start();
}
public void run()
{
int i=0;
while(i<10)
{
q.put(i++);
System.out.println("producer " + i);
}
} // end of run
} // end of producer

class consumer implements Runnable


{
Q q;
Thread t;
consumer(String name, Q q)
{
this.q = q;
t= new Thread(this,name);
t.start();
}
public void run()
{
int i=0;
while(i<9)
{
i= q.get();
System.out.println("consumer "+ i);
}
} // end of run
} // end of consumer

class PandC
{
public static void main(String args[])
{
Q q= new Q();
producer p = new producer("producer",q);
consumer c= new consumer("consumer",q);
//try{
// p.t.join();
// c.t.join();
// }
// catch(InterruptedException e){}
System.out.println(Thread.currentThread().getNa
me());
}
}

SINGLE BUFFER USING


THREAD SLEEP

class Q
{ int n;
synchronized int get()
{
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{}
return n;
}
synchronized void put(int n)
{
this.n=n;
try
{
Thread.sleep(1000);
}
catch(InterruptedException
e){}
}
} // end of class Q

class producer implements Runnable


{ Q q;
Thread t;
producer(String name, Q q)
{ this.q = q;
t= new Thread(this,name);
t.start();
}
public void run()
{ int i=0;
while(i<10)
{ q.put(i);
System.out.println(this.getName() + +
i);
i++;
}
}
}

class consumer implements Runnable


{ Q q;
Thread t;
consumer(String name, Q q)
{ this.q = q;
t= new Thread(this,name);
t.start();
}
public void run()
{ int i=0;
while(i<9)
{
i= q.get();
System.out.println("consumer "+ i);
}
}
} // end of consumer

class PandC
{
public static void main(String args[])
{Q q= new Q();
producer p1 = new producer("producer1",q);
//producer p2 = new producer("producer2",q);
consumer c= new
consumer("consumer",q);
}
}

Single producer
producer 0
consumer 0
producer 1
consumer 1
producer 2
consumer 2
producer 3
consumer 3
producer 4
consumer 4
producer 5
consumer 5
producer 6
consumer 6
producer 7
consumer 7
producer 8
consumer 8
producer 9
consumer 9

Two Producers
producer-1 0
consumer 0
producer-2 0
consumer 0
producer-1 1
consumer 1
producer-2 1
consumer 1
producer-1 2
consumer 2
producer-2 2
consumer 2
producer-1 3
consumer 3
producer-2 3
producer-2 4
consumer 4
producer-1 4
consumer 4
producer-2 5
producer-2 6
consumer 6

producer-1 5
consumer 5
producer-2 7
consumer 7
producer-1 6
consumer 6
producer-2 8
consumer 8
producer-1 7
consumer 7
producer-2 9
consumer 9
producer-1 8
producer-1 9

Multi Threading

Inter Thread Communication/ Cooperation

Three methods used for inter Thread communication and co1.


2.
3.
A.

B.

C.

operation
final void wait() throws InterruptedException
final void notify();
final void notifyAll();
wait()
Tells the calling thread to give up monitor/lock and go to sleep until
some other thread calls notify.
Notify()
Wakes up the thread that call called wait() on the same object.
Calling object does not live the lock. It lives the lock after
completion of synchronized block/ method. Thus it is called notify
and continue.
notifyAll()
Wakes up the all the threads that call called wait() on the same
object. One of the threads will be granted the access.

Inter Thread Communication/ Cooperation

SINGLE BUFFER WAIT() &


NOTIFY()

class Q
{
int n;
boolean valueset=false;
synchronized int get()
{
try{
while(valueset==false) // busy waiting
wait(); // leave the lock
}
catch(InterruptedException e) {}
valueset=false;
notify();
// it will not leave the lock but inform the other thread
// other thread will join the waiting queue
return n;
}
synchronized void put(int n)
{
try
{
while(valueset == true) // busy waiting
wait(); // leave the lock
this.n=n;
valueset=true;
notify();
}
catch(InterruptedException e){}
}
} // end of class Q

class producer implements Runnable


{
int n;
Q q;
Thread t;
producer(String name, Q q,int n)
{
this.n=n;
this.q = q;
t= new Thread(this,name);
t.start();
}
public void run()
{
while(true)
{
q.put(n);
System.out.println(t.getName() + " "+
n);
n++;
}
}

class consumer implements Runnable


{
Q q;
Thread t;
consumer(String name, Q q)
{
this.q = q;
t= new Thread(this,name);
t.start();
}
public void run()
{
while(true)
{
i= q.get();
System.out.println(t.getName()+" "+
i);
}
}
} // end of consumer

class PandC
{
public static void main(String args[])
{
Q q= new Q();
producer p1 = new producer("producer1",q,100);
consumer c= new
consumer("consumer",q);
}
}

Sample Output
producer-1 100
producer-1 101
consumer 100
consumer 101
producer-1 102
consumer 102

BOUNDED BUFFER

class BoundedQueue<E>
{
public BoundedQueue(int capacity)
{
elements = new Object[capacity];
head = 0;
tail = 0;
size = 0;
}
public synchronized E remove()
throws InterruptedException
{
while (size == 0) wait();
E r = (E) elements[head];
head++;
size--;
if (head == elements.length)
head = 0;
notifyAll();
return r;
}

public synchronized void add(E newValue)


throws InterruptedException
{
while (size == elements.length) wait();
elements[tail] = newValue;
tail++;
size++;
if (tail == elements.length)
tail = 0;
notifyAll();
}
private Object[] elements;
private int head;
private int tail;
private int size;
}

class Consumer implements Runnable


{
private BoundedQueue<String> queue;
private int greetingCount;
private static final int DELAY = 10;
public Consumer(BoundedQueue<String> aQueue, int count)
{
queue = aQueue;
greetingCount = count;
}
public void run()
{
try
{
int i = 1;
while (i <= greetingCount)
{
String greeting = queue.remove();
System.out.println(greeting);
i++;
Thread.sleep((int) (Math.random() * DELAY));
}
}
catch (InterruptedException exception)
{
} } // end of run
}

class Producer implements Runnable


{private String greeting;
private BoundedQueue<String> queue;
private int greetingCount;
private static final int DELAY = 10;
}
public Producer(String aGreeting, BoundedQueue<String> aQueue, int count)
{
greeting = aGreeting;
queue = aQueue;
greetingCount = count;
}
public void run()
{
try
{
int i = 1;
while (i <= greetingCount)
{
queue.add(i + ": " + greeting);
i++;
Thread.sleep((int) (Math.random() * DELAY));
}
} // end of run
catch (InterruptedException exception)
{
} } // end of producer

class ThreadTester
{
public static void main(String[] args)
{
BoundedQueue<String> queue = new BoundedQueue<String>(10);
final int GREETING_COUNT = 10;
Runnable run1 = new Producer("Hello, World!", queue, GREETING_COUNT);
Runnable run2 = new Producer("Goodbye, World!", queue, GREETING_COUNT);
Runnable run3 = new Consumer(queue, 2 * GREETING_COUNT);
Thread thread1 = new Thread(run1);
Thread thread2 = new Thread(run2);
Thread thread3 = new Thread(run3);
thread1.start();
thread2.start();
thread3.start();
}
}

Deadlock
When two threads have a circular dependence on a
pair of synchronized objects.
Declaring methods synchronized ensures that
threads executes them fully not partially. { Not
Enough to ensure that program runs correctly}

class SyncThread implements Runnable{


private Object obj1;
private Object obj2;
public SyncThread(Object o1, Object o2)
{
this.obj1=o1;
this.obj2=o2;
}
public void run()
{
String name = Thread.currentThread().getName();
System.out.println(name + "acquiring lock on "+obj1);
synchronized (obj1) {
System.out.println(name + "acquired lock on "+obj1);
work();
System.out.println(name + " acquiring lock on "+obj2);
synchronized (obj2) {
System.out.println(name + " acquired lock on "+obj2);
work();
}
System.out.println(name + " released lock on " +obj2);
}
System.out.println(name + " released lock on " +obj1);
System.out.println(name + " finished execution.");
}

private void work() {


try
{
Thread.sleep(30000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}

class ThreadDeadlock {
public static void main(String[] args) throws InterruptedException {
Object obj1 = new Object();
Object obj2 = new Object();
Object obj3 = new Object();
Thread t1 = new Thread(new SyncThread(obj1, obj2), "t1");
Thread t2 = new Thread(new SyncThread(obj2, obj3), "t2");
Thread t3 = new Thread(new SyncThread(obj3, obj1), "t3");
t1.start();
Thread.sleep(5000);
t2.start();
Thread.sleep(5000);
t3.start();
}
}

t1acquiring lock on java.lang.Object@25d35bf2


t1acquired lock on java.lang.Object@25d35bf2
t2acquiring lock on java.lang.Object@28825459
t2acquired lock on java.lang.Object@28825459
t3acquiring lock on java.lang.Object@31602bbc
t3acquired lock on java.lang.Object@31602bbc
t1 acquiring lock on java.lang.Object@28825459
t2 acquiring lock on java.lang.Object@31602bbc
t3 acquiring lock on java.lang.Object@25d35bf2

Solution of DeadLock
Avoid Nested Locks
Lock Only What is Required
Avoid waiting indefinitely

public void run()


{
String name = Thread.currentThread().getName();
System.out.println(name + "acquiring lock on "+obj1);
synchronized (obj1)
{
System.out.println(name + "acquired lock on "+obj1);
work();
}
System.out.println(name + " acquiring lock on "+obj2);
synchronized (obj2)
{
System.out.println(name + " acquired lock on "+obj2);
work();
}
System.out.println(name + " released lock on " +obj2);
System.out.println(name + " released lock on " +obj1);
System.out.println(name + " finished execution.");
}

t1acquiring lock on java.lang.Object@25d35bf2


t1acquired lock on java.lang.Object@25d35bf2
t2acquiring lock on java.lang.Object@28825459
t2acquired lock on java.lang.Object@28825459
t3acquiring lock on java.lang.Object@31602bbc
t3acquired lock on java.lang.Object@31602bbc
t1 acquiring lock on java.lang.Object@28825459
t2 acquiring lock on java.lang.Object@31602bbc
t1 acquired lock on java.lang.Object@28825459
t2 acquired lock on java.lang.Object@31602bbc
t3 acquiring lock on java.lang.Object@25d35bf2
t3 acquired lock on java.lang.Object@25d35bf2
t1 released lock on java.lang.Object@28825459
t1 released lock on java.lang.Object@25d35bf2
t1 finished execution.
t2 released lock on java.lang.Object@31602bbc
t2 released lock on java.lang.Object@28825459
t2 finished execution.
t3 released lock on java.lang.Object@25d35bf2
t3 released lock on java.lang.Object@31602bbc
t3 finished execution.
BUILD SUCCESSFUL (total time: 1 minute 12 seconds)

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