Professional Documents
Culture Documents
Eee Unit V
Eee Unit V
Eee Unit V
PACKAGES
In java, package is the way of grouping a variety of classes and interfaces together.
The package act as a container for classes.
Types of packages in Java
1. Java API Packages
2. User-defined Packages
JAVA API PACKAGES
Java API provides a large number of classes grouped into different packages according
to their functionality.
Java
lang
PACKAGE NAME
java.lang
java.util
java.io
java.awt
java.net
java.applet
util
io
awt
net
applet
CONTENTS
Language support classes that are
automatically imported.
They include classes for primitive types,
strings, math functions etc.,
Contains classes such as hash tables,
vectors, random numbers and date etc.,
They provide facilities for input/output
support
Contains a set of classes for implementing
graphical user interface.
Contains classes for networking
Contains classes for creating and
implementing applets
1
Package containing
awt package
awt
Color
Package containing
classes
Font
Graphics
Image
Classes containing
methods
The classes of the package can be included in one or more programs by using the
import statements at the top of the file.
import packagename.classname;
or
import packagename.*;
For example, the Color class in the awt package can be imported in two ways:
1. import java.awt.Color;
or
2. import java.awt.*;
2. ACCESSING A PACKAGE
The general form of import statement for accessing a user-defined package is as
follows:
import package1.[package2] .classname;
or
import package1.[package2].*;
Here package1 is the name of the top-level package, package2 is inside package1.
PACKAGE EXAMPLE
Create a folder pack1. The package named pack1 contains a single class class1.
Step 1: Creating the package
class1.java
package pack1;
// package declaration
public class class1
// Class defintion
{
public void add(int a, int b)
{
int r1=a+b;
System.out.println("The sum of two numbers:" +r1);
}
public void sub(int a, int b)
{
int r2=a-b;
System.out.println("The difference of two numbers:" +r2);
}
3
class Testpack
OUTPUT:
The sum of two numbers:30
The difference of two numbers:10
The product of two numbers:100
The quotient of two numbers:15
{
public static void main(String arg[])
{
class1 ob=new class1();
ob.add(10,20);
ob.sub(20,10);
ob.mul(10,10);
ob.div(30,2);
}
}
INTERFACES:
An interface is a collection of abstract methods and constant variables.
A class implements an interface, thereby inheriting the abstract methods of the
interface.
In java, a subclass cannot have more than one superclass, but it can have more
than one interface.
The concept of interface enables us to create classes without the problems
created by multiple inheritance.
DEFINING AN INTERFACE:
Syntax:
interface interfacename
{
variable declaration;
methods declaration;
}
EXTENDING INTERFACES:
Like classes, interfaces can also be extended (inherited). This can be done by
using the extends keyword.
Syntax:
1.An interface can be extended from another interface
interface NAME2 extends NAME1
Interface NAME1
{
//declare final variables and abstract methods
Interface NAME2
}
5
Interface
NAME1
Interface
NAME2
{
Interface
NAME3
IMPLEMENTING INTERFACES:
Syntax:
1.The abstract methods and final variables of an interface can be implemented in a
class by using the following syntax
class NAME2 implements NAME1
Interface NAME1
{
//define the class
Class NAME2
2. In java, a subclass cannot have more than one superclass, but it can have more
than one interface, implemented as follows:
class NAME3 implements NAME1,NAME2
Interface
NAME1
Interface
NAME2
{
//define the class
}
Class
NAME3
Class
NAME1
Interface
NAME2
Class
NAME3
6
In java, a subclass cannot have two superclasses but it can be inherited from
multiple interfaces or a subclass can be inherited from one super class and one
interface.
Class roll
Interface
sports
Class test
Class result
In this hierarchy, the result class has two parents. One is the test class and
the other is an interface named sports. The following program illustrates
the use of interface to substitute multiple inheritance in java.
//PROGRAM : hybrid.java
class roll
{
int rollno;
void getroll(int a)
{
rollno=a;
}
void putroll()
{
System.out.println("Roll no: "+rollno);
}
}
class test extends roll
{
int m1,m2;
void getmark(int x, int y)
{
m1=x;
m2=y;
}
void putmark()
{
System.out.println("Marks obtained");
System.out.println("Mark 1=" +m1);
System.out.println("Mark 2=" +m2);
}
}
7
interface sports
{
final float credit=10.5F;
// Final variable declared
void putcredit();
//Abstract method declared
}
class result extends test implements sports
{
float total;
public void putcredit()
{
total=m1+m2+credit;
putroll();
putmark();
System.out.println("Sports credit:" + credit);
System.out.println("Total score:" +total);
}
}
class hybrid
OUTPUT
{
public static void main(String arg[])
Roll no: 101
{
Marks obtained
result ob=new result();
Mark 1=90
ob.getroll(101);
Mark 2=95
ob.getmark(90,95);
Sports credit:10.5
ob.putcredit();
Total score:195.5
}
}
---------------------------------------------------------------------------------------------------------DIFFERENCE BETWEEN CLASS AND INTERFACE
No
CLASS
INTERFACE
1
The variables of the class can be The variables of an interface are
constant or variable
always declared as constant. i.e their
values are final.
2
The class definition can contain The methods in an interface must be
method definition. The methods abstract. These methods are defined
can be abstract or non-abstract
by the class that implements the
interface
3
Objects can be created
Objects cannot be created. It can only
be inherited
4
It can use access specifiers like It can only use the public access
public, private or protected
specifier
INTERFACE
ABSTRACT CLASS
Interface contains abstract methods Abstract class can have methods
and cannot have implementations
with implementation and abstract
methods without implementations
Variables of a interface are final
Variables of an abstract class may
contain non-final variables
Members of an interface are public Members of a abstract class can be
by default
public, private, protected etc.,
A class can implement multiple
A class can extend only one abstract
interfaces
class
Interfaces are slower compared to
Faster than interfaces.
abstract class due to extra
indirection
2
3
4
5
=======================================================================
EXCEPTION HANDLING
Tasks
1.
2.
3.
4.
EXCEPTION TYPE
ArithmeticException
ArrayIndexOutOfBoundsException
ArrayStoreException
FileNotFoundException
IOException
NumberFormatException
OutOfMemoryException
SecurityException
CAUSE OF EXCEPTION
Caused by math errors such as division by
zero
Caused by bad array indexes
Caused when a program tries to store the
wrong type of data in an array.
Caused by an attempt to open a file that
does not exist.
Caused by general I/O failures, such as
inability to read or write from the file
Caused when a conversion between
strings and number fails
Caused when there is not enough
memory to allocate a new object
Caused when an applet tries to perform
an action that is not allowed by
browsers security setting
9
StackOverFlowException
10
Throws
exception
object
Exception
object creator
catch block
Statements that handles
the exception
Exception
handler
Try block:
Try block contains code that is likely to cause an error condition and throw an
exception
Catch block:
The catch block catches the exception thrown by the try block and handles it
appropriately.
Example 1: Try-Catch block for exception handling
Error2.java
class Error2
{
public static void main(String arg[])
{
int a=10;
int b=5;
int c=5;
int x,y;
try
{
x=a/(b-c);
System.out.println("x=" +x);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
y=a/(b+c);
System.out.println("y=" + y);
}
}
OUTPUT:
Division by zero
y=1
While executing this program, the program did not stop at the point when
exception is raised.
The Exception is found, handled and then the program continued its execution.
If the same code has been executed without try-catch blocks, then the program
would have terminated after displaying runtime errors.
11
}
catch( Exceptiontype1 e)
{
// Statements that processes the exceptiontype1
}
catch( Exceptiontype2 e)
{
// Statements that processes the exceptiontype2
}
EXAMPLE: EXCEPTION HANDLING USING MULTIPLE CATCH BLOCKS
Error3.java
class Error3
{
public static void main(String arg[])
{
int a[ ]={5,10};
int b=5;
try
{
int x=a[2]/b-a[1];
System.out.println(x= +x);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero error");
OUTPUT:
}
catch(ArrayIndexOutOfBoundsException e)
Array Index Error
{
System.out.println("Array Index Error");
y=2
}
catch(ArrayStoreException e)
{
System.out.println("Wrong Data Type");
}
int y=a[1]/a[0];
System.out.println(y=+y);
}
}
The array element a[2] does not exist because the array a has only two
elements with indexes a[0] and a[1].
12
Index
a[2]
is
outside
the
array
boundary,
thus
raising
ArrayIndexOutOfBoundsException.
This exception is handled by catch(ArrayIndexOutOfBoundsException e)
Remaining catch blocks are skipped from execution.
THROWS
If a method is capable of causing an exception that it does not handle, then the
throws clause is used in the method definition statement to guard them against
the exception.
A throws keyword lists the types of exceptions that a method might throw.
Example: throwseg.java
class throwseg
{
static void divide() throws ArithmeticException
{
int x=22, y=0,z;
z=x/y;
}
public static void main(String arg[])
{
try
{
divide();
}
catch(ArithmeticException e)
{
System.out.println("Caught the exception:" +e);
}
}
}
OUTPUT:
Caught the exception:java.lang.ArithmeticException: / by zero
FINALLY BLOCK
The finally block may be added immediately after the try block or after the try
block or after the last catch block.
When a finally block is defined, this is guaranteed to execute, whether or not
an exception is thrown.
Syntax:
try
{
}
13
catch( Exceptiontype1 e)
{
// Statements that processes the exceptiontype1
}
catch( Exceptiontype2 e)
{
// Statements that processes the exceptiontype2
}
finally
{
}
try
//Checking whether the given number is 0 - 9
{
if((x<=0) || (x>=9))
{
Newexception e= new Newexception(The number should be in range 0
to 9");
throw e;
//Throws exception object to the handler
}
else if((y<=0) || (y>=9))
{
Newexception e= new Newexception("The number should be in range 0
to 9");
throw e;
//Throws exception object to the handler
}
else
{
z=x+y;
System.out.println("Result=" +z);
}
}
//End of try block
catch(Newexception e)
// Catch block to handle own exception
{
System.out.println(e);
}
finally
{
System.out.println("Execution over");
}
} //End of main()
}
//End of class
OUTPUT:
First run
Enter the first number
5
Enter the Second number
5
Result=10
Execution over
Second run
MULTITHREADING
Thread:
A thread is similar to a program that has a single flow of control. It has a beginning, a
body and an end and executes commands sequentially.
MULTITHREADING
Main Thread
Start
Start
Start
Switching
Thread A
Switching
Thread B
Thread C
The above java program contains four threads. One main thread and three
other threads.
During execution, the main thread and the other threads A,B & C run
concurrently and share the resources.
Since threads in Java are subprograms of the main application program and
share the same memory space, they are known as lightweight threads.
Since all the threads are running on a single processor, the flow of execution is
shared between threads.
The Java interpreter handles the switching of control between the threads
in such a way that it appears like they run concurrently.
Mutlithreading enables the programmer to do multiple things at one time.
For example, we can send printing tasks into background and continue editing
the word document in foreground. This considerably improves the speed of our
operation.
16
CREATING THREADS
Threads can be created in two ways:
1. By extending the Thread class.
2. By implementing the Runnable Interface.
*1.CREATING THREADS BY EXTENDING THE THREAD CLASS.
The process for thread creation involves 3 steps:
Step1: Define a class that extends(inherits) from the Thread class
Syntax:
class mythread extends Thread
{
}
Here, Thread is the predefined class of the lang package, to implement
multithreading process in Java
Step 2: Implement the run() method
The run() is the main portion of any thread. Using this run() method the
threads can be implemented.
The run() method has been inherited from Thread class and overridden to
implement the code to be executed by our thread.
Syntax:
class mythread extends Thread
{
.
..
public void run()
{
//statements implemented for thread
..
..
}
}
Step 3: Start the thread
Create an object for the user-defined thread class defined above.
Start the threads inside the main() function
Syntax:
mythread ob=new mythread();
ob.start();
The start() method is used to invoke the run() method defined inside the class. So,
the thread starts its execution and becomes active after run() method is invoked.
17
//Runnable object
// Thread object
4. The start() method is invoked on the Thread object created in the previously.
t1.start();
---------------------------------------------------------------------------------------------------------EXAMPLE : CREATING THREADS USING THREAD CLASS
class A extends Thread
{
public void run()
{
for(int i=1; i<=5;i++)
{
System.out.println("From Thread A, i=" + i);
}
}
}
class B extends Thread
{
public void run()
{
for(int j=1; j<=5;j++)
{
System.out.println("From Thread B, j=" + j);
}
}
}
class C extends Thread
{
public void run()
{
for(int k=1; k<=5;k++)
{
System.out.println("From Thread C, K=" + k);
}
}
}
OUTPUT:
From
From
From
From
From
From
From
From
From
From
From
From
From
From
From
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
A, i=1
C, K=1
C, K=2
C, K=3
C, K=4
C, K=5
B, j=1
B, j=2
B, j=3
B, j=4
B, j=5
A, i=2
A, i=3
A, i=4
A, i=5
18
class Threadtest
{
public static void main(String arg[])
{
A ob1=new A();
B ob2=new B();
C ob3=new C();
ob1.start();
ob2.start();
ob3.start();
}
}
The output for the multithreaded program is not sequential. They do not follow
19
1. NEWBORN STATE
If the start() method is called the thread moves to the runnable state.
2. RUNNABLE STATE
In the runnable state, the thread is ready for execution and is waiting for
the availability of the processor.
The threads have joined the queue of threads that are waiting for
execution. It will be served in first-come, first-serve manner.
20
3. RUNNING STATE
In this state, the processor has given its time for execution to the threads
waiting in the queue.
A running thread can relinquish( give up) its control in any of the following
situations
Case 1: suspend()
It can be suspended using the suspend() method.
The suspended thread can be re-invoked by using the resume() method.
This approach is useful when we want to block the thread for sometime,
but not want to kill it.
Case 2: sleep(time)
An active thread can be put to sleep for a specified time period, where the
time is in milliseconds.
The thread is out of the runnable queue for this time period.
After the specified time, the thread re-enters the runnable state.
Case 3: wait()
An active can be told to wait until some occurs. This is done by using the wait()
method.
The notify() method schedules to run the thread again.
21
4. BLOCKED STATE
A thread is said to be in blocked state, when it is prevented from entering
into the runnable state and then the running state.
This happens when the thread is subject to suspend, sleep or wait.
A blocked thread is not runnable , not dead.
5. DEAD STATE
A running thread will be destroyed when it has completed the execution of
run() method.
The thread can also be destroyed voluntarily by use of stop() method.
The thread that can be destroyed using the stop() method in either new born
state, active or blocked state.
EXAMPLE USING THREAD METHODS
class A extends Thread
{
public void run()
{
for(int i=1; i<=5;i++)
{
if(i==1)
yield();
System.out.println("From Thread A, i=" + i);
}
}
}
class B extends Thread
{
public void run()
{
for(int j=1; j<=5;j++)
{
System.out.println("From Thread B, j=" + j);
if(j==3)
stop();
}
}
}
class C extends Thread
{
public void run()
{
for(int k=1; k<=5;k++)
{
System.out.println("From Thread C, K=" + k);
if(k==1)
{
try
{
sleep(1000);
}
22
catch(Exception e)
{
System.out.println(e);
}
}
}
}
}
class Threadmethod
{
public static void main(String arg[])
{
A ob1=new A();
B ob2=new B();
C ob3=new C();
ob1.start();
ob2.start();
ob3.start();
}
}
OUTPUT:
From Thread
From Thread
From Thread
From Thread
From Thread
From Thread
From Thread
From Thread
From Thread
From Thread
From Thread
From Thread
From Thread
B, j=1
B, j=2
B, j=3
C, K=1
A, i=1
A, i=2
A, i=3
A, i=4
A, i=5
C, K=2
C, K=3
C, K=4
C, K=5
This program used the yield() method in thread A. Although thread A started
first, it will give up its control to thread B.
The sleep() method in thread C, started sleeping when k==1. After 1000
milliseconds, it will wake up and continue its execution. During this sleeping
period thread A will be executed.
Thread priority
The threads of same priority are given equal treatment by the java scheduler.
So, they share the processor in first-come first-serve basis.
Java also permits to set the priority of a thread using setPriority() method.
Syntax:
threadobject. setpriority (integer number);
SYNCHRONIZATION
When two or more threads need access to a shared resource (file or memory),
they need some way to ensure that the resource will be used by only one
thread at a time.
For example, Consider that one thread may try to read from the file, while
another thread is still writing to the same file.
Here, conflict occurs. The read process ends with wrong result by reading the
old entries of the file.
To overcome this
synchronization.
problem,
java
enables
technique
known
as
The keyword synchronized is used while declaring both the read() and write()
functions.
Syntax
class A extends Thread
{
public void run()
{
synchronized void read()
{
// Read from the file
}
}
}
class B extends Thread
{
public void run()
{
synchronized void write()
{
// Write contents to the file
}
}
}
When a method is declared as synchronized, Java creates a monitor and hands
it over to the thread that calls the method first.
As long as the thread holds the monitor, no other thread can enter into the
synchronized section.
=======================================================================
24
STRINGS
Strings represent a sequence of characters. In java, strings are the class objects and
implemented using two classes
i)
String
ii)
StringBuffer
A java string is not a character array and is not NULL terminated.
Declaring A String Object:
String stringname=new String(Text);
(or)
String stringname(Text);
---------------------------------------------------------------------------------------------------------JAVA PROGRAM TO PERFORM STRING MANIPULATIONS
---------------------------------------------------------------------------------------------------------stringmanip.java
class stringmanip
{
public static void main(String arg[])
{
String s1="HelloEEE";
String s2;
System.out.println("Original string:" + s1);
// 1. COnverting string to lower case
s2=s1.toLowerCase();
System.out.println("1. Small case string:" + s2);
//2. COnverting to upper case
String s3;
s3=s1.toUpperCase();
System.out.println("2. Upper case string:" + s3);
//3. Replace a character by another
String s4;
s4=s1.replace('H','h');
System.out.println("3. String Replace:" + s4);
25
OUTPUT
Original string:HelloEEE
1. Small case string:helloeee
2. Upper case string:HELLOEEE
3. String Replace:helloEEE
4. Equals method:Strings are not equal
5. Equals method by ignoring case of characters:Strings are equal
6. Length of the string:8
7. The character at position 2 is:e
8. Substring is of HelloEEE:Hell
9. The index of character 'l' is:2
10. Concatenated String:HelloEEE Welcome
=====================================================================================
Using
A stream in Java is a path along which data flows. It has a source and
destination
In file processing, input refers to the flow of data into a program and output
means the flow of data out of a program.
input and output streams:
Java streams are classified into basic types, input stream and output stream.
Input stream extracts data from the source and sends it to the program
Output stream takes data from the program and sends it to the destination.
27
Character Stream
Classes
Input Stream
Classes
Memory
Output
Stream
File
Pipe
Reader
Classes
Memory
Writer
Classes
File
Pipe
28
InputStream class
The input stream classes are used to read 8-bit bytes. It includes the super
class known as InputStream
InputStream methods
Method
read()
read(byte b[])
read(byte b[],int n,int m)
skip(n)
reset()
close()
Description
Reads a byte from the input stream
Reads an array of bytes into b
Reads m bytes starting from nth byte
Skips over n bytes from the input stream
Goes back to the beginning of the stream
Closes the input stream
2.
3.
4.
5.
6.
7.
8.
readInt()
readLong()
readFloat()
readDouble()
readLine()
readChar()
readBoolean()
OutputStream class
The output stream classes are used to write 8-bit bytes. It includes the super
class known as OutputStream
OutputStream methods
Method
write()
write(byte b[])
write(byte b[], int n, int m)
close()
flush()
Description
Writes a byte to the output stream
Writes all bytes in the array b to the output stream
Writes m bytes of array b starting from nth byte
Closes the output stream
Flushes the output stream
30
The character streams can be used to read and write 16-bit unicode characters.
Java provides two kinds of byte stream classes
1.Reader Stream class
2.Writer Stream class
The Reader class contains methods that are identical to InputStream class, but
the Reader class is designed to handle character input.
31
The Writer class contains methods that are identical to OutputStream class, but
the Writer class is designed to handle character output.
CharacterStream classes
Reader
BufferedReader
LineNumberReader
ByteStream classes
InputStream
BufferedInputStream
LineNumberInputStream
CharArrayReader
FileReader
PipedReader
StringReader
None
ByteArrayInputStream
FileInputStream
PipedInputStream
StringInputStream
DataInputStream
CharacterStream classes
Writer
BufferedWriter
CharArrayWriter
ByteStream classes
OutputStream
BufferedOutputStream
ByteArrayOutputStream
32
Writing to files
Writing to a pipe
Writing to a String
Writing primitive
datatypes
FileWriter
PipedWriter
StringWriter
None
FileOutputStream
PipedOutputStream
StringOutputStream
DataOutputStream
INPUT/OUTPUT EXCEPTIONS
I/O Exception class
Function
EOFException
FileNotFoundException
InterruptedIOException
IOException
int ch;
while((ch=in.read()) != -1)
{
out.write(ch);
}
33
catch(IOException e)
{
System.out.println(e);
System.out.println(-1);
}
}
READING/WRITING BYTES
Example for Byte Stream classes
WriteBytes.java
import java.io.*;
class WriteBytes
{
public static void main(String arg[])
{
//Declare and initialize a byte array
byte cities [ ]= {'D','E','L','H','I','\n','C','H','E','N','N','A','I'};
int ch;
//Create an output filestream
FileOutputStream out=null;
try
{
out=new FileOutputStream("city.txt"); //connect outputstream to file
out.write(cities);
//write data to the stream
out.close();
}
catch(IOException e)
{
System.out.println(e);
}
//Create an output filestream
FileInputStream in=null;
try
{
in=new FileInputStream("city.txt");
//connect inputstream to file
while((ch=in.read()) != -1)
//Read until end of the file
{
System.out.print( (char) ch);
}
in.close();
}
OUTPUT:
catch(IOException e)
{
System.out.println(e);
}
}
DELHI
CHENNAI
=====================================================================================
34