Unit 2,3,5
Unit 2,3,5
Method Overloading is a feature in Java that allows a class to have more than one
methods having same name, but with different signatures (Each method must have
different number of parameters or parameters having different types and orders).
Advantage:
✓ Method Overloading increases the readability of the program.
✓ Provides the flexibility to use similar method with different parameters.
In order to overload a method, the argument lists of the methods must differ in either of
these:
return min;
}
public static double minFunction(int n1, double n2)
{
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
Minimum(11,6,3) = 3
Minimum(7.3,9.4) = 7.3
Minimum(11,7.3) = 7.3
Note:-
Method overloading is not possible by changing the return type of the method
because of ambiguity that may arise while calling the method with same parameter
list with different return type.
Example:
class Add
{
static int sum(int a, int b)
{
return a+b;
}
static float sum(int a, int b)
{
return a+b;
}
public static void main(String arg[])
{
System.out.println(sum(10,20));
System.out.println(sum(15,25));
}
}
Output:
Compile by: javac TestOverloading3.java
class Overloading
{
void sum(int a, float b)
{
System.out.println(a+b);
}
void sum(int a, int b, int c)
{
System.out.println(a+b+c);
}
OUTPUT:
40.0
165.0
60
2.2: Objects as Parameters
Java is strictly pass-by-value. But the scenario may change when the parameter passed
is of primitive type or reference type.
Returning Objects:
In Java, a method can return any type of data. Return type may any primitive data type or
class type (i.e. object). As a method takes objects as parameters, it can also return objects
as return value.
Example:
class Add
{
int num1,num2,sum;
Add ob3=calculateSum(ob1,ob2);
System.out.println("Object 1 -> Sum = "+ob1.sum);
System.out.println("Object 2 -> Sum = "+ob2.sum);
System.out.println("Object 3 -> Sum = "+ob3.sum);
}
}
OUTPUT:
Definition:
Benefits:
1. Name control
2. Access control
3. Code becomes more readable and maintainable because it locally group related
classes in one place.
1) Nested class can access all the members (data members and methods) of
outer class including private.
2) Nested classes are used to develop more readable and maintainable code.
3) Code Optimization: It requires less code to write.
Type Description
Member Inner Class A class created within class and outside method.
A class created for implementing interface or
Anonymous Inner Class extending class. Its name is decided by the java
compiler.
Local Inner Class A class created within method.
Static Nested Class A static class created within class.
Nested Interface An interface created within class or interface.
1. Java Member inner class
A non-static class that is created inside a class but outside a method is called member
inner class.
Syntax:
class Outer
//code
class Inner
//code
In this example, we are creating msg() method in member inner class that is accessing
the private data member of outer class.
1. class TestMemberOuter1
2. {
3. private int data=30;
4. class Inner
5. {
6. void msg()
7. {
8. System.out.println("data is "+data);
9. }
10. }
11. public static void main(String args[])
12. {
13. TestMemberOuter1 obj=new TestMemberOuter1();
14. TestMemberOuter1.Inner in=obj.new Inner();
15. in.msg();
16. }
17. }
Output:
2. Java Anonymous inner class
A class that have no name is known as anonymous inner class in java. It should be used
if you have to override method of class or interface. Java Anonymous inner class can be
created by two ways:
1. Class (may be abstract or concrete).
2. Interface
Output:
nice fruits
1. interface Eatable
2. {
3. void eat();
4. }
5. class TestAnnonymousInner1
6. {
7. public static void main(String args[])
8. {
9. Eatable e=new Eatable()
10. {
11. public void eat(){System.out.println("nice fruits");
12. }
13. };
14. e.eat();
15. }
16. }
Output:
nice fruits
A class i.e. created inside a method is called local inner class in java. If you want to
invoke the methods of local inner class, you must instantiate this class inside the
method.
Output:
30
50
Properties:
1. Completely hidden from the outside world.
2. Cannot access the local variables of the method (in which they are defined), but the
local variables has to be declared final to access.
A static class i.e. created inside a class is called static nested class in java. It cannot
access non-static data members and methods. It can be accessed by outer class name.
o It can access static data members of outer class including private.
o Static nested class cannot access non-static (instance) data member or method.
1. class TestOuter1
2. {
3. static int data=30;
4. static class Inner
5. {
6. void msg()
7. {
8. System.out.println("data is "+data);
9. }
10. }
11. public static void main(String args[])
12. {
13. TestOuter1.Inner obj=new TestOuter1.Inner();
14. obj.msg();
15. }
16. }
Output:
data is 30
If you have the static member inside static nested class, you don't need to create
instance of static nested class.
1. class TestOuter2{
2. static int data=30;
3. static class Inner
4. {
5. static void msg()
6. {
7. System.out.println("data is "+data);
8. }
9. }
10. public static void main(String args[])
11. {
12. TestOuter2.Inner.msg();//no need to create the instance of static nested
class
13. }
14. }
Output:
data is 30
2.4: Inheritance
Definition:
Inheritance is a process of deriving a new class from existing class, also called as
“extending a class”. When an existing class is extended, the new (inherited) class has
all the properties and methods of the existing class and also possesses its own
characteristics.
✓ The class whose property is being inherited by another class is called “base class”
(or) “parent class” (or) “super class”.
✓ he class that inherits a particular property or a set of properties from the base classis
called “derived class” (or) “child class” (or) “sub class”.
Extended to
Class B
Derived
Properties and methods
of Class A + B’s own
properties and methods
✓ Subclasses of a class can define their own unique behaviors and yet share some of
the same functionality of the parent class.
➢ ADVANTAGES OF INHERITANCE:
• Reusability of Code:
✓ Inheritance is mainly used for code reusability (Code reusability means that
we can add extra features to an existing class without modifying it).
• Effort and Time Saving:
✓ The advantage of reusability saves the programmer time and effort. Since
the main code written can be reused in various situations as needed.
• Increased Reliability:
✓ The program with inheritance becomes more understandable and easily
maintainable as the sub classes are created from the existing reliably
working classes.
➢ “extends” KEYWORD:
✓ Inheriting a class means creating a new class as an extension of another class.
✓ The extends keyword is used to inherit a class from existing class.
✓ The general form of a class declaration that inherits a superclass is shown here:
✓ Syntax:
[access_specifier] class subclass_name extends superclass_name
{
// body of class
}
In the above example, Vehicle is the super class or base class that holds the
common property of Car and Bike. Car and Bike is the sub class or derived class that
inherits the property of class Vehicle extends is the keyword used to inherit a class.
➢ TYPES OF INHERITACE:
1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance
Note: The following inheritance types are not directly supported in Java.
4. Hierarchical Inheritance
5. Hybrid Inheritance
1. SINGLE INHERITANCE
The process of creating only one subclass from only one super class is known as Single
Inheritance.
✓ Only two classes are involved in this inheritance.
✓ The subclass can access all the members of super class.
1. class Animal
2. {
3. void eat()
4. {
5. System.out.println("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void bark()
11. {
12. System.out.println("barking...");
13. }
14.}
15.class TestInheritance
16.{
17. public static void main(String args[])
18. {
19. Dog d=new Dog();
20. d.bark();
21. d.eat();
22. }
23.}
Output:
$java TestInheritance
barking...
eating...
2. MULTILEVEL INHERITANCE:
✓ The process of creating a new sub class from an already inherited sub class is
known as Multilevel Inheritance.
✓ Multiple classes are involved in inheritance, but one class extends only one.
✓ The lowermost subclass can make use of all its super classes' members.
✓ Multilevel inheritance is an indirect way of implementing multiple inheritance.
✓ Example: Animal → Dog → BabyDog
1. class Animal
2. {
3. void eat()
4. {
5. System.out.println("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void bark()
11. {
12. System.out.println("barking...");
13. }
14. }
15. class BabyDog extends Dog
16. {
17. void weep()
18. {
19. System.out.println("weeping...");
20. }
21. }
22. class TestInheritance2
23. {
24. public static void main(String args[]) {
25. BabyDog d=new BabyDog();
26. d.weep();
27. d.bark();
28. d.eat();
29. }
30. }
Output:
$java TestInheritance2
weeping...
barking...
eating..
3. HIERARCHICAL INHERITANCE
✓ The process of creating more than one sub classes from one super class is called
Hierarchical Inheritance.
Animal
Dog Cat
✓ Example:
1. class Animal
2. {
3. void eat()
4. {
5. System.out.println("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void bark()
11. {
12. System.out.println("barking...");
13. }
14. }
15. class Cat extends Animal
16. {
17. void meow()
18. {
19. System.out.println("meowing...");
20. }
21. }
22. class TestInheritance3
23. {
24. public static void main(String args[])
25. {
26. Cat c=new Cat();
27. c.meow();
28. c.eat();
29. //c.bark();//C.T.Error
30. }
31. }
Output:
meowing...
eating...
The private members of a class cannot be directly accessed outside the class. Only
methods of that class can access the private members directly. However, sometimes it
may be necessary for a subclass to access a private member of a superclass. If you make
a private member public, then anyone can access that member. So, if a member of a
superclass needs to be (directly) accessed in a subclass then you must declare that
member protected.
Following program illustrates how the methods of a subclass can directly access a
protected member of the superclass.
Consider two kinds of shapes: rectangles and triangles. These two shapes have certain
common properties height and a width (or base).
This could be represented in the world of classes with a class Shapes from which we
would derive the two other ones : Rectangle and Triangle
Program : (Shape.java)
Program : (Rectangle.java)
Program : (Triangle.java)
Program : (TestProgram.java)
Output :
Area of rectangle : 20.0
Area of triangle : 25.0
In Java, constructor of base class with no argument gets automatically called in derived
class constructor.
Example:
class A
{
A()
{ System.out.println(“ Inside A’s Constructor”); }
}
class B extends A
{
B()
{ System.out.println(“ Inside B’s Constructor”); }
}
class C extends B
{
C()
{ System.out.println(“ Inside C’s Constructor”); }
}
class CallingCons
{
public static void main(String args[])
{
C objC=new C();
}
}
Output:
After compiler inserts the super constructor, the sub class constructor looks like the
following:
B()
{
super();
System.out.println("Inside B’s Constructor");
}
C()
{
super();
System.out.println("Inside C’s Constructor");
}
✓ Super is a special keyword that directs the compiler to invoke the superclass
members. It is used to refer to the parent class of the class in which the keyword is
used.
✓ super keyword is used for the following three purposes:
1. To invoke superclass constructor.
2. To invoke superclass members variables.
3. To invoke superclass methods.
Example:
class A // super class
{
int i;
A(String str) //superclass constructor
{
System.out.println(" Welcome to "+str);
}
void show() //superclass method
{
System.out.println(" Thank You!");
}
}
class B extends A
{
int i; // hides the superclass variable 'i'.
B(int a, int b) // subclass constructor
{
super("Java Programming"); // invoking superclass constructor
super.i=a; //accessing superclass member variable
i=b;
}
// Mehtod overriding
@Override
void show()
{
System.out.println(" i in superclass : "+super.i);
System.out.println(" i in subclass : "+i);
super.show(); // invoking superclass method
}
}
public class UseSuper {
public static void main(String[] args) {
B objB=new B(1,2); // subclass object construction
objB.show(); // call to subclass method show()
}
}
Output:
Welcome to Java Programming
i in superclass : 1
i in subclass : 2
Thank You!
Program Explanation:
In the above program, we have created the base class named A that contains a instance
variable ‘i’ and a method show(). Class A contains a parameterized constructor that
receives string as a parameter and prints that string. Class B is a subclass of A which
contains a instance variable ‘i’ ( hides the superclass variable ‘i’) and overrides the
superclass method show(). The subclass defines the constructor with two parameters a
and b. The subclass constructor invokes the superclass constructor super(String) by
passing the string “Java Programming” and assigns the value a to the superclass
variable(super.i=a) and b to the subclass variable. The show() method of subclassprints
the values of ‘i’ form both superclass and subclass & invokes the superclassmethod as
super.show().
In the main class, object for subclass B is created and the object is used to invoke
show() method of subclass.
✓ When a method in a subclass has the same name and type signature as a method in
its superclass, then the method in subclass is said to override a method in the
superclass.
Example:
class Bank
{
int getRateOfInterest()// super class method
{
return 0;
}
}
class Axis extends Bank// subclass of bank
{
int getRateOfInterest()// overriding the superclass method
{
return 6;
}
}
class ICICI extends Bank// subclass of Bank
{
int getRateOfInterest()// overriding the superclass method
{
return 15;
}
}
// Mainclass
class BankTest
{
public static void main(String[] a)
{
Axis a=new Axis();
ICICI i=new ICICI();
// following method call invokes the overridden method of subclass AXIS
System.out.println(“AXIS: Rate of Interest = “+a.getRateOfInterest());
Output:
Z:\> java BankTest
AXIS: Rate of Interest = 6
ICICI: Rate of Interest = 15
class A {
void callme() {
System.out.println(“Inside A’s callme method”);
}
}
class B extends A {
//override callme()
void callme() {
System.out.println(“Inside B’s callme method”);
}}
class C extends A
{
//override callme()
void callme() {
System.out.println(“Inside C’s callme method”);
}
}
class Dispatch
{
public static void main(String args[])
{
A a=new A(); //object of type A
B b=new B(); //object of type B
C c=new C(); //object of type C
A r;// obtain a reference of type A
In Method Overloading,
In Method Overriding, sub
Methods of the same class
class have the same method
shares the same name but each
with same name and exactly
Definition method must have different
the same number and type of
number of parameters or
parameters and same return
parameters having different
type as a super class.
types and order.
Method Overloading means Method Overriding means
more than one method shares method of base class is re-
Meaning
the same name in the class but defined in the derived class
having different signature. having same signature.
Method Overloading is to “add” Method Overriding is to
Behavior or “extend” more to method’s “Change” existing behavior of
behavior. method.
✓ For example sending sms, you just type the text and send the message. You don't
know the internal processing about the message delivery.
✓ Abstraction lets you focus on what the object does instead of how it does it.
➢ Abstract Classes:
Example:
abstract class GraphicObject {
int x, y;
...
void moveTo(int newX, int newY) {
...
}
abstract void draw();
abstract void resize();
}
➢ Abstract Methods:
Write a Java program to create an abstract class named Shape that contains 2
integers and an empty method named PrintArea(). Provide 3 classes named
Rectangle, Triangle and Circle such that each one of the classes extends the
class Shape. Each one of the classes contain only the method PrintArea() that
prints the area of the given shape.
1. Final Variable:
Any variable either member variable or local variable (declared inside method or
block) modified by final keyword is called final variable.
✓ The final variables are equivalent to const qualifier in C++ and #define directive
in C.
✓ Syntax:
✓ final data_type variable_name = value;
✓ Example:
final int MAXMARKS=100;
final int PI=3.14;
There is a final variable speedlimit, we are going to change the value of this
variable, but It can't be changed because final variable once assigned a value can never be
changed.
1. class Bike
2. {
3. final int speedlimit=90;//final variable
4. void run( )
5. {
6. speedlimit=400;
7. }
8. public static void main(String args[])
9. {
10. Bike obj=new Bike();
11. obj.run();
12. }
13.}
Output: Compile Time Error
NOTE: Final variables are by default read-only.
2. Final Methods:
✓ Final keyword in java can also be applied to methods.
✓ A java method with final keyword is called final method and it cannot be
overridden in sub-class.
✓ If a method is defined with final keyword, it cannot be overridden in the
subclass and its behaviour should remain constant in sub-classes.
✓ Syntax:
final return_type function_name(parameter_list)
{
// method body
}
✓ Example of final method in Java:
1. class Bike
2. {
3. final void run()
4. {
5. System.out.println("running");
6. }
7. }
8. class Honda extends Bike
9. {
10. void run()
11. {
12. System.out.println("running safely with 100kmph");
13. }
14. public static void main(String args[])
15. {
Honda honda= new Honda();
honda.run();
18. }
19.}
Output:
D:\>javac Honda.java
Honda.java:9: error: run() in Honda cannot override run() in Bike
void run()
3. Final Classes:
✓ Java class with final modifier is called final class in Java and they cannot
be sub-classed or inherited.
✓ Syntax:
final class class_name
{
// body of the class
}
✓ Several classes in Java are final e.g. String, Integer and other wrapper classes.
✓ Example of final class in java:
1. final class Bike
2. {
3. }
4. class Honda1 extends Bike
5. {
6. void run()
7. {
8. System.out.println("running safely with 100kmph");
9. }
10. public static void main(String args[])
11. {
12. Honda1 honda= new Honda1();
13. honda.run();
14. }
15. }
Output:
D:\>javac Honda.java
Honda.java:4: error: cannot inherit from final Bike class Honda extends Bike
^
1 error
Points to Remember:
Advantage of Package:
• Package is used to categorize the classes and interfaces so that they can be easily
maintained.
• Package provides access protection.
• Package removes naming collision.
• To bundle classes and interface
• The classes of one package are isolated from the classes of another package
• Provides reusability of code
• We can create our own package or extend already available package
2.10.1 : CREATING USER DEFINED PACKAGES:
Java package created by user to categorize their project's classes and interface
are known as user-defined packages.
✓ When creating a package, you should choose a name for the package.
✓ Put a package statement with that name at the top of every source file that
contains the classes and interfaces.
✓ The package statement should be the first line in the source file.
✓ There can be only one package statement in each source file
✓ Syntax:
package package_name.[sub_package_name];
public class classname
{ ……..
……..
}
✓ Example:
package pack;
public class class1 {
public static void greet()
{ System.out.println(“Hello”); }
}
• The import keyword is used to make the classes and interface of another package
accessible to the current package.
Syntax:
import package1[.package2][.package3].classname or *;
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
✓ Using packagename.*
• If you use package.* then all the classes and interfaces of this package will be
accessible but not subpackages.
✓ Using packagename.classname
• If you import package.classname then only declared class of this package will be
accessible.
package pack;
public class greeting{
public static void greet()
{ System.out.println(“Hello! Good Morning!”); }
}
package Factorial;
public class FactorialClass
{
public int fact(int a)
{
if(a==1)
return 1;
else
return a*fact(a-1);
}
}
Output:
F:\>java ImportClass
Enter a Number:
5
Hello! Good Morning!
Factorial of 5 = 120
Power(5,2) = 25.0
Access level modifiers determine whether other classes can use a particular field or
invoke a particular method.
There are two levels of access control:
➢ At the top level— public, or package-private (no explicit modifier).
➢ At the member level—public, private, protected, or package-private (no
explicit modifier).
The following table shows the access to members permitted by each modifier.
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
The following figure shows the four classes in this example and how they are related.
Figure: Classes and Packages of the Example Used to Illustrate Access Levels
The following table shows where the members of the Alpha class are visible for each of
the access modifiers that can be applied to them.
Visibility
Modifier Alpha Beta Alphasub Gamma
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
Example:
Z:\MyPack\FirstClass.java
package MyPack;
Z:\MyPack2\SecondClass.java
package MyPack2;
import MyPack.FirstClass;
class SecondClass extends FirstClass {
void method()
{
System.out.println(i); // No Error: Will print "I am public variable".
System.out.println(j); // No Error: Will print “I am protected variable”.
System.out.println(k); // Error: k has private access in FirstClass
System.out.println(r); // Error: r is not public in FirstClass; cannot be accessed
// from outside package
}
public static void main(String arg[])
{
SecondClass obj=new SecondClass();
obj.method();
}
}
Output:
I am public variable
I am protected variable
2.11: INTERFACES
Definition:
An interface is a collection of method definitions (without implementations)
and constant values. It is a blueprint of a class. It has static constants and abstract
methods.
➢ Defining Interfaces:
An interface is defined much like a class. The keyword “interface” is used to
define an interface.
Where,
Access_specifer : either public or none.
Name: name of an interface can be any valid java identifier.
Variables: They are implicitly public, final and static, meaning that they cannot be
changed by the implementing class. They must be initialized with a constant
value.
Methods: They are implicitly public and abstract, meaning that they must be declared
without body and defined only by the implementing class.
As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.
✓ Once an interface has been defined, one or more classes can implement that
interface.
✓ A class uses the implements keyword to implement an interface.
✓ The implements keyword appears in the class declaration following the extends
portion of the declaration.
✓ Syntax:
[access_specifier] class class_name [extends superclassName] implements
interface_name1, interface_name2…
{
//implementation code and code for the method of the interface
}
Rules:
1. If a class implements an interface, then it must provide implementation for all the
methods defined within that interface.
2. A class can implement more than one interfaces by separating the interface
names with comma(,).
3. A class can extend only one class, but implement many interfaces.
4. An interface can extend another interface, similarly to the way that a class can
extend another class.
5. If a class does not perform all the behaviors of the interface, the class must
declare itself as abstract.
✓ Example:
/* File name : Super.java */
interface Super
{
final int x=10;
void print();
}
/* File name : Sub.java */
class Sub implements Super
{
int y=20;
x=100 //ERROR; cannot change modify the value of final variable
Member variables:
• Can be only public and are by default.
• By default are static and always static
• By default are final and always final
Methods:
• Can be only public and are by default.
• Cannot be static
• Cannot be Final
➢ Properties of Interfaces:
1. Interfaces are not classes. So the user can never use the new operator to
instantiate an interface.
Example: interface super {}
X=new Super() // ERROR
2. The interface variables can be declared, even though the interface objects
can’t be constructed.
Super x; // OK
3. An interface variable must refer to an object of a class that implements the
interface.
4. The instanceOf() method can be used to check if an object implements an
interface.
5. A class can extend only one class, but implement many interfaces.
6. An interface can extend another interface, similarly to the way that a class
can extend another class.
7. All the methods in the interface are public and abstract.
8. All the variable in the interface are public, static and final.
➢ Extending Interfaces:
✓ An interface can extend another interface, similarly to the way that a class can
extend another class.
✓ The extends keyword is used to extend an interface, and the child interface
inherits the methods of the parent interface.
✓ Syntax:
[accessspecifier] interface InterfaceName extends interface1, interface2,…..
{
Code for interface
}
Rule: When a class implements an interface that inherits another interface it must
provide implementation for all the methods defined within the interface inheritance
chain.
Example:
interface A
{
void method1();
}
/* One interface can extend another interface. B now has two abstract methods */
interface B extends A
{
void method2();
}
// This class must implement all the methods of A and B
Output:
F:\> java MyClass
--Method from Interface: A—
--Method from Interface: B—
--Method of the class: MyClass--
➢ Difference between Class and Interface:
Class Interface
The class is denoted by a keyword class The interface is denoted by a keyword
interface
The class contains data members and The interfaces may contain data members
methods. but the methods are defined in and methods but the methods are not
the class implementation. thus class defined. the interface serves as an outline
contains an executable code for the class
By creating an instance of a class the class you cannot create an instance of an
members can be accessed interface
The class can use various access specifiers The interface makes use of only public
like public, private or protected access specifier
The members of a class can be constant or The members of interfaces are always
final declared as final
1. interface Bank
2. {
3. float rateOfInterest();
4. }
5. class SBI implements Bank
6. {
7. public float rateOfInterest()
8. {
9. return 9.15f;
10. }
11. }
12. class PNB implements Bank
13. {
14. public float rateOfInterest()
15. {
16. return 9.7f;
17. }
18. }
19. class TestInterface2
20. {
21. public static void main(String[] args)
22. {
23. Bank b=new SBI();
24. System.out.println("ROI: "+b.rateOfInterest());
25. }
26. }
Output:
ROI: 9.15
DOWNLOADED FROM STUCOR APP Department of CSE
CS3391 - Object Oriented Programming
Chapter
Topic Page No.
No.
Types of Exceptions 13
3.5.1 : Built-in Exceptions
3.5 A. Checked Exceptions 14
B. Unchecked Exceptions
3.5.2: User-Defined Exceptions (Custom Exceptions) 18
3.6 Multithreaded Programming 21
3.7 Thread Model 23
3.8 Creating Threads 27
3.9 Thread Priority 31
3.10 Thread Synchronization 33
3.11 Inter-Thread Communication 38
3.12 Suspending, Resuming and Stopping Threads 41
3.13 Wrappers 44
3.14 Autoboxing 47
DOWNLOADED FROM STUCOR APP Department of CSE
UNIT- 3 EXCEPTION HANDLING AND MULTITHREADING
Exception Handling basics - Multiple catch Clauses- Nested try Statements - Java’s built-in
exceptions, User defined exception, Multithreaded Programming: Java Thread Model,
Creating a thread and multiple threads- Priorities- Synchronization- Inter-Thread
communication-Suspending-Resuming and Stopping Threads- Multithreading. Wrappers-
Auto boxing.
Definition:
An Exception is an event that occurs during program execution which disrupts the normal
flow of a program. It is an object which is thrown at runtime.
Occurrence of any kind of exception in java applications may result in an abrupt
termination of the JVM or simply the JVM crashes.
In Java, an exception is an object that contains:
o Information about the error including its type
o The state of the program when the error occurred
o Optionally, other custom information
Exceptions: Exceptions represents errors in the Java application program, written by the
user. Because the error is in the program, exceptions are expected to be handled, either
• Try to recover it if possible
• Minimally, enact a safe and informative shutdown.
Sometimes it also happens that the exception could not be caught and the program may
get terminated. Eg. ArithmeticException
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM has
run out of memory.
Some of these exceptions are caused by user error, others by programmer error, and
others by physical resources that have failed in some manner.
Errors: Errors represent internal errors of the Java run-time system which could not be
handled easily. Eg. OutOfMemoryError.
➢ try Block:
✓ The java code that might throw an exception is enclosed in try block. It must be used
within the method and must be followed by either catch or finally block.
DOWNLOADED FROM STUCOR APP Department of CSE
✓ If an exception is generated within the try block, the remaining statements in the try
block are not executed.
➢ catch Block:
✓ Exceptions thrown during execution of the try block can be caught and handled in a
catch block.
✓ On exit from a catch block, normal execution continues and the finally block is
executed.
➢ finally Block:
A finally block is always executed, regardless of the cause of exit from the try block, or
whether any catch block was executed.
✓ Generally finally block is used for freeing resources, cleaning up, closing
connections etc.
✓ Even though there is any exception in the try block, the statements assured by
finally block are sure to execute.
✓ Rule:
• For each try block there can be zero or more catch blocks, but only one
finally block.
• The finally block will not be executed if program exits(either by calling
System.exit() or by causing a fatal error that causes the process to abort).
try {
// Code block
}
catch (ExceptionType1 e1) {
// Handle ExceptionType1 exceptions
}
catch (ExceptionType2 e2) {
// Handle ExceptionType2 exceptions
}
// ...
finally {
// Code always executed after the
// try and any catch block
}
DOWNLOADED FROM STUCOR APP Department of CSE
Rules for try, catch and finally Blocks:
1) Statements that might generate an exception are placed in a try block.
2) Not all statements in the try block will execute; the execution is interrupted if an
exception occurs
3) For each try block there can be zero or more catch blocks, but only one finally
block.
4) The try block is followed by
i. one or more catch blocks
ii. or, if a try block has no catch block, then it must have the finally block
5) A try block must be followed by either at least one catch block or one finally block.
6) A catch block specifies the type of exception it can catch. It contains the code
known as exception handler
7) The catch blocks and finally block must always appear in conjunction with a try
block.
8) The order of exception handlers in the catch block must be from the most specific
exception
Output:
Program Explanation:
The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following tasks:
• Prints out exception description.
• Prints the stack trace (Hierarchy of methods where the exception occurred).
• Causes the program to terminate.
DOWNLOADED FROM STUCOR APP Department of CSE
Example:
public class Demo
{
public static void main(String args[])
{
try {
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
java.lang.ArithmeticException: / by zero
finally block is always executed
rest of the code...
DOWNLOADED FROM STUCOR APP Department of CSE
Multiple catch is used to handle many different kind of exceptions that may be generated
while running the program. i.e more than one catch clause in a single try block can be used.
Rules:
• At a time only one Exception can occur and at a time only one catch block is executed.
• All catch blocks must be ordered from most specific to most general i.e. catch for
ArithmeticException must come before catch for Exception.
Syntax:
try {
// Code block
}
catch (ExceptionType1 e1) {
// Handle ExceptionType1 exceptions
}
catch (ExceptionType2 e2) {
// Handle ExceptionType2 exceptions
}
DOWNLOADED FROM STUCOR APP Department of CSE
Example:
try
{
int a[]= {1,5,10,15,16};
System.out.println("a[1] = "+a[1]);
System.out.println("a[2]/a[3] = "+a[2]/a[3]);
System.out.println("a[5] = "+a[5]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
DOWNLOADED FROM STUCOR APP Department of CSE
System.out.println("rest of the code");
}
}
Output:
a[1] = 5
a[2]/a[3] = 0
ArrayIndexOutOfBounds Exception occurs
rest of the code
Definition: try block within a try block is known as nested try block.
Before catching an exception, it is must to throw an exception first. This means that
there should be a code somewhere in the program that could catch exception thrown in
the try block.
An exception can be thrown explicitly
1. Using the throw statement
2. Using the throws statement
The Exception reference must be of type Throwable class or one of its subclasses. A detail
message can be passed to the constructor when the exception object is created.
Example:
Output:
In this example, we have created the validate method that takes integer value as a
parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise
print a message welcome to vote.
Example:
1. import java.util.Scanner;
2. public class ThrowsDemo
3. {
4. static void divide(int num, int din) throws ArithmeticException
5. {
6. int result=num/din;
7. System.out.println("Result : "+result);
8. }
9. public static void main(String args[])
10. {
11. int n,d;
12. Scanner in=new Scanner(System.in);
13. System.out.println("Enter the Numerator : ");
14. n=in.nextInt();
15. System.out.println("Enter the Denominator : ");
16. d=in.nextInt();
17. try
18. {
19. divide(n,d);
20. }
21. catch(Exception e)
22. {
23. System.out.println(" Can't Handle : divide by zero ERROR");
24. }
25. System.out.println(" ** Continue with rest of the code ** ");
26. }
27. }
Output:
13
DOWNLOADED FROM STUCOR APP Department of CSE
Built-in exceptions are the exceptions which are available in Java libraries. These
exceptions are suitable to explain certain error situations. Below is the list of important
built-in exceptions in Java.
A. Checked Exceptions:
✓ Checked exceptions are called compile-time exceptions because these exceptions are
checked at compile-time by the compiler.
✓ Checked Exceptions forces programmers to deal with the exception that may be thrown.
✓ The compiler ensures whether the programmer handles the exception using try.. catch ()
block or not. The programmer should have to handle the exception; otherwise, compilation
will fail and error will be thrown.
DOWNLOADED FROM STUCOR APP Department of CSE
Example:
1. ClassNotFoundException 5. NoSuchFileException
2. CloneNotSupportedException 6. NoSuchMethodException
3. IllegalAccessException, 7. IOException
4. MalformedURLException.
Output:
To make program able to compile, you must handle this error situation in try-catch block.
Below given code will compile absolutely fine.
With try-catch
import java.io.*;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
@SuppressWarnings("resource")
FileReader file = new FileReader("src/somefile.java");
System.out.println(file.toString());
}
catch(FileNotFoundException e){
System.out.println("Sorry...Requested resource not availabe...");
} }
}
Output:
Sorry...Requested resource not availabe...
DOWNLOADED FROM STUCOR APP Department of CSE
B. Unchecked Exceptions(RunTimeException):
Example:
1. ArrayIndexOutOfBoundsException
2. ArithmeticException
3. NullPointerException.
class Main {
public static void main(String args[]) {
int x = 0;
int y = 10;
int z = y/x;
}
}
Output:
Output:
NullPointerException..
Output:
The following program illustrates how user-defined exceptions can be created and
thrown.
if(rem==0)
{
System.out.println(arr[i]+" is an Even Number");
}
else
{
EvenNoException exp=new EvenNoException(arr[i]+" is
not an Even Number");
throw exp;
}
}
catch(EvenNoException exp)
{
System.out.println("Exception thrown is "+exp);
}
} // for loop
} // main()
} // class
Output:
0 is an Even Number
Exception thrown is EvenNoException: 3 is not an Even Number
4 is an Even Number
Exception thrown is EvenNoException: 5 is not an Even Number
Program Explanation:
In the above program, the EvenNumberException class is created which inherits the
Exception super class. Then the constructor is defined with the call to the super class
constructor. Next, an array arr is created with four integer values. In the main(), the array
elements are checked one by one for even number. If the number is odd, then the object of
EvenNumberException class is created and thrown using throw clause. The
EvenNumberException is handled in the catch block.
20
Basis for
final finally finalize
comparison
3.6.2 : MULTITHREADING
A program can be divided into a number of small processes. Each small process can be
addressed as a single thread.
Definition: Multithreading
Multithreading is a technique of executing more than one thread, performing different
tasks, simultaneously.
Multithreading enables programs to have more than one execution paths which
executes concurrently. Each such execution path is a thread. For example, one thread
is writing content on a file at the same time another thread is performing spelling check.
MULTITASKING
Definition: Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to maximize the utilization of CPU.
Unit 3
23
Multitasking can be achieved in two ways:
1) Process-based Multitasking (Multiprocessing):-
❖ It is a feature of executing two or more programs concurrently.
❖ For example, process-based multitasking enables you to run the Java compiler at
the same time that you are using a text editor or visiting a web site.
Different states, a thread (or applet/servlet) travels from its object creation to
object removal (garbage collection) is known as life cycle of thread. A thread goes
through various stages in its life cycle. At any time, a thread always exists in any one of
the following state:
24
1. New State
2. Runnable State
3. Running State
4. Waiting/Timed Waiting/Blocked state
5. Terminated State/ dead state
1. New State:
A new thread begins its life cycle in the new state. It remains in this state until the
program starts
the thread by calling start() method, which places the thread in the runnable state.
✓ A new thread is also referred to as a born thread.
✓ When the thread is in this state, only start() and stop() methods can be called.
Calling any other methods causes an IllegalThreadStateException.
✓ Sample Code: Thread myThread=new Thread();
2. Runnable State:
After a newly born thread is started, the thread becomes runnable or running by
calling the run() method.
✓ A thread in this state is considered to be executing its task.
✓ Sample code: myThread.start();
✓ The start() method creates the system resources necessary to run the thread,
schedules the thread to run and calls the thread’s run() method.
3. Running state:
✓ Thread scheduler selects thread to go from runnable to running state. In running
state Thread starts executing by entering run() method.
25
✓ Thread scheduler selects thread from the runnable pool on basis of priority, if
priority of two threads is same, threads are scheduled in unpredictable manner.
Thread scheduler behaviour is completely unpredictable.
✓ When threads are in running state, yield() method can make thread to go in
Runnable state.
❖ Timed Waiting:
A runnable thread can enter the timed waiting state for a specified interval of time
by calling the sleep() method.
✓ After the interval gets over, the thread in waiting state enters into the runnable
state.
✓ Sample Code:
try {
Thread.sleep(3*60*1000);// thread sleeps for 3 minutes
}
catch(InterruptedException ex) { }
❖ Blocked State:
When a particular thread issues an I/O request, then operating system moves the
thread to
blocked state until the I/O operations gets completed.
✓ This can be achieved by calling suspend() method.
✓ After the I/O completion, the thread is sent back to the runnable state.
5. Terminated State:
A runnable thread enters the terminated state when,
(i) It completes its task (when the run() method has finished)
public void run() { }
(ii) Terminates ( when the stop() is invoked) – myThread.stop();
26
New : A thread begins its life cycle in the new state. It remains in this state until the
start() method is called on it.
Runnable : After invocation of start() method on new thread, the thread becomes
runnable.
Running : A thread is in running state if the thread scheduler has selected it.
Waiting : A thread is in waiting state if it waits for another thread to perform a task.
In this stage the thread is still alive.
Terminated : A thread enter the terminated state when it complete its task.
The “main” thread is a thread that begins running immediately when a java
program starts up. The “main” thread is important for two reasons:
1. It is the thread form which other child threads will be spawned.
2. It must be the last thread to finish execution because it performs various shutdown
actions.
✓ Although the main thread is created automatically when our program is started, it
can be controlled through a Thread object.
✓ To do so, we must obtain a reference to it by calling the method currentThread().
Example:
class CurrentThreadDemo {
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println(“Current Thread: “+t);
try {
for(int n=5;n>0;n--) {
System.out.println(n);
Thread.sleep(1000);// delay for 1 second
}
27
} catch(InterruptedException e) {
System.out.println(“Main Thread Interrrupted”);
}
}
}
Output:
Current Thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]
5
4
3
2
1
28
We can create threads by instantiating an object of type Thread. Java defines two ways
to create threads:
• Example:
class MyThread implements Runnable
{
}
}
}
}
public class RunnableDemo {
public static void main(String[] args)
{
MyThread obj=new MyThread();
MyThread obj1=new MyThread();
Thread t=new Thread(obj,"Thread-1");
t.start();
Thread t1=new Thread(obj1,"Thread-2");
t1.start();
}
}
Output:
Thread-0 # Printing 0
Thread-1 # Printing 0
Thread-1 # Printing 1
Thread-0 # Printing 1
Thread-1 # Printing 2
Thread-0 # Printing 2
Thread-0 # Printing 0
Thread-1 # Printing 0
Thread-1 # Printing 1
Thread-0 # Printing 1
Thread-0 # Printing 2
Thread-1 # Printing 2
✓ Every thread in java has some priority, it may be default priority generated by
JVM or customized priority provided by programmer.
✓ Priorities are represented by a number between 1 and 10.
1 – Minimum Priority5 – Normal Priority 10 – Maximum Priority
✓ Thread scheduler will use priorities while allocating processor. The thread which
is having highest priority will get the chance first.
✓ Thread scheduler is a part of Java Virtual Machine (JVM). It decides which thread
should execute first among two or more threads that are waiting for execution.
✓ It is decided based on the priorities that are assigned to threads. The thread having
highest priority gets a chance first to execute.
✓ If two or more threads have same priorities, we can’t predict the execution of
waiting threads. It is completely decided by thread scheduler. It depends on the
type of algorithm used by thread scheduler.
✓ Higher priority threads get more CPU time than lower priority threads.
✓ A higher priority thread can also preempt a lower priority thread. For instance,
when a lower priority thread is running and a higher priority thread resumes (for
sleeping or waiting on I/O), it will preempt the lower priority thread.
✓ If two or more threads have same priorities, we can’t predict the execution of
waiting threads. It is completely decided by thread scheduler. It depends on the
type of algorithm used by thread scheduler.
✓ 3 constants defined in Thread class:
1.public static int MIN_PRIORITY
2.public static int NORM_PRIORITY
3.public static int MAX_PRIORITY
✓ Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is
1 and the value of MAX_PRIORITY is 10.
✓ To set a thread’s priority, use the setPriority() method.
✓ To obtain the current priority of a thread, use getPriority() method.
✓ Example:
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getNam
e());
System.out.println("running thread priority is:"+
Thread.currentThread().getPriority());
}
34
Output:
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
✓ Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
35
3. static synchronization.
2. Cooperation (Inter-thread communication in java)
✓ Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. This can be done by two ways in java:
1. by synchronized method
2. by synchronized block
class Table{
synchronized void printTable(int n)//synchronized method
{
for(int i=1;i<=5;i++) {
System.out.println(n*i);
try{ Thread.sleep(400); }
catch(Exception e) { System.out.println(e); }
}
}
}
36
class Table{
void printTable(int n)
{
synchronized(this) //synchronized block
{
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{ Thread.sleep(400); }catch(Exception e){System.out.println(e);}
}
}
}//end of the method
}
}
}
t1.start();
t2.start();
}
}
Output:
5
10
15
20
25
100
200
300
400
500
39
It is implemented by following methods of Object class and all these methods can be
called only from within a synchronized context.
Example: The following program illustrates simple bank transaction operations with
inter-thread communication:
class Customer{
int Balance=10000;
if(Balance<amount)
{
System.out.println("Less balance; Balance = Rs. "+Balance+"\nWaiting for
deposit...\n");
try
{
wait();
}
catch(Exception e){}
}
41
Balance-=amount;
System.out.println("withdraw completed...");
}
synchronized void deposit(int amount)
{
System.out.println("going to deposit... Rs. "+amount);
Balance+=amount;
System.out.println("deposit completed... Balance = "+Balance);
notify();
}
}
class ThreadCommn
{
public static void main(String args[]) {
Customer c=new Customer();
new Thread()
{
public void run(){c.withdraw(20000);}
}.start();
new Thread(){
public void run(){c.deposit(15000);}
}.start();
}
}
Output:
going to withdraw...20000
Less balance; Balance = Rs. 10000
Waiting for deposit...
The functions of Suspend, Resume and Stop a thread is performed using Boolean-type
42
flags in a multithreading program. These flags are used to store the current status of the
thread.
1. If the suspend flag is set to true, then run() will suspend the execution of the
currently running thread.
2. If the resume flag is set to true, then run() will resume the execution of the
suspended thread.
3. If the stop flag is set to true, then a thread will get terminated.
Example
NewThread(String threadname)
{
name = threadname;
thr = new Thread(this, name);
System.out.println("New thread : " + thr);
suspendFlag = false;
stopFlag = false;
thr.start(); // start the thread
}
synchronized(this)
{
while(suspendFlag)
{
wait();
}
if(stopFlag)
break;
}
}
}
catch(InterruptedException e)
{
System.out.println(name + " interrupted");
}
}
44
class SuspendResumeThread
{
public static void main(String args[])
{
try
{
Thread.sleep(1000);
obj1.mysuspend();
System.out.println("Suspending thread One...");
Thread.sleep(1000);
obj1.myresume();
System.out.println("Resuming thread One...");
obj2.mysuspend();
System.out.println("Suspending thread Two...");
Thread.sleep(1000);
obj2.myresume();
System.out.println("Resuming thread Two...");
obj2.mystop();
}
catch(InterruptedException e)
{
System.out.println("Main thread Interrupted..!!");
}
}
}
Output:
One : 1
two : 1
One : 2
Suspending thread One...
two : 2
two : 3
Resuming thread One...
One : 3
Suspending thread Two...
One : 4
Resuming thread Two...
two : 4
Thread two Stopped!!!
Main thread exiting...
two exiting...
One : 5
One : 6
One : 7
One : 8
One : 9
One exiting...
3.13: Wrappers
Wrappers
Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.
The table below shows the primitive type and the equivalent wrapper class:
Primitive Data Type Wrapper Class
Byte Byte
Short Short
Int Integer
Long Long
Float Float
Double Double
Boolean Boolean
Char Character
46
3.14: Autoboxing
3.14. Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is
known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to
Long, float to Float, boolean to Boolean, double to Double, and short to Short.
Example:
public class WrapperExample1{
public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}
}
Output
20 20 20
3.14.1. Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is
known as unboxing. It is the reverse process of autoboxing.
Example:
47
A Stack Trace is a list of method calls from the point when the application was
started to the current location of execution within the program. A Stack Trace is
produced automatically by the Java Virtual Machine when an exception is thrown
to indicate the location and progression of the program up to the point of the
exception. They are displayed whenever a Java program terminates with an
uncaught exception.
✓ We can access the text description of a stack trace by calling the
printStackTrace() method of the Throwable class.
✓ The java.lang.StackTraceElement is a class where each element represents a
single stack frame.
✓ We can call the getStackTrace() method to get an array of StackTraceElement
objects that we want analyse in our program.
Class Declaration
Following is the declaration for java.lang.StackTraceElement class
public final class StackTraceElement extends Object implements
Serializable
Class constructors
Constructor & Description
StackTraceElement(String declaringClass, String methodName, String fileName,
int lineNumber)
This creates a stack trace element representing the specified execution point.
Parameters:
• declaringClass – the fully qualified name of the class containing the execution point
represented by the stack trace element.
• methodName – the name of the method containing the execution point represented
by
the stack trace element.
• fileName – the name of the file containing the execution point represented by the
stack
trace element, or null if this information is unavailable
• lineNumber – the line number of the source line containing the execution point
represented by this stack trace element, or a negative number if
thisinformation is unavailable. A value of -2 indicates that the
method containing the execution point is a native method.
Throws: NullPointerException – if declaringClass or methodName is null.
JAVAFX Events and Controls: Event Basics – Handling Key and Mouse Events.
Controls: Checkbox, ToggleButton – RadioButtons – ListView – ComboBox –
ChoiceBox – Text Controls – ScrollPane. Layouts – FlowPane – HBox and VBox –
BorderPane – StackPane – GridPane. Menus – Basics – Menu – Menu bars –
MenuItem.
What is JavaFX?
JavaFX is a set of graphics and media packages that enable developers to design,
create, test, debug, and deploy desktop applications and Rich Internet Applications
(RIA) that operate consistently across diverse platforms. The applications built in
JavaFX can run on multiple platforms including Web, Mobile, and Desktops.
Features of JavaFX:
Feature Description
It consists of many classes and interfaces that are written in
Java Library
Java.
FXML is the XML based Declarative markup language. The
FXML coding can be done in FXML to provide the more enhanced GUI
to the user.
Scene Builder generates FXML mark-up which can be ported to
Scene Builder
an IDE.
Web View uses WebKitHTML technology to embed web pages
Web view
into the Java Applications.
Built-in controls are not dependent on operating system. The UI
Built in UI controls
components are used to develop a full featured application.
JavaFX code can be embedded with the CSS to improve the style
CSS like styling
and view of the application.
The JavaFX applications can be embedded with swing code
Swing
using the Swing Node class. We can update the existing swing
interoperability
application with the powerful features of JavaFX.
Canvas API provides the methods for drawing directly in an area
Canvas API
of a JavaFX scene.
Rich Set of APIs JavaFX provides a rich set of API's to develop GUI applications.
Integrated Graphics It is provided to deal with 2D and 3D graphics.
Library
JavaFX graphics are based on Graphics rendered
Graphics Pipeline pipeline(prism). It offers smooth graphics which are hardware
accelerated.
High Performance The media pipeline supports the playback of web multimedia on
Media Engine a low latency. It is based on a Gstreamer Multimedia framework.
Self-contained Self-Contained application packages have all of the application
application resources and a private copy of Java and JavaFX Runtime.
deployment model
1) Stage
✓ Stage(a window) in a JavaFX application is similar to the Frame in a Swing
Application. It acts like a container for all the JavaFX objects.
✓ Primary Stage is created internally by the platform. Other stages can further be
created by the application.
✓ A stage has two parameters determining its position namely Width and Height. It
is divided as Content Area and Decorations (Title Bar and Borders).
✓ There are five types of stages available −
o Decorated
o Undecorated
o Transparent
o Unified
o Utility
✓ We have to call the show() method to display the contents of a stage.
2) Scene
✓ A scene represents the physical contents of a JavaFX application. It contains all
the contents of a scene graph.
✓ The class Scene of the package javafx.scene represents the scene object. At an
instance, the scene object is added to only one stage.
A GUI based applications are mostly driven by Events. Events are the actions that the user
performs and the responses the application generates.
❖ JavaFX provides support to handle events through the base class “Event” which is
available in the package javafx.event.
Examples of Events:
o Action Event — widely used to indicate things like when a button is pressed.
Class:- ActionEvent
Actions:- button pressed.
o Mouse Event — occurs when mouse is clicked
Class:- MouseEvent
Actions:- mouse clicked, mouse pressed, mouse released, mouse moved, mouse
entered target, mouse exited target.
o Drag Event — occurs when the mouse is dragged.
Class:- DragEvent
Actions:- drag entered, drag dropped, drag entered target, drag exited target,
drag over.
o Key Event — indicates that a keystroke has occurred.
Class:- KeyEvent
Actions:- Key pressed, key released and key typed.
o Window Event:
Class:- WindowEvent
Actions:- window hiding, window shown, window hidden, window showing.
o Scroll Event — indicates scrolling by mouse wheel, track pad, touch screen, etc...
o TouchEvent — indicates a touch screen action
5.2.2 : Event Handling:
Event handling is the mechanism that controls the event and decides what should
happen, if an event occurs. It has the code which is known as Event Handler that is
executed when an event occurs.
Event Handling in JavaFX is done by Event Filters and Event Handlers. They contain the
event handling logic to process a generated event.
Every event in JavaFX has three properties:
1. Event source
2. Event target
3. Event type
S.N Property Description
It denotes source of the event i.e. the origin which is responsible
1 Event Source
for generating the event.
It denotes the node on which the event is created. It remains
unaffected for the generated event. Event Target is the instance
2 Event Target
of any of the class that implements the java interface
“EventTarget”.
It is the type of the event that is being generated. It is basically
the instance of EventType class.
3 Event Type
Example: KeyEvent class contains KEY_PRESSED,
KEY_RELEASED, and KEY_TYPED types.
1. Target Selection:
The first step to process an event is the selection of the event target. Event target
is the node on which the event is created. Event target is selected based in the Event
Type.
• For key events, the target is the node that has key focus.
• The node where the mouse cursor is located is the target for mouse events.
2. Route Construction:
Usually, an event travels through the event dispatchers in order in the event
dispatch chain. An Event Dispatch Chain is created to determine the default route
of the event whenever an event is generated. It contains the path from the stage
to the node on which the event is generated.
3. Event Capturing:
In this phase, an event is dispatched by the root node and passed down in the
Event Dispatch Chain to the target node.
Event Handlers will not be invoked in this phase.
If any node in the chain has registered the event filter for the type of event that
occurred, then the filter on that node is called. When the filter completes, the
event is moved down to the next node in the Dispatch Chain. If no event filters
consumes the event, then the event target receives and processes the generated
event.
4. Event Bubbling:
In this phase, a event returns from the target node to the root node along the event
dispatch chain.
Events handlers will be invoked in this phase.
If any node in the chain has a handler for the generated event, that handler is
executes. When the handler completes, the event is bubbled up in the chain. If the
handler is not registered for a node, the event is returned to the bubbled up to next
node in the route. If no handler in the path consumed the event, the rootnode
consumes the event and completes the processing.
Event Filters:
❖ Event Filters provides the way to handle the events generated by the Keyboard
Actions, Mouse Actions, Scroll Actions and many more event sources.
❖ They process the events during Event Capturing Phase.
❖ A node must register the required event filters to handle the generated event on that
node. handle() method contains the logic to execute when the event is triggered.
Syntax:
node.addEventFilter (<Event_Type>, new EventHandler<Event-Type>()
{
public void handle(Event-Type)
{
//Actual logic
});
Where,
First argument is the type of event that is generated.
Second argument is the filter to handle the event.
❖ Removing Event-Filter:
We can remove an event filter on a node using removeEventFilter() method.
Syntax:
node.removeEventFilter(<Input-Event>, filter);
Event Handlers:
❖ Event Filters provides the way to handle the events generated by the Keyboard
Actions, Mouse Actions, Scroll Actions and many more event sources.
❖ They are used to handle the events during Event Bubbling Phase.
❖ A node must register the event handlers to handle the generated event on that node.
handle() method contains the logic to execute when the event is triggered.
Syntax:
node.addEventHandler (<Event_Type>, new EventHandler<Event-Type>()
{
public void handle(<Event-Type> e)
{
//Handling Code
});
Where,
First argument is the type of event that is generated.
Second argument is the filter to handle the event.
❖ Removing Event-Filter:
We can remove an event handler on a node using removeEventHandler() method.
Syntax:
node.removeEventHandler(<EventType>, handler);
A node can register for more than one Event Filters and Handlers.
The interface javafx.event.EventHanler must be implemented by all the event filters and
event handlers.
Key Event − It is an input event that indicates the key stroke occurred on a node.
✓ It is represented by the class named KeyEvent.
✓ This event includes actions like key pressed, key released and key typed.
Example:
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.scene.input.*;
import javafx.scene.control.Alert.*;
@Override
public void start(Stage primaryStage)
{
String str="",str1="";
int d;
public void handle(KeyEvent event)
{
if(event.getCode()== KeyCode.BACK_SPACE)
{
str=str.substring(0,str.length()-1);
tf2.setText(str);
}
else
{
str+=event.getText();
tf2.setText(str);
}
}
};
tf1.setOnKeyPressed(handler1);
tf2.setOnKeyTyped(handler2);
GridPane root = new GridPane();
root.addRow(1,tf1);
root.addRow(2,l1);
root.addRow(3,tf2);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("KeyEvent-Demo");
primaryStage.setScene(scene);
primaryStage.show();
}
Figure 1: When a key is pressed in TextField 1 Figure 2: When backspace key is pressed in TextField 1
5.3.2 : HANDLING MOUSE EVENTS
JavaFX Mouse Events are used to handle mouse events. The MouseEvents works when
you Clicked, Dragged, or Pressed and etc. An object of the MouseEvent class representsa
mouse events.
Example:
import javafx.application.Application;
import javafx.event.Event.*;
import javafx.scene.*;
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.scene.control.*;
import java.util.*;
btn.setText("Mouse Event");
status.setText("Hello");
btn.setOnMousePressed(new EventHandler<MouseEvent>() {
public void handle(MouseEvent me) {
status.setText("Mouse pressed");
}
});
btn.setOnMouseEntered(e-> {
status.setText("Mouse Entered");
});
btn.setOnMouseExited(e-> {
status.setText("Mouse Exited");
});
btn.setOnMouseReleased(e-> {
status.setText("Mouse Released");
});
BorderPane bp = new BorderPane();
bp.setCenter(btn);
bp.setBottom(status);
primaryStage.setTitle("MouseEvent-Demo");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
OUTPUT
5.4: JavaFX UI Controls
import javafx.application.Application;
import javafx.collections.*;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.image.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
import javafx.stage.Stage;
educationListView.getSelectionModel().setSelectionMode(SelectionMode.MU
LTIPLE);
gridPane.add(dobLabel, 0, 1);
gridPane.add(datePicker, 1, 1);
gridPane.add(genderLabel, 0, 2);
gridPane.add(maleRadio, 1, 2);
gridPane.add(femaleRadio, 2, 2);
gridPane.add(reservationLabel, 0, 3);
gridPane.add(yes, 1, 3);
gridPane.add(no, 2, 3);
gridPane.add(technologiesLabel, 0, 4);
gridPane.add(javaCheckBox, 1, 4);
gridPane.add(dotnetCheckBox, 2, 4);
gridPane.add(educationLabel, 0, 5);
gridPane.add(educationListView, 1, 5);
gridPane.add(interest,0,6);
gridPane.add(AoI,1,6);
gridPane.add(locationLabel, 0, 7);
gridPane.add(locationchoiceBox, 1, 7);
gridPane.add(buttonRegister, 2, 8);
OUTPUT:
24
In JavaFX, Layout defines the way in which the components are to be seen on the stage. It
basically organizes the scene-graph nodes.
Layout Panes: Layout panes are containers which are used for flexible and dynamic
arrangements of UI controls within a scene graph of a JavaFX application.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
mc.getItems().addAll(c1,c2);
MenuBar mb = new MenuBar();
mb.getMenus().add(mc);
m1.setOnAction(e -> {
tfNumber1.setText("10");
tfNumber2.setText("20");
});
m2.setOnAction(e ->{
tfNumber1.setText("");
tfNumber2.setText("");
tfResult.setText("");
});
c1.setOnAction(e -> {
pane.setBackground(new Background(new BackgroundFill(Color.RED,null,null)));
});
c2.setOnAction(e -> {
pane.setBackground(new Background(new
BackgroundFill(Color.GREEN,null,null)));
});
btSubtract.setOnAction(e -> {
double a = getDoubleFromTextField(tfNumber1);
double b = getDoubleFromTextField(tfNumber2);
tfResult.setText(String.valueOf(a - b));
});
btMultiply.setOnAction(e -> {
double a = getDoubleFromTextField(tfNumber1);
double b = getDoubleFromTextField(tfNumber2);
tfResult.setText(String.valueOf(a * b));
});
btDivide.setOnAction(e -> {
double a = getDoubleFromTextField(tfNumber1);
double b = getDoubleFromTextField(tfNumber2);
tfResult.setText(b == 0 ? "NaN" : String.valueOf(a / b));
31
});
Menu is a popup menu that contains several menu items that are displayed when
the user clicks a menu. The user can select a menu item after which the menu goes into
a hidden state.
MenuBar is usually placed at the top of the screen which contains several menus. JavaFX
MenuBar is typically an implementation of a menu bar.
Method Explanation
getItems() returns the items of the menu
hide() hide the menu
show() show the menu
getMenus() The menus to show within this MenuBar.
isUseSystemMenuBar() Gets the value of the property useSystemMenuBar
setUseSystemMenuBar(boolean
Sets the value of the property useSystemMenuBar.
v)
setOnHidden(EventHandler v) Sets the value of the property onHidden.
33
JavaFX Menu
✓ In the JavaFX application, in order to create a menu, menu items, and menu bar,
Menu, MenuItem, and MenuBar class is used. The menu allows us to choose options
among available choices in the application.
✓ All methods needed for this purpose are present in the javafx.scene.control.Menu
class.
Example: Java program to create a menu bar and add menu to it and also add
menuitems to the menu
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.VBox;
public class MenuUI extends Application {
@Override
public void start(Stage primaryStage) throws Exception
{
Menu newmenu = new Menu("File");
Menu newmenu2 = new Menu("Edit");
MenuItem m6 = new
MenuItem("Paste");
newmenu.getItems().add(
m1);
newmenu.getItems().add(
m2);
newmenu.getItems().add(
m3);
newmenu2.getItems().add(
m4);
newmenu2.getItems().add(
m5);
newmenu2.getItems().add(
m6); MenuBar newmb =
new MenuBar();
newmb.getMenus().add(ne
wmenu);
newmb.getMenus().add(ne
wmenu2); VBox box = new
VBox(newmb);
Scene scene = new
Scene(box,400,200);
primaryStage.setScene(scene);
primaryStage.setTitle("JavaFX
Menu Example");
primaryStage.show();
}
public static void main(String[] args)
{
Application.launch(args);
}
}
Output:
35