Professional Documents
Culture Documents
OOPS Unit 5
OOPS Unit 5
OOPS Unit 5
Unit – V
Syllabus:
Inheritance – interfaces and inner classes - exception handling – threads - Streams
and I/O
PART – A
1
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
2
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
variable declaration;
methods declaration;
}
10. What are the steps involved in creating our own package?
The steps involved in creating our own package are,
• Declare the package at the • Create a sub directory.
beginning of the file. • Store the listing
• Define the class and declare it as • Compile the file
public.
11. Define thread. (April/May 2011)
A thread is similar to a program that has a single flow of control. It is a tiny
program or module that runs in parallel with others.
12. Define Multitasking or multithreading. (Nov/Dec 2013)
Multitasking or multithreading is the ability to execute several programs
simultaneously. A program that contains multiple flows of control is known as a
multithreaded program.
13. What are the ways to create a thread? (May/Jun 2013)
A thread can be created in two ways,
• By creating a thread class – extends Thread class
• By converting a class to a thread – implements Runnable interface
14. How do you stop and block a thread?
A thread can be stopped using the stop (). It can be blocked using sleep (), suspend ()
and wait () methods.
15. What are the states in the life cycle of a thread?
The various states are,
• Newborn • Blocked
• Runnable • Dead
• Running
3
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
4
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
5
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
6
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
7
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Polymorphism allows one interface to be used for a set of actions i.e. one name
may refer to different functionality. Polymorphism allows a object to accept different
requests of a client (it then properly interprets the request like choosing appropriate
method) and responds according to the current state of the runtime system, all
without bothering the user.
8
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
contains a method with the same name and signature as in the super class then it is
called as method overriding.
9
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
10
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
A final class cannot be extended. A final class implicitly has all the methods
declared as final, but not necessarily the data members.
The syntax of declaring a final type method is:
11
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
An abstract method one that have the empty implementation. All the methods
in any interface are abstract by default. Abstract method provides the standardization
for the “name and signature" of any method. One can extend and implement to these
methods in their own classes according to the requirements.
12
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
PART-B
1. Explain about Inheritance in Java? (April/May 2011) (Nov/ Dec 2011)
Definition 1:
The mechanism of deriving a new class from an already existing class is
known as inheritance.
Definition 2:
Types:
Single inheritance
Multi-level inheritance
Hierarchical inheritance
Hybrid inheritance
Inheritance class:
Syntax:
// body of class.
13
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Note:
Example:
14
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Note:
Private members of superclass is not accessible in subclass,
o superclass is also called parentclass or baseclass,
o subclass is also called childclass or derivedclass.
1. SUPER:
Definition:
Syntax:
.super(arg-list)
15
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Example:
16
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Super can also be used to call methods that are hidden by a subclass.
2. FINAL:
Definition:
i. Final variables
When we put final keyword before method than it becomes final method.
To prevent overriding of method final keyword is used, means final
method can‟t be override.
17
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Example:
18
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Definition:
Defining a method in the subclass that has the same name, same arguments
and same return type as a method in the superclass and it hides the super
class method is called method overriding.
Example:
Xsub(int z , int y)
Output :
{
super y = 200
super(y);
sub z = 100
this.z=z;
}
19
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Overloading VS Overriding:
Multilevel Inheritance:
20
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Note:
The class student serves as a base class for the derived class marks,
which in turn serves as a base class for the derived class percentage.
The class marks is known as intermediated base class since it provides a
link for the inheritance between student and percentage.
The chain is known as inheritance path.
When this type of situation occurs, each subclass inherits all of the
features found in all of its super classes. In this case, percentage inherits
all aspects of marks and student.
21
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
3. When a class hierarchy is created, in what order are the constructors for
the classes that make up the hierarchy called?
22
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
NOTE:
The answer is that in a class hierarchy, constructors are called in order
of derivation, from superclass to subclass.
As you can see from the output the constructors are called in order of
derivation.
If you think about it, it makes sense that constructors are executed in
order of derivation.
Definition:
23
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
In other words, it is the type of the object being referred to (not the type
of the reference variable) that determines which version of an overridden
method will be executed.
class A public class Dynamic_disp
{ {
void callme() public static void main(String args[])
{ {
System.out.println("Inside A's callme A a = new A(); // object of type A
method"); B b = new B(); // object of type B
} C c = new C(); // object of type C
} A r; // obtain a reference of type A
class B extends A r = a; // r refers to an A object
{ // override callme() r.callme();
void callme() // calls A's version of callme
{ r = b;
System.out.println("Inside B's callme // r refers to a B object
method"); r.callme();
} // calls B's version of callme
} r = c; // r refers to a C object
class C extends A r.callme();
{ // override callme() // calls C's version of callme
void callme() }
{ }
System.out.println("Inside C's callme Output :
method");
} Inside A's callme method
} Inside B's callme method
Inside C's callme method
24
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
NOTE:
Here reference of type A, called r, is declared.
The program then assigns a reference to each type of object to r and uses
that reference to invoke callme( ).
25
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Any class that includes an interface must implement all of the methods.
Variables can be declared inside interface declarations.
They are implicitly final and static, means they can not be changed by
implementing it in a class.
They must also be initialized with a constant value.
Example :
interface Item interface Area
{ {
static final int code = 100; static final float pi = 3.14F;
static final String name = "Fan"; float compute ( float x, float y );
void display ( ); void show ( );
} }
26
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Implementing interfaces
To implement an interface, include the implements clause in a class
definition, and then create the methods declared by the interface.
The general form of a class that includes the implements is
Access-specifier class classname [extends superclass]
[implements interface, [, interface..]]
{
// class body
}
Note:
When implementing an interface method, it must be declared as public.
It is possible for classes that implement interfaces to define additional
members of their own.
Example:
class circle implements area
{
Public float compute(float x,float y)
{
return(pi*x*x);
}
}
27
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
28
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Definition 2:
If a class is declared within another class or interface is called nested
class.
Syntax:
//outer class
class OuterClass
{ //inner class
class InnerClass {
}
}
Note:
Inner classes which are not method local, static or anonymous are normal
inner class.
Example:
//outer class
class OuterClass {
//inner class
class InnerClass {
}
}
29
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
1 outer.class
2 inner$outer.class
Note: You can’t directly execute the inner class’s .class file with java
command.
30
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
your code because you can rarely do anything about an error. For
example, if a stack overflow occurs, an error will arise. They are also
ignored at the time of compilation.
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class.
The exception class is a subclass of the Throwable class. Other than the
exception class there is another subclass called Error which is derived
from the Throwable class.
Errors are not normally trapped form the Java programs. These
conditions normally happen in case of severe failures, which are not
handled by the java programs.
Errors are generated to indicate errors generated by the runtime
environment. Example: JVM is out of Memory. Normally programs
cannot recover from errors.
The Exception class has two main subclasses: IOException class and
RuntimeException Class.
31
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Exceptions Methods:
Following is the list of important medthods available in the Throwable class.
32
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Catching Exceptions:
A method catches an exception using a combination of the try and catch
keywords.
A try/catch block is placed around the code that might generate an
exception.
Code within a try/catch block is referred to as protected code, and the
syntax for using try/catch looks like the following:
try
{
//Protected code
}
catch(ExceptionName e1)
{
//Catch block
}
Example:
The following is an array is declared with 2 elements. Then the code tries
to access the 3rd element of the array which throws an exception.
33
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
OUTPUT:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
try
{
//Protected code
}
catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
34
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Example:
try
{
file = new FileInputStream(fileName);
x = (byte) file.read();
}catch(IOException i)
{
i.printStackTrace();
return -1;
}catch(FileNotFoundException f) //Not valid!
{
f.printStackTrace();
return -1;
}
import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
35
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
A method can declare that it throws more than one exception, in which
case the exceptions are declared in a list separated by commas.
For example, the following method declares that it throws a
RemoteException and an InsufficientFundsException:
import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}
36
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
Example:
37
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
OUTPUT:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
Note:
A catch clause cannot exist without a try statement.
It is not compulsory to have finally clauses when ever a try/catch block
is present.
The try block cannot be present without either catch clause or finally
clause.
Any code cannot be present in between the try, catch, finally blocks.
38
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
You just need to extend the Exception class to create your own Exception
class. These are considered to be checked exceptions.
The following InsufficientFundsException class is a user-defined
exception that extends the Exception class, making it a checked
exception.
An exception class is like any other class, containing useful fields and
methods.
Example:
39
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
40
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
}
}
public double getBalance()
{
return balance;
}
public int getNumber()
{
return number;
}
}
41
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
OUTPUT:
Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
Common Exceptions:
The two categories of Exceptions and Errors.
JVM Exceptions: - These are exceptions/errors that are exclusively or
logically thrown by the JVM. Examples : NullPointerException,
ArrayIndexOutOfBoundsException, ClassCastException,
Programmatic exceptions . These exceptions are thrown explicitly by
the application or the API programmers Examples:
IllegalArgumentException, IllegalStateException.
42
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Multitasking allow to execute more than one tasks at the same time, a
task being a program.
In multitasking only one CPU is involved but it can switches from one
program to another program so quickly that's why it gives the
appearance of executing all of the programs at the same time.
Multitasking allow processes (i.e. programs) to run concurrently on the
program.
For Example running the spreadsheet program and you are working with
word processor also. Multitasking is running heavyweight processes by a
single OS.
Multithreading:
43
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
When a program contains multiple threads then the CPU can switch
between the two threads to execute them at the same time.
44
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
New: A new thread begins its life cycle in the new state. It remains in this
state until the program starts the thread. It is also referred to as a born
thread.
Runnable: After a newly born thread is started, the thread becomes
runnable. A thread in this state is considered to be executing its task.
Waiting: Sometimes a thread transitions to the waiting state while the
thread waits for another thread to perform a task.A thread transitions
back to the runnable state only when another thread signals the waiting
thread to continue executing.
Timed waiting: A runnable thread can enter the timed waiting state for
a specified interval of time. A thread in this state transitions back to the
runnable state when that time interval expires or when the event it is
waiting for occurs.
Terminated: A runnable thread enters the terminated state when it
completes its task or otherwise terminates.
45
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Thread Priorities:
Every Java thread has a priority that helps the operating system
determine the order in which threads are scheduled.
Java priorities are in the range between MIN_PRIORITY (a constant of 1)
and MAX_PRIORITY (a constant of 10). By default, every thread is given
priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should
be allocated processor time before lower-priority threads.
Creating a Thread:
You will define the code that constitutes the new thread inside run()
method. It is important to understand that run() can call other methods,
use other classes, and declare variables, just like the main thread can.
After you create a class that implements Runnable, you will instantiate
an object of type Thread from within that class. Thread defines several
constructors. The one that we will use is shown here:
46
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
o void start( );
Example:
47
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
OUTPUT:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
48
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
The second way to create a thread is to create a new class that extends
Thread, and then to create an instance of that class.
The extending class must override the run( ) method, which is the entry
point for the new thread. It must also call start( ) to begin execution of
the new thread.
Example:
49
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
OUTPUT:
50
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
Thread Methods:
51
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
52
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Example:
53
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
{
private int number;
public GuessANumber(int number)
{
this.number = number;
}
public void run()
{
int counter = 0;
int guess = 0;
do
{
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName()
+ " guesses " + guess);
counter++;
}while(guess != number);
System.out.println("** Correct! " + this.getName()
+ " in " + counter + " guesses.**");
}
}
54
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();
System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try
{
thread3.join();
}catch(InterruptedException e)
{
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);
thread4.start();
System.out.println("main() is ending...");
}
}
55
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
OUTPUT:
Starting hello thread...
Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Thread-2 guesses 27
Hello
** Correct! Thread-2 in 102 guesses.**
Hello
Starting thread4...
Hello
Hello
..........remaining result produced.
Thread Synchronization
When two or more threads need access to a shared resource, they need
some way to ensure that the resource will be used by only one thread at
a time.
The process by which this synchronization is achieved is called thread
synchronization.
56
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Syntax:
synchronized(object) {
// statements to be synchronized
}
Example:
57
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
58
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
ob3.t.join();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}
OUTPUT:
[Hello]
[World]
[Synchronized]
10. Write about Java – (Nov/Dec 2010) (April/May 2011) (Nov/ Dec 2011)
i. Streams I/O
ii. File handling concept
Java - Streams, Files and I/O
The stream in the java.io package supports many data such as
primitives, Object, localized characters etc.
A stream can be defined as a sequence of data. The InputStream is
used to read data from a source and the OutputStream is used for
writing data to a destination.
59
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Each time that read( ) is called, it reads a character from the input
stream and returns it as an integer value.
It returns .1 when the end of the stream is encountered. As you can see,
it can throw an IOException.
Example:
60
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
OUTPUT:
Enter characters, 'q' to quit.
123abcq
1
2
3
a
b
c
q
Example:
61
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
str = br.readLine();
System.out.println(str);
} while(!str.equals("end"));
}
}
OUTPUT:
This method writes to the stream the byte specified by byteval. Although byteval
is declared as an integer, only the low-order eight bits are written.
Example:
62
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
import java.io.*;
// Demonstrate System.out.write().
class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
OUTPUT:
Note:
You will not often use write( ) to perform console output because print( )
and println( ) are substantially easier to use.
63
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
1. FileInputStream:
This stream is used for reading data from the files.
Objects can be created using the keyword new and there are several
types of constructors available.
(i) Following constructor takes a file name as a string to create an
input stream object to read the file.:
64
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
2. FileOutputStream:
FileOutputStream is used to create a file and write data into it.
The stream would create a file, if it doesn't already exist, before opening
it for output.
Here are two constructors which can be used to create a
FileOutputStream object.
(i) Following constructor takes a file name as a string to create an input
stream object to write the file.:
65
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Example:
import java.io.*;
66
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
try{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("C:/test.txt");
for(int x=0; x < bWrite.length ; x++){
os.write( bWrite[x] ); // writes the bytes
}
os.close();
1. File Class
2. FileReader Class
3. FileWriter Class
67
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
Directories in Java:
Creating Directories:
There are two useful File utility methods which can be used to create
directories:
The mkdir( ) method creates a directory, returning true on
success and false on failure. Failure indicates that the path
specified in the File object already exists, or that the directory
cannot be created because the entire path does not exist yet.
The mkdirs() method creates both a directory and all the parents
of the directory.
import java.io.File;
class CreateDir {
public static void main(String args[]) {
String dirname = "/tmp/user/java/bin";
File d = new File(dirname);
// Create directory now.
d.mkdirs();
}
}
68
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
You can call list( ) on that object to extract the list of other files and
directories inside. The program shown here illustrates how to use list( )
to examine the contents of a directory:
import java.io.File;
class DirList {
public static void main(String args[]) {
String dirname = "/java";
File f1 = new File(dirname);
if (f1.isDirectory()) {
System.out.println( "Directory of " + dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++) {
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory()) {
System.out.println(s[i] + " is a directory");
} else {
System.out.println(s[i] + " is a file");
}
}
} else {
System.out.println(dirname + " is not a directory");
}
}
}
OUTPUT:
Directory of /mysql
bin is a directory
lib is a directory
69
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
demo is a directory
test.txt is a file
README is a file
index.html is a file
include is a directory
70
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
PART-B
1. (i) Describe the three different types of inheritance with an example
Java program for each. (Nov/ Dec 2011)
Refer-Q-no: 1
(ii) Describe the concept of interface with the syntax. (6) (Nov/ Dec 2011)
Refer-Q-no: 5
2. (i) Write a Java program to demonstrate how to read and write data to a
file. (10) (Nov/ Dec 2011)
Refer-Q-no: 10
(ii) What is a thread? How do you create threads? (6) (Nov/ Dec 2011)
Refer-Q-no: 8
3. Write various forms of interface implementation (may/june 2008)
Refer-Q-no: 5
4. Write java program to throw user defined exception handling?
(may/june 2008)
Refer-Q-no: 7
5. Explain dynamic method dispatch with an example. (Nov/Dec 2013)
Refer-Q-no: 4
6. Explain Streams and IO. (Nov/Dec 2010) (April/May 2011)
Refer-Q-no: 10
8. Explain about Exception handling in Java? (April/May 2011) (Nov/Dec
2011)
Refer-Q-no: 7
9. Explain about Threads in Java? (Nov/Dec 2010) (Nov/Dec 2011)
Refer-Q-no: 8
10. Explain about Interfaces in Java?.(Nov/Dec 2011)
Refer-Q-no: 5
11. Explain about thread synchronization with an example (Nov/Dec 2013)
Refer-Q-no: 9
71
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)
12. Write a Java program to create a user defined exception whenever user
input the word “hello”. (Nov/Dec 2013)
Refer-Q-no: 7
72
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT