OOP With Java
OOP With Java
In the negative side, Java runs more slowly than most modern programming languages because it
is interpreted. To understand this, let us see the Java Virtual Machine (JVM) and the Byte code.
The Java Virtual Machine and the Byte Code
Compilers usually translate a higher level language into the machine language of a particular
type of computer. However, the Java compiler translates Java not into machine language but into
a pseudo machine language called Java Byte code.
Byte code is the machine language for imaginary Java computer. To run Java byte code on a
particular computer, you must install a JVM on that computer.
JVM is a program that behaves like a computer. Such a program is called an interpreter.
2
OOP with Java
3
OOP with Java
4
OOP with Java
Chapter Two
The Inside of Objects and Classes: More OOP Concepts.
Member Functions and Their Components
Class Declaration
class is a java keyword and all the normal keyword restrictions apply. One way of
thinking about a java class is to note that they resemble structures. We simply use the key
word class instead of struct, and the member of the structure become private by default.
the class declaration syntax is:
class class_name{
data_members;
...
class_methods();
...;
}
Instantiation & Initializing class objects.
The process of creating an object from a class is called instantiation. To create an object
from a java class, one must use the „new’ keyword.
Object Creation
No object is actually created by the declaration process. An object declaration simply
declares the name (identifier), which we use to refer to an object. E.g.,:
Account account; designate that the name account is used to refer to an account object,
but the actual Account object is not yet created. We create an object by invoking the new
command. The syntax is:
<object name> = new <class name>(<arguments>);
Where <object name> is the name of a declared object, <class name> is the name of the
class to which the object belongs, and <argument> is a sequence of values passed to the
method.
let us see the distinction between object declaration and object creation/instantiation.
5
OOP with Java
Customer customer;
customer = new Customer();
customer = new Customer();
What do you think will happen? An error? No. it is possible to use the same name to refer to
different objects of the same class.
consider the following figure:
customer
*
Customer Customer
6
OOP with Java
Parameterized constructors
The parameterized constructors can accept values into the constructor that has different
parameters in the constructor. The value would be transferred from the main() method to
the constructor either with direct values or through variables.
Using overloaded constructors
Overloaded constructors enable object of a class to be initialized in different ways. To
overload constructors, simply provide multiple constructor declarations with different
parameter lists.
Attempting to overload a constructor with another constructor that has the exact same
signature (name and parameters) is a syntax error.
for instance, consider the constructors of the following class:
public class Person{
private String firstName;
private String secondName;
private int age;
public Person()
{
this(“No first name”, “No second name”,0);
}
public Person(String fName)
{
this(fName, “No second name”,0);
}
public Person(String fName,String sName)
{
this(fName,sName,0);
}
public Person(String fName,String sName,int a)
{
firstName = fName;
secondName = sName;
age = a;
}
public Person(Person person)
{
this(person.firstName,person.secondName,person.age);
}
}//end class
7
OOP with Java
The above class contains five overloaded constructors that provide convenient ways to
initialize objects of class person. Each constructor guarantees that every object the
constructor initializes begins in a consistent state.
The above class uses the keyword this to call / invoke a specific constructor with the
specified number and type of argument. It is a syntax error, when the „this’ reference is
used in a constructor‟s body to call another constructor of the same class and that
statement is not the first statement in the constructor. It is also a syntax error when a non-
constructor method attempts to invoke a constructor directly via the „this’ reference.
Methods
Methods (sometimes called functions or procedures) allow the programmer to modularize
a program by separating its tasks into self-contained units. These units are sometimes
called programmer defined methods.
A method is invoked or called by a method call. The method call specifies the name of
the method and provides information (arguments) that the called method requires to
perform its task. When the method call completes, the method either returns a result to
the calling method (or caller) or simply returns the control to the caller.
The first line of the method declaration is called the method header. Following the
method header, declaration and statements in brace form the method body, which is a
block. Variables can be declared in any block, and blocks can be nested. A method can’t
be declared inside another method.
the basic format of a method declaration is :
return-value-type method-name(para1,para2,...,paraN)
{
declarations and statements;
}
The method-name is any valid identifier. The return-type is the type of the result returned
by the method to the caller. The return-type void indicates that a method does not return a
value. Methods can return at most one value.
E.g., public double maximum(double x,double y,double z)
{
return Math.max(x,Math.max(y,z));
}
Access specifiers and methods
Access specifiers are used to restrict access to the method. Regardless of what the access
specifier is, the method is accessible from any other method in the same class. However,
although all methods in a class are accessible by all other methods in the same class,
there are certain necessary tasks that you might not want other objects to be able to
perform.
Let us see the access specifiers of Java language; public, private and protected.
8
OOP with Java
public: the public modifier is the most relaxed possible for a method. By specifying a
method as public, it becomes accessible to all classes regardless of their lineage or their
package;
protected: any class that extends the current class can access protected members. But
other classes which are not related to the current class in an inheritance can‟t make use of
the protected members of the current class. If you didn‟t assign a modifier in front of a
class declaration, the class is created with the default properties. By default, all classes
are assigned to package level visibility. This means that while the class may be extended
and employed by other classes, only those objects within the same package may make
use of this class.
private: private is the highest degree of protection that can be applied to a method. A
private method is only accessible by those methods in the same class. Even classes that
extend from the current class do not have access to a private member.
Other important concepts :
final: final classes may not have any subclasses and are created by placing the modifier
final in front of the class declaration. A variable can be decaled as final. Doing so
prevents its contents from being modified. This means that you must initialize a final
variable when it is declared. (In this usage, final is similar to const in C++).
abstract: an abstract class is a class that is incomplete, or to be considered incomplete.
Only abstract classes may have an abstract method. That is, methods that are declared but
not yet implemented. If a class that is not abstract contains an abstract method, then a
compile-time error occurs. A class has abstract methods if any of the following is true; if:
it explicitly contains a declaration of an abstract method. it inherits an abstract method
from its direct superclass.
An abstract class is defined with the modifier abstract. No instance can be created from
an abstract class. consider the following example:
9
OOP with Java
return courseGrade;
}
public String getName()
{
return name;
}
}//end class
An abstract method is a method with the keyword abstract and it ends with a semicolon
instead of a method body. We say a method is implemented if it has a method body.
Accessors and Mutators. / get() and set() Methods
private fields can be manipulated only by methods of the class in which the fields are
declared. Classes often provide public methods to allow clients of the class to set (i.e.,
assign values to) or get (i.e., obtain the values of) private instance variables. These
methods need not be called set and get, but they often are. Set methods are also
commonly called mutator methods (because they typically change a value). Get methods
are also commonly called accessors or query methods.
If an instance variable is declared public, the instance variable can be read or written at
will by any method that has reference to an object of the class in which the instance
variable is declared.
Using a public set and get method ensures that the new value is appropriate for that data
item. For example, an attempt to set the day of the month for a data to 37 would be
rejected; an attempt to set a person‟s weight to a negative value would be rejected, and so
on. So, although set and get methods could provide access to private data, the access is
restricted by the programmer‟s implementation.
Calling and returning: methods
Generally, the calling method controls method calls and their order. The called method is
controlled by the calling method.
Let us see an example:
public class First{
public void next_fun()
{
System.out.println(“Inside next_fun()”);
}
public void third_fun()
{
System.out.println(“inside third_fun()”);
}
}//end class
public class TestFirst{
public static void main(String args[])
{
10
OOP with Java
11
OOP with Java
Passing by address
When we pass an argument (local variable) by address, the variable‟s address is assigned
to the receiving method‟s parameter. The address of the variable not its value is copied to
the receiving method‟s parameter when we pass a variable address. In Java, all the arrays
are passed by address.
Passing arrays to methods
Java automatically passes arrays to methods using simulated call-by reference; the called
methods can modify the element values in the callers, the original values. The value of
the name of the array is the address of the first element of the array. Because the starting
address of the array is passed, the called method knows precisely where the array is
stored.
Although entire array are passed simulated call-by-reference yet the individual array
elements are passed call-by-value, exactly as simple variables are. For a method to
receive an array through a method call, the method‟s parameter list must specify that an
array would be received.
E.g., public class ArrayEg{
public void modifyArray(int num[])
{ for(int i=0;i<num.length;i++)
num[i]+=2;
System.out.println(“inside modifyArray()”);
for(int i=0;i<num.length;i++)
System.out.println(num[i]+” ”);
}}//end class
public class TestArray{
public static void main(String args[])
{
int a[] = new int[10];
for(int i=0;i<a.length;i++)
a[i]=i+1;
System.out.println(“inside main()”);
for(int i=0;i<a.length;i++)
System.out.print(a[i]+ “ ”);
ArrayEg aEg = new ArrayEg();
System.out,println();
aEg.modifyArray(a);
System.out.println();
System.out.println(“back inside main()”);
for(int i=0;i<a.length;i++)
System.out.print(a[i]+ “ ”);
} }//end class
12
OOP with Java
13
OOP with Java
14
OOP with Java
Chapter Three
Inheritance
In inheritance, a new class is defined by means of an older, pre-existing class. This leads
to a situation in which, the new class has all the functionality of the older, pre-existing
class and, additionally, introduces its own specific functionality. We say the new class
inherits the functionality of another existing class.
While speaking of inheritance, the existing class is called the superclass (base class) and
the new class is called subclass (derived class).
Concept of Inheritance
One advantage of OOP is the re-usage of code. The capability to define custom data
types using classes enables us to reuse the code that we develop. This works well if we
always need exactly the same object. In real world, however, we may need an object that
is almost similar to an already developed object but not exactly similar. Inheritance
enables us to reuse an object more quickly; thus making slight adjustments where
necessary.
Superclasses and subclasses
Often, an object of one class “is an” object of another class as well. For instance, in
geometry, a rectangle is a quadrilateral. Thus, in Java, class rectangle can be said to
inherit from class Quadrilateral. Because every subclass object “is an” object of its
superclass, and one superclass can have many subclasses, the set of objects represented
by a superclass typically is larger than the set of objects represented by any of its
subclasses. For example, the superclass vehicle represents all vehicles, including cars,
trucks, boats and so on. By contrast, subclass car represents a smaller, more specific
subset of all vehicles.
Inheritance relationship forms tree-like hierarchical structure
to specify that class TwoDimensionalShape extends (or inherits from) class Shape, class
TwoDimensionalShape could be declared in Java as follows:
public class TwoDimensionalShape extends Shape
15
OOP with Java
Objects of all classes that extend a common superclass can be treated as objects of that
superclass. (i.e., such objects have an “is-a” relationship with the superclass). However,
superclass objects can‟t be treated as objects of their subclasses. For example, all cars are
vehicles, but not all vehicles are cars.
Protected Members
A superclass‟s protected members can be accessed by members of that superclass, by
members of any class derived from that superclass and by members of other classes in the
same package. (Protected members have package access).
Overriding a method
If a class declares an instance method, then the declaration of that method is said to
override any and all methods with the same signature in the superclass.
If a method declaration overrides the declaration of another method, then a compile-time
error occurs if they have different return types or if one has a return type and the other is
void.
The access modifier of the overriding method must provide at least as much access as the
overridden method, or a compile-time error occurs. on more detail:
If the overridden method is public, then the overriding method must be public;
otherwise, a compile-time error occurs.
If the overridden method is protected, then the overriding method must be
protected or public, otherwise, a compile-time error occurs.
If the overridden method has default (package) access, the overriding method
must not be private; otherwise, a compile-time error occurs.
Notice that a private method is never accessible and so can‟t be overridden in the
technical sense of these terms.
Using this () and super ()
Because you frequently want to call the superclass‟s constructor explicitly, there is a
keyword in Java that makes this possible. super() will call the parent‟s constructor which
has the appropriate supplied parameters. It is also possible to have more than one
constructor for a class (which was discussed in the overloading section). If you are
creating more than one constructor, you typically do not want to duplicate the common
code. So you can call a same class constructor using this() keyword, sending any required
parameters.
The keyword super() has two general forms. The first is call of superclass constructor.
The second is used to access a member of the superclass that has been hidden by a
member of the subclass. let us see each use of the super keyword one by one:
public class Student{
private String name;
private int age;
public Student(String name, int age)
{
16
OOP with Java
this.name = name;
this.age = age;
}
public void printData()
{
System.out.println(“Name->”+name);
System.out.println(“Age->”+age);
}
}//end class
17
OOP with Java
Here, member can either be a method or an instance variable. This second form of super()
is most applicable to situations in which member names of a subclass hide members by
the same name in the superclass. Consider the following example.
public class ClassA{
int i;
}//end class
18
OOP with Java
Final keyword prevents overriding. To disallow a method from being overridden, specify
final as a modifier at the start of its declaration. Methods declared as final can‟t be
overridden. Have a look at the following example.
public class ClassA{
public final void firstMethod()
{
System.out.println(“this is a final method declared only once”);
}
}//end class
public class ClassB extends ClassA{
public void firstMethod()
{
System.out.println(“illegal to declare this method again”);
}
}//end class
Final prevents inheritance. Sometimes, you will want to prevent a class from being
inherited. To do this, precede the class declaration with the keyword final. Declaring a
class as final implicitly declares all of its methods as final too. Consider the following
example.
public final clas ClassA{
//…
}//end class
public class ClassB extends ClassA{//illegal inheritance
}//end class
Constructors in subclasses
Instantiating a subclass object begins a chain of constructor calls in which the subclass
constructor, before performing its own tasks, invokes its direct superclasse‟s constructor
either explicitly (via the super reference) or implicitly (calling the superclasse‟s default
constructor or no-argument constructor). Similarly, if the superclass was derived from
another class, the superclass constructor would be required to invoke the constructor of
the next class up in the hierarchy, and so on. The last constructor called in the chain is
always the constructor of class Object. The original subclass constructor‟s body finishes
executing last.
19
OOP with Java
Chapter Four
Polymorphism
Polymorphism allows programmers to send the same message to objects from different
classes. i.e., in its simplest from, polymorphism allows a single variable to refer to
objects from different classes.
Polymorphism enables us to “program in the general” rather than “program in the
specific”. In particular, polymorphism enables us to write programs that process objects
of classes that are part of the same class hierarchy as if they are all objects of their
classes.
With polymorphism, it is possible to design and implement systems that are easily
extensible. New classes can be added with little or no modification to the generic portions
of the program, as long as those classes are part of the inheritance hierarchy that the
program processes generically. The only parts of a program that must be altered to
accommodate new classes are those program components that require direct knowledge
of the new classes that the programmer adds to the hierarchy.
Relationships among Objects in an inheritance hierarchy
Here, we will examine the relationships among classes in a hierarchy. In this section, we
see that an object of a subclass can be treated as object of its superclass. This enables
various interesting manipulations. For example, a program can create an array of
superclass reference that refers to objects of many subclass types. This is allowed despite
that fact that the subclass objects are of different types, because each subclass object is an
object of its subclasses. However, a superclass object is not an object of any of its
subclasses. The “is-a” relationship applies only from a subclass to its direct and indirect
superclasses.
Assigning reference of a subclass to a superclass-type variable
Let us see an example here:
public class Point3{
private int x;
private int y;
public Point3()
{
}
public Point3(int xValue,int yValue)
{
x=xValue;
y=yValue;
}
public void setX(int xValue)
{
20
OOP with Java
x=xValue;
}
public void setY(int yValue)
{
y=yValue;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public String toString()
{
return “[“+getX()+ “, ”+getY()+ “]”;
}
}//end class
public class Circle4 extends Point3{
private double radius;
public Circle4(int xValue, int yValue, double rValue)
{
super(xValue,yValue);
setRadius(rValue);
}
public void setRadius(double rValue)
{
radius = (rValue < 0.0?0.0:rValue);
}
public double getRadius()
{
return radius;
}
public double getDiameter()
{
return 2*getRadius();
}
public double getCircumfrence()
{
21
OOP with Java
return Math.PI*getDiameter();
}
public double getArea()
{
return Math.PI*getRadius()*getRadius();
}
public String toString()
{
return “Center = “+super.toString()+ “; Radius=”+getRadius();
}
}//end class
import javax.swing.*;
public class PolyTest1{
public static void main(String args[])
{
Point3 point = new Point3(30,50);
Circle4 circle = new Circle4(120,89,2.7);
String output = “Call Point3‟s toString with superclass”+
“reference to superclass object:\n”+ point.toString();
output+= “\n\nCall Circle4‟s toString with subclass ”+
“reference to subclass object:\n”+circle.toString();
Point3 pointRef = circle;
Output+= “\n\ncall Circle4‟s toString with superclass ”+
“ refernce to subclass object:\n “+pointRef.toString();
JOptionPane.showMessageDialog(null,output);
System.exit(0);
}
}//end class
In the above program, the statement Point3 pointRef = circle; assigns the reference of
subclass object circle to superclass-type variable pointRef. A superclass-type variable
that contains a reference to a subclass object calls the subclass method; hence,
pointRef.toString() actually calls class Circle4‟s toString method. The Java compiler
allows this “crossover” because an object of a subclass is an object of its superclass.
Assigning a superclass object’s reference to a subclass-type variable
Let us consider the following example:
public class PolyTest2{
public static void main(String args[])
{
Point3 point = new Point3(30,50);
22
OOP with Java
23
OOP with Java
In the above code, we have such an assignment: point = circle; Java compiler allows this
because a Circle4 is a Point3 object. Using point reference, we can only invoke
superclass only methods. But when we try to invoke subclass only methods using point,
the Java compiler generates error on each of these lines, because these are not methods of
the superclass Point3. (in this case, using a Point3 variable, we can invoke only Point3
methods getX, getY, setX, setY and toString)
Summary of the allowed assignments between superclass and subclass variables
Despite the fact that a subclass object also is a superclass object, the subclass and
superclass objects are indeed different. As we have discussed previously, subclass objects
can be treated as if they were superclass objects. This is a logical relationship, because
the subclass contains all the members of the superclass, but the subclass can have
additional subclass-only members. For this reason, assigning a superclass reference to a
subclass-type variable is not allowed without an explicit cast; such an assignment would
leave the subclass-only members undefined for the subclass object.
We have discussed four ways to assign superclass and subclass references to variables of
superclass and subclass types:
1. Assigning a superclass reference to a superclass-type variable is straight forward
2. Assigning a subclass reference to a subclass-type variable is straight forward.
3. Assigning a subclass object’s reference to a superclass type variable is safe,
because the subclass object is an object of its superclass. However, this reference
can be used to invoke only superclass methods. If this code refers to subclass-only
members through the superclass variable, the compiler generates an error.
4. Attempting to assign a superclass object’s reference to a subclass type variable is
a compile-time error. To avoid the error, the superclass reference must be cast to a
subclass type explicitly.
Multiple inheritance and Interfaces
An interface is like a class that can‟t be instantiated. Its purpose is to specify a set of
requirements for a class to implement. These requirements are regarded as a “contract”
between the implementing class and any client class that uses it.
An interface is a description of a capability. It lists the methods that a class must
implement to carry out that capability.
An interface typically consists of declarations of related methods, although an interface
also may contain static and final fields that represent constants. In any case, all interface
members are public. A class that implements an interface typically provides definitions
for the methods declared in the interface.
A class that implements an interface must provide an implementation for all the method
signatures in the interface. An interface declaration introduces a new reference type
whose members are constants and abstract methods.
24
OOP with Java
25
OOP with Java
}
public double getVolume()
{
return 0.0;
}
public String getName()
{
return “Point”;
}
public String toString()
{
return “[”+getX()+ “, ”+getY()+ “]”;
}
}//end class
Use the Circle4 program and the following Cylinder class for the coming illustration
public class Cylinder extends Circle4{
private double height;
public Cylinder(int x,int y,double radius,double heightValue)
{
super(x,y,radius);
setHeight(heightValue);
}
public void setHeight(double heightValue)
{
height = (heightValue <0.0?0.0:heightValue);
}
public double getHeight()
{
return height;
}
public double getArea()
{
return 2 * super.getArea() + getCircumfrence() * getHeight();
}
public double getVolume()
{
return super.getArea() * getHeight();
}
public String getName()
{
26
OOP with Java
return “Cylinder”;
}
public String toString()
{
return super.toString()+ “; Height = ” + getHeight();
}
}//end class
import javax.swing.*;
import java.text.*;
public class InterfaceTest{
public static void main(String args[])
{
DecimalFormat twoDigits = new DecimalFormat(“0.00”);
Point point =new Point(7,11);
Circle4 circle = new Circle4(22,8,3.5);
Cylinder cylinder = new Cylinder(20,30,3.3.3,10.75);
String output = point.getName()+ “:”+point+ “\n”+ circle.getName() +
“:”+circle+ “\n”+ cylinder.getName() + “:”+cylinder+ “\n”;
Shape arrayOfShapes[] = new Shape[3];//create shape array
arrayOfShape[0] = point;
arrayOfShape[1] = circle;
arrayOfShape[2] = cylinder;
for(int i=0; i<arrayOfShapes.length;i++)
{
output += ”\n\n ”+arrayOfShapes[i].getName()+ “:” +
arrayOfShapes[i].toString()+ “\nArea =
”+twoDigits.format(arrayOfShapes[i].getArea())+ “\nVolume = ”+
twoDigits.format(arrayOfShapes[i].getVolume());
}
JOptionPane.showMessageDialog(null,output);
System.exit(0);
}
}//end class
When a class implements an interface, the same “is-a” relationship provided by
inheritance applies. For example, class Point implements Shape. Therefore, a Point object
is a Shape. In fact, objects of any class that extends Point are also Shape object.
Multiple inheritances
A class can be derived from more than one superclass. This concept is called multiple
inheritance. But such a notion can‟t be directly used in Java. Therefore, one has to use an
27
OOP with Java
interface if a class is expected to inherit behaviors from more than one superclass. For
instance, Let us see the declaration of class Point:
public class Point extends Object implements Shape{
}//end class
In Java, all classes inherit from class Object. So whether we write the statement “Point
extends Object” or not, the Java compiler processes the inheritance relationship among
Point and Object classes. Therefore, our class Point will have both the functionality of
class Object and that of Shape, hence multiple inheritance. The point to be underlined
here is, multiple inheritance is only possible through the use of interfaces.
To summarize the discussion of interface; lets see the following comparison.
Unlike a class, an interface:
Declares only method headers and public constants;
Has no constructors
Can‟t be instantiated
Can be implements by a class
Can‟t be implemented by an interface
Can‟t extends a class
Can extend several other interfaces.
Interface are very useful for specifying what a class should be able to do, while deferring
to a later time how the contract should be implemented. But in some cases, interfaces are
too restrictive. They allow no variable definitions (except public final constants) or
executable statements. Often, it is better to proceed with a partial class implementation,
deferring only those methods that depend directly upon the backing data structure. That is
when an abstract class should be used.
28
OOP with Java
Chapter Five
Exception Handling
What is an exception?
An exception is an error that occurs during the execution of a program. Java facilitates
the management of such errors by diverting control to special program bocks that are
called exception handlers.
Exception handling enables programmers to create applications that can resolve (or
handle) exceptions. In many cases, handling an exception allows a program to continue
executing as if no problem had been encountered. These features enable programmers to
write robust and fault-tolerant programs.
Exception-Handling Overview
Program logic frequently tests conditions that determine how program execution should
proceed. Consider the following psudocode;
Perform a task
If the preceding task did not execute correctly
Perform error processing
Perform next task
If the proceeding task did not execute correctly
Perform error processing
…
In this psudocode, we begin by performing a task; then, we test whether that task
executed correctly or not. If not, we perform error processing. Otherwise, we continue
with the next task. Although this form of error handing works, intermixing program logic
with error-handling logic can make the program difficult to read, modify and debug-
especially in large applications. Intermixing program and error-handling logic can
degrade a program‟s performance, because the program must test the error-handling logic
to determine whether the next task can be performed.
Exception handling enables the programmer to remove error-handling code from the
“main line” of the program‟s execution, which improves program clarity and enhances
modifiability.
The causes of exception
An exception is thrown for one of the three reasons:
(a) An abnormal execution condition was synchronously detected by the JVM. Such conditions
arise because:
Evaluation of an expression violates the normal semantics of the Java language, such
as an integer divided by zero.
An error occurs in loading or linking part of the Java program
Some limitation at recourse is executed, such as using too much memory
(b) A throw statement was executed in Java code
29
OOP with Java
There are two kinds of exceptions: the kind that you can prevent by writing better code,
and the kind that you can‟t. The first kind is called unchecked exceptions. They are
instances of the Error class, the run-timeException class, and their extensions. For
example, if the division of an integer by zero is attempted, the system will generate an
ArithmeticException.
Exceptions of the second kind are called checked exceptions because they are “checked”
by the compiler before the program is run. Statements that throw them either must be
placed within a try statement, or they must be declared in their method‟s header. Checked
exceptions are the kind that should be expected and therefore managed by an exception
handler.
30
OOP with Java
Handling of an exception
Java provides try statement to enable exception handling. A try statement consists of
keyword try, followed by braces ({}) that delimit a try block. The try block contains
statements that might cause exceptions and statements that should not execute if an
exception occurs. At least one catch clause (also called an exception handler) or a finally
clause must immediately follow the try block. Each catch clause specifies in parenthesis,
an exception parameter that identifies the exception type the handler can process. The
exception parameter‟s name enables the catch clause to interact with a caught exception
object. After the last catch handler, an optional finally clause provides code that always
execute, whether or not an exception occurs. A finally clause is an ideal location for code
that releases resources to prevent “resource leaks”.
The general try statement in Java has this syntax:
try{
statements;
}catch(exception-type1 idetifier1){
statements;
}catch(exception-type2 identifier2){
statements;
}
...
finally{
statements;
}
The point in the program at which an exception occur (i.e., the location where a method
detects and throws an exception) is called the throw point. If an exception occurs in a try
block, the try block terminates immediately and program control transfers to the first
catch clause that follows the try block. This is known as the termination model of
exception handling, because the try block that encloses a thrown exception terminates
when the exception occurs. When a try block terminates, local variables declared in the
block go out of scope. Next the program searches for the first catch that can process the
type of exception that occurred. The program locates the matching catch by comparing
the thrown exception’s type with each catch’s exception-parameter type until the
program finds a match. A match occurs if the types are identical or if the thrown
exception‟s type is a subclass of the exception parameter‟s type. When a match occurs,
the code contained within the matching catch handler executes. When a catch clause
finishes processing, local variables declared within the catch clause (including the catch
parameter) go out of scope. Any remaining catch clauses that correspond to the try block
are ignored and execution resumes at the first line of code after the try/catch sequence.
31
OOP with Java
If no exceptions occur in a try block, the program ignores the catch handler(s) for that
block. If a finally clause appears after the last catch clause, the finally clause executes
regardless of whether an exception occurs.
If an exception occurs in a method and is not caught, or the statement that caused the
exception is not in a try block, the method that contains the statement terminates
immediately, and the program attempts to locate an enclosing try block in the calling
method. This process is called stack unwinding.
let us consider how to handle an exception using try-catch statement:
try{
num1 = Integer.parseInt(n1);
num2 = Integer.parseInt(n2);
}
catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null,nfe.getMessage());
}
another code fragment that handles an ArithmeticException is
try{
ans = num1/num2;
JOptionPane.showMessageDialog(null,ans);
}
catch(ArithmeticException ae){
JOptionPane.showMessageDialog(null,ae.getMessage());
}
The other way of exception handling is by using the keyword throws. This keyword is
used along methods. If a method is capable of raising an exception that it does not handle,
it must specify that the exception should be handled by the calling method. This is done
by the throws keyword.
let us see an example here:
try{
num1 = Integer.parseInt(firstNumber);
num2 = Integer.parseInt(secondNumber);
result = quotient(num1,num2);//throws an ArithmeticException
}
catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null,nfe.getMessage());
}
catch(ArithmeticException ae){
JOptionPane.showMessageDialog(null,ae.getMessage());
}
...
32
OOP with Java
33
OOP with Java
34
OOP with Java
package javaexception;
/**
*
*/
public class UserTrial {
private int num1,num2;
/** Creates a new instance of UserTrial */
public UserTrial(int a,int b)
{
num1=a;
num2=b;
}
public void show() throws UserDefinedException
{
if(num1<0 || num2>0)
throw new UserDefinedException("Wrong data has been entered");
else
System.out.println("You entered : "+num1+" and "+num2);
}
}
package javaexception;
/**
*
*/
public class Main {
/** Creates a new instance of Main */
public Main() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
UserTrial trial = new UserTrial(-1, 1);
try{
trial.show();
}catch(UserDefinedException ude){
System.err.println("Illegal values entered");
}
}
}
35