Sie sind auf Seite 1von 57

VTU

7th sem B.E (CSE/ISE)

JAVA/ J2EE

Notes prepared by
Mr. Ashok Kumar K
9742024066 | celestialcluster@gmail.com
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:

Classes, Inheritance, Exceptions, Applets

Mr. Ashok Kumar K


9742024066 | celestialcluster@gmail.com

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.

15 reasons to choose VTUPROJECTS.COM for your final year project work

1. Training from the scratch


We train our students on all the languages and technologies required for developing the projects from the
scratch. No prerequisites required.
2. Line by Line code explanation
Students will be trained to such an extent where they can explain the entire project line by line code to their
respective colleges.
3. Study Materials
We provide the most efficient study material for each and every module during the project development
4. Trainers
Each faculty in AKLC will be having 6+ years of corporate Industry experience and will be a subject matter
expert in strengthening student's skillset for cracking any interviews. He will be having a thorough experience
in working on both product and service driven industries.
5. Reports and PPTs
Project report as per the university standards and the final presentation slides will be provided and each
student will be trained on the same.
6. Video manuals
Video manuals will be provided which will be useful in installing and configuring various softwares during
project development
7. Strict SDLC
Project development will be carried out as per the strict Software Development model
8. Technical Seminar topics
We help students by providing current year's IEEE papers and topics of their wish for their final semester
Technical seminars
9. Our Availability
We will be available at our centers even after the class hours to help our students in case they have any
doubts or concerns.
10. Weightage to your Resume
Our students will be adding more weightage to their resumes since they will be well trained on various
technologies which helps them crack any technical interviews
11. Skype/ Team viewer support
In case the student needs an emergency help when he/she is in their colleges, we will be helping out them
through Skype/ Team viewer screen sharing
12. Practical Understanding
Each and module in the project will be implemented and taught to the students giving practical real world
applications and their use.
13. Mock demo and presentations
Each student will have to prepare for mock demo and presentations every week so that he/she will be
confident enough to demonstrate the project in their respective colleges
14. Communication & Soft skills Training
We provide communication and soft skills training to each students to help improve their presentation and
demonstration skills.
15. Weekly monitoring
Each student will be monitored and evaluated on the status of the project work done which helps the students
to obtain thorough understanding on how the entire project will be developed

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.

2.1 CLASSES AND OBJECTS


Here, in this topic we are going to explore the classes and objects concepts which are the basic building blocks of any object oriented
programming language..

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

A class can be declared through the following 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

<class_name> obj_name = new <class_name> (<contructor arguments>);

Example

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.

Creating a class

class Student {
int regno;
String name;
double score;

public void setStudentDetails(int a, String s, double d) {


regno = a;
name = s;
score = d;
}

public void printStudentDetails() {


System.out.println("Student regno : " + regno);
System.out.println("Student name : " + name);
System.out.println("Student score : " + score + "%");
}
}

Creating an object

Student stud = new Student();

Object's members can be accessed using a dot operator as follows

stud.setStudentDetails(24, "Arun", 45.89);


stud.printStudentDetails();

Observations

 Memory allocation for an object

For understanding purpose, lets break down the object creation statement into two steps:

Step 1: Creating a variable of class type that can refer to an object

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

Step 2: Instantiation and Initialization

stud = new Student();

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 | celestialcluster@gmail.com
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.

These two steps can be visualized as follows

 Instance Variables and Class Variables

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.

 We learnt how to create an object. Then, who destroys them?


Remember, it's JVM. You don't need to worry about object destruction. It will be done through a
process called Garbage Collection (discussed later).

 Class name can be any legal Identifier.

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

Example program for Classes and Objects

// Class Definition.

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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 Student {

// Instance variable
int regno;
String name;
double score;

// Methods
public void setStudentDetails(int a, String s, double d) {
regno = a;
name = s;
score = d;
}

public void printStudentDetails() {


System.out.println("Student regno : " + regno);
System.out.println("Student name : " + name);
System.out.println("Student score : " + score + "%");
}
}

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

Data Type Default Value

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
byte 0

short 0

int 0

long 0L

float 0.0f

double 0.0d

char '\u0000'

String (or any object) null

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

Student has one constructor:

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.

Look at the below example,

class Student {
int regno;
String name;
double score;

// Three argument constructor


Student (int rno, String nm, double sc) {
....
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
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.
}

// Two argument constructor


Student (String nm, double sc) {
....
}

// Zero argument constructor


Student () {
....
}
}

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:

Student stud1 = new Student(009, "Neel", 89.56);

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:

Student stud1 = new Student( "Neel", 89.56);

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.

Student stud1 = new Student();

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

Uses of "this" keyword

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;

// Three argument constructor


Student (int rno, String nm, double sc) {
this(); // call zero argument constructor
this(nm, sc); // Call two argument constructor
....
}

// Two argument constructor


Student (String nm, double sc) {
....
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
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.
}

// Zero argument constructor


Student () {
....
}
}

 '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;

// Three argument constructor


Student(int regno, String name, double score) {
this.regno = regno;
this.name = name;
this.score = 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();
}
}

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
2.1.3 Garbage Collection

Remember, when you instantiate an object using 'new' keyword, the memory for this object will be allocated in JVM heap.

Concept and Definition:

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.

When an object becomes eligible for Garbage Collection?

An object could be eligible for Garbage Collection in any of these scenarios.


 All references of that object explicitly set to null.
 Object is created inside a block and reference goes out scope once control exit that block.
 Parent object set to null, if an object holds reference of another object and when you set container object's reference null, child
or contained object automatically becomes eligible for garbage collection.

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.

2.1.4 "finalize()" method

Concept and Definition

Every object in Java can have a finalize() method defined within it. Syntax to define a finalize() method is:

protected void finalize() {


// finalization code here
}

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.

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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 Student {

public void sayHello() {


System.out.println("Hello world ..");

}
// finalize method
protected void finalize() {
System.out.println("Inside finalize method .. ");
}

public class Example {


// Main function
public static void main(String[] args) {
Student s1 = new Student();
s1.sayHello();
}

Can you really guess the output of this program?


If you are expecting the output to be the execution of both 'sayHello()' and 'finalize()' method, then your understanding on
finalize() concept is not perfect yet.

Below is the output of the above program.

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:

public class Example {


// Main funnction
public static void main(String[] args) {
Student s1 = new Student();
s1.sayHello();
System.gc(); // Initiates Garbage Collection
}

Output:

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.

2.1.5 “static” Keyword

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.

The keyword 'static' in Java can be prefixed to any of these:

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

static String principalName;

Student(int r, String n, double s) {


regno = r;
name = n;
score = s;
}
}

In the main function, let’s create an object 'stud1',

Student.principalName = “Hemanth”;
Student stud1 = new Student(7, "Ajay", 76.45);

Memory allocation at this point, looks like,

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.

Let’s create another object 'stud2', and let’s change the principal’s name.

Student stud2 = new Student(9, "Arun", 87.24);


Student.principalName = “Chandrashekhar”;

The memory allocation now looks like,

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 | celestialcluster@gmail.com
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 method.. !! This can be called without creating an object


public static void sayHello() {
System.out.println("Hello everybody, Good Morning .. ");
}

// Non Static method.. !! This requires an object


public void printStudentDetails() {
System.out.println("Reg no .. " + regno);
System.out.println("Name .. " + name);
System.out.println("Score .. " + score);
}
}

public class Test {


// Main funnction
public static void main(String[] args) {
Student.sayHello(); // Right

Student.printStudentDetails(); // Wrong: Compiler throws an


error here

Student s1 = new Student();


s1.printStudentDetails(); // Right
}

Restrictions on static methods

 They can only call other static methods.


 They must only access static data.
 They cannot refer to 'this' or 'super' in any way.

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

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
}
public static void sayHello() {
System.out.println("Hello everybody, Good Morning .. ");
}
public void printStudentDetails() {
System.out.println("Reg no .. " + regno);
System.out.println("Name .. " + name);
System.out.println("Score .. " + score);
}
static {
sayHello();
}

public class Example {


// Main funnction
public static void main(String[] args) {
System.out.println("I am the main function");
Student stud = new Student();
}

static {
System.out.println("I am the static block in the main class");
}

Output

2.1.6 Inner Classes and Nested Classes

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.

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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

Advantages of Nested Classes

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

public void sayGoodMorning() {


System.out.println("Good Morning .. ");
}
}

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.

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

Definition and Concept

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.

class DerivedClass extends BaseClass {

Example

class Animal {
public void eat() {
System.out.println("EATING THRICE A DAY");
}
public void sleep() {
System.out.println("SLEEPING FOR 8 HOURS");
}

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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 Dog extends Animal {


public void bark() {
System.out.println("Bow Bow");
}
}

class Cat extends Animal {


public void meow() {
System.out.println("Meow Meow");
}
}

Inheritance provides code reuse

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.

Thus, we can conclude that Inheritance provides Code Reusability.

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.

 Superclass variable can reference a subclass object, but not vice-versa.

public class Example {


public static void main(String[] args) {
Animal animal = new Dog(); // RIGHT, because all Dogs are Animals
animal.eat();
animal.sleep();

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:

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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 Animal {
int num_of_legs;
String type_of_animal;

Animal (int num_of_legs, String type_of_animmal) {


this.num_of_legs = num_of_legs;
this.type_of_animal = type_of_animmal;
}
public void eat() {
System.out.println("EATING THRICE A DAY");
}
public void sleep() {
System.out.println("SLEEPING FOR 8 HOURS");
}
}

class Dog extends Animal {


String name_of_dog;

Dog (int num_of_legs, String type_of_animmal, String name_of_dog) {


super(num_of_legs,type_of_animmal ); // Invokes superclass
constructor
this.name_of_dog = name_of_dog;
}

public void bark() {


System.out.println("Bow Bow");
}
}

class Cat extends Animal {


String name_of_cat;

Cat (int num_of_legs, String type_of_animmal, String name_of_cat) {


super(num_of_legs,type_of_animmal ); // Invokes superclass
constructor
this.name_of_cat = name_of_cat;
}
public void meow() {
System.out.println("Meow Meow");
}
}

public class Test {


// Main funnction
public static void main(String[] args) {
Dog dog = new Dog(4, "Cornivorous", "Jimmy");
dog.eat();
dog.sleep();
dog.bark();
}

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

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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 B extends A {
int i;
B (int a, int b) {
this.i = a; // Refers to derived class member
super.i = b; // Refers to superclass member
}
}

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

The point of interest here is the order of execution of constructors when we


create an object of the class 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");
}
}

public class Test {


// Main funnction
public static void main(String[] args) {
D d1 = new D();
}

Output

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
We can conclude from the output that, the order of execution of constructors is in the same order as the
derivation, from superclass to subclass.
This is because super(); will be the first statement in every class' constructor: when you create an Object
of class D, the D's class constructor will be invoked which passes the call to its super class constructor
C() which further passes to B(), and eventually it passes on the call to Object() where the initialization of
the memory takes place to this program after which the constructor A() will be executed continuing till D()
in the order of derivation.

 Multiple Inheritance in Java

No, Multiple inheritance is NOT allowed in Java. Multilevel inheritance is when a class inherits from more than one
superclass. For example,

Here, Pegasus inherits from both horse and a flying bird.


This kind of inheritance given rise to many problems in C++ which can be
thought of as a reason for Java discouraging it.

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.

How multiple inheritance is achieved in Java?

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:

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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 A is a base class which has been inherited by class A along with implementing the other three interfaces
namely P, Q, and R.

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

class Hyundai extends Car implements Trainer, Student {


public void moveRight() {
System.out.println("Moving Right .. ");
}
public void moveLeft() {
System.out.println("Moving Left .. ");
}
public void accelerate() {
System.out.println("Accelerating .. ");
}
public void brake() {
System.out.println("Applying brake .. ");
}
}

public class Example


{
public static void main(String [] args)
{

Trainer trainer = new Hyundai();


trainer.moveLeft(); // RIGHT

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
trainer.moveRight(); // RIGHT
trainer.accelerate(); // RIGHT
trainer.brake(); // RIGHT

Student student = new Hyundai();


student.moveLeft(); // RIGHT
student.moveRight(); // RIGHT
student.accelerate(); // ERROR: student have no access to
accelerate()
student.brake(); // ERROR: student have no access to brake()
}
}

2.2.2 Overloading and Overriding

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 {

public void sum (int a, int b) {


System.out.println("Sum of "+a+" and "+b+" is .. "+(a+b));
}

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
public void sum(String a, String b) {
System.out.println("Concatenation of "+a+" and "+b+" is .. "+a+b);
}
}

public class Test


{
public static void main(String [] args)
{
A a1 = new A ();
a1.sum(7, 9);
a1.sum("AKLC ", "JMASTER");

}
}

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

void sum(int a) and int sum(int a)

void sum(int a, float b) and void sum (float a, int b)

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 | celestialcluster@gmail.com
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 {

public void eat() {


System.out.println("EATING THRICE A DAY");
}

// Overridden method
public void sleep() {
System.out.println("SLEEPING FOR 8 HOURS");
}
}

class Dog extends Animal {

// Overriding method
public void sleep() {
System.out.println("DOG SLEEPING FOR 4 HOURS");
}

public void bark() {


System.out.println("Bow Bow");
}
}

class Cat extends Animal {


public void meow() {
System.out.println("Meow Meow");
}
}

public class Test


{
public static void main(String [] args)
{
Dog dog = new Dog();
Cat cat = new Cat();
dog.sleep();
cat.sleep();

}
}

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.

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.

Dynamic Method Dispatch

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 {

public void eat() {


System.out.println("EATING THRICE A DAY");
}

// Overridden method
public void sleep() {
System.out.println("SLEEPING FOR 8 HOURS");
}
}

class Dog extends Animal {

// Overriding method
public void sleep() {
System.out.println("DOG SLEEPING FOR 4 HOURS");
}

public void bark() {


System.out.println("Bow Bow");
}
}

class DomesticDog extends Dog {


public void sleep() {
System.out.println("DOG SLEEPING FOR 6 HOURS");
}
}

class WildDog extends Dog {


public void sleep() {
System.out.println("DOG SLEEPING FOR 2 HOURS");
}
}

public class Example


{
public static void main(String [] args)
{
Animal animal1 = new Animal();
Animal animal2 = new Dog();
Animal animal3 = new DomesticDog();

animal1.sleep(); // calls Animal's sleep()


animal2.sleep(); // calls Dog's sleep()
animal3.sleep(); // calls DomesticDog's sleep()

}
}

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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

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.

class DomesticDog extends Dog {


public void sleep() {
super.sleep(); // calls Dog' sleep()
System.out.println("DOG SLEEPING FOR 6 HOURS");
}
}

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.

2.2.3 "final" Keyword in Java

You can use final keyword in java for three different uses.

 Variables can be made final


 Methods can be made final
 Class can be made final

'final' variables

Concept and Definition

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 | celestialcluster@gmail.com
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
}
}

'final' methods: To prevent Overriding

Concept and Definition

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

class Dog extends Animal {


// WRONG: Cannot override a final method
public void eat() {
System.out.println("EATING TWICE A DAY");
}

// RIGHT
public void sleep() {
System.out.println("SLEEPING FOR 4 HOURS");
}
}

'final' classes: To prevent Inheritance

Concept and Definition

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.

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 {

2.2.4 Abstract classes in Java

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

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class.
However, if it does not, the subclass must also be declared abstract

Example:

// abstract class
abstract class Animal {
void sleep() {
System.out.println("Sleeping for 8 hours");
}

abstract void sound(); // abstract function


}

class Dog extends Animal {


public void sound() {
System.out.println("BOW BOW");
}
}

class Cat extends Animal {


public void sound() {
System.out.println("MEOW MEOW");
}
}

public class Example


{
public static void main(String [] args)
{
Animal animal1 = new Animal(); // WRONG: Abstract class cannot be initiated
Animal animal2 = new Dog(); // RIGHT
Animal animal3 = new Cat(); // RIGHT
}
}

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.

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.

Java's default exception handling mechanism

Let's see with the help of below example, what happens in Java if something goes wrong in the runtime.

public class Test {


public static void main(String[] args) {
int a = 10;
int b = 0;
System.out.println("Before Division");
double res = a/b;
System.out.println("After Division");
}
}

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

 Print the error message in the console


 Terminate the program

You can realize this in the following output to the program shown above

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.

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.

public class Test {


public static void main(String[] args) {
System.out.println("Before Division");
fun1();
System.out.println("After Division");
}
public static void fun1() {
fun2();
}
public static void fun2 () {
fun3();
}
public static void fun3 () {
fun4();
}
public static void fun4() {
int a = 10;
int b = 0;
double res = a/b;
}
}

Output

2.3.2 Different Type of Exceptions

Generally, Exceptions can be broadly classified into Checked


Exceptions and Unchecked Exceptions

 Checked Exceptions are also called as Compile time


Exceptions which are checked by compiler to make sure the
programmer has written the handler for these. If not, it will
throw a compile time error.

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
 Unchecked Exceptions are also called as Runtime
Exceptions which are not known to the compiler at compile
time. Hence, compiler is not able to check them for the
handlers.

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

Exception class Meaning


ClassNotFoundException Class not found.

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable
interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.

Below table shows the complete list of all Unchecked Exception classes in Java

Exception class Meaning


ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
EnumConstantNotPresentException An attempt is made to use an undefined enumeration value.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked
thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread
state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
TypeNotPresentException Type not found.
UnsupportedOperationException An unsupported operation was encountered.

2.3.3 Java's Exception handling in brief

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

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
All the checked exceptions thrown out of a particular method will be specified as such using the throws clause in the
function signature.

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.

2.3.4 Using try and catch

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

public class Example {


public static void main(String[] args) { Output
try {
int a = 10;
int b = 2;
System.out.println("Before Division");
int res = a/b;
System.out.println("After Division");
} catch (ArithmeticException e) {
System.out.println("Exception occured");
}
System.out.println("Bye");
}
}
public class Example {
public static void main(String[] args) { Output
try {
int a = 10;
int b = 0;
System.out.println("Before Division");
int res = a/b;
System.out.println("After Division");
} catch (ArithmeticException e) {
System.out.println("Exception occured");
}
System.out.println("Bye");
}

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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

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

Displaying the description of the exception

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

Displaying the method call stack (stack trace) of the exception

Call stack can be printed using e.printStackTrace() as follows.

catch (ArithmeticException e) {
System.out.println("Exception occured");
e.printStackTrace();
}

Output

Catching Generic Exception

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;

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
System.out.println("No Exception");

} catch (Exception e) {
System.out.println("Exception occured");
e.printStackTrace();
}

Output

Multiple catch clauses

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

Unreachable code error

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

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.

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"); Unreachable catch block for


ArrayIndexOutOfBoundsExceptio
} catch (Exception e) { n. It is already handled by the
System.out.println("Exception occured"); catch block for Exception
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception occured");
e.printStackTrace();
}

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

Nested try catch blocks

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) {

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
System.out.println("Exception occured");
e.printStackTrace();
}
System.out.println("No Exception");

} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception occured");
e.printStackTrace();
} catch (NullPointerException e) {
System.out.println("Exception occured");
e.printStackTrace();
}

2.3.5 throw, throws, and finally

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 | celestialcluster@gmail.com
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();
}

}
}

 throw keyword will be mainly used for two purposes:


 Re-throwing an exception object from the catch block
 Throwing a custom exception (dealt later)

Example for re-throwing an exception

public class Example {


public static void main(String[] args) {
try {
fun();
}
catch (ArithmeticException e) {
System.out.println("Exception caught in main function");
}
}

private static void fun() {


try {
int a = 10;
int b = 0;
int res = a/b;
} catch (ArithmeticException e) {
System.out.println("Exception caught in sub function");
throw e;
}

}
}

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.

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
A method can indicate to the compiler that the exception handling is done in the caller of the method using throws clause in
the method declaration.

Example

public class Example {


public static void main(String[] args) {
try {
fun();
} catch (IOException e) {
e.printStackTrace();
}
}

private static void fun() throws IOException {


// This tries to open a file 'sample.txt' in the class path
PrintWriter out = new PrintWriter(new FileWriter("sample.txt"));
out.close();
}
}

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

public class Test { Output


public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int res = a/b;
System.out.println("No Exception
occured");
}
catch (Exception e) {
System.out.println("Exception
occured");
}
finally {
System.out.println("Executing
finally block");
}
}
}
public class Test { Output
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
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.
public static void main(String[] args) {
try {
int a = 10;
int b = 10;
int res = a/b;
System.out.println("No Exception
occured");
}
catch (Exception e) {
System.out.println("Exception
occured");
}
finally {
System.out.println("Executing
finally block");
}
}
}

2.3.6 Custom Exceptions

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 LowBalanceException extends Exception {


double amt;

public LowBalanceException(double amt) {


this.amt = amt;
}

public String toString() {


return "HOLD ON! LOW ON BALANCE ! YOU CAN ONLY WITHDRAW "+amt+ " AT
THIS TIME";
}

class Account {
long accnum;
static final double minBalance = 5000;
double balance = 0;

Account(long accnum, int openingBalance) {


this.accnum = accnum;
balance = openingBalance;
}

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
void deposit(double amt) {
balance = balance + amt;
}

void withdraw(double amt) throws LowBalanceException {


if ((balance - amt) < minBalance) {
LowBalanceException e = new LowBalanceException (balance -
minBalance);
throw e;
} else {
balance = balance - amt;
}
}

double getBalance() {
return balance;
}

public class Example {


public static void main(String[] args) {
try {
Account acc = new Account(1234, 9000);
System.out.println("OPENING BALANCE : " + acc.getBalance());
System.out.println("DEPOSITING 5000/-");
acc.deposit(5000);
System.out.println("NEW BALANCE: " + acc.getBalance());
System.out.println("WITHDRAWING 3000/-");
acc.withdraw(3000);
System.out.println("NEW BALANCE: " + acc.getBalance());
System.out.println("WITHDRAWING 12000/-");
acc.withdraw(12000);
} catch (LowBalanceException e) {
System.out.println(e); // Calls e.toString()
}

}
}

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.

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
2.3.7 Chained Exceptions

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:

Throwable getCause() This method returns the underlying exception


Throwable initCause(Throwable) This method associates an exception with another
exception that actually caused this exception.
Throwable(String, Throwable) This Constructor associates an exception with
another exception that actually caused this
exception. String argument is the description of
cause exception
Throwable(Throwable) This Constructor associates an exception with
another exception that actually caused this
exception.

Example

class LowBalanceException extends Exception {


public String toString() {
return "HOLD ON! LOW ON BALANCE ! ";
}
}

class EMIPaymentFailedException extends Exception {


public String toString() {
return "EMI PAYMENT FAILED DUE TO SOME REASONS.";
}
}

class Account {
long accnum;
static final double minBalance = 5000;
double balance = 0;

Account(long accnum, int openingBalance) {


this.accnum = accnum;
balance = openingBalance;
}
void deposit(double amt) {
balance = balance + amt;
}

double getBalance() {
return balance;
}

void autoEMIPayment(double amt) throws EMIPaymentFailedException {


try {
if ((balance - amt) < minBalance) {
EMIPaymentFailedException e = new
throw e;
}
else {
balance = balance - amt;

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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

} catch (EMIPaymentFailedException e) {
LowBalanceException e2 = new LowBalanceException();
e.initCause(e2);
throw e;
}
}

public class Test {


public static void main(String[] args) {
Account acc = new Account(1234, 9000);
System.out.println("OPENING BALANCE : " + acc.getBalance());
try {
acc.autoEMIPayment(2000);
System.out.println("First EMI Payment Successful");
acc.autoEMIPayment(2000);
System.out.println("Second EMI Payment Successful");
acc.autoEMIPayment(2000);
System.out.println("Third EMI Payment Successful");
} catch (EMIPaymentFailedException e) {
System.out.println("Exception during EMI payment");
System.out.println("Toplevel Exception .. "+e);
System.out.println("Cause Exception .. "+e.getCause());
}

}
}

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.

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.

2.3 APPLETS

2.3.1 Basics

Concept and Definition

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

Two types of Applet

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

 All applets are subclasses (either directly or indirectly) of Applet.

 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 Applet class

The list of all methods contained within Applet class is given below along with the description.

Return type Method name and 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()

Gets the AccessibleContext associated with this Applet.

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.

AppletContext getAppletContext()

Determines this applet's context, which allows the applet to query and affect the environment in which it
runs.

String getAppletInfo()

Returns information about this applet.

AudioClip getAudioClip(URL url)

Returns the AudioClip object specified by the URL argument.

AudioClip getAudioClip(URL url, String name)

Returns the AudioClip object specified by the URL and name arguments.

URL getCodeBase()

Gets the base URL.

URL getDocumentBase()

Gets the URL of the document in which this applet is embedded.

Image getImage(URL url)

Returns an Image object that can then be painted on the screen.

Image getImage(URL url, String name)

Returns an Image object that can then be painted on the screen.

Locale getLocale()

Gets the locale of the applet.

String getParameter(String name)

Returns the value of the named parameter in the HTML tag.

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

Determines if this applet is active.

Boolean isValidateRoot()

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
Indicates if this container is a validate root.

static AudioClip newAudioClip(URL url)

Get an audio clip from the given URL.

void play(URL url)

Plays the audio clip at the specified absolute URL.

void play(URL url, String name)

Plays the audio clip given the URL and a specifier that is relative to it.

void resize(Dimension d)

Requests that this applet be resized.

void resize(int width, int height)

Requests that this applet be resized.

void setStub(AppletStub stub)

Sets this applet's stub.

void showStatus(String msg)

Requests that the argument string be displayed in the "status window".

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.

2.3.2 Applet Architecture

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>

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
</applet>
*/

public class AppletSkel extends Applet {


// Called first.
public void init() {
// initialization
}

/* Called second, after init(). Also called whenever


the applet is restarted. */
public void start() {
// start or resume execution
}

// Called when the applet is stopped.


public void stop() {
// suspends execution
}

/* Called when applet is terminated. This is the last


method executed. */
public void destroy() {
// perform shutdown activities
}

// Called when an applet's window must be restored.


public void paint(Graphics g) {
// redisplay contents of window
}
}

When an applet begins, following methods are called in sequence.

1. init ()
2. start()
3. paint()

When an applet is terminated, following methods are called in sequence.

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

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.

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

It has the following general form:

void drawString(String message, int x, int y)

Here, message is the string to be output beginning at x,y.

import java.awt.*;
import java.applet.*;

/*
<applet code="Sample" width=300 height=50>
</applet>
*/
public class One extends Applet {
String msg;

public void init() {


setBackground(Color.blue);
setForeground(Color.white);
msg = "Inside init( ) --";
}

public void start() {


msg += " Inside start( ) --";
}

public void paint(Graphics g) {


msg += " Inside paint( ) --";
g.drawString(msg, 10, 30);
}
}

Output:

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.

2.3.4 Requesting Repainting

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

The repaint() method has four forms.

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,

left & top are the co-ordinates


height & width are the region's height and width
maxDelay specifies the maximum number of milliseconds that can elapse before update() is called.

Example: Simple Banner Applet

import java.awt.*;
import java.applet.*;

/*
<applet code="SimpleBanner" width=300 height=50>
</applet>
*/

public class SimpleBanner extends Applet implements Runnable {


String msg = " A Simple Moving Banner.";
Thread t = null;
int state;
boolean stopFlag;

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
public void init() {
setBackground(Color.blue);
setForeground(Color.white);
}

// Start thread
public void start() {
t = new Thread(this);
stopFlag = false;
t.start();
}

// Entry point for the thread that runs the banner.


public void run() {
char ch;
for (;;) {
try {
repaint();
Thread.sleep(250);
ch = msg.charAt(0);
msg = msg.substring(1, msg.length());
msg += ch;
if (stopFlag)
break;
} catch (InterruptedException e) {
}
}
}

// Pause the banner.


public void stop() {
stopFlag = true;
t = null;
}

// Display the banner.


public void paint(Graphics g) {
g.drawString(msg, 50, 30);
}
}
2.3.5 Using the status window.

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

public void paint(Graphics g) {


g.drawString("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
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.
}
}

Output:

2.3.6 The HTML <applet> Tag

Oracle currently recommends that the APPLET tag be used to start an applet from both an HTML document and from an applet viewer.

Syntax of Applet tag is given below:

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

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com


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.
 ALIGN is an optional attribute that specifies the alignment of the applet.
 VSPACE and HSPACE are optional. VSPACE specifies the space, in pixels, above and below the applet. HSPACE specifies
the space, in pixels, on each side of the applet.
 PARAM NAME and VALUE: The PARAM tag allows you to specify applet-specific arguments in an HTML page.

2.3.7 Passing parameters to Applets

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;

public void start() {


String param;
fontName = getParameter("fontName");
if (fontName == null)
fontName = "Not Found";
param = getParameter("fontSize");
try {
if (param != null)
fontSize = Integer.parseInt(param);
else
fontSize = 0;
} catch (NumberFormatException e) {
fontSize = -1;
}
param = getParameter("leading");
try {
if (param != null)
leading = Float.valueOf(param).floatValue();
else
leading = 0;
} catch (NumberFormatException e) {
leading = -1;
}
param = getParameter("accountEnabled");
if (param != null)
active = Boolean.valueOf(param).booleanValue();
}

public void paint(Graphics g) {


g.drawString("Font name: " + fontName, 0, 10);
g.drawString("Font size: " + fontSize, 0, 26);
Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com
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.
g.drawString("Leading: " + leading, 0, 42);
g.drawString("Account Active: " + active, 0, 58);
}
}

2.3.8 getDocumentBase() and getCodeBase()

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:

2.3.9 Playing Audio files using AudioClip Interface

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 | celestialcluster@gmail.com
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;

public class LoadSoundApplet extends Applet {

AudioClip audioClip;

public void init() {


audioClip = getAudioClip(getCodeBase(), "anthem.wav");
}

public void paint(Graphics g) {


audioClip.loop();
}

Necessary HTML file to run the above applet is given here:

<html>
<head>
<title>Applet sound example</title>
</head>
<body>

<applet code="LoadSoundApplet" width=100 height=50>


</applet>

</body>
</html>

Mr. Ashok Kumar K | 9742024066 | celestialcluster@gmail.com

Das könnte Ihnen auch gefallen