0% found this document useful (0 votes)
6 views

Oops Java 1-5mod Notes (1)

Uploaded by

Alka Rani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Oops Java 1-5mod Notes (1)

Uploaded by

Alka Rani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 192

BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

Module 3
Syllabus

Inheritance: Inheritance Basics, Using super, Creating a Multilevel Hierarchy, When


Constructors Are Executed, Method Overriding, Dynamic Method Dispatch, Using Abstract
Classes, Using final with Inheritance, Local Variable Type Inference and Inheritance, The Object
Class.
Interfaces: Interfaces, Default Interface Methods, Use static Methods in an Interface, Private
Interface Methods.

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

Inheritance: Acquiring properties from one class (Parent class) into Another class (child class)
is called Inheritance. Parent class is also called as Super class or Base class and Child class is
also called as Sub class or Derived class. Super class do not have knowledge of Sub class. But
Sub class is having knowledge of Parent Class and Its own class.
The Acquiring properties from Parent class to child class are:
 Instance variables of Super class can be accessible inside subclass
 Methods of super class can be accessible inside sub class.

Inheritance represents the IS-A relationship which is also known as a parent-


child relationship.
Advantages of Inheritance:
 Code reusability
 Duplicate code is eliminated
The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
}
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.

Java Program to demonstrate Inheritance


class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output: Programmer salary is:40000.0
Bonus of programmer is:10000

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.

Types of inheritance in java

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

Single Inheritance Example:When a class inherits another class, it is known as a single


inheritance. In the example given below, Dog class inherits the Animal class, so there is the single
inheritance.

class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
Output:
barking...
eating...
Multilevel Inheritance Example: When there is a chain of inheritance, it is known as multilevel
inheritance. As you can see in the example given below, BabyDog class inherits the Dog class
which again inherits the Animal class, so there is a multilevel inheritance.

class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){
System.out.println("weeping...");
}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Output:
weeping...
barking...
eating...

Hierarchical Inheritance Example: When two or more classes inherits a single class, it is known
as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal
class, so there is hierarchical inheritance.
class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class Cat extends Animal{
void meow(){

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

System.out.println("meowing...");
}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}
}
Output:
meowing...
eating...

Inheritance Basics: To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword. To see how, let’s begin with a short example. The following
program creates a superclass called A and a subclass called B. Notice how the keyword extends
is used to create a subclass of A.
// A simple example of inheritance.Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}

void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

A superOb = new A();


B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}

The output from this program is shown here:


Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24

Using super: The super keyword in java is a reference variable which is used to refer
immediate parent class object. Whenever you create the instance of subclass, an instance of
parent class is created implicitly which is referred by super reference variable.
Usage of java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1. super is used to refer immediate parent class instance variable. We can use super
keyword to access the data member or field of parent class. It is used if parent class and child
class have same fields. Sub-class variable hides the super-class variable in class sub-class.
class Animal{
String color="white";

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

}
class Dog extends Animal{
String color="black"; //this hides color in Animal
void printColor(){
System.out.println(color); //prints color of Dog class
System.out.println(super.color); //prints color ofAnimal class
}
}

class Mainclass{
public static void main(String[ ] args){
Dog d=new Dog();
d.printColor();

}
}
Output: black
white

2. super is used to invoke super-class(parent class) constructor.. The super keyword


can also be used to invoke the parent class constructor. Let's see a simple example:

class A {
int i;
private int j;
A(int a, int b) {
i=a;
j=b;
}
void addij(){
int k=i+j;
System.out.println("(i+j=)"+k);
}
}
class B extends A {
int k;
B(int a, int b, int c){
super(a,b);
k=c;
}void addik() {
System.out.println("i: " + i);
//System.out.println("j: " + j); //Error j is private cannot access j in B
System.out.println("k: " + k);

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

int c=i+k;
System.out.println("i+k="+c);
}
}
class Mainclass{
public static void main(String[ ] args){
B b=new B(1,2,3);
b.addij();
b.addik();
}
}
Output: (i+j=)3
i: 1
k: 3
i+k=4
3. super is used to invoke super-class(parent class) method.. The super keyword can
also be used to invoke the parent class method when parent class method and child class
method names are same in other words method is overridden.
Let's see a simple example:
class Animal{
void eat(){
System.out.println("All Animals can eat...");
}
}
class Dog extends Animal{
void eat(){
System.out.println("eating bread...");
}
void bark(){
System.out.println("barking...");
}
void work(){
super.eat();
bark();
}
}
class Mainclass{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}
}

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

Creating a Multilevel Hierarchy: The level of the inheritance is two or more then we can call
it as multilevel inheritance. you can build hierarchies that contain as many layers of inheritance
as you like. As mentioned, it is perfectly acceptable to use a subclass as a superclass of another.
For example, given three classes called A, B, and C, C can be a subclass of B, which is a subclass
of A. When this type of situation occurs, each subclass inherits all of the traits found in all of its
superclasses. In this case, C inherits all aspects of B and A. To see how a multilevel hierarchy can
be useful, consider the following program. In it, the subclass BoxWeight is used as a superclass
to create the subclass called Shipment. Shipment inherits all of the traits of BoxWeight and Box,
and adds a field called cost, which holds the cost of shipping such a parcel.
class Box {
private double width;
private double height;
private double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}

double volume() {
return width * height * depth;
}
}
class BoxWeight extends Box {
double weight;
BoxWeight(double w, double h, double d, double m) {
super(w, h, d);
weight = m;
}

}
class Shipment extends BoxWeight {
double cost;
Shipment(double w, double h, double d,double m, double c) {
super(w, h, d, m);
cost = c;
}
}
class Mainclass{
public static void main(String args[]){
Shipment shipment1 = new Shipment(10, 20, 15, 10, 3.41);
Shipment shipment2 = new Shipment(2, 3, 4, 0.76, 1.28);
double vol;

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

vol = shipment1.volume();
System.out.println("Volume of shipment1 is " + vol);
System.out.println("Weight of shipment1 is "+ shipment1.weight);
System.out.println("Shipping cost: $" + shipment1.cost);
System.out.println();
}
}
When Constructors Are Called: When a class hierarchy is created, in what order are the
constructors for the classes that make up the hierarchy called? For example, given a subclass called B and
a superclass called A, is A’s constructor called before B’s, or vice versa? 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. The following program illustrates when constructors are executed:
// Demonstrate when constructors are called.
// Create a super class.
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
The output from this program is shown here:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

Method Overriding in Java: If subclass (child class) has the same method as declared in the
parent class, it is known as method overriding in java. In other words, If subclass provides
the specific implementation of the method that has been provided by one of its parent class,
it is known as method overriding.

Usage of Java Method Overriding

 Method overriding is used to provide specific implementation of a method that


is already provided by its super class.
 Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

class Bank{
int getRateOfInterest(){
return 0;
}
}
class SBI extends Bank{
int getRateOfInterest(){
return 8;
}
}

class ICICI extends Bank{


int getRateOfInterest(){
return 7;
}
}
class AXIS extends Bank{
int getRateOfInterest(){
return 9;
}
}
class Test2{

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

public static void main(String args[]){


SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Dynamic Method Dispatch: 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.
// Dynamic Method Dispatch
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r;
r = a; // r refers to an A object

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

r.callme(); // calls A's version of callme


r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
The output from the program is shown here:
Inside A’s callme method
Inside B’s callme method
Inside C’s callme method
Using final with Inheritance: The final keyword in java is used to restrict the user. The
java final keyword can be used in many context. Final can be:
1. variable
2. method
3. class

final variable: There is a final variable speedlimit, we are going to change the value of this
variable, but It can't be changed because final variable once assigned a value can never be
changed.

class Bike9{
final int speedlimit=90; //final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
} Output: Compile Time Error

Java final method: If you make any method as final, you cannot override it.
class Bike{
final void run(){
System.out.println("running");
}
}

class Honda extends Bike{


void run(){
System.out.println("running safely with 100kmph");
}
}

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

class MainClass{
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
} Output: Compile Time Error

Java final class: If you make any class as final, you cannot inherit it.
final class Bike{
int add(){
return 10;
}

}
class Honda1 extends Bike{
void run(){
System.out.println("running safely with 100kmph");
}
class MainClass{
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
Output: Compile Time Error
Abstract Classes: There are situations in which you will want to define a super-class that declares
the structure of a given abstraction without providing a complete implementation of every method.
That is, sometimes you will want to create a super-class that only defines a generalized form that
will be shared by all of its subclasses, leaving it to each subclass to fill in the details.To declare an
abstract method, use this general form:
abstract type name(parameter-list);
As you can see,
 no method body is present.
 Any class that contains one or more abstract methods must also be declared abstract. To
declare a class abstract, you simply use the abstract keyword in front of the class
keyword at the beginning of the class declaration.
 There can be no objects of an abstract class. That is, an abstract class cannot be directly
instantiated with the new operator. Such objects would be useless, because an abstract
class is not fully defined.

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

// Using abstract methods and classes.


abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}

abstract double area(); // area is now an abstract method


}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println("Area is " + figref.area());
figref = t;
System.out.println("Area is " + figref.area());
}
}

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

Output: Area is: 45.000


Area is: 40.00
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in java is a mechanism to achieve abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve abstraction and multiple
inheritance in Java. Java Interface also represents IS-A relationship. It cannot be
instantiated just like abstract class. In other words, Interface fields are public, static and final
by default, and methods are public and abstract.

Understanding relationship between classes and interfaces

An interface is defined much like a class. This is the general form of an interface:
access interface name {
type final-varname1 = value;
type final-varname2 = value;
type final-varnameN = value;

return-type method-name1(parameter-list);
return-type method-name2(parameter-list);

// ...

return-type method-nameN(parameter-list);

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

Java Interface Example

interface printable{
int x=100;
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
// obj.x++; cannot change the value of the x because it is final
}
}

Multiple inheritance in Java by interface

Example:
interface Printable{
void print();
}

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){
System.out.println("Hello");
}
public void show(){
System.out.println("Welcome");
}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}
}

Default Interface Methods: The non-abstract methods which are defined inside the interface are
called as Default Interface methods. The concept of default method is used to define a method with
default implementation. You can override default method also to provide more specific
implementation for the method.

interface Sayable{
default void say(){
System.out.println("Hello, this is default method");
}
void sayMore(String msg);
}
public class DefaultMethods implements Sayable{
public void sayMore(String msg){ // implementing abstract method
System.out.println(msg);
}
public static void main(String[] args) {
DefaultMethods dm = new DefaultMethods();
dm.say(); // calling default method
dm.sayMore("Work is worship"); // calling abstract method

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

}
}
Output:
Hello, this is default method
Work is worship

Static Methods inside Interface: You can also define static methods inside the interface. Static
methods are used to define utility methods. Static methods are nowhere related to objects. We can
access static methods using Interface name. The following example explain, how to implement
static method in interface?
interface Sayable{
static void sayLouder(String msg){
System.out.println(msg);
}
}
public class DefaultMethods implements Sayable{
public static void main(String[] args) {
Sayable.sayLouder("Helloooo..."); // calling static method
}
}
Output: Helloooo...
Private Interface Methods: we can create private methods inside an interface. Interface allows
us to declare private methods that help to share common code between non-abstract methods.

interface Sayable{
default void say() {
saySomething();
}
// Private method inside interface
private void saySomething() {
System.out.println("Hello... I'm private method");
}
}
public class PrivateInterface implements Sayable {
public static void main(String[] args) {
Sayable s = new PrivateInterface();

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

s.say();
}
}
Output: Hello... I'm private method
Object class: The Object class is the parent class of all the classes in java by default. The Object
class is beneficial if you want to refer any object whose type you don't know. Notice that parent
class reference variable can refer the child class object, know as upcasting. The Object class
provides some common behaviors to all the objects such as object can be compared, object can be
cloned, object can be notified etc.

The Object class provides many methods. They are as follows:

S.NO Methods Description

1 public final Class getClass() Returns the Class class object of this object.
The Class class can further be used to get the
metadata of this class.

2 public int hashCode() returns the hashcode number for this object.

3 public boolean equals(Object obj) compares the given object to this object.

4 public String toString() returns the string representation of this object.


wakes up single thread, waiting on this object's
5 public final void notify() monitor.
wakes up all the threads, waiting on this
6 public final void notifyAll() object's monitor.
is invoked by the garbage collector before
7 protected void finalize()throws Throwable object is being garbage collected.

public final void wait()throws causes the current thread to wait, until another
8 InterruptedException thread notifies (invokes notify() or notifyAll()
method).
public final void wait(long timeout,int auses the current thread to wait for the
9 nanos)throws InterruptedException specified milliseconds and nanoseconds, until
another thread notifies (invokes notify() or
notifyAll() method).
protected Object clone() throws creates and returns the exact copy (clone) of
10 CloneNotSupportedException this object.

vtucode.in
BCS306A(OBJECT ORIENTED PROGRAMMING WITH JAVA)

vtucode.in
Module 4

Packages: Packages, Packages and Member Access, Importing Packages.

Exceptions: Exception-Handling Fundamentals, Exception Types, Uncaught Exceptions, Using try


and catch, Multiple catch Clauses, Nested try Statements, throw, throws, finally, Java’s Built-in
Exceptions, Creating Your Own Exception Subclasses, Chained Exceptions.

website: vtucode.in

Defining a Package
 A set of classes and interfaces grouped together are known as
Packages in JAVA.
 To create a package is quite easy: simply include a package
command as the first statement in a Java source file.
 Any classes declared within that file will belong to the specified
package.
 The package statement defines a name space in which classes are stored.
 If you omit the package statement, the class names are put into the default
package, which has no name
 While the default package is fine for short, sample programs, it is
inadequate for real applications.
 This is the general form of the package statement:
Packages and Member Access
 Classes and packages are both means of encapsulating and
containing the name space and scope of variables and methods.
 Packages act as containers for classes and other subordinate packages.
 Classes act as containers for data and code.
 The class is Java’s smallest unit of abstraction. Because of the
interplay between classes and packages, Java addresses four categories
of visibility for class members:
Importing Packages.
 Java includes the import statement to bring certain classes, or entire
packages, into visibility.
 Once imported, a class can be referred to directly, using only its name.
 The import statement is a convenience to the programmer and is not
technically needed to write a complete Java program.
 If you are going to refer to a few dozen classes in your application,
however, the import statement will save a lot of typing.
 In a Java source file, import statements occur immediately following the
package statement (if it exists) and before any class definitions.
 This is the general form of the import statement:


Here, pkg1 is the name of a top-level package, and pkg2 is the name
of a subordinate package inside the outer package separated by a dot
(.).
 you specify either an explicit classname or a star (*), which indicates
that the Java compiler should import the entire package.
 This code fragment shows both forms in use:
MODULE-4
CHAPTER-2
Exceptions
An exception is an abnormal condition that arises in a code sequence at run
time. In other words, an exception is a run time error

Exception-Handling Fundamentals
 Java exception handling is managed via five keywords: try, catch,
throw, throws, and finally.
 Program statements that you want to monitor for exceptions are
contained within a try block.
 If an exception occurs within the try block, it is thrown.
 Your code can catch this exception (using catch) and handle it in some
rational manner.
 System-generated exceptions are automatically thrown by the Java
run time system.
 To manually throw an exception, use the keyword throw. Any
exception that is thrown out of a method must be specified as such by
a throws clause.
 Any code that absolutely must be executed after a try block completes is
put in a finally block.
Exception Types

Exception Types
 All exception types are subclasses of the built-in class Throwable.
 Thus, Throwable is at the top of the exception class hierarchy.
 Immediately below Throwable are two subclasses that partition
exceptions into two distinct branches.
 One branch is headed by Exception.
 This class is used for exceptional conditions that user programs
should catch. This is also the class that you will subclass to create
your own custom exception types.
 There is an important subclass of Exception, called
RuntimeException.
 Exceptions of this type are automatically defined for the programs
that you write and include things such as division by zero and invalid
array indexing.
 The other branch is topped by Error, which defines exceptions that
are not expected to be caught under normal circumstances by your
program.
 Exceptions of type Error are used by the Java run-time system to
indicate errors having to do with the run-time environment, itself.
 Stack overflow is an example of such an error.

we haven’t supplied any exception handlers of our own, so the
exception is caught by the default handler provided by the Java run-
time system.
 Any exception that is not caught by your program will ultimately be
processed by the default handler.
 The default handler displays a string describing the exception, prints
a stack trace from the point at which the exception occurred, and
terminates the program.

Using try and catch


 Although the default exception handler provided by the Java run-
time system is useful for debugging, you will usually want to handle
an exception yourself.
 Doing so provides two benefits.
First, it allows you to fix the error.
Second, it prevents the program from automatically terminating.
 Most users would be confused, to prevent this Programmers used
guard against and handle a run-time error, simply enclose the code
that you want to monitor inside a try block.
 Immediately following the try block, include a catch clause that
specifies the exception type that you wish to catch.
Multiple catch Clauses
 In some cases, more than one exception could be raised by a single
piece of code.
 To handle this type of situation, you can specify two or more catch
clauses, each catching a different type of exception.
 When an exception is thrown, each catch statement is inspected in
order, and the first one whose type matches that of the exception is
executed.
 After one catch statement executes, the others are bypassed, and
execution continues after the try / catch block.
 The following example traps two different exception types:
Nested try Statements
 The try statement can be nested.
 That is, a try statement can be inside the block of another try.
 Each time a try statement is entered, the context of that exception is
pushed on the stack.
 If an inner try statement does not have a catch handler for a
particular exception, the stack is unwound and the next try
statement’s catch handlers are inspected for a match.
 This continues until one of the catch statements succeeds, or until all
of the nested try statements are exhausted.
 If no catch statement matches, then the Java run-time system will
handle the exception.
 Here is an example that uses nested try statements:
OUTPUT

throw
 So far, you have only been catching exceptions that are thrown by the
Java run-time system.
 However, it is possible for your program to throw an exception
explicitly, using the throw statement.
 The general form of throw is shown here: throw ThrowableInstance;
 Here, ThrowableInstance must be an object of type Throwable or a
subclass of Throwable.
 Primitive types, such as int or char, as well as non-Throwable
classes, such as String and Object, cannot be used as exceptions.
There are two ways you can obtain a Throwable object: using a
parameter in a catch clause or creating one with the new operator.
 The flow of execution stops immediately after the throw statement;
any subsequent statements are not executed.
 The nearest enclosing try block is inspected to see if it has a catch
statement that matches the type of exception.
 If it does find a match, control is transferred to that statement. If
not, then the next enclosing try statement is inspected, and so on. If
no matching catch is found, then the default exception handler halts
the program and prints the stack trace.
 Here is a sample program that creates and throws an exception. The
handler that catches the exception rethrows it to the outer handler.
Throws
 If a method is capable of causing an exception that it does not handle, it
must specify this behavior so that callers of the method can guard
themselves against that exception.
 You do this by including a throws clause in the method’s declaration.
 A throws clause lists the types of exceptions that a method might
throw. This is necessary for all exceptions, except those of type Error
or RuntimeException, or any of their subclasses.
 All other exceptions that a method can throw must be declared in the
throws clause. If they are not, a compile-time error will result.
finally
 finally creates a block of code that will be executed after a try /catch
block has completed and before the code following the try/catch block.
 The finally block will execute whether or not an exception is thrown.
 If an exception is thrown, the finally block will execute even if no
catch statement matches the exception.
 Any time a method is about to return to the caller from inside a try/catch
block, via an uncaught exception or an explicit return statement, the
finally clause is also executed just before the method returns.
 This can be useful for closing file handles and freeing up any other
resources that might have been allocated at the beginning of a method
with the intent of disposing of them before returning.
 The finally clause is optional.
 However, each try statement requires at least one catch or a finally clause

Java’s Built-in Exceptions


 In the language of Java, these are called unchecked exceptions because
the compiler does not check to see if a method handles or throws these
exceptions. The unchecked exceptions defined in java.lang are listed
in Table 10-1.
 Table 10-2 lists those exceptions defined by java.lang that must be
included in a method’s throws list if that method can generate one of
these exceptions and does not handle it itself.
 These are called checked exceptions.
 In addition to the exceptions in java.lang, Java defines several more that
relate to its other standard packages.
Creating Your Own Exception Subclasses
 The Exception class does not define any methods of its own.
 It does, of course, inherit those methods provided by Throwable.
 Thus, all exceptions, including those that you create, have the methods
defined by Throwable available to them.
 They are shown in Table 10-3. You may also wish to override one or
more of these methods in exception classes that you create.
 Exception defines four public constructors.
 Two support chained exceptions.
 The other two are shown here:

 The first form creates an exception that has no description.


 The second form lets you specify a description of the exception.
Chained Exceptions
 Beginning with JDK 1.4, a feature was incorporated into the
exception subsystem: chained exceptions.
 The chained exception feature allows you to associate another
exception with an exception.
 This second exception describes the cause of the first exception.
 For example, imagine a situation in which a method throws an
ArithmeticException because of an attempt to divide by zero.
 However, the actual cause of the problem was that an I/O error occurred,
which caused the divisor to be set improperly.
 Although the method must certainly throw an ArithmeticException,
since that is the error that occurred, you might also want to let the
calling code know that the underlying cause was an I/O error.
 Chained exceptions let you handle this, and any other situation in
which layers of exceptions exist.
 To allow chained exceptions, two constructors and two methods were
added to Throwable. The constructors are shown here:

 In the first form, causeExc is the exception that causes the current
exception.
 That is, causeExc is the underlying reason that an exception occurred.
 The second form allows you to specify a description at the same time
that you specify a cause exception.
 These two constructors have also been added to the Error, Exception,
and RuntimeException classes.
 The chained exception methods supported by Throwable are
getCause( ) and initCause( ).
 These methods are shown in Table 10-3 and are repeated here for the
sake of discussion.
 The getCause( ) method returns the exception that underlies the current
exception.
 If there is no underlying exception, null is returned.
 The initCause( ) method associates causeExc with the invoking
exception and returns a reference to the exception.
 Thus, you can associate a cause with an exception after the exception has
been created.
 However, the cause exception can be set only once.
 Thus, you can call initCause( ) only once for each exception object.
 Furthermore, if the cause exception was set by a constructor, then you
can’t set it again using initCause( ).
 In general, initCause( ) is used to set a cause for legacy exception
classes that don’t support the two additional constructors described
earlier.
 Here is an example that illustrates the mechanics of handling chained
exceptions:
MODULE-5
Chapter - 1
Multithreaded
Programming

 Java provides built-in support for multithreaded


programming.
 A multithreaded program contains two or more parts
that can run concurrently. Each part of such a
program is called a thread, and each thread defines a
separate path of execution.
 Thus, multithreading is a specialized form of
multitasking.
 However, there are two distinct types of multitasking:
process-based and thread-based.
 It is important to understand the difference between the
two.
 For many readers, process-based multitasking is the
more familiar form.
 A process is, in essence, a program that is executing.
 Thus, process-based multitasking is the feature that
allows your computer to run two or more programs
concurrently.
 For example, process based multitasking enables you to
run the Java compiler at the same time that you are using
a text editor or visiting a web site.
 In a thread-based multitasking environment, the
thread is the smallest unit of dispatchable code.
 This means that a single program can perform two or
more tasks simultaneously.
 Multithreading enables you to write efficient programs
that make maximum use of the processing power
available in the system.
 One important way multithreading achieves this is by
keeping idle time to a minimum.
 Multithreading helps you reduce this idle time because
another thread can run when one is waiting.

The Java Thread Model


 The Java Thread Model The Java run-time system
depends on threads for many things, and all the class
libraries are designed with multithreading in mind.
 In fact, Java uses threads to enable the entire
environment to be asynchronous. This helps reduce
inefficiency by preventing the waste of CPU cycles.
 Single-threaded systems use an approach called an
event loop with polling.
 In this model, a single thread of control runs in an
infinite loop, polling a single event queue to decide
what to do next.
 Once this polling mechanism returns with, say, a
signal that a network file is ready to be read, then the
event loop dispatches control to the appropriate event
handler.
 Until this event handler returns, nothing else can
happen in the program.
 This wastes CPU time.
 It can also result in one part of a program dominating
the system and preventing any other events from
being processed.
 In general, in a single-threaded environment, when a
thread blocks (that is, suspends execution) because it
is waiting for some resource, the entire program stops
running.
 The benefit of Java’s multithreading is that the main
loop/polling mechanism is eliminated. One thread can
pause without stopping other parts of your program.
 Multithreading allows animation loops to sleep for a
second between each frame without causing the whole
system to pause.
 When a thread blocks in a Java program, only the single
thread that is blocked pauses.
 All other threads continue to run.
 As most readers know, over the past few years, multi-core
systems have become common place. Of course, single-
core systems are still in widespread use.
 It is important to understand that Java’s multithreading
features work in both types of systems.
 In a single core system, concurrently executing
threads share the CPU, with each thread receiving a
slice of CPU time.
 Therefore, in a single-core system, two or more
threads do not actually run at the same time, but idle
CPU time is utilized.
 However, in multi-core systems, it is possible for two or
more threads to actually execute simultaneously.
 In many cases, this can further improve program
efficiency and increase the speed of certain operations.
 It provides a powerful means of creating multithreaded
applications that automatically scale to make best use of
multi-core environments.
 The Fork/Join Framework is part of Java’s support
for parallel programming, which is the name
commonly given to the techniques that optimize some
types of algorithms for parallel execution in systems
that have more than one CPU.
 Threads exist in several states. Here is a general
description. A thread can be running. It can be ready
to run as soon as it gets CPU time.
 A running thread can be suspended, which temporarily
halts its activity.
 A suspended thread can then be resumed, allowing it to
pick up where it left off.
 A thread can be blocked when waiting for a resource.
 At any time, a thread can be terminated, which halts its
execution immediately. Once terminated, a thread cannot
be resumed.
Thread Priorities
 Java assigns to each thread a priority that determines
how that thread should be treated with respect to the
others.
 Thread priorities are integers that specify the relative
priority of one thread to another.
 a higher-priority thread doesn’t run any faster than a
lower-priority thread if it is the only thread running.
 Instead, a thread’s priority is used to decide when to
switch from one running thread to the next. This is
called a context switch.
 The rules that determine when a context switch takes
place are simple:
 A thread can voluntarily relinquish
control: This is done by explicitly
yielding, sleeping, or blocking on pending
I/O. In this scenario, all other threads are
examined, and the highest-priority thread
that is ready to run is given the CPU.
 A thread can be preempted by a higher-
priority thread: In this case, a lower-
priority thread that does not yield the
processor is simply preempted—no matter
what it is doing— by a higher-priority
thread. Basically, as soon as a higher-
priority thread wants to run, it does.
This is called preemptive multitasking.
In cases where two threads with the same priority are
competing for CPU cycles, the situation is a bit
complicated.
For operating systems such as Windows, threads of equal
priority are time-sliced automatically in round-robin fashion.
For other types of operating systems, threads of equal priority
must voluntarily yield control to their peers. If they don’t, the
other threads will not run.
The Main Thread
 When a Java program starts up, one thread begins
running immediately. This is usually called the main
thread of your program, because it is the one that is
executed when your program begins.
 The main thread is important for two reasons:
1. It is the thread from which other “child” threads
will be spawned.
2. Often, it must be the last thread to finish
execution because it performs various
shutdown actions.
3. Although the main thread is created
automatically when your program is started,
it can be controlled through a Thread object.
4. To do so, you must obtain a reference to it by
calling the method currentThread( ), which
is a public static member of Thread.
5. Its general form is shown here:

static Thread currentThread( )

 This method returns a reference to the thread in


which it is called.
 Once you have a reference to the main thread,
you can control it just like any other thread.
Implementing Runnable
 The easiest way to create a thread is to create a class
that implements the Runnable interface.
 Runnable abstracts a unit of executable code.
 You can construct a thread on any object that implements
Runnable.
 To implement Runnable, a class need only implement
a single method called run( ), which is declared like
this:
public void run( )
 Inside run( ), you will define the code that constitutes the
new thread.
 It is important to understand that run( ) can call other
methods, use other classes, and declare variables, just
like the main thread can.
 The only difference is that run( ) establishes the entry
point for another, concurrent thread of execution
within your program.
 This thread will end when run( ) returns.
 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:
Thread(Runnable threadOb, String threadName)
 In this constructor, threadOb is an instance of a class
that implements the Runnable interface. This defines
where execution of the thread will begin.
 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.
 In essence, start( ) executes a call to run( ). The start( )
method is shown here: void start( )
Using isAlive( ) and join( )
 As mentioned, often you will want the main thread to
finish last.
 In the preceding examples, this is accomplished by
calling sleep( ) within main( ), with a long enough delay
to ensure that all child threads terminate prior to the main
thread
 However, this is hardly satisfactory solution, and it also
raises a larger question: How can one thread know when
another thread has ended? Fortunately, Thread provides a
means by which you can answer this question.
 Two ways exist to determine whether a thread has
finished.
 First, you can call isAlive( ) on the thread.
 This method is defined by Thread, and its general
form is shown here:
final boolean isAlive( )
 The isAlive( ) method returns true if the thread upon
which it is called is still running.
 It returns false otherwise.
 While isAlive( ) is occasionally useful, the method that
you will more commonly use to wait for a thread to
finish is called join( ), shown here:
final void join( ) throws InterruptedException
 This method waits until the thread on which it is called
terminates.
 Its name comes from the concept of the calling thread
waiting until the specified thread joins it.
 Additional forms of join( ) allow you to specify a
maximum amount of time that you want to wait for
the specified thread to terminate.
OUTPUT
Thread Priorities
 Thread priorities are used by the thread scheduler to
decide when each thread should be allowed to run.
 In theory, over a given period of time, higher-priority
threads get more CPU time than lower-priority threads.
 In practice, the amount of CPU time that a thread gets
often depends on several factors besides its priority. (For
example, how an operating system implements
multitasking can affect the relative availability of CPU
time.)
 A higher-priority thread can also preempt a lower-
priority one.
 For instance, when a lower-priority thread is running
and a higher-priority thread resumes (from sleeping
or waiting on I/O, for example), it will preempt the
lower-priority thread.
 In theory, threads of equal priority should get equal
access to the CPU. But you need to be careful.
 Remember, Java is designed to work in a wide range of
environments. Some of those environments implement
multitasking fundamentally differently than others.
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 is achieved is called
synchronization.
 Key to synchronization is the concept of the monitor.
 A monitor is an object that is used as a mutually
exclusive lock.
 Only one thread can own a monitor at a given time.
 When a thread acquires a lock, it is said to have entered
the monitor.
 All other threads attempting to enter the locked monitor
will be suspended until the first thread exits the monitor.
 These other threads are said to be waiting for the monitor.
 A thread that owns a monitor can reenter the same
monitor if it so desires.
 You can synchronize your code in either of two ways.
Both involve the use of the synchronized keyword, and
both are examined here.

Using Synchronized Methods


 Synchronization is easy in Java, because all objects have
their own implicit monitor associated with them.
 To enter an object’s monitor, just call a method that
has been modified with the synchronized keyword.
 While a thread is inside a synchronized method, all other
threads that try to call it (or any other synchronized
method) on the same instance have to wait.
 let’s begin with a simple example that does not use it—
but should.
The synchronized Statement
 While creating synchronized methods within classes
that you create is an easy and effective means of
achieving synchronization, it will not work in all cases.
 To understand why, consider the following. Imagine that
you want to synchronize access to objects of a class
that was not designed for multithreaded access.
 That is, the class does not use synchronized methods.
Further, this class was not created by you, but by a third
party, and you do not have access to the source code.
 Thus, you can’t add synchronized to the appropriate
methods within the class.
 How can access to an object of this class be
synchronized? Fortunately, the solution to this
problem is quite easy: You simply put calls to the
methods defined by this class inside a synchronized
block.
Interthread Communication
 As you will see, this is especially easy in Java.
 As discussed earlier, multithreading replaces event loop
programming by dividing your tasks into discrete, logical
units.
 Threads also provide a secondary benefit: they do away
with polling. Polling is usually implemented by a loop
that is used to check some condition repeatedly.
 Once the condition is true, appropriate action is taken.
 This wastes CPU time.
 For example, consider the classic queuing problem,
where one thread is producing some data and another is
consuming it.
 To make the problem more interesting, suppose that the
producer has to wait until the consumer is finished before
it generates more data.
 In a polling system, the consumer would waste many
CPU cycles while it waited for the producer to produce.
 Once the producer was finished, it would start polling,
wasting more CPU cycles waiting for the consumer to
finish, and so on.
 Clearly, this situation is undesirable.
 To avoid polling, Java includes an elegant inter process
communication mechanism via the wait( ), notify( ), and
notifyAll( ) methods.
 These methods are implemented as final methods in
Object, so all classes have them.
 All three methods can be called only from within a
synchronized context.
 Although conceptually advanced from a computer
science perspective, the rules for using these methods are
actually quite simple:
 Before working through an example that
illustrates interthread communication, an
important point needs to be made.
 Although wait( ) normally waits until notify( ) or
notifyAll( ) is called, there is a possibility that in very
rare cases the waiting thread could be awakened(stop
of sleep) due to a spurious wakeup.(without
satisfaction)
 In this case, a waiting thread resumes without notify( )
or notifyAll( ) having been called.
 (In essence, the thread resumes for no apparent reason.)
Because of this remote possibility, Oracle recommends
that calls to wait( ) should take place within a loop that
checks the condition on which the thread is waiting.
Deadlock
 A special type of error that you need to avoid that
relates specifically to multitasking is deadlock, which
occurs when two threads have a circular dependency
on a pair of synchronized objects.
 For example, suppose one thread enters the monitor on
object X and another thread enters the monitor on object
Y.
 If the thread in X tries to call any synchronized method
on Y, it will block as expected.
 However, if the thread in Y, in turn, tries to call any
synchronized method on X, the thread waits forever,
because to access X, it would have to release its own lock
on Y so that the first thread could complete.
 Deadlock is a difficult error to debug for two reasons:
Suspending, Resuming, and Stopping Threads
 Sometimes, suspending execution of a thread is useful.
 For example, a separate thread can be used to display
the time of day.
 If the user doesn’t want a clock, then its thread can be
suspended.
 Whatever the case, suspending a thread is a simple
matter.
 Once suspended, restarting the thread is also a simple
matter.
 The mechanisms to suspend, stop, and resume threads
differ between early versions of Java, such as Java 1.0,
and modern versions, beginning with Java 2.
 Prior to Java 2, a program used suspend( ), resume( ),
and stop( ), which are methods defined by Thread, to
pause, restart, and stop the execution of a thread.
 The suspend( ) method of the Thread class was
deprecated by Java 2 several years ago.
 This was done because suspend( ) can sometimes cause
serious system failures.
 Assume that a thread has obtained locks on critical
data structures.
 If that thread is suspended at that point, those locks are
not relinquished.(retreat)
 Other threads that may be waiting for those resources can
be deadlocked.
 The resume( ) method is also deprecated.
 It does not cause problems, but cannot be used without
the suspend( ) method as its counterpart.
 The stop( ) method of the Thread class, too, was
deprecated by Java 2.
 This was done because this method can sometimes cause
serious system failures.
 Assume that a thread is writing to a critically important
data structure and has completed only part of its changes.
 If that thread is stopped at that point, that data structure
might be left in a corrupted state. The trouble is that stop(
) causes any lock the calling thread holds to be released.
 Thus, the corrupted data might be used by another
thread that is waiting on the same lock.
 Because you can’t now use the suspend( ), resume( ),
or stop( ) methods to control a thread, you might be
thinking that no way exists to pause, restart, or
terminate a thread.
 But, fortunately, this is not true. Instead, a thread must
be designed so that the run( ) method periodically
checks to determine whether that thread should
suspend, resume, or stop its own execution.
MODULE-5
CHAPTER-2
Enumerations,
Type Wrappers
and
Autoboxing
Enumerations
 Versions of Java prior to JDK 5 lacked one feature
that many programmers felt was needed:
enumerations.
 In its simplest form, an enumeration is a list of named
constants.
 Although Java offered other features that provide
somewhat similar functionality, such as final variables,
many programmers still missed the conceptual purity of
enumerations— especially because enumerations are
supported by many other commonly used languages.
 Beginning with JDK 5, enumerations were added to the
Java language, and they are now an integral and widely
used part of Java.
 In their simplest form, Java enumerations appear
similar to enumerations in other languages. However,
this similarity may be only skin deep because, in Java,
an enumeration defines a class type.
 By making enumerations into classes, the capabilities of
the enumeration are greatly expanded.
 For example, in Java, an enumeration can have
constructors, methods, and instance variables.
 The values( ) method returns an array that contains a
list of the enumeration constants.
 The valueOf( ) method returns the enumeration
constant whose value corresponds to the string passed
in str.
 In both cases, enum-type is the type of the
enumeration.
Type Wrappers
 As you know, Java uses primitive types (also called
simple types), such as int or double, to hold the basic
data types supported by the language.
 the primitive types are not part of the object hierarchy,
and they do not inherit Object.
 Despite the performance benefit offered by the primitive
types, there are times when you will need an object
representation.
 For example, you can’t pass a primitive type by
reference to a method. Also, many of the standard
data structures implemented by Java operate on
objects, which means that you can’t use these data
structures to store primitive types.
 To handle these (and other) situations, Java provides
type wrappers, which are classes that encapsulate a
primitive type within an object.
 The type wrapper classes are described in detail in
Part II, but they are introduced here because they
relate directly to Java’s autoboxing feature.
 The type wrappers are Double, Float, Long, Integer,
Short, Byte, Character, and Boolean.
 These classes offer a wide array of methods that allow
you to fully integrate the primitive types into Java’s
object hierarchy.
The Numeric Type Wrappers
 By far, the most commonly used type wrappers are those
that represent numeric values.
 These are Byte, Short, Integer, Long, Float, and
Double.
 All of the numeric type wrappers inherit the abstract
class Number.
 Number declares methods that return the value of an
object in each of the different number formats.
 These methods are shown here:
Autoboxing
 Beginning with JDK 5, Java added two important
features: autoboxing and auto-unboxing.
 Autoboxing is the process by which a primitive type is
automatically encapsulated (boxed) into its equivalent
type wrapper whenever an object of that type is
needed.
 There is no need to explicitly construct an object.
 Auto-unboxing is the process by which the value of a
boxed object is automatically extracted (unboxed)
from a type wrapper when its value is needed.
 There is no need to call a method such as intValue( ) or
doubleValue( ).
 The addition of autoboxing and auto-unboxing greatly
streamlines the coding of several algorithms, removing
the tedium of manually boxing and unboxing values.
 It also helps prevent errors.
 Moreover, it is very important to generics, which operate
only on objects.
 Finally, autoboxing makes working with the Collections
Framework.
 With autoboxing, it is no longer necessary to manually
construct an object in order to wrap a primitive type.
 You need only assign that value to a type-wrapper
reference.
 Java automatically constructs the object for you.
 For example, here is the modern way to construct an
Integer object that has the value 100:
Autoboxing and Methods
 In addition to the simple case of assignments, autoboxing
automatically occurs whenever a primitive type must
be converted into an object;
 auto-unboxing takes place whenever an object must be
converted into a primitive type.
 Thus, autoboxing/unboxing might occur when an
argument is passed to a method, or when a value is
returned by a method.
Autoboxing/Unboxing Occurs in Expressions
 In general, autoboxing and unboxing take place
whenever a conversion into an object or from an
object is required.
 This applies to expressions.
 Within an expression, a numeric object is
automatically unboxed.
 The outcome of the expression is reboxed, if necessary.
 For example, consider the following program:

You might also like