Académique Documents
Professionnel Documents
Culture Documents
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>
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
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
static boolean
static boolean
static boolean
static boolean
static boolean
static boolean
static boolean
static boolean
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)
sort(long[] a)
static void
static void
sort(Object[] a)
static void
sort(Object[] a, Comparator c)
static void
static void
static void
sort(short[] a)
static void
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();
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();
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
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;
}
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;
}
Predict OutPut
int x[] = new int[10];
for(int i=0;i<x.length;i++)
System.out.print(x[i]+" ");
0000000000
"+ 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
Todays Lecture
String
Strings in Java
1. strings in java are handled by two classes String &
StringBuffer
4. String(String x)
<< Creates a String frorm another String >>
5. String(byte bytes[]) << Creates a String frorm byte Array>>
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.
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
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
Examples :
char ch = xyz.charAt(1); // ch will be y
char ch = xyz.charAt(3);
//StringIndexOutOfBoundsException
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(" ");
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)
getBytes[]
toCharArray[ ]
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);
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
if (s1 == s2)
S.O.P(Hello);
else
S.O.P(Hi);
if (s1.equals(s2))
S.O.P(Hello);
else
S.O.P(Hi);
Hello
Hello
String s1 = "OOP";
String s2 = "OOP";
String s3 = "java";
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
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
1.
2.
3.
1.
2.
1.
2.
3.
Home Exercise
1.
2.
String toLowerCase()
String toUpperCase()
Examples :
S.O.P(object.toUpperCase());
S.O.P(OBJECT.toLowerCase());
No of characters to be
matched
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));
Index 20 to 39
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.
this
is
a
test
BITS Pilani, Pilani Campus
StringTokennizer
Constructors
StringTokennizer(String str)
StringTokennizer(String str, String delimiters)
Examples
String str = "BITS C342,83,Object Oriented Programming,Lecture Section
3;MWF 9,Sunita;Bansal,3160;
StringTokenizer
Methods
1. int countTokens()
Counts the number of tokens in StringTokennizer based upon
delimiters
3. String nextToken()
Returns the next token in String form
4. Object nextElement()
Same as nextToken() but returns next Token in Object Form not in
String Form
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
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
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
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());
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
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()
StringBuffer(int size)
StringBuffer(String str)
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
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
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
1.
2.
3.
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
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.
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>);
Example
public interface A
{
double PI = 3.14156;
void show();
void display();
}
<<interface>> <<interface>>
A
<<interface>>
Interface Example
interface Area
{
double PI = 3.1456;
Area
double area();
double perimeter();
}
interface Volume extends Area
{
double volume();
}
Volume
<<interface>>
Area
Circle
<<class>>
{
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);
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();
}
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.
.
}
.
}
.
}
{
......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
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
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());
}
}
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]);
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()
{}
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
Length:1.0
Length:5.0
Length:8.0
Length:10.0
Length:10.0
ArrayList Class
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);
System.out.println(lst1.size()
);
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
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);
}
}
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);
}
}
}
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
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
//
//
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
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); }}
Nested Classes
Non-static nested class(inner class)
Member inner class
Anonymous inner class
Local inner class
Nested Class
Java programming language allows you to define a class
within another class
class OuterClass
{ ...
Enclosing Class
OR Outer 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
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();
}
}
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
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
a=30
b=20
this.b=-40
Outer b=10
Anonymous Inner
classes
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
} [;]
class innertest1
{
public static void main(String args[])
{
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;
}
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 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
{
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);
}
} // 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
}
}
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.
Types of Exceptions
A.
Unchecked Exceptions
Whether you catch the exception or not compiler will pass the
compilation process.
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
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]);
}
}
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)
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
Catch
block
the
checked
exception
in
try
catch
Throwable
Exception
Error
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());
int a = Integer.parseInt(br.readLine());
int b = Integer.parseInt(br.readLine());
System.out.println("Sum is :"+(a+b));
}
}
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.
..
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
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);
}
catch(ArithmeticException e)
{
System.out.println(e.toString());
}
catch(NumberFormatException e)
{
System.out.println(e.toString());
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e.toString());
}
OUTPUT
What will be o/p if you execute it like
1. Java Exceptiondemo4
2. java Exceptiondemo4 1
3. java exceptiondemo4 oop
. }
. }
}
}
try
{
Statement A;
Statement B;
try
{
Statement C;
Statement D;
}
}
catch(AException e) {
catch(BException e) {
catch(CException e) {
catch(DException e) {
.
.
.
.
}
}
}
}
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) { .
{
{
}
}
}
}
.
.
}
}
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
XException
YException
ZException
ZException
extends
extends
extends
extends
RunTimeException { }
AritmeticException { }
ArrayIndexOutOfException { }
IndexOutOfBoundsException { }
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;
}
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)
<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;
}
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;
}
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)
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
InvalidIdNoYearException
InvalidNameException
InvalidIdNoDesciplineException
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;
}
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;
}
}}
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
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();
System.out.println(e.getClass().getName());
Adding the suffix .class to a type also yields the Class object.
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()
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(BOX other) {
<< Implement equals OVERLOADING
logic>>
class
Student {
Student Parameter
}
}
public boolean equals(Student
other) {
<< Implement equals logic>>
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
Assumption :
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
}
}
}
Values in Java
1.
2.
3.
4.
Examples :
10 , 10.35 , true
new BOX(10,6,8);
new int[] { 10,6,8}
null
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
Example
Whats Expected
x1
Examples
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
The ArrayStoreException
Rectangle[] is a subtype of Shape[] ?.
TRUE
Array References
GUI
1.
2.
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.
JFrame Examples
JFrame f1 = new JFrame(); // Creates a Frame with no
title
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
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.
void setEnabled(boolean b)
void setVisible(boolean b)
Shows/enable or hides this component depending on the value of parameter b
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
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.
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
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
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);
}
}
// For Shapes
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);
}
}
class FrameTest1
{
public static void main(String args[])
{
JFrame f1 =new JFrame("My Frame");
f1.setLayout(new BorderLayout());
rectComponent r1 = new rectComponent(50,100);
EVENT HANDLING
Event
1.
2.
3.
4.
5.
6.
Event Source
listeners
1.
2.
Event Listeners
1.
2.
3.
1.
2.
3.
4.
5.
6.
7.
8.
Event Classes
EventObject (Super Class for for all events,
java.util.*)
Object getSource()
String toString()
1.
2.
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);
}
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));
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.*;
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
Circle
Rectangle
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.event.*;
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
<<
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: ");
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);
}
}
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);
Start
Stop
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(); } }
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
class MainThread {
System.out.println(Thread.currentThread().isAlive());
id=1; name=main; priority=5
} }
state=RUNNABLE; threadGroupName=main
true
Thread Basics
2. Thread States :
1. New
2. Runnable
3. Blocked
4. Dead
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
}
}
}
Which
is
better
??
Thread or runnable
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
" +
Sample output:
th1 0
th1 1
th1 2
Main0
th1 3
Main1
Main2
th2 0
Main3
th1 4
Main4
Example
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
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
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.
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();
}
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);
}
}
Threads share access to common objects and hence can conflict with
each other and corrupt data structure.
Race Condition may occur
Race
1.
2.
3.
4.
1.
2.
Synchronization
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();
}
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();
}
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 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());
}
}
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 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
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.
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 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;
}
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 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();
}
}
Solution of DeadLock
Avoid Nested Locks
Lock Only What is Required
Avoid waiting indefinitely