VTU 7 Sem B.E (CSE/ISE) : Java/ J2Ee
VTU 7 Sem B.E (CSE/ISE) : Java/ J2Ee
JAVA/ J2EE
Notes prepared by
Mr. Ashok Kumar K
9742024066 | [email protected]
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Unit 2:
2.1.1 Basics
Class
A class is a blueprint or prototype from which objects are created. It's just a template for an object and describes an object’s behavior to
the JVM.
Object
An object is a real instance of a class. It can be any real world entity we come across in our life. Example an Animal is an Object, also a
Bank is an Object, a Human is an Object etc.
A class just describes how a Dog looks like. (Say, a dog has 4 legs, it barks, it eats etc.), but an Object refers
to a real Dog
Syntax
class <class_name> {
type1 var1;
type2 var2;
...
typeN varN;
type1 method1() {
}
type2 method2() {
}
....
typen methodN() {
}
}
An object of the class can be created using the following syntax
Example
Creating a class
class Student {
int regno;
String name;
double score;
Creating an object
Observations
For understanding purpose, lets break down the object creation statement into two steps:
Student stud;
Here ‘stud’ is just like a normal local variable (allocated in stack memory) for the defining block. It
will be initially pointing to a null object (literally meaning NOTHING).
Here the object is instantiated with using a new keyword in java. A dynamic memory will be created in
the heap memory and the reference for this will be assigned to the local variable created in step 1.
The object will also be initialized by JVM. It does so by making a call to the object's constructor
(discussed later). You can pass arguments to the constructor within the parenthesis following the
Mr. Ashok Kumar K | 9742024066 | [email protected]
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
class name on RHS of the above statement.
Variables within the class created without the keyword 'static' prefixed are called instance variables
or object variables or non-static variables. A separate memory space for these types of variables will
be created for each instance of a class.
Variables within the class created with the keyword 'static' prefixed are called class variables or static
variables. This type of variables actually shares the value among all the instances of a class. We will
see in detail with an example, a bit later.
A single .java file can contain any number of classes within it, but only one class can be made as
public and it should be the main class (main class is the one which contains the main function).
The name of the .java file should be the name of the main class.
// Class Definition.
// Instance variable
int regno;
String name;
double score;
// Methods
public void setStudentDetails(int a, String s, double d) {
regno = a;
name = s;
score = d;
}
// Main Class.
public class Example1 {
// Main function
public static void main(String[] args) {
// Object creation
Student s1 = new Student();
s1.setStudentDetails(24, "Arun", 45.89);
s1.printStudentDetails();
}
Output
2.1.2 Constructors
Definition:
A constructor is a special method that is used to initialize a newly created object and is called just after the memory is allocated for the
object. It can be used to initialize the objects to required values at the time of object creation. It is not mandatory for the coder to write a
constructor for the class.
If you don't write a constructor, Java provides a default constructor that initializes the object members to its default values.
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false
A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method
declarations—except that they use the name of the class and have no return type.
Example
class Student {
Student (int rno, String nm, double sc) {
regno = rno;
name = nm;
score = sc;
}
}
Observations
Parameterized Constructor
You can create more than one constructor for a class each having different signatures from one
another. Sounds something familiar? Right, it implies the constructors can be overloaded. Purpose of
having the constructor overloaded is to provide more than one ways of initializing an object. So, the
user of the object can initialize an object using any of the constructors provided. Remember, if you
don't provide any constructor, Java will provide a default zero argument constructors.
class Student {
int regno;
String name;
double score;
If the user of a class has all the three values (name, regno, and score) for a particular student,
he/she can use three argument constructor to create an object initializing it to these values, as
follows:
If the user of a class has only two values (name, and score) and the regno should be auto generated
by the class itself, then he/she can use two argument constructor to create an object, as follows:
If the user of a class doesn't have any idea about the initial values, he can simply go ahead and use
the default zero argument constructor to create an object, and he can assign the values at any time
later on.
"this" keyword
Java defines the 'this' keyword to be used within any method to refer to the current object. Within
an instance method or a constructor, this is a reference to the current object — the object whose
method or constructor is being called. You can refer to any member of the current object from within
an instance method or a constructor by using 'this'.
There are many uses of 'this' keyword, but we are very young at this point of time to explore
everything. So let's see few uses of 'this' keyword which can be understood now:
'this' keyword can be used to call a constructor within another constructor of the same
class. If used, it must be the first statement in the constructor.
class Student {
int regno;
String name;
double score;
'this' keyword can be used to resolve the name space collision. Name space collision is
the situation where the member variables of a class and the local variables within a
constructor have same names.
class Student {
int regno;
String name;
double score;
'this' can be used to return an object, and 'this' can be used as a parameter for an object.
class Student {
....
public Student getStudent () {
return this;
}
}
Constructor Chaining
Like, 'this' keyword is actually a reference for the current object being used; the 'super' keyword
is actually a reference to the parent class of the current object being used. If a class does not extend
any parent class, then by default it's going to extend an Object class (present in java.lang
package). So you can think Object class as the default parent (base class) for all the classes in Java.
We are going to deal with 'super' keyword in later point of time. For now, you can think of 'super'
keyword as the way to make a call to base class constructor from its derived class.
The user of a class is invoking a class' constructor, and this class' is passing the constructor call to its
base class' constructor, and the base class' constructor in turn can pass the call to its base class'
constructor, and so on. This chain of constructor calls starting from an object continuing till Object
class' constructor can be referred as Constructor Chaining.
class Student {
Student() {
// pass the constructor call to its base class' constructor
super();
}
}
Remember, when you instantiate an object using 'new' keyword, the memory for this object will be allocated in JVM heap.
Garbage collection is a mechanism provided by JVM to reclaim heap space from objects which are eligible for Garbage collection.
Garbage collection relieves java programmer from memory management and gives more time to focus on business logic. Garbage
Collection in Java is carried by a daemon thread called Garbage Collector. You cannot force Garbage collection in Java; it will only
trigger if JVM thinks it needs a garbage collection based on Java heap size.
Observations
Java Heap is divided into three generation for sake of garbage collection. These are
Young generation (further divided into three parts: Eden space, Survivor 1, and Survivor 2 space)
Tenured or Old generation, and
Perm area.
New objects are created into young generation and subsequently moved to old generation. String pool is
created in Perm area of Heap, garbage collection can occur in perm space but depends upon JVM to JVM.
Minor garbage collection is used to move object from Eden space to Survivor 1 and Survivor 2 space and
Major collection is used to move object from young to tenured generation. Whenever Major garbage
collection occurs application threads stops during that period which will reduce application’s performance
and throughput.
Every object in Java can have a finalize() method defined within it. Syntax to define a finalize() method is:
finalize() method is a special method in Java which is called just before the Garbage Collector reclaims this object. The intent is for
finalize() to release system resources such as open files, open sockets, open database connections etc, before getting collected.
The keyword protected is a specifier that prevents access to finalize() by code defined outside its class.
class Student {
}
// finalize method
protected void finalize() {
System.out.println("Inside finalize method .. ");
}
As you can see, the finalize() method is not called here. Remember, finalize() is not like a destructor in C++.
finalize() method will not be called simply because the object moves out of scope, instead it will be called only when JVM performs
a Garbage collection which is an undetermined process.
There is an alternative to invoke finalize() method, you can initiate a Garbage Collection manually by making a call to System.gc()
method. Replace the main function in above example with the one below:
Output:
It is possible to create a member of a class that can be used by itself, without reference to a specific instance. To create such a
member, precede its declaration with the keyword 'static'. When a member is declared static, it can be accessed before any
objects of its class are created, and without reference to any object.
Variables
Methods
Blocks
Static Variables
Static variables are also called class variables which actually shares the value among all the instances of a class. It is created by
prefixing the keyword 'static' while declaring a variable. It tells the compiler that there is exactly one copy of this variable in existence
regardless of how many times the class has been instantiated. Memory for static variables will be allocated in Code Segment of JVM
memory.
Example:
class Student {
int regno;
String name;
double score;
Student.principalName = “Hemanth”;
Student stud1 = new Student(7, "Ajay", 76.45);
Let’s create another object 'stud2', and let’s change the principal’s name.
You can now realize from the above figure, the static variable 'principalName' is actually shared among 'stud1' and 'stud2',
meaning, if you reassign a value to 'principalName' w.r.t 'stud2', this change also reflects in 'stud1' as well.
Static Methods
Conceptually, static methods are same as static variables, i.e., they are independent of any specific instance of an object. They are
bound at class level and not at object level.
Static methods can be invoked without creating an instance of its defining class. The most familiar example for static method is our
main function. We prefix the main function with static keyword thus allowing JVM to execute this method without instantiating main
class.
Example
class Student {
int regno;
String name;
double score;
Mr. Ashok Kumar K | 9742024066 | [email protected]
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Static Blocks
Static blocks are also called Static initialization blocks. A static initialization block is a normal block of code enclosed in braces, { }, and
proceeded by the static keyword.
Syntax:
static {
// Logic
}
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The JVM guarantees that
static initialization blocks are called in the order that they appear in the source code. Remember, this code will be executed when JVM
loads the class. JVM combines all these blocks into one single static block and then executes. Restriction on static methods also
applies to static blocks.
Example:
class Student {
int regno;
String name;
double score;
static {
System.out.println("I am the static block in the Student class");
static {
System.out.println("I am the static block in the main class");
}
Output
Java allows you to define a class within another class. Such a class is called a nested class as shown below:
class OuterClass {
class NestedClass {
....
}
....
}
Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static
nested classes. Non-static nested classes are called inner classes.
class OuterClass {
static class StaticNestedClass {
....
}
class InnerClass {
....
}
....
}
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to
other members of the enclosing class, even if they are declared private. Static nested classes do not have
access to other members of the enclosing class.
It increases encapsulation
It constitutes to more readable and maintainable code
Example:
class OuterClass {
class InnerClass {
public void makeCall() {
sayHello(); // RIGHT
sayGoodMorning(); // RIGHT
}
}
static class StaticNestedClass {
public void makeCall() {
sayHello(); // RIGHT
sayGoodMorning(); // WORNG: static
nested class can't
access non static member
}
}
public static void sayHello() {
System.out.println("Hello World .. ");
}
2.2 INHERITANCE
Here, we are going to explore one of the most important characteristics of any object oriented programming language – Inheritance.
2.2.1 Basics
Generally, a process by which a child class acquires the properties (state and behavior) of its parent class is referred to as Inheritance.
For example, Hyundai is a parent class whose properties are inherited by the classes named iTen, iTwenty, Verna, Getz etc.
Inheritance can also be referred to the concept of Generalization, which is the process of extracting common characteristics (states and
behavior) from two or more classes, and combining them into a generalized super class.
A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from
which the subclass is derived is called a superclass (also a base class or a parent class).
Excepting java.lang.Object, which has no superclass, every class in Java has one and only one direct superclass. In the absence of
any explicit superclass, every class is implicitly a subclass of java.lang.Object.
Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived
from the topmost class, java.lang.Object. Such a class is said to be descended from all the classes in the inheritance chain
stretching back to java.lang.Object. Below figure helps us to visualize the concept of Inheritance.
Syntax
Inheritance in Java can be done by using 'extends' keyword likewise in the following syntax.
Example
class Animal {
public void eat() {
System.out.println("EATING THRICE A DAY");
}
public void sleep() {
System.out.println("SLEEPING FOR 8 HOURS");
}
Idea behind inheritance is, when you have the same piece of code repeated in more than one class, you can avoid this duplication of
code by creating a general class that contains the duplicated code and having those classes extending this general class. Thus no
need to write the duplicated code in all the subclasses, you are writing it only once in the general class.
From the above example you can see that eat() and sleep() are the codes that are common to both Dog and a Cat. The duplication
of the code is avoided by defining a general class Animal and having the eat() and sleep() method within it. Cat and Dog just
extends the Animal class.
Observations
A subclass inherits all the public and protected members (fields, methods, and nested classes) from its superclass.
Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can
be invoked from the subclass.
A subclass does not inherit the private members of its parent class. However, if the superclass has public or
protected methods for accessing its private fields, these can also be used by the subclass.
Dog dog = new Animal(); // WRONG, because all Animals are not Dogs
}
}
Using super
super can be used here to make a call to superclass constructor from the derived class constructor.
Example:
super can also be used to refer to superclass member when there is a name collision between
superclass member and a derived class member.
Example:
class A {
int i;
}
Multilevel Inheritance
As discussed before, Java does allows a class to extend another class which further extends another class and so
on, eventually the top most class will be java.lang.Object. This type of inheritance is called as Multilevel
Inheritance (more than one level of inheritance).
Figure on the right gives an example for multilevel inheritance, where Object is
the topmost superclass and class D is at the leaf level.
class A {
A() {
System.out.println("A's Constructor");
}
}
class B extends A {
B() {
System.out.println("B's Constructor");
}
}
class C extends B {
C() {
System.out.println("C's Constructor");
}
}
class D extends C {
D() {
System.out.println("D's Constructor");
}
}
Output
No, Multiple inheritance is NOT allowed in Java. Multilevel inheritance is when a class inherits from more than one
superclass. For example,
We can think of two reasons why Java doesn't allows multiple inheritance
To avoid ambiguity error
Ambiguity error arises when Horse and Bird both defines a function
with the same name and Pegasus runs into a situation of dilemma upon
invoking that function w.r.t its object.
Multiple inheritance will be rarely used.
Java supports a limited form a multiple inheritance by allowing a class to inherit from one other class and an
unlimited number of interfaces. Meaning, a class can extend only one class but it can implement unlimited number
of interfaces.
Example:
Programming Example:
Suppose if you are a newly joined student in car driving school, assume you are allowed only to use the steering
wheel of the car on day 1 while only the trainer will be having access to brake and the accelerator.
The question here is how to implement the access restriction to the student on the car object?
Interface comes as a solution for this. Idea behind interface is, rather than using the object directly, use it through
an interface, so that you can only use that feature of an object which is defined in the interface.
Definition: An interface is a reference type, similar to a class that can contain only constants, method signatures,
and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented
by classes or extended by other interfaces
class Car {
void start() {
System.out.println("Starting Car .. ");
}
void killEngine() {
System.out.println("Engine Killled .. ");
}
}
interface Trainer {
void moveRight();
void moveLeft();
void accelerate();
void brake();
}
interface Student {
void moveLeft();
void moveRight();
}
The word "Polymorphism" refers to the ability to take more than one form. In terms of programming, the polymorphism refers to the
process in which a member function of a class behaves differently for different inputs
At this point of time, you can think of two different ways in which Java provides the Polymorphism feature.
Method Overloading
Concept:
Consider a Chess application, here we will have to implement the move() operation for all the pawns. Are we
going to select 9 different names for move() function of different pawns? How confusing it is.
To make it so simple and achieve polymorphism, we will define a different move() functions for different pawns
but the name of all these functions will be the same, move(). Only thing that differs is the argument list within
the parenthesis. We will pass 'Queen' object to call move() on queen, we will pass 'King' object to call
move() on king, and so on. This way the user of the object invokes only one function move(), and will observe
different results depending on type of input. This is what we call method overloading.
Definition:
When you have more than one method with the same name but different arguments, the methods are said to
be overloaded. The arguments list within the parenthesis should be differing either by type of parameters or
the number of parameters.
Please note, the return type of the functions will not come into picture here. Meaning, if two functions have
same function name and argument list but with different return types, you can't call them as overloaded
functions because return type alone can't decide it.
Example:
class A {
}
}
Output
More on Overloading:
Method overloading is called Static polymorphism because the call to the overloaded functions will be
resolved at compile time.
These are not overloaded functions, instead they lead to ambiguity errors
Method Overriding
Concept:
Consider our very first example on Inheritance, Dog and Cat extends Animal. Here we can see the Animal
class defines the common (general) characteristics of all its subclasses, for instance sleep() method which
makes the Animal to sleep for 8 hours. Assume a situation where all the animals in our application sleep for 8
hours but only the Dog sleeps for 4 hours. How will you implement this change in sleep() function which
should reflect only in Dog class alone? Overriding is a solution for this.
Overriding is nothing but simply redefining the sleep() function again the subclass (Dog class) so that the new
definition hides the previous definition for sleep() function in parent class (Animal class).
Definition:
An instance method in a subclass with the same signature (name, plus the number and the type of its
parameters) and return type as an instance method in the superclass overrides the superclass's method.
Note that an overriding method can also return a subtype of the type returned by the overridden method. This
is called a covariant return type.
Mr. Ashok Kumar K | 9742024066 | [email protected]
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
Example:
class Animal {
// Overridden method
public void sleep() {
System.out.println("SLEEPING FOR 8 HOURS");
}
}
// Overriding method
public void sleep() {
System.out.println("DOG SLEEPING FOR 4 HOURS");
}
}
}
Output
More on Overriding:
Method overriding is called Dynamic polymorphism because a call to overridden functions is resolved
at runtime.
Method overriding occurs only when the names and the type signatures of the two methods are
identical. If they are not, then the two methods are simply overloaded.
Concept:
Here we will focus on method overriding in bit detail. We know that a base class reference can be given to a
derived class object. The simple question I am going to answer in this topic is what if we call an overridden
method on this object?
Example:
class Animal {
// Overridden method
public void sleep() {
System.out.println("SLEEPING FOR 8 HOURS");
}
}
// Overriding method
public void sleep() {
System.out.println("DOG SLEEPING FOR 4 HOURS");
}
}
}
We can conclude from the above program, it is the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be executed.
Therefore, if a superclass contains a method that is overridden by a subclass, then when different types of
objects are referred to through superclass reference variable, different versions of the method are executed.
Since this decision should be made base on the type of the object, the JVM can make this decision only at
runtime since the object will not be available at the compile time.
Definition:
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time,
rather than compile time.
Note:
If you want to invoke an overridden method (base class method) from the overriding method (derived class
method), you should use 'super' keyword as illustrated in below example.
Remember, it’s not mandatory that your class should override the base class method. It is completely dependent on your
implementation. Two questions for you at this point of time.
1. How will you enforce a restriction that a particular method in base class should never be overridden in the derived class?
2. How will you enforce a restriction that a particular method in base class should mandatorily be overridden in the derived
class?
Yes, Java provides a feature to enforce such restrictions. Following couple of topics deals with them.
You can use final keyword in java for three different uses.
'final' variables
A final variable can be only once assigned a value. This value cannot be changed latter. If final variable is used
Mr. Ashok Kumar K | 9742024066 | [email protected]
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
in a class then it must assigned a value in a class constructor. Attempting to change the value of final
variable/field will generate error.
Syntax:
final <datatype> <var_name>;
Example
class Animal {
int age = 8;
final int legs = 4; // RIGHT: final variables can be assigned a value here
final int tails;
A () {
tails = 1; // RIGHT: final variable can be assigned a value in
constructor
}
void increment() {
age = age + 10;
legs = legs + 1; // ERROR: Can't modify the final variable
tails = tails + 1; // ERROR: Can't modify the final variable
}
}
If you want to enforce a restriction like, a particular method in the base class should never be overridden in the
derived class, simply prefix that method definition with the 'final' keyword.
A final method cannot be overridden by sub class.
Example:
class Animal {
// This is a final method
final public void eat() {
System.out.println("EATING THRICE A DAY");
}
public void sleep() {
System.out.println("SLEEPING FOR 8 HOURS");
}
}
// RIGHT
public void sleep() {
System.out.println("SLEEPING FOR 4 HOURS");
}
}
Unless a class definition has been prefixed with 'final', any other class can override it. There is no restriction
on that. Java provides a feature where you can restrict a class from being inherited. This can be done by
prefixing a class definition with 'final' keyword.
A class declared final cannot be sub classed. Other classes cannot extend final class. It provides some benefit to
security and thread safety.
Example
class Animal {
}
// RIGHT
final class Dog extends Animal {
}
// WRONG: Cannot subclass the final class Dog
class DomesticDog extends Dog {
Concept
There are situations in which you will want to define a superclass 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 superclass 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 put it differently, you may encounter some situations where you need to enforce a restriction that some functions in the base class
has to mandatorily overridden by the derived class. If you want to enforce this restriction on any method in base class, simply prefix its
declaration with 'abstract' keyword. Remember, you should not give the definition for abstract functions in the base class because
mandatorily it will be defined in derived classes.
If a class contains one or more abstract methods, it's like a class containing one or more methods without any definition (just the
declaration), so it's obvious that the class is not complete until any other class inherits it and gives the definition for these methods. The
conclusion is you cannot create a direct objects of the abstract class, all you can do is having its reference to the object of the derived
class.
Definitions
Abstract method
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon) like this:
abstract void fun(int a);
Abstract class
An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be
instantiated, but they can be subclassed. If a class includes abstract methods, the class itself must be declared abstract, as in:
class A {
abstract void fun(int a);
}
Example:
// abstract class
abstract class Animal {
void sleep() {
System.out.println("Sleeping for 8 hours");
}
2.3 EXCEPTIONS
2.3.1 Basics
Concept
There's always a tendency for erroneous situations to occur either within a program or beyond it. For example consider a program
which tries to divide a number 10 by an input number entered by the user. What if the number entered by the user is 0 (zero)? The
program attempts to divide 10 by 0 (zero) which causes the application to crash. Another example for erroneous situation is when you
try to create an object and there isn't enough space in the JVM heap to allocate the memory for it. These kind of erroneous situations
are called Exceptions. Java provides a wonderful exception handling mechanism to avoid an application crash.
Definition
Generally, Exceptions are such anomalous conditions which change the normal flow of execution of a program. Exceptions are used for
signaling erroneous (exceptional) conditions which occur during the run time processing.
In Java, Exception is an object that describes an exceptional condition that has occurred in a piece of code.
Let's see with the help of below example, what happens in Java if something goes wrong in the runtime.
When an exception occurs within a method, the method creates (throws) an object to describe the exception. This object is called as
Exception Object, which contains the complete information about what went wrong here, ex: type of exception, state of program, line
number in the source where this exception occurred and so on.
After a method throws an object, it will be caught by the block of code written to handle it. If you have not handled an exception in your
program, the exception object will be caught by the runtime system and it handles it in its own way. i.e., default exception handling will
come into picture which only does two things
You can realize this in the following output to the program shown above
You can see a short description of what went wrong and then the program has been terminated. The S.O.P statement written after the
division has not been executed.
The description of the error printed in the console is called the stack trace of the exception which prints the method call hierarchy. You
can see the method call stack for the modified version of above program.
You should clearly observe the type of object that's been created is ArithmeticException. It is one of the inbuilt classes in Java used to
represent an exception caused during arithmetic operations. There are various other types of classes in Java to represent different
scenarios where an exception occurs.
Output
Exception classes
There may be various scenarios where an exception might occur. Arithmetic exception which we saw in previous topic is one among
them. For exception in Java, there is a built in class used to represent the scenario. Hence, whenever an exception occurs, JVM will
throw an object of the corresponding class which well describes the exception scenario. Below figure shows the exception class
hierarchy. You can see, Throwable is the root of all the exceptions.
Throwable, declared in java.lang, is the root of entire exception family. It has two children, Exception and Error classes.
Exception class: Object of its subclasses are created and thrown whenever unusual condition occur which can be caught
and handled it programmatically. It can be either checked exceptions or unchecked exceptions. Example:
ArithmeticException
Error class: Error class will be created and thrown when a serious problem occurs beyond the application scope which can't
be controlled within an application. Example: OutOfMemoryError will be thrown when JVM is running short of memory.
Checked Exception classes directly inherit the Exception class while Unchecked Exception inherits from a subclass of Exception
called RuntimeException.
Below table shows the complete list of all Checked Exception classes in Java
Below table shows the complete list of all Unchecked Exception classes in Java
Java provides five keywords for exception handling. They are dealt in detail in later topics. Here we will see them in brief.
try
Program statements that you need to monitor for exception will be placed inside try block. If any exception occurs within a
try block, the corresponding exception class is created and thrown.
catch
A try block should be mandatorily followed by a catch block which will be executed if the exception object is thrown from
the try block. Technically, we say that catch block catches the exception thrown by a try block.
throw
A programmer can use throw keyword to manually throw an exception.
throws
finally
If you want some piece of code to be executed without depending on whether a exception occurs or not, you can place
such piece of code inside a finally block.
Concept
Use try block to enclose the piece of code which you need to monitor for exceptions. Exceptions thrown from the try block will be caught
by the corresponding catch block. A catch block is mandatory for every try block. Remember, a single try block can have more than one
catch block.
Syntax
try {
// Piece of code which you are monitoring for exception
} catch (Exception_Class ex) {
// This block will be executed if an exception occurs in above try block
}
Example
You can observe the above examples. In the first example there is no exception being thrown from the try block, hence the catch block
will simple be skipped. In the second example there is an ArithmeticException thrown from the try block which is caught by the catch
block which is capable of catching ArtithmeticException.
Observations
Exception description can be printed in the catch block using e.getMessage() as follows.
catch (ArithmeticException e) {
System.out.println("Exception occured");
System.out.println(e.getMessage());
}
Output
catch (ArithmeticException e) {
System.out.println("Exception occured");
e.printStackTrace();
}
Output
If you are not sure about what kind of exception is thrown from a try block, you are still able to catch it using a generic
catch clause as follows, which catches any type of exception thrown.
try {
int a = 10;
int b = 0;
int res = a/b;
} catch (Exception e) {
System.out.println("Exception occured");
e.printStackTrace();
}
Output
As mentioned earlier, in the scenario where more than one type of exception will be thrown from a single try block, you
can have more than one catch blocks, one corresponding to each type of exception object thrown.
Example, below try block is capable of throwing ArithmeticException and ArrayIndexOutOfBoundsException.
Hence I have written two catch blocks one for each of these exception.
try {
int arr[] = {2,4,5,6};
arr[10] = 90;
int a = 10;
int b = 0;
int res = a/b;
System.out.println("No Exception");
} catch (ArithmeticException e) {
System.out.println("Exception occured");
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception occured");
e.printStackTrace();
}
Output
When you use multiple catch statements, it is important to remember that exception subclasses must come before any
of their super classes. This is because a catch statement that uses a superclass will catch exceptions of that type plus
any of its subclasses. Thus, a subclass would never be reached if it came after its superclass. This is called unreachable
code error in Java.
Example
try {
int arr[] = {2,4,5,6};
arr[10] = 90;
int a = 10;
int b = 0;
int res = a/b;
try {
int arr[] = {2,4,5,6};
arr[10] = 90;
int a = 10;
int b = 0;
int res = a/b;
System.out.println("No Exception");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception occured");
e.printStackTrace();
} catch (Exception e) {
System.out.println("Exception occured");
e.printStackTrace();
}
You can write a try block within another try block. This kind of try blocks is called Nested try blocks. 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 outer try statement’s catch handlers are
inspected for a match. This continues until one of the catch statements succeeds, or until the entire nested try
statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception.
Example
try {
int arr[] = { 2, 4, 5, 6 };
arr[2] = 90;
try {
int a = 10;
int b = 20;
int res = a / b;
String s = null;
System.out.println(s.length());
} catch (ArithmeticException e) {
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception occured");
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("Exception occured");
e.printStackTrace();
}
throw keyword
Concept
Regardless of who throws an exception (JVM or a programmer) it's always thrown with the throw statement. So far you have
only been catching an exception thrown by Java runtime system. It's also possible for you to throw an exception manually
using throw statement.
Example
try {
ArithmeticException e = new ArithmeticException("This is thrown
by me");
throw e;
} catch (Exception e) {
e.printStackTrace();
}
Output
Observations
Not all the objects can be thrown. Remember, only those objects which are subclasses of Throwable
can be thrown.
Example
public class Example {
public static void main(String[] args) {
try {
Example ex = new Example();
Mr. Ashok Kumar K | 9742024066 | [email protected]
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
throw ex; // ERROR: can't throw this object.
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
output
throws keyword
Concept
Exception thrown by a method can be handled either within the same method or in the caller of that method. We generally
prefer the later one since caller of the method will be given full freedom to handle the exception in its own way. In this case,
the method which throws an exception should indicate to the compiler that the exception handling is not done within it but it's
done in the caller of that method, else it will give a compilation error.
Example
Observations
Since compiler is aware of only checked exceptions, it will give a compilation error only for
unhandled checked exceptions. Therefore, only checked exceptions should be specified in the
throws clause mandatorily. However, there is no restriction like you should not specify unchecked
exceptions in the throws clause
finally keyword
Concept
The finally block always executes when the try block exits. This ensures that the finally block is executed regardless of
exception occurs or not. Putting cleanup code in a finally block is always a good practice, even when no exceptions are
anticipated. Cleanup code meaning, releasing the external resources (like SQL connection, hard disk files etc).
Example
Concept
Java provides a wonderful feature where you can create your own exception class. This is definitely required in your application where
you wish to handle certain abnormal situation in your own way.
Example, in a banking application, when a person tries to withdraw the amount even though he have lesser than the minimum balance.
Java doesn't have any built in exception class that describes this scenario. You need to define one.
Syntax:
All you want to do is create a new class to represent the custom exception and extend it either directly the Throwable class or the
Exception class or the RuntimeException class
Example:
class Account {
long accnum;
static final double minBalance = 5000;
double balance = 0;
double getBalance() {
return balance;
}
}
}
Output
You can observe the above program. class LowBalanceException extends Exception class thus it is a custom exception defined by
us and it has overridden toString() method in Throwable class to print the appropriate exception message.
Concept
It is possible to associate one exception with another exception, thus recording the exact cause for an exception. That is, one exception
causing another exception is called Exception Chaining.
These are the methods and constructors added in Throwable class to support exception chaining:
Example
class Account {
long accnum;
static final double minBalance = 5000;
double balance = 0;
double getBalance() {
return balance;
}
} catch (EMIPaymentFailedException e) {
LowBalanceException e2 = new LowBalanceException();
e.initCause(e2);
throw e;
}
}
}
}
Output
The above example is a slight modification of the previous example. I have created another custom exception and added a new method
within Account class.
You can see from the output, EMIPaymentFailedException is associated with LowBalanceException. That is, these two exceptions
are in chain.
2.3 APPLETS
2.3.1 Basics
Applet is a Java program that can be embedded into HTML pages. Java applets run on the Java enables web browsers such as Mozilla
and Internet explorer.
Applet is designed to run remotely on the client browser, so there are some restrictions on it. Applet can't access system resources on
the local computer. Applets are used to make the web site more dynamic and entertaining.
The class Applet provides the foundation for creating applets in Java. The class Applet is contained in java.applet package
1. The first are those based directly on the Applet class. These applets use the Abstract Window Toolkit (AWT) to provide the
graphic user interface.
2. The second types are those based on the Swing class JApplet.
Because JApplet inherits Applet, all the features of Applet are also available in JApplet.
Observations
Applets are not stand-alone programs. Instead, they run within either a web browser or an applet viewer.
Execution of an applet does not begin at main( ). Instead, execution of an applet is started and controlled with
an entirely different mechanism,
To use an applet, it is specified in an HTML file. One way to do this is by using the <APPLET> tag.
The applet will be executed by a Java-enabled web browser when it encounters the <APPLET> tag within the
HTML file.
The list of all methods contained within Applet class is given below along with the description.
void destroy()
Called by the browser or applet viewer to inform this applet that it is being reclaimed and that it should
destroy any resources that it has allocated.
AccessibleContext getAccessibleContext()
AppletContext getAppletContext()
Determines this applet's context, which allows the applet to query and affect the environment in which it
runs.
String getAppletInfo()
Returns the AudioClip object specified by the URL and name arguments.
URL getCodeBase()
URL getDocumentBase()
Locale getLocale()
String[][] getParameterInfo()
Returns information about the parameters that are understood by this applet.
void init()
Called by the browser or applet viewer to inform this applet that it has been loaded into the system.
Boolean isActive()
Boolean isValidateRoot()
Plays the audio clip given the URL and a specifier that is relative to it.
void resize(Dimension d)
void start()
Called by the browser or applet viewer to inform this applet that it should start its execution.
void stop()
Called by the browser or applet viewer to inform this applet that it should stop its execution.
Applets are event driven. An Applet waits until an event occurs. The AWT notifies the applet about an event by calling event handler
that has been provided by the applet. The applet takes appropriate action and then quickly return control to AWT. All swing components
descend from the AWT container class. User initiates interaction with the applet (and not the other way around)
An Applet skeleton
import java.awt.*;
import java.applet.*;
/*
<applet code="AppletSkel" width=300 height=100>
1. init ()
2. start()
3. paint()
1. stop()
2. destroy()
init()
The init() method is the first method to be called. This is where you should initialize variables. This method is called only
once during the run time of your applet.
start()
The start( ) method is called after init(). It is also called to restart an applet after it has been stopped. Whereas init() is
called once - the first time an applet is loaded, start( ) is called each time an applet’s HTML document is displayed onscreen.
So, if a user leaves a web page and comes back, the applet resumes execution at start().
paint()
The paint() method is called each time your applet’s output must be redrawn.The paint() method has one parameter of type
Graphics. This parameter will contain the graphics context, which describes the graphics environment in which the applet is
running.
stop()
The stop() method is called when a web browser leaves the HTML document containing the applet - when it goes to another
page.
destroy()
The destroy() method is called when the environment determines that your applet needs to be removed completely from
memory. At this point, you should free up any resources the applet may be using. The stop() method is always called before
destroy().
2.3.3 A simple applet that sets the foreground and background colors and outputs a string.
To output a string to an applet, use drawString( ), which is a member of the Graphics class. Typically, it is called from within either
update( ) or paint( ).
import java.awt.*;
import java.applet.*;
/*
<applet code="Sample" width=300 height=50>
</applet>
*/
public class One extends Applet {
String msg;
Output:
The repaint() method is defined by the AWT. It causes the AWT run-time system to execute a call to your applet’s update() method,
which, in its default implementation, calls paint().
1. void repaint()
2. void repaint(int left, int top, int width, int height)
3. void repaint(long maxDelay)
4. void repaint(long maxDelay, int x, int y, int width, int height)
Here,
import java.awt.*;
import java.applet.*;
/*
<applet code="SimpleBanner" width=300 height=50>
</applet>
*/
// Start thread
public void start() {
t = new Thread(this);
stopFlag = false;
t.start();
}
showStatus() function can be used to print the message in the status bar of an applet
Example:
import java.awt.*;
import java.applet.*;
/*
<applet code="StatusWindow" width=300 height=50>
</applet>
*/
public class StatusWindow extends Applet {
public void init() {
setBackground(Color.blue);
setForeground(Color.white);
}
Output:
Oracle currently recommends that the APPLET tag be used to start an applet from both an HTML document and from an applet viewer.
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
[HTML Displayed in the absence of Java]
</APPLET>
CODEBASE is an optional attribute that specifies the base URL of the applet code, which is the directory that will be searched
for the applet’s executable class file
CODE is a required attribute that gives the name of the file containing your applet’s compiled .class file.
ALT tag is an optional attribute used to specify a short text message that should be displayed if the browser recognizes the
APPLET tag but can’t currently run Java applets.
NAME is an optional attribute used to specify a name for the applet instance.
WIDTH and HEIGHT are required attributes that give the size (in pixels) of the applet display area.
The <APPLET> tag in HTML allows you to pass parameters to your applet. To retrieve a parameter, use the getParameter() method. It
returns the value of the specified parameter in the form of a String object.
Example:
import java.awt.*;
import java.applet.*;
/*
<applet code="ParamDemo" width=300 height=80>
<param name=fontName value=Courier>
<param name=fontSize value=14>
<param name=leading value=2>
<param name=accountEnabled value=true>
</applet>
*/
public class ParamDemo extends Applet {
String fontName;
int fontSize;
float leading;
boolean active;
getDocumentBase() returns the URL of the directory holding the HTML file that started the applet.
getCodeBase() returns the URL of the directory from which the applet’s class file was loaded.
Example:
import java.awt.*;
import java.applet.*;
import java.net.*;
/*
<applet code="Bases" width=300 height=50>
</applet>
*/
public class Bases extends Applet {
public void paint(Graphics g) {
String msg;
URL url = getCodeBase(); // get code base
msg = "Code base: " + url.toString();
g.drawString(msg, 10, 20);
url = getDocumentBase(); // get document base
msg = "Document base: " + url.toString();
g.drawString(msg, 10, 40);
}
}
Output:
Below example is a Java applet which continuously plays an audio clip named “anthem.wav” loaded from applets parent directory.
import java.applet.Applet;
Mr. Ashok Kumar K | 9742024066 | [email protected]
www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K.
Registration started. Contact 9742013378 or 9742024066 and lock your project at the earliest.
import java.applet.AudioClip;
import java.awt.Graphics;
AudioClip audioClip;
<html>
<head>
<title>Applet sound example</title>
</head>
<body>
</body>
</html>