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

Developing Applications Using Java SE (1)

The document provides an introduction to Java programming, detailing its history, principles, and features such as being platform-independent, object-oriented, and multithreaded. It also covers the setup of the Java environment, the structure of Java applications, and the creation and execution of basic Java applications and applets. Additionally, it includes lab exercises for practical application of the concepts discussed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Developing Applications Using Java SE (1)

The document provides an introduction to Java programming, detailing its history, principles, and features such as being platform-independent, object-oriented, and multithreaded. It also covers the setup of the Java environment, the structure of Java applications, and the creation and execution of basic Java applications and applets. Additionally, it includes lab exercises for practical application of the concepts discussed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 238

JavaTM Education & Technology Services

Java Programming

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 1
Lesson 1

Introduction To Java

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 2
Brief History of Java

• Java was created by Sun Microsystems in May


1995.

• The Idea was to create a language for controlling


any hardware, but it was too advanced.

• A team - that was called the Green Team - was


assembled and lead by James Gosling.

• Platform and OS Independent Language.

• Free License; cost of development is brought to a


minimum.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 3
Brief History of Java

• From mobile phones to handheld devices, games


and navigation systems to e-business solutions,
Java is everywhere!

• Java can be used to create:


– Desktop Applications,
– Web Applications,
– Enterprise Applications,
– Mobile Applications,
– Smart Card Applications.
– Embedded Applications (Sun SPOT- Raspberry Pi)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 4
Java Principles

• Primary goals in the design of the Java


programming language:
– Simple, object oriented, and easy to learn.
– Robust and Secure.
– Architecture neutral and portable.
– Compiled and Interpreted.
– Multithreaded.
– Networked.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 5
Java Features

• Java is easy to learn!


▪ Syntax of C++
▪ Dynamic Memory Management (Garbage
Collection)
▪ No pointers

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 6
Java Features cont’d

• Machine and Platform Independent

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 7
Java Features cont’d

• Java is both, compiled and interpreted

compile Interpret JVM


Source Intermediate
One time Run
Code Code
ONLY Every Time

MyFile.java MyClass.class

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 8
Java Features cont’d

• Java depends on dynamic linking of libraries

JVM + +
Libraries compiler
+
JRE utilities

JDK

Java development Kit (JDK)


JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 9
Java Features cont’d

• Java is fully Object Oriented


▪ Made up of Classes.
▪ No multiple Inheritance.
• Java is a multithreaded language
▪ You can create programs that run multiple threads of
execution in parallel.
▪ Ex: GUI thread, Event Handling thread, GC thread
▪ Java is networked
▪ Predefined classes are available to simplify network
programming through Sockets(TCP-UDP)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 10
Java Environment Setup

• Download JDK 8
http://bit.ly/3TJqjJA

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 11
Java Environment Setup

• Once you installed Java on your machine,


– you would need to set environment variables to point
to correct installation directories:
• Assuming you have installed Java in
c:\Program Files\java\jdk directory\bin\

• Open 'Control Panel ' then 'Advanced System Settings'

• Click on the 'Environment variables' button under the


'Advanced' tab.

• Now alter the 'Path' variable so that it also contains the path
to the Java executable.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 13
Java Environment Setup

2
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 14
First Java Application

class HelloWorld
{
public static void main(String[] args)
{
System.out.println(“Hello Java”);
}
}

File name: hello.java

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 15
First Java Application cont’d

• The main() method:


– Must return void.

– Must be static.
• because it is the first method that is called by the Interpreter
(HelloWorld.main(..)) even before any object is created.

– Must be public to be directly accessible.

– It accepts an array of strings as parameter.


• This is useful when the operating system passes any command
arguments from the prompt to the application.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 16
System.out.println(“Hello”);

• out is a static reference that has been created in


class System.
• out refers to an object of class PrintStream. It is a
ready-made stream that is attached to the standard
output (i.e. the screen).

System PrintStream

+ PrintStream out:static

+ Print(String):void
+ Println(String):void

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 17
Compiling and Running a Java Application

• To compile:
Prompt> javac hello.java

• If there are no compiler errors, then the file


HelloWorld.class will be generated.

• To run:
Prompt> java HelloWorld
Hello Java
Prompt>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 18
Java Structure

• Classes are placed in packages.

• We must import any classes that we will use


inside our application.

• Classes that exist in package java.lang are


imported by default.

• Any Class by default extends Object class.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 19
Java Structure cont’d

• The following are some package names that


contain commonly used classes of the Java
library:
java javax
awt swing
io mail
net media
applet
util
lang

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 20
Specifying a Package

• If no package is specified,
– then the compiler places the .class file in the default
package (i.e. the same folder of the .java file).

• To specify a package for your application,


– write the following line of code at the beginning of your
class:
package mypkg;

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 21
Specifying a Package

• To compile and place the .class in its proper location:

Prompt> javac -d . hello.java

Current Directory

• To run:

Prompt> java mypkg.HelloWorld

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 22
JAR File

• Packages can be brought together in one


compressed JAR file.

• The classes of Java Runtime Libraries (JRE)


exist in rt.jar.

• JAR files can be made executable by writing a


certain property inside the manifest.mf file that
points to the class that holds the main(..)
method.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 23
How to make JAR file

• To create a compressed JAR file:


prompt> jar cf <archive_name.jar> <files>

• Example:
prompt> jar cf App.jar HelloWorld.class

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 24
How to make JAR file cont’d

• To create an executable JAR file:


1. Create text file that list the main class.
“The class that has the main method”
2. Write inside the text file this text:
Main-Class: <class name>
3. Then run the jar utility with this command line:

prompt>jar cmf <text-file> <archive_name.jar> <files>

Or without manifest file:


prompt>jar cef <entry-point> <archive_name.jar>
<files>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 25
Standard Naming Convention
“The Hungarian Notation.”

• Class names:
MyTestClass , RentalItem
_______________________________________________________________________

• Method names:
myExampleMethod() , getCustomerName()
_______________________________________________________________________

• Variables:
mySampleVariable , customerName
_______________________________________________________________________

• Constants:
MY_STATIC_VAR , MAX_NUMBER
_______________________________________________________________________

• Package:
pkg1 , util , accesslayer

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 26
Applets

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 27
Overview

Web Server
(www.abc.com)

www.abc.com\index.html

Download
MyApplet.class

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 28
Applet Features

• Machine and Platform Independent

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 29
Applets

• An Applet is a client side Java program that runs


inside the web browser.

• The .class file of the applet is downloaded from


the web server to the client’s machine

• The JVM interprets and runs the applet inside the


browser.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 30
Applet Security

• In order to protect the client from malformed files


or malicious code, the JVM enforce some
security restrictions on the applet:
▪ Syntax is checked before running.

▪ No I/O operations on the hard disk.

▪ Communicates only with the server from which it was


downloaded.

• Applets can prompt the client for additional


security privileges if needed.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 31
Applet Life Cycle

Applet init() Applet start() Applet


Constructing Initialized Running

start()
Constructor
stop()

Applet destroy() Applet


Destroyed Stopped
start end
state state

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 32
Applet Life Cycle

• The life cycle of Applet:


__________________________________________________________________________________________________
▪ init():
• called when the applet is being initialized for the first time.
__________________________________________________________________________________________________

▪ start():
• called whenever the browser’s window is activated.
__________________________________________________________________________________________________
▪ paint(Graphics g):
• called after start() to paint the applet, or
• whenever the applet is repainted.
__________________________________________________________________________________________________

▪ stop():
• called whenever the browser’s window is deactivated.
__________________________________________________________________________________________________

▪ destroy():
• called when the browser’s window is closed.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 33
Applet Life Cycle cont’d

• You can refresh the applet anytime by calling:


repaint(),

– which will invoke update(Graphics g) to clear the


applet,

– which in turn invokes paint(Graphics g) to draw the


applet again.

• To create your own applet, you write a class that


extends class Applet,
– then you override the appropriate methods of the life
cycle.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 34
Basic Java Applet

import java.applet.Applet;
import java.awt.Graphics;

public class HelloApplet extends Applet{


public void paint(Graphics g){
g.drawString(“Hello Java”, 50, 100);
}
}

Note: Your class must be made public or else the browser


will not be able to access the class and create an object of it.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 35
Basic Java Applet cont’d

• In order to run the applet we have to create a simple HTML


web page, then we invoke the applet using the <applet> tag.

• The <applet> tag requires 3 mandatory attributes:


▪ code
▪ width
▪ height

• An optional attribute is codebase, which specifies the path of


the applet’s package.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 36
Basic Java Applet cont’d

• Write the following in an HTML file e.g. mypage.html:

<html>
<body>
<applet code=“HelloApplet”
width=400 height=350>
</applet>
</body>
</html>

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 37
Compiling and Running an Applet

• Save the Hello Applet Program in your assignments folder in


a file named: HelloApplet.java
– When a class is made public, then you have to name the file after it.

• To compile write in cmd this command:


javac HelloApplet.java

• An applet is not run like an application.


• Instead, you browse the HTML file from your web browser, or
by using the applet viewer:
appletviewer mypage.html
from the command prompt.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 38
Lab Exercise

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 39
1. Simple Prompt Application

• Create a simple non-GUI Application that prints out the


following text on the command prompt:
Hello Java

• Note: specify package and create executable jar file.

• Bonus: Modify the program to print a string that is passed


as an argument from the command prompt.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 40
2. Basic Applet

• Create an applet that displays: Hello Java.

• Bonus: Try to pass some parameters from the HTML


page to the applet. For example, display the parameters
on the applet.

Hint:
use the self closing tag: <param name= value= />

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 41
Lesson 2

Introduction to OOP
Using Java

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 42
Introduction to OOP

• What is OOP?
– OOP is mapping the real world to Software

– OOP is a community of interacting agents called


objects.

– Each object has a role to play.

– Objects can share some of its characteristics with


each other, but each object is unique by it self.

– Objects can interact with each other to accomplish


tasks.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 43
Introduction to OOP

• What is OOP?
– Each object is an instance of a class.

– The method invoked by an object is determined by the


class of the receiver.

– All objects of a given class use the same method in


response to similar messages.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 44
Introduction to OOP - Class

• What is a Class?
– A class is a blueprint of objects.
– A class is an object factory.
– A class is the template to create the object.
– A class is a user defined datatype
• Object:
– An object is an instance of a class.
– The property values of an object instance is different
from the ones of other object instances of a same class
– Object instances of the same class share the same
behavior (methods).
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 45
Introduction to OOP – Object & Class

• Class reflects concepts.


• Object reflects instances that embody those
concepts.

class

object

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 46
Introduction to OOP - Object

• What is an Object?
– An object is a software bundle of variables and related
methods.

• Object consists of:


– Data (object’s Attributes)

– Behavior (object’s methods)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 47
Introduction to OOP – Object & Class

• Assume we have this object [SerratedDisc].

• How can we describe its Class?


• First it’s a serrated disc lets give it that name
SerratedDisc.
• Second each disk has a size, and
numberOfPins.
• Last thing it can spin.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 48
Introduction to OOP – Object & Class

• So we have two different concepts here are very


important.

Class Object
Encapsulates the attributes, The living thing that interacts
and behaviors into a blue-print and actually runs.
code to provide the design
concept.

Ex: class SerratedDisc { SerratedDisc serr_Car =


size new SerratedDisc ();
numberOfPins
spin size = 10
} numberOfPins = 8

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 49
How to create a class?

• To define a class, we write:


<access-modifier>* class <name>
{
<attributeDeclaration>*
<methodDeclaration>*
<constructorDeclaration>*
}

• Example:

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 50
OOP Principles

• Object Oriented has main three principles:

Polymorphism

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 51
Encapsulation

• It is to encapsulate the data and behaviors in one class.


• In addition it is a language mechanism for restricting
access to some of the object's components.
• Data hiding is done in Java using the public, and private
key words.

private class members can only


be accessed within the class

Public class members can be accessed


within the class or from another class
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 52
Encapsulation cont’d

Accessible within same class

Cannot be accessed outside the


class

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 53
Encapsulation cont’d

• As we can see in the previous example private class


members are not accessible outside the class.
• These keywords are called access modifiers, and it can
be added to attributes and methods.
• The point of encapsulation is to hide class attributes from
the outside world so other objects can not access them
directly, but to let class methods to be an interface to
access them.
setter

getter

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 54
Encapsulation cont’d

• Exposing object attributes might lead to misuse of this


attributes.
• Instead of exposing object attributes OOP uses the setter
and getter methods.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 55
Encapsulation cont’d

• Now we can access the object attribute through the setter


and getter method like the following:

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 56
Coding Guidelines

• Think of an appropriate name for your class.


– Don't use XYZ or any random names.

• Class names starts with a CAPITAL letter.


– not a requirement it is a convention

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 57
Declaring Methods

• To declare a method:
<modifier>* <Return type> <name> ([<Param Type> <Param
Name>]*)
{
<Statement>*
}
• Example:

class StudentRecord {
private String name;
public String getName(){ return name; }
public void setName(String str){ name=str; }
public static String getSchool(){...........}
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 58
Declaring Methods

• The following are characteristics of methods:


– It can return one or no values

– It may accept as many parameters it needs or no


parameter at all.

– After the method has finished execution, it goes back to


the method that called it.

– Method names should start with a small letter.

– Method names should be verbs.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 59
Class and constructor

• To make use of this class we need to construct an object


of this class.
SerratedDisc serr_Car = new SerratedDisc ();

• Constructing an object is like building it and making it


ready for action inside the program.
• To construct an object we use a special type of methods
called Constructor
• A constructor is simply a public method that does not
have a return and its name matches the class name
(case sensitive).

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 60
Class and constructor cont’d

• By default any class - we write - has a constructor without


the need to write it, called default constructor.
• The default constructor does nothing but it must be called
before creating an object.
• The constructor is the best place to put initialization per-
object.
• If no constructors are written then the compiler uses the
class’ default constructor.
• If we wrote a custom constructor that takes arguments
then there will not be a default constructor.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 61
Class and constructor cont’d

• To construct an object of class we use the new keyword.

The disc is created


Asking the disc to spin

• The output of this program will be like

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 62
Class and constructor cont’d

• To add a constructor to our class we need to code extra


method like - with the same name of the class (case
sensitive).

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 63
Class and constructor cont’d

• Now to construct an object we need to use the new


constructor.

• Now using the default constructor is illegal because we


have our constructor and the default constructor as if it
has never existed.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 64
Instance and Static Members Members

• Any attribute or method are declared inside the class


body are called instance variable, or method.
• For each new object is created and a new location for its
instance attributes is located inside the memory.
• Methods are located once.
• When a method is called from an object, a reference
points to the that object would be passed to the method
implicitly. Such reference is called this reference.
• Using the this reference is not obligatory within the class.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 65
Instance and Static Members cont’d

• There is some cases we must use the this reference, like:

• Attributes and methods can be declared static.


• Static attributes do not belong to a single instance of this
class. They belong to the class itself and could act as
shared resources to all instances.
• Static variable are located only once inside memory
before the creation of any object.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 66
Instance and Static Members cont’d

• Static variables can be referenced at any method inside


the class (instance, or static).
• Static methods can only access the static variables of the
class.
• Public static variables, or methods can be accessed
outside the class using the class name without the need
to construct new object.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 67
Instance and Static Members cont’d

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 68
Lab Assignments

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 69
2. Simple Prompt Application

• Create a simple non-GUI Application that represent


complex number and has two methods to add and subtract
complex numbers:

Complex number: x + yi , 5+6i

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 70
3. Simple Prompt Application

• Create a simple non-GUI Application that represent


Student and has method to print student info. :

Student : name, age, track……

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 71
Lesson 3
OOP II and Applet

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 72
Inheritance

• Inheritance:
– Inheritance is to extend the functionality of an existing class
– Inheritance represents is – a relationship between the Child and
its Parent.

• Using inheritance comes with a set of benefits:


– Reduces the amount of code needed to be written by
developers.
– Makes the code easy to maintain and update.
– Helps in building more reasonable class hierarchy and
simulating to the real world.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 73
Inheritance

Animal

Kind of
or
is - a In Java

Inheritance

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 74
Inheritance

• the super reference can only point to parent public


members.

Child Parent

super

• In the animal example we want to be able to access the


private members of the parent class without the need to
violate the encapsulation rule.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 75
Inheritance

• We can mark our attributes and methods as protected to


indicate that it is accessible to child classes but not to
the out side world.

Now all of this attributes


are accessible inside
the Animal class or any
sub class of it, but not
accessible to any class
out side that hierarchy

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 76
polymorphism
• As polymorphism can be seen in inheritance it also can
be seen in class attributes and methods.
• The first polymorphism concept that can be seen inside
one class or more than one class with inheritance
relationship is the overloading.
• Overloading is re-writing a method with a name already
defined for another method inside the same class or a
parent, but with changing the method parameter section.
– Changing method parameter types.
– Changing method parameter order.
– Changing method parameter count.
• Note: changing the method return type is not considered
overloading and will give compilation error
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 77
Polymorphism (overloading)

Compilation error

Note: attributes cannot be overloaded.


JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 78
polymorphism

• Second type of polymorphism is overriding.


• Overriding is re-writing a method typically as it was
written in its parent class inside a child class.
• Overriding can only happen inside different classes
inside the same class hierarchy structure.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 79
Polymorphism (overriding)

• Now if we try to call the play method inside the Dog class
the newly overridden method inside the Dog class will
respond.
• If we want to call the parent method we can use the
super reference.
• Overloading and overriding are used to redefine the
method implementation with preserving the method
name.
• This helps the class users to remember only a little about
my class, and in the other hand the class will behave
differently according to the implemented method.
• Note: overriding can be done to attributes but it is not
recommended.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 80
polymorphism

• Polymorphism allows that one reference type can point to


different objects as long as they are in the correct class
hierarchy.

• And when calling the overridden method play() it will call


the correct object method of the Dog class.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 81
Data Abstraction

• Abstraction is the process by which a data and programs


are defined with a presentation similar in form to its
meaning while hiding away the implementation details.
• Abstraction is a concept or idea not attached to any
instance.

Animal

numOfLegs
speed
name
play()
eat(AnimalFood f)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 82
Data Abstraction

• At this point the class Animal is not will defined and


implementing its methods at this point will be pointless.
• Also instantiating an object of class Animal is also
pointless as the Animal class is only a concept class to
indicate that any animal can have this properties but it is
only abstract definition.
• So its better to declare the class Animal as abstract
class, rather than declaring a normal class.
• This provides a more professional and efficient class
hierarchy building.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 83
Data Abstraction

• Abstract class is created by adding the abstract key word


before the class name.

• At this point the we cannot instantiate any objects from


this class.
• Abstract class can have zero or more abstract method.
• Abstract method is a method with no implementation
body only the method signature.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 84
Data Abstraction

• Abstract class can be inherited by other classes and its


abstract methods overridden to provide an
implementation to a case of this abstract class.
• Inheriting from abstract class without overriding its
abstract methods makes your child class also abstract.
• Overriding the abstract method is a must or declare your
child class as abstract too.
• Abstract class can have zero or more abstract methods,
but abstract methods cannot exist in normal class.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 85
Lesson 4
Data Types & Operators

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 86
Identifiers
• An identifier is the name given to a feature
(variable, method, or class).
• An identifier can begin with either:
– a letter,
– $, or
– underscore.

• Subsequent characters may be:


– a letter,
– $,
– underscore, or
– digits.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 87
Data types

• Data types can be classified into two types:

Primitive Reference

Boolean boolean 1 bit (true/false)


byte 1B (-27 → 27-1) (-128 → +127) Arrays
short 2B (-215 → 215-1) (-32,768 to +32,767)
Integer
int 4B (-231 → 231-1)
Classes
long 8B (-263 → 263-1)

Floating float 4B Standard: IEEE 754 Specification


Point double 8B Standard: IEEE 754 Specification Interfaces
Character char 2B unsigned Unicode chars (0 → 216-1)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 88
Wrapper Classes

• Each primitive data type has a corresponding


wrapper class.
boolean → Boolean

byte → Byte

char → Character

short → Short

int → Integer

long → Long

float → Float

double → Double

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 89
Wrapper Classes cont’d

• There are three reasons that you might use a


wrapper class rather than a primitive:
1. As an argument of a method that expects an object.

2. To use constants defined by the class,


• such as MIN_VALUE and MAX_VALUE,
that provide the upper and lower bounds of the data type.

3. To use class methods for


• converting values to and from other primitive types,
• converting to and from strings,
• converting between number systems (decimal, octal, hexadecimal,
binary).

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 90
Wrapper Classes cont’d

• They have useful methods that perform some


general operation, for example:

primitive xxxValue() → convert wrapper object to primitive

primitive parseXXX(String) → convert String to primitive

Wrapper valueOf(String) → convert String to Wrapper

Integer i2 = new Integer(42);


byte b = i2.byteValue();
double d = i2.doubleValue();

String s3 = Integer.toHexString(254);
System.out.println("254 is " + s3);

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 91
Wrapper Classes cont’d

• They have special static representations, for


example:

POSITIVE_INFINITY

In class Float & Double


NEGATIVE_INFINITY

NaN Not a Number

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 92
Literals

• A literal is any value that can be assigned to a primitive


data type or String.
boolean true false
char ‘a’ …. ’z’ ‘A’ …. ‘Z’
‘\u0000’ …. ‘\uFFFF’
‘\n’ ‘\r’ ‘\t’
Integral data 15 Decimal (int)
type 15L Decimal (long)
017 Octal
0XF Hexadecimal
Floating point 73.8 double
data type 73.8F float
5.4 E-70 5.4 * 10-70
5.4 e+70 5.4 * 1070
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 93
Operators

• Operators are classified into the following


categories:
▪ Unary Operators.
▪ Arithmetic Operators.
▪ Assignment Operators.
▪ Relational Operators.
▪ Shift Operators.
▪ Bitwise and Logical Operators.
▪ Short Circuit Operators.
▪ Ternary Operator.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 94
Operators cont’d

• Unary Operators:
+ - ++ -- ! ~ ()
positive negative increment decrement boolean bitwise casting
complement inversion

Widening
(implicit casting)

byte short int long float double

Narrowing
char (requires explicit casting)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 95
Operators cont’d

• Arithmetic Operators:

+ - * / %
add subtract multiply division modulo

• Assignment Operators:

= += -= *= /= %= &= |= ^=

• Relational Operators:

< <= > >= == != instanceof

Operations must be performed on homogeneous data types


JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 96
Operators cont’d

• Shift Operators:
>> << >>>
right shift left shift unsigned right shift

• Bitwise and Logical Operators:


& | ^
AND OR XOR

• Short Circuit Operators:


&& ||
(condition1 AND condition2) (condition1 OR condition2)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 97
Operators cont’d

• Ternary Operator:

condition ?true statement:false statement

int y=15;
int z=12;
int x=y<z?10:11;
If(y<z)
x=10;
else
x=11;

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 98
Operators cont’d
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative * / %
additive + -
shift << >> >>>
relational < > <= >= instanceof
equality == !=
Bitwise and Logical AND &
bitwise exclusive OR ^
Bitwise and Logical inclusive OR |
Short Circuit AND &&
Short Circuit OR ||
ternary ?:
assignment = op=
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 99
Reference Data types: Classes

• General syntax for creating an object:


MyClass myRef; // just a reference
myRef = new MyClass(); // construct a new object

• Or on one line:
MyClass myRef = new MyClass();

• An object is garbage collected when there is no reference


pointing to it.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 100
Reference Data types: Classes cont’d

String str1; // just a null reference


str1 = new String(“Hello”); // object construction Memory
Heap
String str2 = new String(“Hi”); “Hello”

String s = str1; //two references to the same object


“Hi”

str1 = null;

s = null; // The object containing “Hello” will


// now be eligible for garbage collection.
str1 str2 s

Stack

str1.anyMethod(); // ILLEGAL!
//Throws NullPointerException

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 101
Lesson 5
Using Arrays & Strings

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 102
What is Array?

• An Array is a collection of variables of the same


data type.

• Each element can hold a single item.

• Items can be primitives or object references.

• The length of the array is determined when it is


created.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 103
What is Array?

• Java Arrays are homogeneous.

• You can create:


– An array of primitives,
– An array of object references, or
– An array of arrays.

• If you create an array of object references, then you


can store subtypes of the declared type.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 104
Declaring an Array

• General syntax for creating an array:


Datatype[] arrayIdentifier; // Declaration
arrayIdentifier = new Datatype [size]; // Construction
• Or on one line, hard coded values:
Datatype[] arrayIdentifier = { val1, val2, val3, val4 };

• To determine the size (number of elements) of an array at


runtime, use:
arrayIdentifier.length

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 105
Declaring an Array cont’d

• Example1: Array of Primitives:


Memory
int[] myArr;

myArr = new int[3]; [0] 15


Heap
[1] 30
myArr[0] = 15 ;
[2] 45
myArr[1] = 30 ;
myArr[2] = 45 ;

Stack myArr
System.out.println(myArr[2]);

myArr[3] = … ; // ILLEGAL!
//Throws ArrayIndexOutOfBoundsException

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 106
Declaring an Array cont’d

• Example2: Array of Object References:


Memory
String[] namesArr;
“Hello”
namesArr = new String[3]; [0]
Heap “James”
namesArr[0].anyMethod() // ILLEGAL! [1]

//Throws NullPointerException [2]

“Gosling”
namesArr[0] = new String(“Hello”);
namesArr[1] = new String(“James”); Stack
namesArr
namesArr[2] = new String(“Gosling”);

System.out.println(namesArr[1]);

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 107
String Operations

• Although String is a reference data type (class),


– it may figuratively be considered as the 9th data type
because of its special syntax and operations.

– Creating String Object:


String myStr1 = new String(“Welcome”);
String sp1 = “Welcome”;
String sp2 = “ to Java”;

– Testing for String equality:


if(myStr1.equals(sp1))

if(myStr1.equalsIgnoreCase(sp1))

if(myStr1 == sp1)
// Shallow Comparison (just compares the references)
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 108
Strings Operations cont’d

• The ‘+’ and ‘+=‘ operators were overloaded for class String
to be used in concatenation.

String str = myStr1 + sp2; // “Welcome to Java”


str += “ Programming”; // “Welcome to Java Programming”
str = str.concat(“ Language”); // “Welcome to Java Programming Language”

• Objects of class String are immutable


– you can’t modify the contents of a String object after construction.

• Concatenation Operations always return a new String


object that holds the result of the concatenation. The
original objects remain unchanged.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 109
String Pool

• String objects that are created without using the


“new” keyword are said to belong to the “String
Pool”.
Memory

“Hello”
String s1 = new String(“Hello”);
“Welcome”
String s2 = new String(“Hello”); Heap

“Hello”
String strP1 = “Welcome” ;
String strP2 = “Welcome” ;

Stack s1 s2 strP1 strP2

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 110
String Pool cont’d

• String objects in the pool have a special behavior:


– If we attempt to create a fresh String object with exactly the same
characters as an object that already exists in the pool (case
sensitive), then no new object will be created.

– Instead, the newly declared reference will point to the existing


object in the pool.

• Such behavior results in a better performance and saves


some heap memory.

• Remember: objects of class String are immutable.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 111
Lesson 6
Controlling Program Flow

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 112
Flow Control: Branching - if, else

• The if and else blocks are used for binary branching.


• Syntax:
if(boolean_expr)
{

… //true statements

}
[else]
{

… //false statements

}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 113
if, else Example

int grade = 48;


int grade = 48;
if(grade > 60)
System.out.println(“Pass”);
Grade>60 false else
? {
System.out.println(“Fail”);
}
true

print(“Pass”); print(“fail”);

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 114
Flow Control: Branching - switch

• The switch block is used for multiple branching.


• Syntax:

switch(myVariable){ • byte
case value1: • short

… • int
break; • char
case value2:
… • enum
… • String “Java 7”
break;
default:

}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 115
Flow Control: Iteration – while loop

• The while loop is used when the termination condition


occurs unexpectedly and is checked at the beginning.
• Syntax:

while (boolean_condition)
{



}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 116
while loop Example

int x = 0;
while (x<10) {
System.out.println(x);
int x = 0;
x++;
}
false
x<10?

true

print(x);
x++;

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 117
Flow Control: Iteration – do..while loop

• The do..while loop is used when the termination condition


occurs unexpectedly and is checked at the end.
• Syntax:
do
{



}
while(boolean_condition);

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 118
do..while loop Example

int x = 0;
do{
int x = 0; System.out.println(x);
x++;
} while (x<10);
print(x);
x++;

false
x<10?

true

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 119
Flow Control: Iteration – for loop

• The for loop is used when the number of iterations is


predetermined.
• Syntax:

for (initialization ; loop_condition ; step)


{



} for (int i=0 ; i<10 ; i++)
{


}

• You may use the break and continue keywords to skip


or terminate the iterations.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 120
Flow Control: Iteration – for loop

for (initialization ; loop_condition ; step)

initialization

Loop false
condition

true
statements

step

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 121
Flow Control: Iteration –Enhanced for loop
for (type identifier : iterable_expression)
{
// statements
}

• The first element:


– is an identifier of the same type as the
iterable_expression

• The second element:


– is an expression specifying a collection of objects or
values of the specified type.
• The enhanced loop is used when we want to
iterate over arrays or collections.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 122
Flow Control: Iteration –Enhanced for loop example

double[] samples = new double[50];

double average = 0.0;


for(int i=0;i<samples.length;i++)
{
average += samples[i];
}

average /= samples.length;

double average = 0.0;


for(double value : samples)
{
average += value;
}
average /= samples.length;

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 123
The break statement

• The break statement can be used in loops or


switch.
• It transfers control to the first statement after the
loop body or switch body.
......
while(age <= 65)
{
balance = payment * l;
if (balance >= 25000)
break;
}
......

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 124
The continue statement

• The continue statement can be used Only in


loops.
• Abandons the current loop iteration and jumps to
the next loop iteration.
......
for(int year=2000; year<= 2099; year++){
if (year % 100 == 0)
continue;
}
......

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 125
Comments in Java

• To comment a single line:


// write a comment here

• To comment multiple lines:


/* comment line 1
comment line 2
comment line 3 */

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 126
Printable Class Documentation (Javadoc)

• To write professional class, method, or variable


documentation:
/** javadoc line 1
javadoc line 2
javadoc line 3 */

– You can then produce the HTML output by typing the


following command at the command prompt:

javadoc myfile.java

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 127
Printable Class Documentation (Javadoc)

• The Javadoc tool parses tags within a Java doc


comment.

• These doc tags enable you to


– auto generate a complete, well-formatted API
documentation from your source code.

• The tags start with (@).

• A tag must start at the beginning of a line.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 128
Example of Javadoc

• Example 1:

/**
* @author khaled
*/

• Example 2:

/**
* @param args the command line arguments
*/

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 129
Lab Exercise

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 130
1. Command Line Calculator

• Create a simple non-GUI Application that carries out the


functionality of a basic calculator (addition, subtraction,
multiplication, and division).

• The program, for example, should be run by typing the


following at the command prompt:
java Calc 70 + 30

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 131
2. String Separator

• Create a non-GUI Application that accepts a well formed IP


Address in the form of a string and cuts it into separate parts
based on the dot delimiter.

• The program, for example, should be run by typing the


following at the command prompt:
java IPCutter 163.121.12.30

• The output should then be:


163
121
12
30
• Using: 1. split 2. StringTokenizer 3. substring & indexOf
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 132
• Write a program that print the following patterns:
using 2 loops:

* *
** **
*** ***
**** ****
• Bonus: Write the same program using 1 loop

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 133
Lesson 6
Modifiers-Access Specifiers
Essential Java Classes(Graphics-
Font-Color-Exception Classes)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 134
Lesson 6 Outline

❑ Modifiers and Access Specifiers

❑ Graphics, Color, and Font Class

❑ Exception Handling

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 135
Modifiers and Access Specifiers

• Modifiers and Access Specifiers are a set of keywords that


affect the way we work with features (classes, methods, and
variables).

• The following table illustrates these keywords and how they are
used.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 136
Modifiers and Access Specifiers cont’d
Top Level Free Floating
Keyword Methods Variables
Class Block
public Yes Yes Yes -
protected - Yes Yes -
(friendly)* Yes Yes Yes -
private - Yes Yes -

final Yes Yes Yes -


static - Yes Yes Yes
abstract Yes Yes - -
native - Yes - -
transient - - Yes -
volatile - - Yes -
synchronized - Yes - -

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 137
package1 package2

Public Class A Class F


w Class B o Class G
public x Aa public p Ff
protected y protected q
private z private r

Class C Class H

package3 package4
import package2.F;
import package1.A; import package1.A;

Class D Class I
Class E Class J
package1.A a Ff

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 138
package1 package2

Public Class A Class F


w o Class G
Class B
public x public p Ff
Aa
protected y protected q o, p, q
private z w, x, y private r

Class C Class H
w, x, y o, p, q
package3 package4
import package1.A; import package1.A;
class D extends package1.A
Class I
Class D Class E Class J
x y package1.A a Ff
x

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 139
Graphics Class

• The Graphics object is your means of communication with the


graphics display.

• You can use it to draw strings, basic shapes, and show images.

• You can also use it to specify the color and font you want.

• You can write a string using the following method:


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

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 140
Graphics Class cont’d

• Some basic shapes can be drawn using the following methods:


void drawLine(int x1, int y1, int x2, int y2);

void drawRect(int x, int y, int width, int height);

void fillRect(int x, int y, int width, int height);

void drawOval(int x, int y, int width, int height);

void fillOval(int x, int y, int width, int height);

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 141
Color Class

• In order to work with colors in your GUI application you use the
Color class.

• Commonly Used Constructor(s):


▪ Color(int r, int g, int b)
▪ Color(float r, float g, float b)

• Commonly Used Method(s):


▪ int getRed()
▪ int getGreen()
▪ int getBlue()
▪ Color darker()
▪ Color brighter()

• Objects of class Color are immutable.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 142
Color Class cont’d

• There are 13 predefined color objects in Java. They are all


declared as public static final objects in class Color
itself:
▪ Color.RED
▪ Color.ORANGE
▪ Color.PINK
▪ Color.YELLOW
▪ Color.GREEN
▪ Color.BLUE
▪ Color.CYAN
▪ Color.MAGENTA
▪ Color.GRAY
▪ Color.DARK_GRAY
▪ Color.LIGHT_GRAY
▪ Color.WHITE
▪ Color.BLACK

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 143
Color Class cont’d

• To specify a certain color to be used when drawing on the


applet’s Graphics object use the following method of class
Graphics:
▪ void setColor (Color c)

• To change the colors of the foregoround or background of any


Component, use the following method of class Component:
▪ void setForeground(Color c)
▪ Void setBackground(Color c)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 144
Font Class

• In order to create and specify fonts in your GUI application you


use the Font class.

• Commonly Used Constructor(s):


▪ Font(String name, int style, int size)

• To specify a certain font to be used when drawing on the


applet’s Graphics object use the following method of class
Graphics:
▪ void setFont (Font f)

• To change the font of any Component, use the following


method of class Component:
▪ void setFont(Font f)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 145
Font Class cont’d

• To obtain the list of basic fonts supported by all platforms you


can write the following line of code:

Toolkit t= Toolkit.getDefaultToolkit();
String[] s = t.getFontList();

• Objects of class Font are immutable.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 146
Exceptions

• An exception is an object that’s created when an


abnormal situation arises in your program during
runtime.

• Example:
– attempting to open a file that does not exist, or
– attempting to write in a file that the OS has marked as
read only.
– attempting to use a reference whose value is null, or
– attempting to access an array element that is beyond
the actual size of the array.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 147
Exceptions cont’d

• The exception object has description about the


nature of the problem.

• The exception is said to be thrown when the


problem occurs

• The code receiving the exception object as a


parameter is said to catch it.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 148
How Does Java Handle Exceptions?

Exception
Object

Yes Handler No
for this
exception?

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 149
Exceptions cont’d

Throwable

Exception Error
e.g. Out of Memory
e.g. Stack Overflow

… … IOException RunTimeException

Checked Exceptions

… … NullPointerException

Unchecked Exceptions

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 150
Exception Handling

• In order to deal with an exception,

1. Catch the exception and handle it by include three


kinds of code blocks: try, catch, and finally.

2. Let the exception pass to the calling method by


declare the method to throw the same exception.

3. Catch the exception and throw a different exception.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 151
Handling Exceptions

1. Including three kinds of code blocks to handle


them: try, catch, and finally.
• The try block:
encloses the code that may throw one or more
exceptions.
• The catch block:
encloses code that handles exceptions of a particular
type that may be thrown in the associated try block.
• The finally block:
is used to write code that will always definitely be
executed before the method ends, whether the
exception occurs or not.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 152
Handling Exceptions

public class Test{


public void testMethod(){
MyClass m = new MyClass();
try{
...
m.myMethod(7); //a method that throws an exception
...
}
catch(SomeException ex){
//handle the exception here
ex.printStackTrace(); //print details of the exception
}
}
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 153
Handling Exceptions

• Moreover, you could also use a finally block:

public class Test{


public void testMethod(){
MyClass m = new MyClass();
try{
...
}
catch(XYZException ex){
//handle the exception here
}
finally{
//the code that will always be executed
}
}
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 154
Throwing Exceptions

2. declare the method to throw the same exception:

public class Test{


public void testMethod() throws XYZException
{
MyClass m = new MyClass();
m.myMethod(7);
}
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 155
Throwing an Exception

• Now let’s take a closer look at MyClass and readData


method to see how an exception is created and thrown:

public class MyClass{


public String readData() throws EOFException{
...
if(n < length)
throw new EOFException();
return s;
}
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 156
Considerations Regarding Exceptions

• If several method calls throw different exceptions,


– then you can do either of the following:
1. Write separate try-catch blocks for each method.

2. Put them all inside the same try block and then
write multiple catch blocks for it
(one catch for each exception type).

3. Put them all inside the same try block and then
just catch the parent of all exceptions: Exception.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 157
Considerations Regarding Exceptions

• If more than one catch block are written after each other,

– then you must take care not to handle a parent exception before a
child exception

– (i.e. a parent should not mask over a child).

– Anyway, the compiler will give an error if you attempt to do so.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 158
Example

try { ...... }
catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: “);
}
catch (IOException e) {
System.err.println("Caught IOException: “);
}

In Java 7:
try { ...... }
catch (FileNotFoundException | IOException e) {
System.err.println(“...................“);
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 159
Considerations Regarding Exceptions cont’d

• An exception is considered to be one of the parts of


a method’s signature. So, when you override a
method that throws a certain exception, you have to
take the following into consideration:
– You may throw the same exception.
– You may throw a subclass of the exception
– You may decide not to throw an exception at all
– You CAN’T throw any different exceptions other than the
exception(s) declared in the method that you are
attempting to override
• A try block may be followed directly by a finally
block.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 160
The try-with-resources “Java 7”

• The try-with-resources statement:


– is a try statement that declares one or more
resources.
• A resource:
– is an object that must be closed after the program is finished
with it.
– The try-with-resources statement ensures that each
resource is closed at the end of the statement.
– Any object that implements
java.lang.AutoCloseable, which includes all objects
which implement java.io.Closeable, can be used as
a resource.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 161
The try-with-resources example “Java 7”

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Example2 { public static void main (String[] args)
{
try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
{
String line;
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 162
Lab Exercise

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 163
1. List of Fonts on Applet

• Create an applet that displays the list of available fonts in the


underlying platform.

• Each font should be written in its own font.

• If you encounter any deprecated method|(s), follow the


compiler instructions to re-compile and detect which method is
deprecated. Afterwards, use the help (documentation) to see
the proper replacement for the deprecated method(s).

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 164
2. Drawing a Lamp on Applet

• Create an applet that makes use of the Graphics class


drawing methods.

• You may draw the following lamp:

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 165
Lesson 7

Interfaces

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 166
Interfaces

• In OOP, it is sometimes helpful to define what a


class must do but not how it will do it.
• An abstract method defines the signature for a
method but provides no implementation.
• A subclass must provide its own implementation of
each abstract method defined by its superclass.
• Thus, an abstract method specifies the interface to
the method but not the implementation.
• In Java, you can fully separate a class’ interface from
its implementation by using the keyword interface.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 167
Interfaces

• An interface is syntactically similar to an abstract class,


in that you can specify one or more methods that have no
body.
• Those methods must be implemented by a class in order
for their actions to be defined.
• An interface specifies what must be done, but not how to
do it.
• Once an interface is defined, any number of classes can
implement it.
• Also, one class can implement any number of interfaces.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 168
Example of Interfaces
MyInterface

computeArea()

implements implements

Shape Building

// common attributes // common attributes


// of Shape // of buildings

// common methods // common methods


// of Shape // of buildings
computeArea() computeArea()

extends extends extends extends

Circle Rectangle Apartment Villa

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 169
Interfaces

Here is a simplified general form of a traditional interface:


• Access specifier is either public or
Access specifier interface
not used (friendly)
name
{ • methods are declared using only their
ret-type method-name1(param- return type and signature.
list);
ret-type method-name2(param- • They are, essentially, abstract
list); methods and are implicitly public.
type var1 = value;
type var2 = value; • Variables declared in an interface are
:: not instance variables.
::
• Instead, they are implicitly public,
} final, and static and must be
initialized.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 170
Interfaces

Here is an example of an interface definition.

public interface Numbers


{
int getNext(); // return next number in series
void reset(); // restart
void setStart(int x); // set starting value
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 171
Implementing Interfaces

The general form of a class that includes the


implements clause looks like this:

Access Specifier class classname extends superclass implements interface {


// class-body
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 172
Implementing Interfaces
// Implement Numbers.
• Class ByTwos implements the
class ByTwos implements Numbers
{ Numbers interface
int start;
int val;
public ByTwos() {
start = 0; • Notice that the methods
val = 0; getNext( ), reset( ),
}
public int getNext() { and setStart( ) are declared
val += 2;
return val; using the public access specifier
}
public void reset() {
val = start;
}
public void setStart(int x)
{
start = x;
val = x;
}
}
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 173
Implementing Interfaces
public class Demo {
public static void main (String args[]) {
Implementing Interfaces
ByTwos ob = new ByTwos();
for (int i = 0; i < 5; i++) {
System.out.println("Next value is " + ob.getNext());
System.out.println("\n Resetting");
ob.reset();
for (int i = 0; i < 5; i++)
System.out.println("Next value is " + ob.getNext());
System.out.println("\n Starting at 100");
ob.setStart(100);
for (int i = 0; i < 5; i++)
System.out.println("Next value is " + ob.getNext());
} }

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 174
Implementing Interfaces
// Implement Numbers.
class ByThrees implements • Class ByThrees provides
Numbers
{
another implementation of the
int start; Numbers interface
int val;
public ByThrees() {
start = 0;
val = 0; • Notice that the methods
} getNext( ), reset( ), and setStart(
public int getNext() {
val += 3; return val; ) are declared using the public
}
public void reset() { access specifier
val = start;
}
public void setStart (int x)
{
start = x;
val = x;
}
}
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 175
Using interface reference

class Demo2
{
public static void main (String args[])
{
ByTwos twoOb = new ByTwos();
ByThrees threeOb = new ByThrees();
Numbers ob;
for(int i=0; i < 5; i++) {
ob = twoOb;
System.out.println("Next ByTwos value is " +
ob.getNext());
ob = threeOb;
System.out.println("Next ByThrees value is " +
ob.getNext());
}
JavaTM Education & Technology Services
} }
Copyright© Information Technology Institute http://jets.iti.gov.eg 176
General Consideration about interfaces

• Variables can be declared in an interface, but they are


implicitly public, static, and final.

• To define a set of shared constants, create an interface


that contains only these constants, without any methods.

• One interface can inherit another by use of the keyword


extends. The syntax is the same as for inheriting
classes.

• When a class implements an interface that inherits


another interface, it must provide implementations for all
methods required by the interface inheritance chain.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 177
Lesson 8

Multi-Threading

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 178
What is Thread?

• A Thread is
– A single sequential execution path in a program

– Used when we need to execute two or more program


segments concurrently (multithreading).

– Used in many applications:


• Games , animation , perform I/O

– Every program has at least two threads.

– Each thread has its own stack, priority & virtual set of
registers.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 179
What is Thread?

• Multiple threads do not mean that they execute in


parallel when you’re working in a single CPU.
– Some kind of scheduling algorithm is used to manage
the threads (e.g. Round Robin).

– The scheduling algorithm is JVM specific (i.e.


depending on the scheduling algorithm of the
underlying operating system)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 180
Threads

• several thread objects that are executing concurrently:


Main Thread

th1
Garbage Event Dispatcher
Collection Thread Thread
th2 run()

th3

run()

run()

Daemon Threads (System) User Created Threads


JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 181
Threads cont’d

• Threads that are ready for execution are put in the


ready queue.
– Only one thread is executing at a time, while the others
are waiting for their turn.

• The task that the thread carries out is written


inside the run() method.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 182
The Thread Class

▪ Class Thread
▪ start()
▪ run()
▪ sleep()
▪ suspend()*
▪ resume()*
▪ stop()*

▪ Class Object
▪ wait()
▪ notify()
▪ notifyAll()

* Deprecated Methods (may cause deadlocks in some situations)


JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 183
Working with Threads

• There are two ways to work with threads:


Thread
▪ Extending Class Thread:

1. Define a class that extends Thread.


start()
2. Override its run() method. run() { }

3. In main or any other method:

a. Create an object of the subclass. MyThread

b. Call method start().

run() {
…………
}
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 184
Working with Threads cont’d

public class MyThread extends Thread 1


{
public void run() 2 Thread
{
… //write the job here
}
} start()
run() { }
• in main() or in the init() method of an …
applet or any method:
MyThread
public void anyMethod()
{
MyThread th = new MyThread(); 3.a
th.start(); 3.b run() {
} …………
}
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 185
Working with Threads

• There are two ways to work with threads:


▪ Implementing Interface Runnable:

1. Define a class that implements Runnable.

2. Override its run() method .

3. In main or any other method:

a. Create an object of your class.

b. Create an object of class Thread by passing


your object to the constructor that requires a
parameter of type Runnable.

c. Call method start() on the Thread object.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 186
Working with Threads cont’d

class MyTask implements Runnable 1 Runnable


{
public void run() 2
{
void run();
… //write the job here
}
}
MyTask Thread
• in main() or in the init()
method or any method: void run(){
3 ……… Thread()
public void anyMethod() } Thread(Runnable r)
start()
{
run() { }
MyTask task = new MyTask(); a
Thread th = new Thread(task); b
th.start(); c
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 187
Extending Thread VS. Implementing Runnable

• Choosing between these two is a matter of taste.

• Implementing the Runnable interface:


– May take more work since we still:
• Declare a Thread object
• Call the Thread methods on this object
– Your class can still extend other class

• Extending the Thread class


– Easier to implement
– Your class can no longer extend any other class

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 188
Example: DateTimeApplet
public class DateTimeApp extends Applet implements Runnable{
Thread th;
public void init(){
th = new Thread(this);
th.start();
}
public void paint(Graphics g){
Date d = new Date();
g.drawString(d.toString(), 50, 100);
}
public void run(){
while(true){
try{
repaint();
Thread.sleep(1000); //you’ll need to catch an exception here
}catch(InterruptedException ie){ie.printStackTrace();}
}
}
}
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 189
Thread Life Cycle

Complete the task or stop()*


Running Dead
De-selected
yield()**

Selected by
schedule

Sleeping Waiting blocked

Ready

start()
* Deprecated function
** there is no guarantee that yield() method will put the current thread into ready state
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 190
Synchronization

• Race conditions occur when


– Multiple threads access the same object
(shared resource)

• Example:
Two threads want to
access the same file, one
thread reading from the
file while another thread
writes to the file.

They can be avoided by synchronizing the threads which


access the shared resource.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 191
Unsynchronized Example

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 192
Synchronized method

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 193
Lab Exercise

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 194
1. Date and Time Applet

•Create an applet that displays date and time on it.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 195
2. Text Banner Applet

•Create an applet that displays marquee string on it.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 196
3. Animation Ball Applet

•Create an applet that displays ball which moves


randomly on this applet.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 197
Lesson 9

Inner Classes

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 198
Inner Classes

• The Java programming language allows you to define a


class within another class.

– Such a class is called a nested class.

class OuterClass
{
...
class InnerClass
{
...
}
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 199
Why Use Inner Classes?

• There are several reasons for using inner


classes:

1. It is a way of logically grouping classes that are only


used in one place.

• If a class is useful to only one other class, then it is logical to


embed it in that class and keep the two together.

• Nesting such "helper classes" makes their package more


streamlined.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 200
Why Use Inner Classes?

• There are several reasons for using inner


classes:

2. It increases encapsulation.

• Consider two top-level classes, A and B, where B needs


access to private members of A. By hiding class B within
class A, A's members can be declared private and B can
access them.

• In addition, B itself can be hidden from the outside world.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 201
Why Use Inner Classes?

• There are several reasons for using inner


classes:

3. Nested classes can lead to more readable and


maintainable code.

• Nesting small classes within top-level classes places the code


closer to where it is used.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 202
Types of Inner Classes

• There are broadly four types of inner classes:

1. Normal Member Inner Class

2. Static Member Inner Class

3. Local Inner Class (inside method body)

4. Local Anonymous Inner Class

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 203
1. Normal Member Inner Class

public class OuterClass{


private int x ;
public void myMethod(){
MyInnerClass m = new MyInnerClass();
..
}

class MyInnerClass{
public void aMethod(){
//you can access private members of the outer class here
x = 3 ;
}
}
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 204
1. Normal Member Inner Class

• In order to create an object of the inner class you need to


use an object of the outer class.

• The following line of code could have been written inside


the method of the enclosing class:

MyInnerClass m = this.new MyInnerClass();

• The following line of code is used to create an object of


the inner class outside of the enclosing class:

OuterClass obj = new OuterClass() ;


OuterClass.MyInnerClass m = obj.new MyInnerClass();

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 205
1. Normal Member Inner Class

• An inner class can extend any class and/or implement any


interface.

• An inner class can assume any accessibility level:


• private, (friendly), protected, or public.

• An inner class can have an inner class inside it.

• When you compile the java file, two class files will be
produced:
▪ MyClass.class
▪ MyClass$MyInnerClass.class

• The inner class has an implicit reference to the outer class.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 206
1. Normal Member Inner Class

The inner class has an implicit reference to the outer class


public class MyClass{
private int x ;
public void myMethod(){
MyInnerClass m = new MyInnerClass();
}
class MyInnerClass{
int x ;
public void aMethod(){
x = 10 ; //x of the inner class
MyClass.this.x = 25 ; // x of the outer class
}
}
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 207
Example

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 208
2. Static Inner Class

• You know, The normal inner class has implicitly


a reference to the outer class that created it.
– If you don’t need a connection between them, then
you can make the inner class static.

• A static inner class means:


– You don’t need an outer-class object in order to create
an object of a static inner class.

– You can’t access an outer-class object from an object


of a static inner class.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 209
2. Static Inner Class

• Static Inner Class:

– is among the static members of the outer class.

– When you create an object of static inner class, you don’t need to
use an object of the outer class (remember: it’s static!).

– Since it is static, such inner class will only be able to access the
static members of the outer class.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 210
2. Static Inner Class (Example)

public class OuterClass{


int x ;
static int y;
public static class InnerClass{
public void aMethod(){
y = 10; // OK
x = 33; // wrong
}
}
}

OuterClass.InnerClass ic= new OuterClass.InnerClass();


JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 211
3. Local Inner Class

public class MyClass {


private int x ;
public void myMethod(final String str, final int a){
final int b = 5;
class MyLocalInnerClass{
public void aMethod(){
//you can access private members of the outer class
//and you can access final local variables of the method
}
}
MyLocalInnerClass myObj = new MyLocalInnerClass();
}
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 212
3. Local Inner Class

• The object of the local inner class can only be created


below the definition of the local inner class (within the
same method).

• The local inner class can access the member variables of


the outer class.

• It can also access the local variables of the enclosing


method if they are declared final.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 213
4. Anonymous Inner Class

public class MyClass extends Applet


{
int x ;
public void init()
{
Thread th = new Thread(new Runnable()
{
public void run()
{
..
}

});
th.start();
}
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 214
4. Anonymous Inner Class

• The whole point of using an anonymous inner class is to


implement an interface or extend a class and then
override one or more methods.

• Of course, it does not make sense to define new methods


in anonymous inner class; how will you invoke it?

• When you compile the java file, two class files will be
produced:
▪ MyClass.class

▪ MyClass$1.class

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 215
Lesson 10

Event Handling

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 216
Event Handling

• Event Delegation Model was introduced to Java


since JDK 1.1
• This model realizes the event handling process as
two roles:
– Event Source
– Event Listener.
• The Source:
– is the object that fired the event,
• The Listener:
– is the object that has the code to execute when notified
that the event has been fired.
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 217
Event Handling

Registration
Event Registration Event Listener
Registration Event Listener
Source Event Listener

• An Event Source may have one or more Event


Listeners.

• The advantage of this model is:


• The Event Object is only forwarded to the listeners that
have registered with the source.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 218
Event Handling

• When working with GUI, the source is usually one


of the GUI Components (e.g. Button, Checkbox,
…etc).

• The following piece of code is a simplified example


of the process:

Button b = new Button(“Ok”);


//Constructing a Component (Source)
MyListener myL = new MyListener(); //Constructing a Listener
b.addActionListener(myL); //Registering Listener with Source

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 219
Event Handling

• Let’s look at the signature of the registration


method:
void addActionListener(ActionListener l)

• In order for a listener to register with a source for a


certain event,
– it has to implement the proper interface that
corresponds to the designated event, which will enforce
a certain method to exist in the listener.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 220
Event Handling Example

1. Write the listener code:


class MyListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// handle the event here
// (i.e. what you want to do
// when the Ok button is clicked)
}
}

2. Create the source, and register the listener with it:


public class MyApplet extends Applet{
public void init(){
Button b = new Button(“Ok”);
MyListener myL = new MyListener();
b.addActionListener(myL);
}
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 221
Event Dispatching Thread

Registration
Button
Action
ActionListener
Event

Action
Event

Event Queue
JVM

Action Registration
Event Button ActionListener

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 222
Event Dispatching Thread
• When examining the previous button example:
▪ The button (source) is created.
▪ The listener is registered with the button,
▪ The user clicks on the Ok button.
▪ An ActionEvent object is created and placed on the event
queue.
▪ The Event Dispatching Thread processes the events in
the queue.
▪ The Event Dispatching Thread checks with the button to see if
any listeners have registered themselves.
▪ The Event Dispatcher then invokes the
actionPerformed(..) method, and passes the ActionEvent
object itself to the method.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 223
Event Handling Example
public class ButtonApplet extends Applet{
int x;
Button b;
public void init(){
b = new Button(“Click Me”);
b.addActionListener(new MyButtonListener());
add(b);
}
public void paint(Graphics g){
g.drawString(“Click Count is:“ + x, 50, 200);
}
class MyButtonListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
x++ ;
repaint() ;
}
}}
JavaTM Education & Technology Services
Copyright© Information Technology Institute http://jets.iti.gov.eg 224
Event Handling Example

public class ButtonApplet extends Applet{


int x;
Button b;
public void init(){
b = new Button(“Click Me”);
b.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent ev){
x++ ;
repaint() ;
}
});
add(b);
}
public void paint(Graphics g){
g.drawString(“Click Count is:“ + x, 50, 200);
}
}

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 225
Event Class Hierarchy
EventObject

AWTEvent

ActionEvent AdjustmentEvent ComponentEvent ItemEvent TextEvent

ContainerEvent PaintEvent InputEvent FocusEvent WindowEvent

KeyEvent MouseEvent

MouseWheelEvent

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 226
Events Classes and Listener Interfaces

Listener
Event Method(s)
Interface(s)
ActionEvent ActionListener actionPerformed (ActionEvent e)

AdjustmentEvent AdjustmentListener adjustmentValueChanged (AdjustmentEvent e)

componentHidden (ComponentEvent e)
componentShown (ComponentEvent e)
ComponentEvent ComponentListener
componentMoved (ComponentEvent e)
componentResized (ComponentEvent e)

ItemEvent ItemListener itemStateChanged (ItemEvent e)

TextEvent TextListener textValueChanged (TextEvent e)

componentAdded (ComponentEvent e)
ContainerEvent ContainerListener
componentRemoved (ComponentEvent e)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 227
Events Classes and Listener Interfaces

Listener
Event Method(s)
Interface(s)
focusGained (FocusEvent e)
FocusEvent FocusListener
focusLost (FocusEvent e)

windowClosed (WindowEvent e)
windowClosing (WindowEvent e)
windowOpened (WindowEvent e)
WindowEvent WindowListener windowActivated (WindowEvent e)
windowDeactivated (WindowEvent e)
windowIconified (WindowEvent e)
windowDeiconfied (WindowEvent e)

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 228
Events Classes and Listener Interfaces

Event Listener Interface(s) Method(s)

keyPressed (KeyEvent e)
KeyEvent KeyListener keyReleased (KeyEvent e)
keyTyped (KeyEvent e)

mousePressed (MouseEvent e)
mouseReleased (MouseEvent e)
MouseListener mouseClicked (MouseEvent e)
mouseEntered (MouseEvent e)
MouseEvent mouseExited (MouseEvent e)

mouseMoved (MouseEvent e)
MouseMotionListener
mouseDragged (MouseEvent e)

MouseWheel
MouseWheelListener mouseWheelMoved (MouseWheelEvent e)
Event

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 229
Adapters

• When working with listener interfaces that have more than


one method,

– it is a tedious task to override all the methods of the interface when


we only need to implement one of them.

• Therefore, for each listener interface with multiple


methods,

– there is a special Adapter class that has implemented the interface


and overridden all the methods with empty bodies.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 230
Adapters

• You then only need to extend the corresponding Adapter


class instead of implementing the interface, then overriding
the required methods only.

• For example, the WindowListener interface has a


corresponding WindowAdapter class.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 231
Lab Exercise

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 232
1. Button Count Applet

• Create an applet that has two buttons one to


increment the counter value and one to decrement
this value.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 233
2. Moving Text Using Keyboard

• Create an applet that displays string which user


can move it using arrow keys.

 →

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 234
3. Play and Pause Animation

• Create an applet that has two buttons one to let


ball star moving randomly and one to pause this
ball moving.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 235
4. Drag Ball Applet

• Create an applet that draws an oval which the


user can drag around the applet.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 236
5. Draw Single Line Applet

• Create an applet that allows the user to draw


one line by dragging the mouse on the applet.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 237
6. Draw Multiple Lines Applet

• Modify the previous exercise to allow the user to


draw multiple lines on the applet.

• Store the drawn lines in an array to be able to


redraw them again when the applet is repainted.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 238
7. Draw Multiple Lines – using Vector

•In the pervious exercise the user can only draw a


certain number of lines because of the fixed array
size.
•Modify the pervious exercise, by storing the lines in a
Vector, to allow an unlimited number.

JavaTM Education & Technology Services


Copyright© Information Technology Institute http://jets.iti.gov.eg 239

You might also like