OOPS Unit 5

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 73

Mailam Engineering College, Mailam.

Department of Information Technology


(CS2311/U-V)

Unit – V
Syllabus:
Inheritance – interfaces and inner classes - exception handling – threads - Streams
and I/O
PART – A

1. What is inheritance? What are its types?


The mechanism of deriving a new class from an already existing class is known
as inheritance. Its types are,
• Single inheritance • Hierarchical inheritance
• Multi-level inheritance • Hybrid inheritance
2. How does a subclass constructor invoke a super class constructor? (may/jun
2013)
A subclass constructor invokes a super class constructor by using the super
keyword. The super keyword is subjected to certain conditions,
• Super may bee used within a subclass constructor method
• It should be the first statement of the sub class method.
• It must match the order and type of the instance variables declared in the
super class.
3. Define method overriding. (Nov/Dec 2011)
Method overriding is a mechanism in which the sub class method overrides the
base class method. If the same function name is present in the base class and the sub
class then the sub class method overrides the base class method.
4. What are final variables, methods and classes? (Nov/Dec 2011)
In order to prevent the subclasses from overriding the members of a super class
we can declare them as final using the keyword „final‟.
e.g, final int SIZE = 100;
final void show () {……..}
final class A {……}
5. What is the various visibility controls used in java?
The various visibility controls used in java are,

1
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

• Public access • Private protected access


• Private access • Friendly access
• Protected access
6. What are the rules of thumb?
The rules of thumb are,
• Use public if the field is to be visible everywhere.
• Use protected if the field is to be visible everywhere in the current package
and also subclasses in the other packages.
• Use “default” if the field is to be visible everywhere in the current package
only.
• Use private protected if the field is to be visible only in sub classes, regardless
of packages.
• Use private if the field is not to be visible anywhere except in its own class.
7. What are the steps involved in creating an array?
Creation of an array involves three steps,
• Declare the array – two forms,
type array-name [];
type [] array-name;
• Create memory locations
array-name = new type [size];
• Put values into the memory locations
array-name [subscript] = value;
type array-name [] = { list of values};
8. What is an interface? (April/May 2011)
An interface is basically a kind of class. It contains abstract methods and final
variable declarations. It does not specify any code to implement these methods and
data fields contain only constants. It is used to implement multiple inheritance.
9. How do you implement an interface? (Nov/Dec 2011)
An interface can be implemented as follows,
class class-name implements interface-name
{

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)

16. Define synchronization?


Synchronization is the process by which only one class is allowed to access a member
function at a time. It is done using the qualifier „synchronized‟. e.g., synchronized void
show () {……..}
17. Define error. What are its types?
An error is a wrong that can make a program go wrong. There are two types of errors
namely,
• Compile time errors
• Run time errors
18. What is an exception? What are the steps involved in exception handling?
(April/May 2011) (Nov/Dec 2011)
An exception is a condition that is caused by a run time error in a program. The steps
involved in exception handling are,
• Hit the exception • Catch the exception
• Throw the exception • Handle the exception
19. Give the syntax of exception handling code.
The syntax of exception handling code is given by,
try
{
statements
}
catch ( Exception-type e)
{
statements
}
20. What is an applet? What are its types?
An applet is a small java program that is primarily used in internet computing. The
types of applets are,
• Local applets
• Remote applets

4
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

21. What are the various states in an applet life cycle?


The various states in an applet life cycle are,
• Born or initialization state
• Running state
• Display state
• Idle state
• Dead or destroyed state
22. What is Inheritance?
It is the concept that is used for reusability purpose. Inheritance is the mechanism
through which we can derive classes from other classes. The derived class is called as
child class or the subclass or we can say the extended class and the class from which
we are deriving the subclass is called the base class or the parent class.
23. What are all the types of inheritance available in java?
The following kinds of inheritance are there in java.
 Simple Inheritance
 Multilevel Inheritance
24. What is Single Inheritance?
Simple Inheritance
When a subclass is derived simply from its parent class then this mechanism
is known as simple inheritance. In case of simple inheritance there is only a sub class
and its parent class. It is also called single inheritance or one level inheritance.
25. What is multilevel inheritance in java?
It is the enhancement of the concept of inheritance. When a subclass is derived
from a derived class then this mechanism is known as the multilevel inheritance. The
derived class is called the subclass or child class for its parent class and this parent
class works as the child class for it's just above (parent) class. Multilevel inheritance
can go up to any number of levels.

5
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

26. Give an example for Single Inheritance.


class A { class B extends A{
int x; public static void main(String args[]){
int y; A a = new A();
int get(int p, int q){ a.get(5,6);
x=p; y=q; return(0); a.Show();
} }
void Show(){ void display(){
System.out.println(x); System.out.println("B");
} }
} }

27. Give an example for multilevel inheritance?


class A { }
int x; }
int y;
int get(int p, int q){ class C extends B{
x=p; y=q; return(0); void display(){
} System.out.println("C");
void Show(){ }
System.out.println(x); public static void main(String args[]){
} A a = new A();
} a.get(5,6);
class B extends A{ a.Show();
void Showb(){ }
System.out.println("B"); }

6
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

28. Why java does not support multiple inheritances?


Multiple Inheritances
The mechanism of inheriting the features of more than one base class into a
single class is known as multiple inheritances. Java does not support multiple
inheritances but the multiple inheritances can be achieved by using the interface. In
Java Multiple Inheritance can be achieved through use of Interfaces by implementing
more than one interfaces in a class.
29. What is Super Keyword?
The super is java keyword. As the name suggest super is used to access the
members of the super class. It is used for two purposes in java.
The first use of keyword super is to access the hidden data variables of the super
class hidden by the sub class.
30. What is class hierarchy in java?
 The class hierarchy defines the inheritance relationship between the classes.
The root of the class hierarchy is the class Object. Every class in Java directly
or indirectly extends (inherits from) this class.
 In single inheritance, a class is derived from one direct super class. In Java,
multiple inheritances is not supported; a class can only have one direct super
class.
31. What is a class relationship?
is-a Relationships
 Objects of one class can be subclasses (members) of another class. For
example, a Dog is an Animal.
 The table below illustrates some is-a relationships. A GradStudent is-a
Student. A Temporary employee is- an Employee. It is correct to assume that a
Rectangle is a specific type of shape, but it is not correct that every Shape is a
Rectangle.
SuperClass SubClass
Student GradStudent, UnderGradStudent

7
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

Shape Circle, Triangle, Rectangle


Loan CarLoan, HomeLoan, BusinessLoan
Employee Part-Time, Full-Time, Temporary
BankAccount CheckingAccount, SavingsAccount
has-a Relationships
 Not every class relationship is an inheritance relationship. Class relationships
can be has-a relationships, meaning classes have members that are references
to objects of other class types.
 For example, if an Employee has an Office, this indicates that the object office is
a data member of the Employee class. It would not be correct to say that Office
is-a Employee, because it shares no data or methods with the Employee class.

32. What is Polymorphism?

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.

33. What are all the types of polymorphism available in java?


There are two types of polymorphism:
1. Compile-time polymorphism
2. Runtime Polymorphism

34. What is Compile time polymorphism?

In compiletime Polymorphism, method to be invoked is determined at the


compile time. Compile time polymorphism is supported through the method
overloading concept in java.
Method overloading means having multiple methods with same name but with
different signature (number, type and order of parameters).
35. What is run time polymorphism?
In runtime polymorphism, the method to be invoked is determined at the run
time. The example of run time polymorphism is method overriding. When a subclass

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.

36. Give the example for Compile time Polymorphism.


class A{ public class polyone{
public void fun1(int x){ public static void main(String[] args){
System.out.println("The value of A obj=new A();
class A is : " + x); // Here compiler decides that fun1(int) is to
} be called and "int" will be printed.
public void fun1(int x,int y){ obj.fun1(2);
System.out.println("The value of // Here compiler decides that fun1(int,int)is
class B is : " + x + " and " + y); to be called and "int and int" will be printed.
} obj.fun1(2,3);
} }
}

37. Give an Example for runtime polymorphism.


class A{ public class polytwo{
public void fun1(int x){ public static void main(String[] args){
System.out.println("int in Class A is : A obj;
"+ x); obj= new A(); // line 1
} obj.fun1(2); // line 2 (prints "int in
} Class A is : 2")
class B extends A{ obj=new B(); // line 3
public void fun1(int x){ obj.fun1(5); // line 4 (prints ""int in
System.out.println("int in Class B is : Class B is : 5")
"+ x); }
} }
}

9
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

38. What is Dynamic Binding?


Runtime Polymorphism otherwise called as Dynamic Binding.
39. Explain Dynamic Binding with an Example.
class A{ public class polytwo{
public void fun1(int x){ public static void main(String[] args){
System.out.println("int in Class A obj;
A is : "+ x); obj= new A(); // line 1
} obj.fun1(2); // line 2 (prints "int in
} Class A is : 2")
obj=new B(); // line 3
class B extends A{ obj.fun1(5); // line 4 (prints ""int in
public void fun1(int x){ Class B is : 5")
System.out.println("int in Class }
B is : "+ x); }
} C:\roseindia>javac polytwo.java
} C:\roseindia>java polytwo
int in Class A is : 2
int in Class B is : 5

40. What is Final keyword?


 The final is a keyword. This is similar to const keyword in other languages.
This keyword may not be used as identifiers i.e. you cannot declare a variable
or class with this name in your Java program.
 In the Java programming language, the keyword "final" is used with different
entity, which makes it unchangeable later. It is a modifier that indicates that a
class cannot be extended, a variable cannot be changed, and a method cannot
be overridden. We can have final methods, final classes, final data members,
final local variables and final parameters.

10
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

41. What is a final data member?


 variables: A variable declared with the final keyword cannot be modified by the
program, once it has been initialized. It can only be assigned to once.
 Unlike the constant value, the value of a final variable is not necessarily known
at compile time.
 Final variable comes in mostly two important situations: to prevent accidental
changes to method parameters, and with variables accessed by anonymous
classes.
 The syntax of declaring a final type variable is:
public final double radius = 126.45;
42. What is a final method?
 A final method cannot be overridden by subclasses and not be hidden.
 This technology prevents unexpected behavior from a subclass for altering a
method that may be crucial to the function of the class.
 private and static methods are always implicitly final in Java, since they
cannot be overridden.
 The syntax of declaring a final type method is:
public class MyFinalClass {
public final void myFinalMethod()
{
???...
????
} }

38. What is Final Class?

 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:

public final class MyFinalClass {


???...}

11
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

43. What is Abstract Class?

An abstract class is a class that is declared by using the abstract keyword. It


may or may not have abstract methods. Abstract classes cannot be instantiated, but
they can be extended into sub-classes.

44. What is an Abstract Methods?

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.

e.g. public abstract abs_value();

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:

 The derivation of one class from another class is called Inheritance.

Types:
 Single inheritance
 Multi-level inheritance
 Hierarchical inheritance
 Hybrid inheritance

Inheritance class:

 A class that is inherited is called a superclass.


 The class that does the inheriting is called as subclass.
 A subclass inherits all instance variables and methods from its
superclass and also has its own variables and methods.
 One can inherit the class using keyword extends.

Syntax:

Class subclass-name extends superclass-name

// 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:

 A class has only one super class.


 Java does not support Multiple Inheritance.
 One can create a hierarchy of inheritance in which a subclass becomes a
superclass of another subclass.
 However, no class can be a superclass of itself.

Example:

class A //superclass class inhe2


{ {
int num1; //member of superclass public static void main(String args[])
int num2; //member of superclass {
void setVal(int no1, int no2) B subob = new B();
//method of superclass subob.setVal(5,6); //calling
{ superclass method throgh subclass
num1 = no1; object
num2 = no2; subob.mul();
} System.out.println("Multiplication
} is " + subob.multi);
}
class B extends A //subclass B }
{ Output :
int multi; //member of subclass
void mul() //method of subclass Multiplication is 30
{
multi = num1*num2; //accessing
member of superclass from subclass
}
}

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.

SUPER - FINAL - KEYWORDS IN JAVA:

1. SUPER:

Definition:

 Super keyword is used to call a superclass constructor and to call or


access super class members (instance variables or methods).

Syntax:

.super(arg-list)

 When a subclass calls super() it is calling the constructor of its immediate


superclass.
 super() must always be the first statement executed inside a subclass
constructor.
 super.member
 Here member can be either method or instance variables.
 This second form of super is most applicable to situation in which member
names of a subclass hide member of superclass due to same name.

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:

class A1 void show()


{ {
public int i; System.out.println("i in superclass = " +
A1() super.i );
{ System.out.println("i in subclass = " + i
i=5; );
} }
} }

class B1 extends A1 public class Usesuper


{ {
int i; public static void main(String[]
B1(int a, int b) args)
{ {
super(); //calling super class B1 b = new B1(10,12);
constructor b.show();
//now we will change value of
superclass variable i }
super.i=a; //accessing superclass }
member from subclass Output :
i=b;
} i in superclass = 10
i in subclass = 12

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:

 Final keyword can be use with variables, methods and class.

i. Final variables

 When we want to declare constant variable in java we use final keyword.

Syntax: final variable name = value;

ii. Final method

 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.

Syntax: final methodname(arg)

iii. Final class

 A class that can not be sub classed is called a final class.


 This is archived in java using the keyword final.
 Any attempt to inherit this class will cause an error and compiler will not
allow it.

Syntax: final class class_name { ... }

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:

final class aa public class Final_Demo


{ {
final int a=10; public static void main(String[] args)
public final void ainc() {
{ bb b1 = new bb();
a++; // The final field aa.a b1.ainc();
cannot be assigned }
}
}

class bb extends aa // The type


bb cannot subclass the final class
aa
{
public void ainc() //Cannot
override the final method from aa
{
System.out.println("a = " + a);
}
}

18
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

2. Explain in detail about Method overriding?

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:

class Xsuper void display()


{ {
int y; System.out.println("super y = " +y);
Xsuper(int y) System.out.println("sub z = " +z);
{ }
this.y=y;
} }
void display() public class TestOverride
{ {
System.out.println("super y public static void main(String[] args)
= " +y); {
} Xsub s1 = new Xsub(100,200);
} s1.display();
class Xsub extends Xsuper }
{
int z; }

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:

 Method overloading is compile time polymorphism.


 Method overriding is run time polymorphism.
 Overloading a method is a way to provide more than one method in one
class which has same name but different argument to distinguish them.
 Defining a method in the subclass that has the same name, same
arguments and same return type as a method in the superclass is called
method overriding.

Multilevel Inheritance:

class student class percentage extends marks


{ {
int rollno; int per;
String name;
percentage(int r, String n, int t, int p)
student(int r, String n) {
{ super(r,n,t);
rollno = r; //call super class(marks) constructor
name = n; per = p;
} }
void dispdatas() void dispdatap()
{ {
System.out.println("Rollno = " + dispdatam();
rollno); // call dispdatap of marks class
System.out.println("Name = " + System.out.println("Percentage =
name); " + per);
} }
} }

20
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

class marks extends student class Multi_Inhe


{ {
int total; public static void main(String args[])
marks(int r, String n, int t) {
{ percentage stu = new
super(r,n); percentage(1912, "SAM", 350, 50);
//call super class (student) constructor //call constructor percentage
total = t; stu.dispdatap();
} // call dispdatap of percentage class
void dispdatam() }
{ }
dispdatas(); Output :
// call dispdatap of student class
System.out.println("Total = " + Rollno = 1912
total); Name = SAM
} Total = 350
} Percentage = 50

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?

class X class Z extends Y


{ // Create another subclass by
X() extending B.
{ {
System.out.println("Inside X's Z()
constructor."); {
} System.out.println("Inside Z's
} constructor.");
}
class Y extends X }
// Create a subclass by extending
class A. public class CallingCons
{ {
Y() public static void main(String args[])
{ {
System.out.println("Inside Y's Z z = new Z();
constructor."); }
} }
} Output:

Inside X's constructor.


Inside Y's constructor.
Inside Z's constructor

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.

 Further, since super( ) must be the first statement executed in a


subclass’ constructor, this order is the same whether or not super( )
is used.

 If super( ) is not used, then the default or parameterless constructor of


each superclass will be executed.

 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.

 Because a superclass has no knowledge of any subclass, any


initialization it needs to perform is separate from and possibly
prerequisite to any initialization performed by the subclass.
Therefore, it must be executed first.

4. Explain in detail about Dynamic Method Dispatch? (Nov/Dec 2013)

Dynamic Method Dispatch:

Definition:

Dynamic method dispatch is the mechanism by which a call to an


overridden method is resolved at run time, rather than compile time.

 Dynamic method dispatch is important because this is how Java


implements run-time polymorphism.
 Method to execution based upon the type of the object being referred to
at the time the call occurs. Thus, this determination is made at run time.

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( ).

 As the output shows, the version of callme( ) executed is determined


by the type of object being referred to at the time of the call.

5. Write in detail about Java –Interface? With suitable example program


JAVA – INTERFACES (Nov/ Dec 2011) (May/Jun 2011) (May/June 2008)
Definition:
An interface is basically a kind of class. Like classes, interfaces contain
methods and variables but with a major difference. The difference is that
interfaces define only abstract methods and final variables. It does not specify
any code to implement these methods and data field contain only constants.
Syntax:
[Access-specifier] interface interface-name
{
Access-specifier return-type method-name(parameter-list);
final type var1=value;
}
Note:
 Where, Access-specifier is either public or it is not given.
 When no access specifier is used, it results into default access specifier
and if interface has default access specifier then it is only available to
other members of the same package.
 When it is declared as public, the interface can be used by any other
code of other package.
 Interface-Name: name of an interface, it can be any valid identifier.
 The methods which are declared having no bodies they end with a
semicolon after the parameter list. Actually they are abstract methods;

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 ( );
} }

Various forms of interface implementation

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);
}
}

Interfaces can be extended:


interface volume extends area
{
void display();
}

27
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

Multiple inheritance using interface


class student public void display()
{ {
int rollno; System.out.println("Displaying
String name = new String(); student details .. ");
int marks; System.out.println("Rollno = " +
student(int r, String n, int m) rollno);
{ System.out.println("Name = " +
rollno = r; name);
name = n; System.out.println("Marks = " +
marks = m; marks);
} }
} }
interface stuinterface public class Multi_inhe_demo
{ {
void display(); public static void main(String
} args[])
class studerived extends student {
implements stuinterface studerived obj = new
{ studerived(1912, "Ram", 75);
studerived(int r, String n, int m) obj.display();
{ }
super(r,n,m); }
} Output :

Displaying student details..


Rollno = 1912
Name = Ram
Marks = 75

28
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

6. Write short note on Inner class of Java?


Definition 1:
Inner classes allow you to define one class inside another class this is
called as “inner” classes. A class can have member classes, just like how
classes can have member variables and methods.

Definition 2:
If a class is declared within another class or interface is called nested
class.

Types of nested classes are as given below:


 Static Member Classes: It is defined as static member in a class or an
interface.
 Non-static Member Classes: It is defined as instance members of
another classes.
 Local Classes: It is defined in a block, like inside a method body or a
local block.
 Anonymous Classes: It can be defined as expressions and instantiated
on the fly.

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 {
}
}


If you compile above code it will produce two class file.

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.

7. Explain about Exception handling in Java? (April/May 2011) (Nov/Dec


2011)
Definition:
An exception is a condition that is caused by a runtime error in the
program. When java interpreter encounters an error such as dividing b zero, it
creates an exception object and throws it.
Java - Exceptions Handling
An exception is a problem that arises during the execution of a program. An
exception can occur for many different reasons, including the following:
 A user has entered invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications, or
the JVM has run out of memory.

Three categories of exceptions:


 Checked exceptions: A checked exception is an exception that is
typically a user error or a problem that cannot be foreseen by the
programmer. For example, if a file is to be opened, but the file cannot be
found, an exception occurs. These exceptions cannot simply be ignored
at the time of compilation.
 Runtime exceptions: A runtime exception is an exception that occurs
that probably could have been avoided by the programmer. As opposed
to checked exceptions, runtime exceptions are ignored at the time of
compilation.
 Errors: These are not exceptions at all, but problems that arise beyond
the control of the user or the programmer. Errors are typically ignored in

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.

SN Methods with Description

1 public String getMessage()


Returns a detailed message about the exception that has occurred. This
message is initialized in the Throwable constructor.

2 public Throwable getCause()


Returns the cause of the exception as represented by a Throwable object.

3 public String toString()


Returns the name of the class concatenated with the result of getMessage()

4 public void printStackTrace()


Prints the result of toString() along with the stack trace to System.err, the
error output stream.

5 public StackTraceElement [] getStackTrace()


Returns an array containing each element on the stack trace. The element
at index 0 represents the top of the call stack, and the last element in the
array represents the method at the bottom of the call stack.

6 public Throwable fillInStackTrace()


Fills the stack trace of this Throwable object with the current stack trace,
adding to any previous information in the stack trace.

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.

// File Name : ExcepTest.java


import java.io.*;
public class ExcepTest{
public static void main(String args[]){
try{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException e){

33
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

System.out.println("Exception thrown :" + e);


}
System.out.println("Out of the block");
}
}

OUTPUT:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

Multiple catch Blocks:


 A try block can be followed by multiple catch blocks. The syntax for
multiple catch blocks looks like the following:

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;
}

The throws/throw Keywords:


 If a method does not handle a checked exception, the method must
declare it using the throws keyword. The throws keyword appears at the
end of a method's signature.
 You can throw an exception, either a newly instantiated one or an
exception that you just caught, by using the throw keyword. Try to
understand the different in throws and throw keywords.
 The following method declares that it throws a RemoteException:

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)

throw new RemoteException();


}
//Remainder of class definition
}

 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
}

The finally Keyword


 The finally keyword is used to create a block of code that follows a try
block. A finally block of code always executes, whether or not an
exception has occurred.
 Using a finally block allows you to run any cleanup-type statements that
you want to execute, no matter what happens in the protected code.
 A finally block appears at the end of the catch blocks and has the
following syntax:

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:

public class ExcepTest{

public static void main(String args[]){


int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;

37
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

System.out.println("First element value: " +a[0]);


System.out.println("The finally statement is executed");
}
}
}

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.

Declaring you own Exception:


 You can create your own exceptions in Java. Keep the following points in
mind when writing your own exception classes:

 All exceptions must be a child of Throwable.


 If you want to write a checked exception that is automatically enforced
by the Handle or Declare Rule, you need to extend the Exception class.
 If you want to write a runtime exception, you need to extend the
RuntimeException class.
 We can define our own Exception class as below:

38
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

class MyException extends Exception{


}

 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:

// File Name InsufficientFundsException.java


import java.io.*;

public class InsufficientFundsException extends Exception


{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}

39
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

 To demonstrate using our user-defined exception, the following


CheckingAccount class contains a withdraw() method that throws an
InsufficientFundsException.

// File Name CheckingAccount.java


import java.io.*;

public class CheckingAccount


{
private double balance;
private int number;
public CheckingAccount(int number)
{
this.number = number;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount) throws
InsufficientFundsException
{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);

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;
}
}

 The following BankDemo program demonstrates invoking the deposit()


and withdraw() methods of CheckingAccount.

// File Name BankDemo.java


public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try
{
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{

41
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

System.out.println("Sorry, but you are short $"


+ e.getAmount());
e.printStackTrace();
}
}
}

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)

8. Explain in detail about Multithreading Program with suitable java


program?
Multithreading Programming:
Multitasking:

 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:

 Multithreading is a technique that allows a program or a process to


execute many tasks concurrently (at the same time and parallel). It
allows a process to run its tasks in parallel mode on a single processor
system
 In the multithreading concept, several multiple lightweight processes are
run in a single process/task or program by a single processor.
 For Example, When you use a word processor you perform a many
different tasks such as printing, spell checking and so on.
Multithreaded software treats each process as a separate program.
 In Java, the Java Virtual Machine (JVM) allows an application to have
multiple threads of execution running concurrently. It allows a program
to be more responsible to the user.

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.

Advantages of multithreading over multitasking :

 Reduces the computation time.


 Improves performance of an application.
 Threads share the same address space so it saves the memory.
 Context switching between threads is usually less expensive than
between processes.
 Cost of communication between threads is relatively low.

Life Cycle of a Thread:

 A thread goes through various stages in its life cycle.


 For example, a thread is born, started, runs, and then dies.
 Following diagram shows complete life cycle of a thread.

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:

 Java defines two ways in which this can be accomplished:

 by implement the Runnable interface.


 by extend the Thread class, itself.

1. Create Thread by Implementing Runnable:

 The easiest way to create a thread is to create a class that implements


the Runnable interface.
 To implement Runnable, a class need only implement a single method
called run( ), which is declared like this:

o public void run( )

 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 Thread(Runnable threadOb, String threadName);

 Here threadOb is an instance of a class that implements the Runnable


interface and the name of the new thread is specified by threadName.
 After the new thread is created, it will not start running until you call its
start( ) method, which is declared within Thread. The start( ) method is
shown here:

o void start( );

Example:

// Create a new thread.


class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}

// This is the entry point for the second thread.


public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(500);

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.

2. Create Thread by Extending Thread:

 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:

// Create a second thread by extending Thread


class NewThread extends Thread {
NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}

// This is the entry point for the second thread.


public void run() {
try {

49
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

for(int i = 5; i > 0; i--) {


System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}

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:

Child thread: Thread[Demo Thread,5,main]

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:

SN Methods with Description

public void start()


1 Starts the thread in a separate path of execution, then invokes the run()
method on this Thread object.

public void run()


2 If this Thread object was instantiated using a separate Runnable target, the
run() method is invoked on that Runnable object.

public final void setName(String name)


3 Changes the name of the Thread object. There is also a getName() method
for retrieving the name.

public final void setPriority(int priority)


4 Sets the priority of this Thread object. The possible values are between 1
and 10.

51
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

public final void setDaemon(boolean on)


5
A parameter of true denotes this Thread as a daemon thread.

public final void join(long millisec)


The current thread invokes this method on a second thread, causing the
6
current thread to block until the second thread terminates or the specified
number of milliseconds passes.

public void interrupt()


7 Interrupts this thread, causing it to continue execution if it was blocked for
any reason.

public final boolean isAlive()


8 Returns true if the thread is alive, which is any time after the thread has
been started but before it runs to completion.

 Invoking one of the static methods performs the operation on the


currently running thread

SN Methods with Description

public static void yield()


1 Causes the currently running thread to yield to any other threads of the
same priority that are waiting to be scheduled

public static void sleep(long millisec)


2 Causes the currently running thread to block for at least the specified
number of milliseconds

public static boolean holdsLock(Object x)


3
Returns true if the current thread holds the lock on the given Object.

4 public static Thread currentThread()

52
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

Returns a reference to the currently running thread, which is the thread


that invokes this method.

public static void dumpStack()


5 Prints the stack trace for the currently running thread, which is useful
when debugging a multithreaded application.

Example:

// File Name : DisplayMessage.java


// Create a thread to implement Runnable
public class DisplayMessage implements Runnable
{
private String message;
public DisplayMessage(String message)
{
this.message = message;
}
public void run()
{
while(true)
{
System.out.println(message);
}
}
}

// File Name : GuessANumber.java


// Create a thread to extentd Thread
public class GuessANumber extends Thread

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.**");
}
}

// File Name : ThreadClassDemo.java


public class ThreadClassDemo
{
public static void main(String [] args)
{
Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);

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();

Runnable bye = new DisplayMessage("Goodbye");


Thread thread2 = new Thread(hello);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.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.

9. Write short note on Thread Synchronization?

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)

 The synchronized keyword in Java creates a block of code referred to as a


critical section.
 Every Java object with a critical section of code gets a lock associated
with the object.
 To enter a critical section, a thread needs to obtain the corresponding
object's lock.

Syntax:

synchronized(object) {
// statements to be synchronized
}

Example:

// File Name : Callme.java


// This program uses a synchronized block.
class Callme {
void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}

// File Name : Caller.java

57
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

class Caller implements Runnable {


String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}

// synchronize calls to call()


public void run() {
synchronized(target) { // synchronized block
target.call(msg);
}
}
}
// File Name : Synch.java
class Synch {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");

// wait for threads to end


try {
ob1.t.join();
ob2.t.join();

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.

Reading Console Input:


 Java input console is accomplished by reading from System.in.
 To obtain a character-based stream that is attached to the console, you
wrap System.in in a BufferedReader object, to create a character
stream.
 Syntax to obtain BufferedReader:

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

59
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

 Once BufferedReader is obtained, we can use read( ) method to reach a


character or readLine( ) method to read a string from the console.

Reading Characters from Console:


 To read a character from a BufferedReader, we would read( ) method
whose sytax is as follows:

Int read( ) throws IOException

 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:

// Use a BufferedReader to read characters from the console.


import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
// Create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) br.read();
System.out.println(c);
} while(c != 'q');
}
}

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

Reading Strings from Console:


 To read a string from the keyboard, use the version of readLine( ) that is
a member of the BufferedReader class. Its general form is shown here:

String readLine( ) throws IOException

Example:

// Read a string from console using a BufferedReader.


import java.io.*;
class BRReadLines {
public static void main(String args[]) throws IOException
{
// Create a BufferedReader using System.in
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'end' to quit.");
do {

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:

Enter lines of text.


Enter 'end' to quit.
This is line one
This is line one
This is line two
This is line two
end
end

Writing Console Output:


 Console output is most easily accomplished with print( ) and println( ),
described earlier.
 These methods are defined by the class PrintStream which is the type of
the object referenced by System.out.
 Because PrintStream is an output stream derived from OutputStream, it
also implements the low-level method write( ).
 Thus, write( ) can be used to write to the console. The simplest form of
write( ) defined by PrintStream is shown here:

void write(int byteval)

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.

Reading and Writing Files:


 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.
 The hierarchy of classes to deal with Input and Output streams.

63
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

 The two important streams are FileInputStream and


FileOutputStream.

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.:

InputStream f = new FileInputStream("C:/java/hello");

 (ii)Following constructor takes a file object to create an input stream


object to read the file. First we create a file object using File() method as
follows:

File f = new File("C:/java/hello");


InputStream f = new FileInputStream(f);

64
Prepared by: Mrs. S. AMUTHA, AP/IT
Mr. P. MATHIVANAN, AP/IT
Mailam Engineering College, Mailam.
Department of Information Technology
(CS2311/U-V)

SN Methods with Description

1 public void close() throws IOException{}


This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.

2 protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the close
method of this file output stream is called when there are no more
references to this stream. Throws an IOException.

3 public int read(int r)throws IOException{}


This method reads the specified byte of data from the InputStream. Returns
an int. Returns the next byte of data and -1 will be returned if it's end of
file.

4 public int read(byte[] r) throws IOException{}


This method reads r.length bytes from the input stream into an array.
Returns the total number of bytes read. If end of file -1 will be returned.

5 public int available() throws IOException{}


Gives the number of bytes that can be read from this file input stream.
Returns an int.

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)

OutputStream f = new FileOutputStream("C:/java/hello")

 (ii) Following constructor takes a file object to create an output stream


object to write the file. First we create a file object using File() method as
follows:

File f = new File("C:/java/hello");


OutputStream f = new FileOutputStream(f);

SN Methods with Description

1 public void close() throws IOException{}


This method closes the file output stream. Releases any system resources
associated with the file. Throws an IOException.

2 protected void finalize()throws IOException {}


This method cleans up the connection to the file. Ensures that the close
method of this file output stream is called when there are no more
references to this stream. Throws an IOException.

3 public void write(int w)throws IOException{}


This methods writes the specified byte to the output stream.

4 public void write(byte[] w)


Writes w.length bytes from the mentioned byte array to the OutputStream.

Example:

import java.io.*;

public class fileStreamTest{

public static void main(String args[]){

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();

InputStream is = new FileInputStream("C:/test.txt");


int size = is.available();

for(int i=0; i< size; i++){


System.out.print((char)is.read() + " ");
}
is.close();
}catch(IOException e){
System.out.print("Exception");
}
}
}

File Navigation and I/O:


 There are several other classes that we would be going through to get to
know the basics of File Navigation and I/O.

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.

Following example creates "/tmp/user/java/bin" 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();
}
}

Compile and execute above code to create "/tmp/user/java/bin".


Note: Java automatically takes care of path separators on UNIX and Windows
as per conventions. If you use a forward slash (/) on a Windows version of Java,
the path will still resolve correctly.
Reading Directories:
 A directory is a File that contains a list of other files and directories.
When you create a File object and it is a directory, the isDirectory( )
method will return true.

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

ANNA UNIVERSITY QUESTIONS


PART - A
1. What are the two ways of creating java threads? (Nov/ Dec 2010)
Refer-Q-no: 13
2. Define Interface. state its use (May/Jun 2012)
Refer-Q-no: 8
3. What is thread? (May/Jun 2012)
Refer-Q-no: 11
4. What is the difference between superclass and subclass (may/jun 2013)
Refer-Q-no: 2
5. What is a inner class? [Nov/Dec 2012]
Refer-Q-no: Part b 6
6. Which class and interface in java us used to create thread and which is
most advantageous method? (May/Jun 2013)
Refer-Q-no: 13
7. Define interface (Nov/Dec 2013)
Refer-Q-no: 8
8. What are exceptions? (Nov/Dec 2013)
Refer-Q-no: 18
9. What is Multithreading? (Nov/Dec 2013)
Refer-Q-no: 12

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

You might also like