M251 - Meetings 3-4-5-7-8-9-10-11-13&14
M251 - Meetings 3-4-5-7-8-9-10-11-13&14
M251 - Meetings 3-4-5-7-8-9-10-11-13&14
1
Objectives
Visibility Modifiers
To define private data fields with appropriate get and set methods.
2
O.O. Programming Concepts
Object-oriented programming (OOP) involves programming
using objects.
An object represents an entity in the real world that can be
distinctly identified. An object is an instance of a class.
For example, a student, a desk, a circle, a button, and even a
loan can all be viewed as objects. An object has a unique
identity, state, and behaviors.
The state of an object consists of a set of data fields (also
known as properties, attributes) with their current values.
The behavior of an object is defined by a set of methods.
3
Objects
Data Fields:
radius is _______
Methods:
getArea
5
An Example of Classes
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field
/** Zero-argument-Construct */
Circle() {
}
Constructors
/** One-argument Construct */
Circle(double newRadius) {
radius = newRadius;
}
//One-argument constructor
Circle(double newRadius) {
radius = newRadius;
}
9
.Constructors, cont
11
Declaring Object Reference
Variables
Invoking constructor
Data_Type Object_name Create a new
memory to initialize the
location for the created object
object
13
Accessing Class Members
(2) Using a simple name a name without a reference and dot notation,
e.g., getArea(); or radius = 1;
•14
animation
;yourCircle.radius = 100
15
animation
Create a
circle
16
animation
;yourCircle.radius = 100
: Circle
radius: 5.0
Assign object
reference to myCircle
17
animation
yourCircle no value
Declare yourCircle
18
animation
yourCircle.radius = 100;
yourCircle no value
: Circle
Create a new
radius: 1.0
Circle object
19
animation
radius: 5.0
yourCircle.radius = 100;
Assign object
reference to : Circle
yourCircle
radius: 1.0
20
animation
: Circle
Change radius in
yourCircle radius: 100.0
21
Caution
22
Data fields (Attributes)
The data fields can be of primitive types as any
other variables or reference types.
23
The null Value
24
Default Value for a Data Field
26
Example
Java assigns default values for attributes (by
default constructor), but NO default valuee
to local variables inside a method.
public class Test {
} 27
Differences between Variables of
Primitive Data Types and Object (Reference) Types
radius = 1
28
Copying Variables of Primitive Data
Types and Object (reference) Types
Primitive type assignment: i = j Object type assignment: c1 = c2
i 1 i 2 c1 c2 c1
c2
j 2 j 2
29
Garbage Collection
31
Data fields and Methods
Data fields can be classified into:
32
Instance Variables and Instance
Methods
Instance variables belong to a specific
instance (object). For example:
Circle myCircle = new Circle(5.0);
myCircle : Circle
radius: 5.0
Static constants are final variables shared by all the instances of the class,
You can access class variables and methods using class name.
34
Static Variable Example
Public class VariableDemo {
static int count=0;
36
Scope of Variables
37
Static methods (also known as a class methods) and
their uses
• Static
methods carry out general functions not associated with objects.
• Class Variable can be accessed directly in a class method, inan instance
method and in constructor.
– For example, the static method max within the class Math returns the greater
of its two arguments. The method header for one version of max looks like this:
public static double max (double a, double b)
{
if (a>b)
return a;
else
return b;
}
To access it: double val = Math.max(Math.PI, 4.0);
The main method is a static method.
38
Static Variables, Constants,
.and Methods, cont
39
Packages
A package is used to associate a number of classes that are closely
related to one another.
– if classes form a cohesive group, they should be marked as belonging to the same
package.
– For example, Java has a collection of classes named java.math.
– If we wanted to make use of this package, we would add a statement to
advise the Java system of this, by adding an import statement at the
beginning of our program. In this case we would say:
40
Access modifiers
There are three keywords associated with controlling levels of access to class members
in Java: public, protected & private. These are known as access modifiers.
Example:
41
Visibility Modifiers and
Accessor/Mutator Methods
By default, the class, variable, or method can be
accessed by any class in the same package.
public
The class, data, or method is visible to any class in any package using
qualified name (a reference and a dot notation).
private
The data or methods can be accessed only by the declaring class. The get and
set methods are used to read and modify private properties.
Protected
The data or methods are accessible inside class where they are declared, and
inside subclasses. All class in the same package can access protected member
using qualified name.
No modifier: default members can be accessed by all classes in the same
package using qualified name
42
The private modifier restricts access to within a class, the default modifier
restricts access to within a package, and the public modifier enables unrestricted
access.
43
The default modifier on a class restricts access to within a package, and the
public modifier enables unrestricted access.
44
NOTE
45
Why Data Fields Should Be private?
To protect data.
46
Getter and setter methods
Usually you need to declare a setter and a getter methods for each
instance variable.
For example, inside the class Circle, we need to add another method:
public double getRadius(){
return radius}
In the main method: we invoke getRadius() using object name.
47
Setter Method
CircleWithPrivateDataFields
TestCircleWithPrivateDataFields Run
49
M251 Meeting 4:
Thinking in Objects and ArrayList
class
Edited by: Dr. Bayan Abu Shawar
AOU-Jordan
50
Objectives
Passing objects to methods
Using this keyword
Methods overloading
Array of Objects
.To apply Encapsulation and class abstraction
ArrayList
Stack and Queue Data Structures
51
Passing Objects to Methods
TestPassObject Run
52
Passing Objects to methods example
{ public class TestPassObject
{ )(public static void main
;Circle c1 = new Circle(1)
.Print areas for radius 1, 2, 3, 4, and 5 //
;int n = 5
;printAreas(c1, n)
+ " System.out.println("\n" + "Radius is
;))(c1.getRadius
;System.out.println("n is " + n)
}
{ public static void printAreas( Circle a, int times)
;System.out.println("Radius \t\tArea")
{ while (times >= 1)
+ "System.out.println(a.getRadius() + "\t\t
;))(a.getArea
;a.setRadius(a.getRadius() + 1)
} ;--times
}
End Class //}
53
The keyword this
55
Calling Overloaded Constructor
57
Array of Objects
;Circle[] circleArray = new Circle[10]
The above statement creates the array which can hold
.references to ten Circle objects
It doesn't create the circle objects themselves. They have to
be created separately using the constructor of the
.Student class
The Circle objects have to be instantiated using the constructor of the Circle
class and their references should be assigned to the array elements in the
following way.
for(int i=0; i<circleArray.length; i++)
circleArray[i] = new circle();
//Invoking methods
double x = circleArray[0].getRadius();
59
Class Abstraction and Encapsulation
Class abstraction means to separate class implementation
.from the use of the class
The creator of the class provides a description of the class
.and let the user know how the class can be used
The user of the class does not need to know how the class
is implemented. The detail of implementation is encapsulated
.and hidden from the user
60
Object-Oriented Thinking
You studied before the fundamental
programming techniques for problem solving
.using loops, methods, and arrays
The studies of these techniques lay a solid
foundation for object-oriented programming. All
the previous code was written in the main
method so you could not re-use it in other
.projects
Classes provide more flexibility and
.modularity for building reusable software
61
Example: Defining Classes and Creating
Objects
TV
channel: int The current channel (1 to 120) of this TV.
volumeLevel: int The current volume level (1 to 7) of this TV.
on: boolean Indicates whether this TV is on/off.
62
Class TV
{ public class TV
public void setVolume(int
newVolumeLevel) { Attributes//
if (on && newVolumeLevel
int channel = 1; // Default channel >= is
1 &&
1
newVolumeLevel <= 7)
int volumeLevel = 1;volumeLevel
// Default =volume level is 1
newVolumeLevel;
boolean on} = false; // By default TV is off
:Similarities
Both can store a number of references (elements).
69
Generic Type
ArrayList is known as a generic class with a generic
.>type E, e.g., ArrayList<E
Note that : you need to use Wrapper Classes instead of primitive Data type
.inside the angle brackets <…> or any Object-Type
:Example 1
;)(>ArrayList <Integer> list2 = new ArrayList <Integer
for(String x : cityList)
;system.out.println( x)
DistinctNumbers Run
78
Array Lists from/to Arrays
It is also possible to create an equivalent list from a array
.list using the static method Arrays.asList(array)
;System.out.println(list)
79
Creating an array of objects from
an ArrayList
It is possible to start with a List and create
an equivalent array containing the same
elements in the same order by using:
.toArray() method
String[ ] array1 = new String[list.size()];
list.toArray(array1);
Collections Utility Class
;System.out.println(Collections.max(l1))
;System.out.println(Collections.min(l1))
84
Shuffling an Array List
The elements in a list can be put into
random order by passing the list as an
argument to the shuffle() method. For
,example
;Integer[] array = {3, 5, 95, 4, 15, 34, 3, 6, 5}
;Collections.shuffle(list)
;System.out.println(list)
85
Exercise(3)
Create an array of Integer with values: .1
90,70,88,66,94,93
Create an Integer list name it list1 to have the .2
.same values as integer array
.Print the list1 .3
Print list1 in reverse order .4
Print out the maximum and minimum number in .5
list1
.Print out the summation of list1 .6
;Rearrange list1 in random order .7
Exercise(3)-Solution
1-2//
;Integer[] a1 = {90,70,88,66,94,93}
;ArrayList<Integer> list1 = new ArrayList<Integer>(Arrays.asList(a1))
3 //
;System.out.println(list1)
4//
;Collections.reverse(list1)
;System.out.println(list1)
5//
;System.out.println("Maximum is " + Collections.max(list1))
;System.out.println("Minimum is "+ Collections.min(list1))
6//
;double s =0
for(Integer y : list1)
;s = s+ y
;System.out.println(“List summation = "+ s)
7//
;Collections.shuffle(list1)
;System.out.println(list1)
Stack Data Structure
88
Example
89
Designing the StackOfIntegers Class
Push()
Pop()
90
Stack Applications
91
Stack Animation
https://liveexample.pearsoncmg.com/dsanimation/StackeBook.html
92
The MyStack Classes
Implement MyStack class as shown in class diagram
below. The stack will be represented as an ArrayList of
.Integers
MyStack
MyStack
-list: ArrayList A list to store elements.
+isEmpty(): boolean Returns true if this stack is empty.
+getSize(): int Returns the number of elements in this stack.
+peek(): Object Returns the top element in this stack.
+pop(): Object Returns and removes the top element in this stack.
+push(o: Object): void Adds a new element to the top of this stack.
+search(o: Object): int Returns the position of the first element in the stack from
the top that matches the specified element.
93
Class stack as an ArrayList
import java.util.ArrayList;
;System.out.println(y.pop())
;System.out.println(y.pop())
}
}
The Queue Data Structure
Waiting lists
Access to shared resources (e.g., printer)
Multiprogramming
Exercise (4)
103
Motivations
Suppose you will define classes to model
circles, rectangles, and triangles. These
classes have many common features.
What is the best way to design these
classes so to avoid redundancy? The
.answer is to use inheritance
104
Objectives
Relationships between classes
Inheritance Relationship
To define a subclass from a superclass.
To invoke the superclass’s constructors and methods using the
super keyword.
To override instance methods in the subclass.
To distinguish differences between overriding and overloading.
To explore the toString() method in the Object class.
To explore the equals() method in the Object class.
To discover polymorphism and dynamic binding.
To describe casting and explain why explicit down casting is
necessary.
105
Inheritance Relationship between
classes
There are different types of relationships
:between
has-a relationship( classes
Composition
Aggregation
Inheritance is-a relationship(
Aggregating Aggregated
Class Class
107
Composition Relationships
. Composition is a stronger form of aggregation
,If the aggregating (composing) object is deleted
108
Class Representation
An aggregation relationship is usually
represented as a data field in the aggregating
:class. follows
public class Name { public class Student { public class Address {
... private Name name; ...
} private Address address; }
...
}
Composition Aggregation
1 1 1..3 1
Name Student Address 109
Aggregation or Composition
110
Inheritance
SuperClass
Subclass
Subclass
Inheritance
UML notation
The Class Heirarchy
:There are two types in Java hierarchy
1. user-defined
2. Java class library.
public class Subclass-name extends Superclass-name
{
//methods and fields
}
Superclasses and Subclasses
SimpleGeometricObject
-color: String The color of the object (default: white).
-filled: boolean Indicates whether the object is filled with a color (default: false).
-dateCreated: java.util.Date The date when the object was created.
+GeometricObject() Creates a GeometricObject.
+GeometricObject(color: String, Creates a GeometricObject with the specified color and filled
filled: boolean) values.
+getColor(): String
+setColor(color: String): void
Returns the color.
Sets a new color.
SimpleGeometricObject
+isFilled(): boolean Returns the filled property.
+setFilled(filled: boolean): void Sets a new filled property. Circle
+getDateCreated(): java.util.Date Returns the dateCreated.
+toString(): String Returns a string representation of this object.
Rectangle
Circle Rectangle
-radius: double -width: double
+Circle() -height: double TestCircleR
+Circle(radius: double) +Rectangle() ectangle
+Circle(radius: double, color: String, +Rectangle(width: double, height: double)
filled: boolean) +Rectangle(width: double, height: double
+getRadius(): double color: String, filled: boolean)
+setRadius(radius: double): void +getWidth(): double
+getArea(): double +setWidth(width: double): void Run
+getPerimeter(): double +getHeight(): double
+getDiameter(): double +setHeight(height: double): void
+printCircle(): void +getArea(): double
+getPerimeter(): double
118
Example: SimpleGeometricObject Class
import java.util.Date;
public class SimpleGeometricObject { public boolean isFilled()
private String color = "white"; { return filled; }
private boolean filled;
private Date dateCreated; public void setFilled(boolean
filled) { this.filled = filled;}
public SimpleGeometricObject() {
dateCreated = new java.util.Date(); public Date getDateCreated()
} {
public SimpleGeometricObject(String return dateCreated;
color, boolean filled) { }
dateCreated = new Date();
this.color = color; public String toString() {
this.filled = filled; return "created on " +
} dateCreated +
public String getColor() { return "\ncolor: " + color +
color; } " and filled: " +
filled;
public void setColor(String color) }
{this.color = color;}
}
Continue: Circle class
public class Circle extends
SimpleGeometricObject { public double getArea()
private double radius; { return radius * radius *
Math.PI; }
public Circle() { }
public double getDiameter()
public Circle(double radius)
{ return 2 * radius; }
{ this.radius = radius; }
public double getPerimeter()
public Circle(double radius, String
{ return 2 * radius * Math.PI; }
color, boolean filled)
{ this.radius = radius;
public void printCircle() {
setColor(color);
System.out.println("The circle
setFilled(filled); }
is created " + getDateCreated()
public double getRadius() + " and the radius is " +
{ return radius; } radius);
public void setRadius(double radius) }
{ this.radius = radius; } }
Continue: Class Rectangle
public class Rectangle extends
SimpleGeometricObject {
public void setWidth(double width)
private double width, height;
{ this.width = width; }
public Rectangle() { } public double getHeight()
123
Superclass’s Constructor Is Always
Invoked
A constructor may invoke an overloaded constructor or
its superclass’s constructor. If none of them is invoked
explicitly, the compiler puts super() as the first
statement in the constructor. For example,
public A() { public A() {
is equivalent to
} super();
}
124
Using the Keyword super
125
Defining a Subclass
A subclass inherits from a superclass. A
:subclass can also
Have new properties
Have new methods
Override the methods of the superclass
126
Calling Superclass Methods
You could rewrite the printCircle() method in the
Circle class as follows:
127
Overriding Methods in the
Superclass
A subclass inherits methods from a superclass. Sometimes it
is necessary for the subclass to modify the implementation of
a method defined in the superclass. This is referred to as
method overriding.
public class Circle extends GeometricObject {
// Other methods are omitted
128
NOTE
An instance method can be overridden
only if it is accessible.
Thus a private method cannot be
overridden, because it is not accessible
outside its own class.
If a method defined in a subclass is
private in its superclass, the two methods
are completely unrelated. 129
NOTE
class B { class B {
public void p(double i) { public void p(double i) {
System.out.println(i * 2); System.out.println(i * 2);
} }
} }
132
Overriding
{public class Parent public class Test{
public void method(int i) public static void main()
};System.out.println(“parent:”+i) { { Parent k = new child();
} Parent P = new Parent();
{ public class child extends Parent Child c = new child();
public void method(int i) c.metod(1);
};System.out.println(“child:”+i*2) { p.method(2);
} k.method(3);
}
}
134
Accessibility Summary
public
protected -
default - -
private - - -
135
Visibility Modifiers
package p1;
public class C1 { public class C2 {
public int x; C1 o = new C1();
protected int y; can access o.x;
int z; can access o.y;
private int u; can access o.z;
cannot access o.u;
protected void m() {
} can invoke o.m();
} }
package p2;
136
A Subclass Cannot Weaken the
Accessibility
A subclass may override a protected
method in its superclass and change its
visibility to public.
However, a subclass cannot weaken the
accessibility of a method defined in the
superclass. For example, if a method is
defined as public in the superclass, it must
be defined as public in the subclass.
137
The final Modifier
The final class cannot be extended
:(inherited)
{ final class Math
...
}
138
The Object Class and Its Methods
Every class in Java is descended from the
java.lang.Object class. If no inheritance is
specified when a class is defined, the
.superclass of the class is Object
139
The toString() method in Object
The toString() method returns a string representation of the
object. The default implementation returns a string consisting
of a class name of which the object is an instance, the at sign
.(@), and a number representing this object
141
NOTE
The == comparison operator is used for comparing
two primitive data type values or for determining
whether two objects have the same references.
The equals method is intended to test whether two
objects have the same contents, provided that the
method is modified in the defining class of the
objects.
The == operator is stronger than the equals
method, in that the == operator checks whether the
two reference variables refer to the same object.
142
The instanceof Operator
143
Exercise
Cn Cn-1 ..... C2 C1
149
Generic Programming
public class PolymorphismDemo {
public static void main(String[] args) {
m(new GraduateStudent()); Polymorphism allows methods to be
m(new Student());
m(new Person()); used generically for a wide range of
}
m(new Object()); object arguments. This is known as
.generic programming
public static void m(Object x) {
System.out.println(x.toString()); If a method’s parameter type is a
}
} superclass (e.g., Object), you may
class GraduateStudent extends Student {
pass an object to this method of any of
} the parameter’s subclasses (e.g.,
class Student extends Person { .Student or String)
public String toString() {
return "Student"; When an object (e.g., a Student
}
} object or a String object) is used in the
method, the particular implementation
class Person extends Object {
public String toString() { of the method of the object that is
return "Person"; invoked (e.g., toString) is determined
}
} .dynamically
150
Casting Objects
You have already used the casting operator to convert
variables of one primitive type to another. Casting can
also be used to convert an object of one class type to
.another within an inheritance hierarchy
In the preceding section, the statement
m(new Student());
Orange x = (Orange)Fruit;
153
TIP
To help understand casting, you may also
consider the analogy of fruit, apple, and
orange with the Fruit class as the
superclass for Apple and Orange. An
apple is a fruit, so you can always safely
assign an instance of Apple to a variable
.for Fruit
However, a fruit is not necessarily an
apple, so you have to use explicit casting
to assign an instance of Fruit to a variable
.of Apple
154
Meeting 7: Abstract Classes
and Interfaces.
156
Abstract method in Abstract class
An abstract class defines a common set of methods and a
common set of instance variables for its subclasses. An
abstract class should contain at least one abstract method.
An abstract method: a method header defined in a class
without implementation.
One cannot create instances of abstract classes.
Abstract classes are specified in the class header using the
Java keyword abstract.
GeometricObject
Circle
Rectangle
TestGeometricObject
Run
161
Example: SimpleGeometricObject Class
import java.util.Date;
public class GeometricObject { public boolean isFilled()
private String color = "white"; { return filled; }
private boolean filled;
private Date dateCreated; public void setFilled(boolean filled)
{ this.filled = filled;}
protected GeometricObject() {
dateCreated = new java.util.Date(); public Date getDateCreated()
} {
protected GeometricObject(String return dateCreated;
color, boolean filled) { }
dateCreated = new Date();
this.color = color; public String toString() {
this.filled = filled; return "created on " +
} dateCreated +
public String getColor() { return "\ncolor: " + color +
" and filled: " +
color; }
filled;
}
public void setColor(String color)
{this.color = color;}
public abstract double getArea();
public abstract double getPremieter();
}
Continue: Circle class
public class Circle extends
GeometricObject { public double getDiameter()
private double radius; { return 2 * radius; }
{ this.width = width; } }
public double getHeight()
{ return height; }
Abstract class without abstract method
165
superclass of abstract class may be
concrete
166
Concrete method overridden to be
abstract
A subclass can override a method from its
superclass to define it abstract. This is rare,
but useful when the implementation of the
method in the superclass becomes invalid in
the subclass. In this case, the subclass must be
defined abstract.
167
Abstract class as type
You cannot create an instance from an abstract class
using the new operator, but an abstract class can be
used as a data type. Therefore, the following
statement, which creates an array whose elements
are of GeometricObject type, is correct.
GeometricObject[] geo = new GeometricObject[10];
168
Continue
We can then store references to objects of any subclass of
.GeometricObjects in the array, e.g
;geo[0] = new Circle(5)
;geo[1] = new Rectangle(3,4)
What is an interface?
Why is an interface useful?
How do you define an interface?
How do you use an interface?
170
What is an interface?
? Why is an interface useful
An interface is a classlike construct that
contains only constants and abstract methods.
171
Interfaces
176
?How to use an Itnerface
180
Example: The Comparable
Interface
// This interface is defined in
// java.lang package
package java.lang;
181
Example
1 System.out.println(new Integer(3).compareTo(new Integer(5)));
2 System.out.println("ABC".compareTo("ABE"));
3 java.util.Date date1 = new java.util.Date(2013, 1, 1);
4 java.util.Date date2 = new java.util.Date(2012, 1, 1);
5 System.out.println(date1.compareTo(date2));
182
The Comparable Interface
.This interface allows comparing or sorting objects
Any class that implements the Comparable interface must have a
met
.>< The type that the comparison will involve is added in
The compareTo method allows the class to define an appropriate
.measure of comparisonhod compareTo
Defining Classes to Implement
Comparable
184
ComparableRectangl Class
public class ComparableRectangle extends Rectangle implements
{ >Comparable<ComparableRectangle
public ComparableRectangle(double width, double height)
{ super(width, height); }
{ public int compareTo(ComparableRectangle o)
if (getArea() > o.getArea())
;return 1
else if (getArea() < o.getArea())
;return -1
else
} ;return 0
};)(getArea +
}
Multiple inheritance in Java is not
allowed
Java avoids multiple inheritance problems
.by the use of interfaces
Class can implement more than one
interface, and extend one class ONLY–
this gives an alternative to multiple
.inheritance
public class MonthlyEmployee
} { extends Employee implements Comparable, Serializable
Exercise
Interfaces vs. Abstract Classes
188
Interfaces vs. Abstract Classes
DIFFERENCES
:Interface
.An interface is not a class
All its methods are abstract
.Only constant data is allowed
An interface can be implemented by any number of unrelated classes, which declare
.this using the implements keyword. A class may implement any number of interfaces
:Abstract class
.An abstract class uses the keyword abstract in the class header
It normally has at least one abstract method, either defined within the class or
inherited from a superclass, and its abstract methods must be explicitly declared
.abstract
It can also have concrete methods (that is, it may be fully implemented)
.It can also have instance variables, unlike an interface
It can only constrain its own concrete subclasses, by requiring them to implement its
.abstract methods
All classes share a single root, the Object class, but there is no single root for
.interfaces
Interfaces vs. Abstract Classes
SIMILARITIES
.They can both place requirements on objects of other classes
Both can have abstract methods (although neither need have
.abstract methods)
You cannot create objects of an abstract class type or an interface
.type
You can create reference variables of either type. These are
normally used to refer to an object of a subclass of the abstract type
.or to an object of a class that implements the interface, respectively
Both can inherit: the abstract class from another class; the interface
.only from another interface
?Whether to use an interface or a class
Abstract classes and interfaces can both be used to model common
features.
191
Guidelines for Designing a Class
A class should describe a )Coherence(
single entity, and all the class operations
should logically fit together to support a
.coherent purpose
You can use a class for students, for
example, but you should not combine
students and staff in the same class, because
.students and staff have different entities
.Designing a Class, cont
A single entity with too many )Separating responsibilities(
responsibilities can be broken into several classes to
.separate responsibilities
The classes String, StringBuilder, and StringBuffer all deal
.with strings, for example, but have different responsibilities
.The String class deals with immutable strings
.The StringBuilder class is for creating mutable strings
The StringBuffer class is similar to StringBuilder except
that StringBuffer contains synchronized methods for
.updating strings
.Designing a Class, cont
Classes are designed for reuse. Users
can incorporate classes in many different
combinations, orders, and environments.
Therefore, you should design a class that
imposes no restrictions on what or when
the user can do with it. To do this follow
:the below instructions
.Designing a Class, cont
Design the properties (attributes) to ensure that the user can set
,properties in any order, with any combination of values
.Design methods to function independently of their order of occurrence
.Provide a public no-arg constructor
override the equals() method and the toString() method defined in
.the Object class whenever possible
.Follow standard Java programming style and naming conventions
.Choose informative names for classes, data fields, and methods
Always place the data declaration before the constructor, and place
.constructors before methods
Always provide a constructor and initialize variables to avoid
.programming errors
Using Visibility Modifiers
Each class can present two contracts – one for the users
.of the class and one for the extenders of the class
Make the fields private and accessor methods public if
.they are intended for the users of the class
Make the fields or method protected if they are intended
.for extenders of the class
The contract for the extenders encompasses the
.contract for the users
The extended class may increase the visibility of an
instance method from protected to public, or change its
implementation, but you should never change the
.implementation in a way that violates that contract
.Using Visibility Modifiers, cont
A class should use the private modifier to hide its
.data from direct access by clients
You can use get methods and set methods to provide
users with access to the private data, but only to private
.data you want the user to see or to modify
A class should also hide methods not intended for
client use. In this case the method is declared as
private and only used by another method inside the
.class. This is know as helper method
Using the static Modifier
200
Objectives
Introduction .1
Input and output streams .2
Reading text input .3
Writing text output to a file .4
Reading from a Web .5
Exceptions .6
Declaring and handling exceptions .7
201
Introduction
:In this meeting, we aim to study
Error Handling
We show how to deal with error conditions in a Java program, by
;means of exceptions or otherwise
202
Input-Output Streams
.Java relies on the concept of a stream for providing its input/output facilities
A stream is essentially a sequence of bytes, representing a flow of
.data from a source to a destination
.All the streams provided in Java can be found in the java.io package
;*.Any program that uses streams needs to include the statement: import java.io
203
Reading text from the keyboard using
Scanner class
import java.util.*;
Import
java.util.* library that includes try{
the Scanner class
Scanner sc = new Scanner(System.in);
Step1: define a Scanner object, String s = sc.nextLine();
sc or any name. To take input from System.out.println(s);
the keyboard, use (System.in).
sc.close();
}
Step2: use the Scanner object
catch(FileNotFoundException e){
to get data.
System.out.println(e);
Step3: close the Scanner when }
finished using it!
204
Reading text from a File using
Scanner class
Import import java.util.*;
java.util.*; library that includes import java.io.*;
the Scanner class.
java.io.*; that includes File class.
try{
Step1.1: create a File object that File fr = new File(“C:/test.txt”);
points to your text file. Scanner sc = new Scanner(fr);
Step 1.2: define a Scanner object, String s = sc.nextLine();
sc or any name. To take input from
System.out.println(s);
the text file, use the file object you
created in Step1.1 sc.close();
}
Step2: use the Scanner object catch(FileNotFoundException e){
to get data. System.out.println(e);
}
Step3: close the Scanner when
finished using it! 205
Common Scanner Methods
:Input methods
s = sc.next() Returns next “token” (i.e. "word“).
s = sc.nextLine() Returns an entire input line as a String.
i = sc.nextInt() Returns next integer value.
d = sc.nextDouble() Returns next double value.
206
Writing text to a file using
PrintWriter class
import java.io.*;
Import
java.io.*; that includes File class.
try{
File fw = new File(“C:/test.txt”);
Step1.1: create a File object that
PrintWriter pr = new PrintWriter(fw);
points to your text file.
Step 1.2: define a PrintWriter pr.println(“Enjoy M251 module”);
object, pr or any name, which you pr.println(“Good Luck”);
can use it to write into the text file, pr.close();
use the file object you created in }
Step1.1 catch(FileNotFoundException e){
Step2: use the PrintWriter object System.out.println(e);
to write data. }
Step3: close the PrintWriter when Note: Any data in the test.txt file will
finished using it! be erased before writing the new
data using println method.
207
Exercise(1)
Write a Java code to write the following lines .1
into a new text file: luck.txt
Study well for the final exam
It will be an easy exam
Just study well and concentrate during the exam
Good luck.
Then write another Java code to print the .2
contents of luck.txt file, and to print the number
.of lines in the file
208
Solution 1.1
;"String name = "D:\luck.txt
;File fw = new File(name)
{try
;PrintWriter wr = new PrintWriter(fw)
;wr.println("Study well for the final exam")
;wr.println("It will be an easy exam")
;wr.println("Just study well and concentrate during the exam")
;wr.println("Good Luck")
;)(wr.close
}
catch(Exception e)
} ;System.out.println("Error: "+ e) {
209
Solution 1.2
;"String name = "D:\luck.txt
;File fr = new File(name)
{try
;Scanner readfrom = new Scanner(fr)
;String s; int count=0
while(readfrom.hasNextLine())
{
;++s = readfrom.nextLine(); count
;System.out.println(s)
}
;)(readfrom.close
;System.out.println(“Number of lines in the file is: ”+ count)
}
catch(Exception e)
} ;System.out.println("Error"+ e) {
210
Reading/Writing Objects
To make an object persistent, the state of an object
should be stored in a file. So you could write states of
objects in a file, or you could use data in stored file to
.create new objects
you need to access each attribute for reading or writing
using for example: objectName.getX() or
;)(objectName.setX
In order to print content of an ArrayList of Circls,
Rectangles, etc. You need to use for each and access
.each attribute using getter method
211
Exercise(2)
:Create a new class: Deal_Rectangles that has the following methods
Write a static method to fillRectangles() that take a list of objects as an
argument and fill it with rectangle objects.
Write a static Java method writeToFile() to write a list of rectangles into a
text file: “rectangles.txt“.
Write a static Java method readFromFile() to read content of
“rectangles.txt”, and return contents as a list.
Write a static Java method printArea() which takes the list returned from
redFromFile() method and print area of each rectangle in the list.
Create a list of recangles in main method, then invoke fillRectangles()
and writeToFile(), readFromFile().
214
{)(public static ArrayList<Rectangle> readFromFile
;)(>ArrayList<Rectangle> list = new ArrayList<Rectangle
Note that: you need to {use: try
;File f = new ): when
File("c:/rectangles.txt")
owhile(s.hasNext()
;Scanner
you want s = to read
new each
Scanner(f)
element
;double in w, the line and
h; String colorstore
it in a different variable.
{ while(s.hasNext())
owhile(s.hasNextLine() ):
;)(w = s.nextDouble(); h = s.nextDouble
when you need to read a
whole line ;)(color
as a =string,
s.next or
;list.add(newcount number of lines in a file
Rectangle(w,h,color))
as in the solution of
while// }
exercise(1.2), in this case
also while(s.hasNext();)(s.close): will
work. try// }
catch(Exception e){ System.out.println("there is an error: "+e); }
;return list
}
215
{public static void printArea(ArrayList<Rectangle> list)
for(Rectangle x : list)
;System.out.println(x.getArea())
}
end of class Deal_Rectangle//}
import java.util.*;
public class Meeting7_ex2 {
public static void main(String[] args) {
ArrayList<Rectangle> list, list1;
list = new ArrayList<Rectangle>();
Deal_Rectangles.create(list);
Deal_Rectangles.writeToFile(list);
list1 = Deal_Rectangles.readFromFile();
Writing_Rectangles.printArea(list1);
}
} 216
Exceptions
217
When to use Exception Handling
Java's Exception Handling can be used to deal with potentially serious or
.unpredictable error conditions
Examples of serious errors that could occur within a Java program are as
:follows
218
Example of: InputMismatchException
219
Exception Types
The Throwable class represents the ClassNotFoundException
most general class for describing
exceptions. ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Error VirtualMachineError
220
System Errors
Exceptions that should not be caught or declared
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Error VirtualMachineError
222
Runtime Exceptions
Exceptions that Need not be caught or declared
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
223
Unchecked Exceptions
Error, and RunTime Exception
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Unchecked
Error VirtualMachineError Exception: No
need to caught or
Many more classes declared.
224
Unchecked Exception
Exceptions that Need not be caught or declared
Unchecked Exceptions: reflects an error in programming.
The programmer has failed to take into account a problem which
was predictable and should have been treated. It could be treated
.using if-Statement or try-catch
:For example
ArrayIndexOutOfBoundsException occurs when a program tries to
access an array with an index outside the valid limits.
ArithmeticException arises when an illegal arithmetic condition
occurs, such as an attempt to divide an integer by zero.
NumberFormatException can be caused by an application expecting
to read a number of some sort, when the data does not have the
appropriate format.
NullPointerException happens when an application attempts to use
null in a case where an object is required: for example, invoking a
method on a null reference.
225
Checked Exceptions vs.
Unchecked Exceptions
226
Checked Exception
Checked Exceptions: meaning that the compiler forces the
programmer to check and deal with the exceptions. This could be
achieved using try-catch or throws. Checked exceptions relate to
problems that can be foreseen but cannot necessarily be detected
.before they occur
:For example
EOFException occurs when a program attempts to read past the
end of a file.
227
Exception Handling
:Exception handling works as illustrated below
228
Handling Checked Exception
229
Handling Checked Exception using
throws keyword
When declaring an exception in the
method header, you use the keyword
throws followed by the type of
.exception expected
Example1: If the method
unexpectedly came to the end of the
file when expecting to read more
data, then the method would
generate an exception of type public boolean checkFormat(String fileName)
.EOFException
throws EOFException, MalformedURLException
Example2: A method may be capable
of generating more than one type of {
checked exception. In this case you
//Code for method
.need to list all the possible types
}
Example3: If some or all of the
possible exception types in a list are
subclasses of a particular exception
class, it may be possible to shorten
the list. This works because
EOFException and
MalformedURLException are
.subclasses of IOException
230
Handling Checked Exception using try-
catch statements (Catching Exception)
To deal with an exception that has been thrown, we use a try-catch
.statement
.Each try should be followed by at least 1 catch
When this handler code is executed, the variable within the catch
clause will contain a reference to the exception object that has been
.thrown
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (Exceptionn exVar3) {
handler for exceptionn;
} 231
Example of Catching an Exception
public static void main(String[] args) { public static void main(String[] args) {
try{ try{
File myFile = new File("C:/test.txt"); File myFile = new File("C:/test.txt");
Scanner sc = new Scanner(myFile); Scanner sc = new Scanner(myFile);
String s = sc.nextLine(); String s = sc.nextLine();
System.out.println(s); System.out.println(s);
sc.close(); sc.close();
} }
catch(FileNotFoundException e){ catch(Exception e){
System.out.println(e); System.out.println(e);
} }
} }
233
Cautions When Using Exceptions
234
When to Throw Exceptions
An exception occurs in a method. If you want
the exception to be processed by its caller,
you should create an exception object and
.throw it
If you can handle the exception in the method
where it occurs, there is no need to throw it.
you can handle it using If-Statement, which is
.the case with Unchecked Exception
235
When to Use Exceptions
?When should you use the try-catch block in the code
o You should use it to deal with unexpected error conditions,
(checked Exceptions).
o Do not use it to deal with simple, expected situations.
if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");
{ try
;statements
}
{ catch(TheException ex)
;handling ex
}
{ finally
;finalStatements
238 }
animation
;Next statement
239
animation
;Next statement
240
animation
;Next statement
241
animation
;Next statement
242
animation
;Next statement
243
animation
;Next statement
244
animation
;Next statement
245
Meeting 9-10: JavaFX Basics
Application
Override the start(Stage) method
Stage, Scene, and Nodes
Stage
Scene
Button
MyJavaFX Run
MultipleStageDemo Run
249
Continue: Basic Structure of JavaFX
A JavaFx class must extend
javafx.application.Application and overrides the start
.method
;import javafx.application.Application
;import javafx.scene.Scene
;*.import javafx.scene.control
;import javafx.stage.Stage
Example(1)
{ public class MyJavaFX extends Application
Override // Override the start method in the Application@
{ public class public void start(Stage primaryStage)
Create a button and place it in the scene //
;Button btOK = new Button("OK")
;Scene scene = new Scene(btOK, 200, 250)
primaryStage.setTitle("MyJavaFX"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
The main method is only needed for the IDE with limited * JavaFX * **/
/* .support. Not needed for running from the command line
public static void main(String[] args) { launch(args); }
}
OutPut
Note that: The displayed button is always
centered in the scene and occupies the
.entire window
You can use container classes called
Panes, for automatically laying out the
.nodes in a desired location and size
:You need to
1. place nodes inside a pane then
2. place the Pane into the Scene.
Panes, UI Controls, and Shapes
A Scene can contain a
control, Group, or a Pane, but
not a Shape or an
ImageView.
Group
ShowCircleCentered Run
257
Layout Panes
JavaFX provides many types of panes for organizing
.nodes in a container
258
FlowPane: arrange the nodes in the pane horizontally from left to right
.(Default), or vertically from top to bottom, in the order in which they were added
MultipleStageDemo Run
259
FlowPane
You can specify the way the nodes placed either
:by using
Orientation.HORIZONTAL: placed horizonatlly
(default)
Orientation.VERTICAL: the nodes are placed
.vertically
You can specify the gap between nodes in pixels
if needed using setter and getter of attributes:
Hgap or vgap
FlowPane Attributes
ShowGridPane
Run
267
GridPane- Example
{ public class Lecture11 extends Application root.add(b[0],0,0);
public void start(Stage primaryStage) root.add(b[1],1,0); //col 1, row 0
{
root.add(b[2], 0,1);
root.add(b[3], 1,1);
;Button[] b = new Button[5]
root.add(b[4], 0,2);
for(int i=0; i< b.length; i++)
Scene scene = new Scene(root, 300, 250);
;b[i] = new Button("Button "+ i)
primaryStage.setTitle(“Grid Layout");
primaryStage.setScene(scene);
;)(GridPane root = new GridPane
primaryStage.show();
;root.setAlignment(Pos.CENTER)
}
nodes are placed in center of//
GridPane
public static void main(String[] args) {
;root.setHgap(6)
launch(args);
;root.setVgap(5) }
}
Output-GridLayout
BorderPane: can place nodes in five regions: top, bottom, left,
right and center, using the setTop(node), setBottom(node), setLeft(node),
setRight(node), and setCenter(node)
ShowBorderPane Run
270
BorderPane-Example
public class Lecture11 extends root.setTop(b[0]);
{ Application root.setLeft(b[1]);
public void start(Stage root.setRight(b[2]);
{ primaryStage) root.setCenter(b[3]);
;Button[] b = new Button[5] root.setBottom(b[4]);
for(int i=0; i< b.length; i++)
b[i] = new Button("Button "+ Scene scene = new Scene(root, 200, 250);
;i) primaryStage.setTitle(“Border Layout");
BorderPane root = new primaryStage.setScene(scene);
;)(BorderPane primaryStage.show();
}
;root.setAlignment(b[0],Pos.TOP_CENTER)
root.setAlignment(b[4],Pos.BOTTOM_CENT public static void main(String[] args) {
;ER) launch(args);
}
}
Output-Border Layout
Hbox: layout its children in a single
horizontal row
273
Vbox: layout its children in a single
vertical coloumn
ShowHBoxVBox Run
274
Frequently Used UI Controls
275
Frequently Used UI Controls
Label TextField
CheckBox
Button
Radio Buttons
Labeled
A label is a display area for a short text, a node, or both.
It is often used to label other controls (usually text
fields). Labels and buttons share many common
properties. These common properties are defined in the
.Labeled class
:How to create
;Label lb = new Label("Hello there")
)(Setting: To set the text on the label setText •
;lb.setText("Good Bye")
)(Getting: To get the text from a label getText •
;)(String currentLabelStr = lb.getText
277
ButtonBase and Button
A button is a control that triggers an action event when
clicked. JavaFX provides regular buttons, toggle
buttons, check box buttons, and radio buttons. The
common features of these buttons are defined in
.ButtonBase and Labeled classes
:How to create
Button offButton = new Button(); // without label
Button onButton = new Button("Cancel"); //with label
:How to create
TextArea ta = new TextArea ( ); // empty
;TextArea ta = new TextArea (“This is Text Area”)
:How to create •
;CheckBox noviceUserType = new CheckBox("Novice")
;CheckBox expeUserType = new CheckBox("Experienced")
;)(boolean b = expeUserType.isSelected
RadioButton
Radio buttons, also known as option buttons, enable you to choose a
.single item from a group of choices
In appearance radio buttons resemble check boxes, but check boxes
display a square that is either checked or blank, whereas radio buttons
.display a circle that is either filled (if selected) or blank (if not selected)
:How to create
Create the buttons )1( //
;RadioButton fr = new RadioButton("French",)
;RadioButton en = new RadioButton("English",)
sn.setSelected(true); //initially selected
Group the buttons )2( //
;)(ToggleGroup languageGroup = new ToggleGroup
;fr.setToggleGroup(languageGroup)
;en.setToggleGroup(languageGroup)
Note: The aim of using a ToggleGroup object is to tell Java that a set of buttons
are grouped together and have the property that only one of the buttons can be
selected at a time, that means the radio button that was selected previously
282
.becomes unselected
Event Driven Programming
Suppose you want to write a GUI
:program that
lets the user enter a loan amount,
annual interest rate, and number of
.years
then click the Compute Payment
button to obtain the monthly
.payment and total payment
?How do you accomplish the task
You have to use event-driven
programming to write the code to
LoanCalculator Run
respond to the button-clicking
.event
283
Procedural vs. Event-Driven
Programming
284
Events
An event can be defined as a type of
signal to the program that something
.has happened
285
Event Classes
286
Event Handler
To respond to a button click, you need to write the code
to process the button-clicking action (what will be the
result if you press this button). There fore you have two
:members in this process
Event source object: where the object is originated that
.fires an action such as clicking a button
The event handler or event listener object: which is an
object that you create to handle the action event on a
.button, it contains a method for processing the event
Registering Handlers & Handling events
:An event handler object should do two things to handle an event
You need to create a handler object as an instance of the .1
corresponding event-handler interface to ensure the handler has the
correct method for processing the event. JavaFx defines a unified
handler interface EventHandler<T extends Event> for an event T,
where T is a generic type that is a sub type of event. The handler
.interface contains the handle(T e) method for handling events
The handler object must be registered by the source object. .2
.Registration methods depend on the event type
For an action event, the method setOnAction().
For a mouse-pressed event, the method is
setOnMousePressed().
For a keypressed event, the method is
setOnKeyPressed().
Selected User Actions and Handlers
289
Handling events
292
animation
Using Inner class to handle an event
public class HandleEvent extends Application {
public void start(Stage primaryStage) { 1. Start from the main
method to create a
…
window and display
OKHandlerClass handler1 = new OKHandlerClass();
it
btOK.setOnAction(handler1);
CancelHandlerClass handler2 = new CancelHandlerClass();
btCancel.setOnAction(handler2);
…
primaryStage.show(); // Display the stage
}
}
new SuperClassName/InterfaceName() {
// Implement or override methods in superclass
or interface
// Other methods if necessary
}
Anonymous Inner Classes (cont.) )2(
AnonymousHandlerDemo Run
299
Anonymous Inner Classes (cont.) )2(
From previous example//
{ )(>btOK.setOnAction( new EventHandler<ActionEvent
{public void handle(Actionevent e)
;System.out.println("OK button clicked")
method // }
event Handler // }
argument// ;)
(a) Anonymous inner class event handler (b) Lambda expression event handler
301
Lambda Expressions )3(
From previous example//
(btOK.setOnAction
e->{ System.out.println("OK
button clicked"); }
;)
Lambda Expression (cont.) )3(
btSubtract.setOnAction(e -> {
tfResult.setText(Double.parseDouble(tfNumber1.getText()) -
Double.parseDouble(tfNumber2.getText()) + "");
});
btMultiply.setOnAction(e -> {
tfResult.setText(Double.parseDouble(tfNumber1.getText()) *
Double.parseDouble(tfNumber2.getText()) + "");
});
btDivide.setOnAction(e -> {
tfResult.setText(Double.parseDouble(tfNumber1.getText()) /
Double.parseDouble(tfNumber2.getText()) + "");
});
}
public static void main(String[] args) {
launch(args);
}
} // end of class
The MouseEvent Class
MouseEventDemo Run
307
Event Registered Methods
The KeyEvent Class
KeyEventDemo Run
309
Shapes
JavaFX provides many shape classes for drawing texts,
lines, circles, rectangles, ellipses, arcs, polygons, and
polylines.
310
Text
311
Text Example
ShowText Run
312
Exampe Dragging a Text
;import javafx.application.Application Scene scene = new Scene(pane, 300, 100);
;import javafx.scene.Scene
;import javafx.scene.layout.Pane primaryStage.setTitle("MouseEventDemo");
;*.import javafx.scene.text primaryStage.setScene(scene);
primaryStage.show();
;import javafx.stage.Stage
}
;*.import javafx.scene.paint
{ public class Mouse extends Application public static void main(String[] args) {
{ public void start(Stage primaryStage) launch(args);
;)(Pane pane = new Pane }
Text text = new Text(20, 20, "Programming is
;fun") }
text1.setFont(Font.font("Courier",
;FontWeight.BOLD, FontPosture.ITALIC, 15))
;text.setFill(Color.RED)
;pane.getChildren().addAll(text)
{ >- text.setOnMouseDragged(e
;text.setX(e.getX())
;text.setY(e.getY())
;)}
Line
ShowLine Run
314
Rectangle
315
Rectangle Example
ShowRectangle Run
316
Circle
317
Exercie(2): ControlCircle
ControlCircle Run
318
Controlcircle Solution
;import javafx.application.Application
;import javafx.geometry.Pos
;*.import javafx.scene
;*.import javafx.scene.control
;*.import javafx.scene.layout
;*.import javafx.scene.shape
;import javafx.stage.Stage
;*.import javafx.scene.paint
Controlcircle Solution(cont.)
public class Mouse extends Application {
public void start(Stage primaryStage) {
323
Motivations
H-trees, depicted in Figure below, are used in a very
large-scale integration (VLSI) design as a clock
distribution network for routing timing signals to all
parts of a chip with equal propagation delays. How do
you write a program to display H-trees? A good
.approach is to use recursion
324
Objectives
To describe what a recursive method is and the benefits of
.using recursion
To develop recursive methods for recursive mathematical
.functions
To explain how recursive method calls are handled in a call
.stack
.To solve problems using recursion
.To get the directory size using recursion
. To solve the Tower of Hanoi problem using recursion
.To draw fractals using recursion
To discover the relationship and difference between recursion
.and iteration
325
Recursive Algorithm
1, if n 0
Factorial (n)
1 2 3 .. (n 1) n if n 1 otherwise
factorial(5) = 5 * 4* 3* 2* 1 =120
Factorial(4)*5=
Factorial(3)*4*5=
Factorial(2)*3*4*5=
Factorial(1)*2*3*4*5=
factorial(0)*1*2*3*4*5=
120>>>>>> 1*1*2*3*4*5=
Approach 1: Iterative-Factorial
int n = 5, fact = 1;
;factorial(0) = 1
;factorial(n) = n*factorial(n-1)
!n! = n * (n-1)
1 = !0
ComputeFactorial Run
330
Computing Factorial-Recursion
{ public static long factorial(int n)
// Base case if (n == 0)
;return 1
else
;return n * factorial(n - 1)
}
{ public static void main(String[] args)
;Scanner input = new Scanner(System.in)
;System.out.print("Enter a non-negative integer: ")
;)(int n = input.nextInt
System.out.println("Factorial of: " + n + " is " +
;factorial(n))
}
Computing Factorial
animation factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4)
332
Computing Factorial
animation factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
333
Computing Factorial
animation factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
factorial(2) * 3 * 4 =
334
Computing Factorial
animation factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
) factorial(2) * 3 ( * 4 =
) )factorial(1) * 2( * 3( * 4 =
335
Computing Factorial
animation factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
factorial(2) * 3 * 4 =
)factorial(1) * 2( * 3 * 4 =
))factorial(0) * 1( * 2 ( * 3 * 4 =
336
Computing Factorial
animation factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
factorial(2) * 3 * 4 =
)factorial(1) * 2( * 3 * 4 =
))factorial(0) * 1( * 2 ( * 3 * 4 =
)))1 * 1 ( * 2 ( * 3 * 4 =
337
Computing Factorial
animation factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
factorial(2) * 3 * 4 =
)factorial(1) * 2( * 3 * 4 =
))factorial(0) * 1( * 2 ( * 3 * 4 =
)))1 * 1 ( * 2 ( * 3 * 4 =
)1 * 2 ( * 3 * 4 =
338
Computing Factorial
factorial(0) = 1;
animation
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
factorial(2) * 3 * 4 =
)factorial(1) * 2( * 3 * 4 =
))factorial(0) * 1( * 2 ( * 3 * 4 =
)))1 * 1 ( * 2 ( * 3 * 4 =
)1 * 2 ( * 3 * 4 =
2*3*4=
339
Computing Factorial
factorial(0) = 1;
animation
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
)factorial(2) * 3( * 4 =
))factorial(1) * 2( * 3( * 4 =
)))factorial(0) * 1( * 2 ( * 3( * 4 =
))))1 * 1 ( * 2 ( * 3( * 4 =
))1 * 2 ( * 3( * 4 =
)2 * 3( * 4 =
)6 ( * 4 =
340
Computing Factorial
animation factorial(0) = 1;
factorial(n) = n*factorial(n-1);
factorial(4) = 4 * factorial(3)
)factorial(2) * 3( * 4 =
))factorial(1) * 2( * 3( * 4 =
)))factorial(0) * 1( * 2 ( * 3( * 4 =
))))1 * 1 ( * 2 ( * 3( * 4 =
))1 * 2 ( * 3( * 4 =
)2 * 3( * 4 =
)6( * 4 =
341 24 =
Trace Recursive factorial
Executes factorial(4)
animation
factorial(4)
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack
return 2 * factorial(1)
Step 3: executes factorial(1)
Step 6: return 1
return 1 * factorial(0)
Step 4: executes factorial(0)
Step 5: return 1 Space Required
for factorial(4)
return 1 Main method
342
Trace Recursive factorial
animation
factorial(4)
Step 0: executes factorial(4)
Step 9: return 24 Executes factorial(3)
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack
return 2 * factorial(1)
Step 3: executes factorial(1)
Step 6: return 1
return 1 * factorial(0) Space Required
for factorial(3)
Step 4: executes factorial(0)
Step 5: return 1 Space Required
for factorial(4)
343
Trace Recursive factorial
animation
344
Trace Recursive factorial
animation
return 2 * factorial(1)
Space Required
Step 3: executes factorial(1) for factorial(1)
Step 6: return 1 Space Required
for factorial(2)
return 1 * factorial(0) Space Required
for factorial(3)
Step 4: executes factorial(0)
Step 5: return 1 Space Required
for factorial(4)
return 1 Main method
345
Trace Recursive factorial
animation
346
Trace Recursive factorial
animation
factorial(4) returns 1
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack
347
Trace Recursive factorial
animation
348
Trace Recursive factorial
animation
349
Trace Recursive factorial
animation
350
Trace Recursive factorial
animation
351
Trace Recursive factorial
animation
returns factorial(4)
factorial(4)
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Stack
return 2 * factorial(1)
Step 3: executes factorial(1)
Step 6: return 1
return 1 * factorial(0)
Step 4: executes factorial(0)
Step 5: return 1 Space Required
for factorial(4)
return 1 Main method
352
factorial(4) Stack Trace
5 Space Required
for factorial(0)
4 Space Required
for factorial(1)
Space Required
for factorial(1)
3 Space Required
for factorial(2)
Space Required
for factorial(2)
Space Required
for factorial(2)
2 Space Required
for factorial(3)
Space Required
for factorial(3)
Space Required
for factorial(3)
Space Required
for factorial(3)
1 Space Required
for factorial(4)
Space Required
for factorial(4)
Space Required
for factorial(4)
Space Required
for factorial(4)
Space Required
for factorial(4)
6 Space Required
for factorial(1)
Space Required
for factorial(2)
7 Space Required
for factorial(2)
Space Required Space Required 8 Space Required
for factorial(3) for factorial(3) for factorial(3)
Space Required Space Required Space Required
for factorial(4) for factorial(4) for factorial(4)
9 Space Required
for factorial(4)
353
Other Examples
Assume the below method: What will be the out of f(5)?
f(0) = 0;
f(n) = n+ f(n-1); f(5) = 5+ f(4)
Java method//
4 + f(3)
{public static int f (int n)
3 + f(2)
2 + f(1)
if (n==0)
1 + f(0)
return 0 0
else
;return n+f(n-1)
F(5) = 5+4+3+2+1+0 = 15
}
354
Fibonacci Numbers
…Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89
indices: 0 1 2 3 4 5 6 7 8 9 10 11
The series starts by 0, 1 then each element is the summation of the previous two
.elements
;fib(0) = 0
;fib(1) = 1
fib(index) = fib(index -1) + fib(index -2); index >=2
3: call fib(1)
357
Problem Solving Using Recursion
Let us consider a simple problem of printing a message
for n times. You can break the problem into two
subproblems: one is to print the message one time and
the other is to print the message for n-1 times. The
second problem is the same as the original problem
with a smaller size. The base case for the problem is
n==0. You can solve this problem using recursion as
:follows
;nPrintln(“Welcome”, 5)
public static void nPrintln( String message, int times) {
if (times >= 1) {
System.out.println(message);
nPrintln(message, times - 1);
} // The base case is times == 0
} 358
Think Recursively
Many of the problems presented in the early
chapters can be solved using recursion if you
think recursively. For example, the palindrome
:problem can be solved recursively as follows
public static boolean isPalindrome(String s) {
if (s.length() <= 1) // Base case
return true;
else if (s.charAt(0) != s.charAt(s.length() - 1)) // Base case
return false;
else
return isPalindrome(s.substring(1, s.length() - 1)); }
Mlkklm >>> lkkl >>>> KK >>> true it is palindrome
mlkHlm >>>> lkHl >>> kH >> False it is not palindrome
359
Directory Size
The preceding examples can easily be solved without
using recursion. This section presents a problem that
is difficult to solve without using recursion. The
problem is to find the size of a directory. The size of a
directory is the sum of the sizes of all files in the
directory. A directory may contain subdirectories.
Suppose a directory contains files , , ..., , and
.subdirectories , , ..., , as shown below
directory
f1 f2 ... fm d1 d2 dn
...
1 1 1 1 1 1
360
Directory Size
The size of the directory can be defined
:recursively as follows
size( d ) size( f1 ) size( f 2 ) ... size( f m ) size( d1 ) size( d 2 ) ... size( d n )
DirectorySize Run
361
Directory size Solution
{ public static long getSize(File file)
long size = 0; // Store the total size of all files
if (file.isDirectory())
{
File[] files = file.listFiles(); // All files and subdirectories
for (int i = 0; files != null && i < files.length; i++)
size += getSize(files[i]); // Recursive call
}
else
Base case //
;)(size += file.length
;return size
}
Tower of Hanoi
The problem involves moving a special number of
disks of distinct sizes from one tower to another while
:observing the following rules
There are n disks labeled 1, 2, 3, . . ., n, and three
towers labeled A, B, and C.
No disk can be on top of a smaller disk at any time.
All the disks are initially placed on tower A.
Only one disk can be moved at a time, and it must
be the top disk on the tower.
363
.Tower of Hanoi, cont
The objective
of the problem
is:
to move all
the disks from
A to B with
the assistance
of C
364
Solution to Tower of Hanoi
.The Tower of Hanoi problem can be decomposed into three subproblems
365
Solution to Tower of Hanoi
TowerOfHanoi Run
366
Solution of Tower of Hanoi Problem
https://www.cs.cmu.edu/~cburch/survey/recurse/hanoiex.html
;System.out.println("Move disk " + n + " from " + fromT+ " to " + toT)
{ else
;System.out.println("Move disk " + n + " from " + fromT+ " to " + toT)
}
}
Trace Tower of Hanoi Program
moveDisks(3, ’A’, ’B’, ’C’)
Exercise 18.3 GCD
gcd(2, 3) = 1
gcd(2, 10) = 2
gcd(25, 35) = 5
gcd(205, 301) = 5
gcd(m, n)
;gcd(m, n) = n if m % n = 0
;gcd(m, n) = gcd(n, m % n); otherwise
//Java method
public static int gcd(int m, int n){
if (m%n==0)
return n;
else
return gcd(n, m%n);
}
372
?Fractals
373
Sierpinski Triangle
It begins with an equilateral triangle, which is considered to be the .1
.Sierpinski fractal of order (or level) 0, as shown in Figure (a)
Connect the midpoints of the sides of the triangle of order 0 to .2
.create a Sierpinski triangle of order 1, as shown in Figure (b)
Leave the center triangle intact. Connect the midpoints of the sides .3
of the three other triangles to create a Sierpinski of order 2, as
.shown in Figure (c)
You can repeat the same process recursively to create a Sierpinski .4
.triangle of order 3, 4, ..., and so on, as shown in Figure (d)
You can try next example after fishing meeting 11 and 12 (by your .5
own)
374
Sierpinski Triangle Solution
SierpinskiTriangle
Run
375
Recursion vs. Iteration
Recursion is an alternative form of program control.
.It is essentially repetition without a loop
376
Advantages of Using Recursion
377
Meeting 13: Sets and Maps
379
Motivations
The “No-Fly” list is a list, created and maintained by the
U.S. government’s Terrorist Screening Center, of people
who are not permitted to board a commercial aircraft for
travel in or out of the United States. Suppose we need to
write a program that checks whether a person is on the
No-Fly list. You can use a list to store names in the No-
Fly list. However, a more efficient data structure for this
.application is a set
Suppose your program also needs to store detailed information
about terrorists in the No-Fly list. The detailed information
such as gender, height, weight, and nationality can be retrieved
using the name as the key. A map is an efficient data structure
for such a task.
380
The Collection FrameWork
383
The Collection interfaces
The Collection interface is the root interface for
manipulating a collection of objects: Set, List,
.Queue
:The Collections Framework does three things
It specifies a set of collection interfaces
recommends some constructors for the classes that
implement them;
provides some utility classes.
These, together with collection classes meeting
these specifications are said to constitute the
.Collections Framework
An Interface
The following abstract methods are defined for any class that
:implements the iterator
E next(): returns the next element in the iteration(E is the type the
interface is implemented for)
while (listX.hasNext())
;System.out.print( listX.next() + " , ")
, Mlk , lolo
Some of Collection Interface
Methods
The Set Interface
A set is a not ordered collection in which every element
.is unique (i.e. there are no duplicates)
A set can grow and shrink as elements are added or
.removed (dynamic size)
The contents of a set are not indexed, so we have no
way of reaching a particular item except by stepping
.through the elements until we come to the one we want
The most general kind of set is unordered, although we will see that
.ordered sets also exist
You should think of a set as a pool of objects, none of which can
appear twice, and we can add things to the pool or remove them as
.we please
The Set Interface
The Set interface extends the Collection
.interface
It does not introduce new methods or
constants, but it stipulates that an instance of Set
.contains no duplicate elements
The concrete class that implements Set must
ensure that no duplicate elements can be added
.to the set
That is NO two elements e1 and e2 can be in
the set such that e1.equals(e2) is true.no
393
duplicate
The Set Interface
Hierarchy
394
Creating a Set
Whenever we use any kind of collection from the Java Collections
:Framework there are three things we must do first
Choose an implementation class. That is, what class will the actual .2
collection belong to? Implementation class: HashSet
Declare an element type. What data type will the collection contain? .3
A set of String, Integer, Doubles, etc, the element type should be a
.reference type not primitive the same as ArrayList
Wrapper classes .4
HasheSet, TreeSet, &
LinkedHashSet
You can declare an object of
Set<Element_Type> collection, and create
:it using any of the below concrete classes
HashSet doesn’t maintain any kind of order of its
elements and unique.
TreeSet sorts the elements in ascending order and
unique .
LinkedHashSet maintains the insertion order and
unique.
Declaring and creating a variable to reference a
set for holding strings
Class object = new Constrcutor();
;)( >Interface <E> nameobject = new Constructor <E
Declaration
Creation
Decaring and Creatng a Set
Collection
;)(>Collection Interface<E> name = new CocreteClass<E
.set4 will have the same content of set3 but in ascending order//
The HashSet Class
The HashSet class is a concrete class that
.implements Set
For efficiency, objects added to a hash set
need to implement the hashCode method in
a manner that properly disperses the hash
.code
)( >HashSet <E
HashSet <E> (c: Collection<E>)
399
The SortedSet Interface and the
TreeSet Class
SortedSet is a subinterface of Set, which
guarantees that the elements in the set are sorted –
. ascending
TreeSet is a concrete class that implements the
SortedSet interface. You can use an iterator to
.traverse the elements in the sorted order
)( >TreeSet <E
TreeSet <E> (c: Collection<E>)
400
LinkedHashSet Class
Using iterator
For-each statement
{ public static void main(String[] args)
Create a hash set //
;)( >Set <String> set = new HashSet <String
Add strings to the set //
set.add("London"); set.add("Paris"); set.add("New York");
;set.add("San Francisco"); set.add("Beijing")
set.add("New York"); // <<<<<<<<<< not added
;System.out.println(set)
Display the elements in the hash set //
for (String s: set)
;System.out.print(s.toUpperCase() + " ")
System.out.print(“Size = ”+ set.size() ); >>>> Size = 5
}
Exercise(1)
CountKeywords Run
408
Bulk Operations on Set Interface
The interface Set defines several useful bulk operations; that is,
operations that involve every element in one or more sets. Below
are some of the bulk Operations : Let us assume that set1 and set2
.reference instances of classes that implement Set
;set1.containsAll(set2)
.Answers true if set1 contains all the elements in set2
set1.addAll(set2); //set1 = set1 Union set2
Adds all of the elements in set2 to set1, if they are not already present,
answering true if set1 was altered. Union between two sets
set1.retainAll(set2); set1 = set1 intersect set2
Retains any elements set1 has in common with set2, answering true if set1
was changed. Intersection between two sets
set1.removeAll(set2); //set1 = set1 – set2
Removes any elements from set1 that set1 has in common with set2,
answering true if set1 was changed. Set difference
Bulk Operations on Set Interface
Operations that alter the contents of the receiver are
referred to as destructive operations, whereas those that
.do not are referred to as nondestructive operations
414
Map Interface and Class Hierarchy
415
The Map Interface UML Diagram
416
Some of the Methods of the Map Interface
Concrete Map Classes
418
Concrete classes to implement Map
Interface
There are three concrete classes that
:implements Map interface
HashMap: is implemented as a hash table, and
there is no ordering on keys or values.
TreeMap: is implemented based on red-black
tree structure, and it is ordered by the key.
LinkedHashMap: inherits HashMap, and is
implemented as linked list that maintains the
insertion order.
Declare and create a Map
?How to declare a HashMap
Similar to ArrayList, and Set but with the types of both
.the key and value
Map <String,String> table1 = new HashMap <String,String> (); OR
table4 will have the same content of able 3 but in ascending order//
.based on the key
Traversing Map Collection
You can use for each statement to iterate
.a Map row by row
For(Key_Type variable: Map_Name.keySet()){
//the key is stored in variable, to obtain the value use
//Map_name.get(variable)
}
:Example
;)( >Map <String, String> table1 = new HashMap <String,String
for( String key : table1 . keySet())
;System.out.println(key+” “+ table1.get(key) )
Exercise(3): Using HashMap and
TreeMap
This exercise creates a hash map that maps names to their
.ages
The program first creates a hash map with the name as its key and
age as its value: (“Smith”,30), (“Anderson", 31), (“Lewis", 29), and
("Cook", 29). Then display the content.
Print out the names whose age are greater than or equal to 30.
Print out the age of Lewis
The program then creates a tree map from the hash map, and
displays the mappings in ascending order of the keys.
TestMap Run
422
Exercise(3)_Solution
public class TestMap {
public static void main(String[] args) {
// Create a HashMap
Map<String, Integer> hashMap = new HashMap<String, Integer>();
hashMap.put("Smith", 30); hashMap.put("Anderson", 31);
hashMap.put("Lewis", 29); hashMap.put("Cook", 29);
System.out.println(treeMap);
}
}// end class
Exercise(4): Counting the Occurrences of
Words in a String
Write Java program to count the occurrences of words
in a text and displays the words and their occurrences in
:ascending order of the words. Assume text is
Good morning. Have a good class. " + "Have a good"
"!visit. Have fun
The program uses a hash map to store a pair
consisting of a word and its count. For each word, check
whether it is already a key in the map. If not, add the key
and value 1 to the map. Otherwise, increase the value
.for the word (key) by 1 in the map
.Display the content of the Map
CountOccurrenceOfWords Run
425
Solution of Exercise(4)
;*.import java.util
{ public class CountOccurrenceOfWords
{ public static void main(String[] args)
;"!String text = "Good morning. Have a good class. " + "Have a good visit. Have fun
;)(>Map<String, Integer> map = new TreeMap<String, Integer
String[] words = text.split("\\W+"); // split text into words , this mean the
.delimiter will be anything that is not a word
{ for (int i = 0; i < words.length; i++)
;)(String key = words[i].toLowerCase
{ if (key.length() > 0)
if (!map.containsKey(key))
;map.put(key, 1)
{ else
;int value = map.get(key)
;++value
} ;map.put(key, value)
}
for// }
Continue Solution of Exercise(4)
;System.out.println(“Words \t Count”)
;)”----------------------------“(System.out.println
for(String t : map.keySet())
;System.out.println(t+”\t“+ map.get(t))
main//}
class//}
Important Notes
The Collection Framework has two rooted interfaces:
.Collection, and Map
Set, List, and Queue are sub-Interfaces from Collection
.Interface
Distinguish between Collection Interface, and the
Collections class that is used to do some operations on
the ArrayList such as: reverse, sort, etc as you studied in
.Meeting6
You did not use Collection Interface methods directly,
you use its sub-Interfaces to declare objects of Set, List,
or Queue then use objects to invoke methods. Wherein
Collections class methods are used using Collections
.class to invoke methods: Collections.sort(x), etc
Meeting 14: Threads
Thread states
430
Threads in Java
Java is a Threaded language which allows a program to do several things at
.once
Threads are separate activities within a program, each of which has a beginning
.and an end
Example: You might want to monitor the keyboard for a key being pressed by a –
user and, at the same time, track the movement of the mouse by the user and
repaint the screen. Each of these tasks/activities can be thought of as a single
.thread in one program
The Java system has a component known as the scheduler that makes
.decisions about which thread to run next
Threads are not the actual static code itself but rather they are the dynamic
process of executing that code
So far, all of the programs that you have written have had only one thread and
.this has been the thread started by the main method
Introduction
• Concurrent systems
– It is an area of computer science that represents the concepts surrounding
the use of threads.
– a concurrent system consists of a collection of separate activities or tasks
that are simultaneously at some stage between their starting and finishing
point.
43
2
Creating Threads
• A thread is treated as an object in Java and the Thread class is found
in the java.lang library. <<< no import is needed
– The Thread class has a number of methods for creating, destroying and
modifying threads.
• Threaded classes can be defined in two ways:
43
3
Creating Threads
2.1 Inheriting from the Thread class
•The general approach is
(1) Define a class by extending the Thread class and overriding the run
method.
• In the run method, you should write the code that you wish to run when this
particular thread has started running state.
(2) Create an instance object of the above class
(3) Start running the instance using the start() method that is defined
in Thread.
Exampl The output
e
•
434
Creating Threads
2.2 Implementing the Runnable interface
•The general approach is
(1) Define a class that implements Runnable and overriding the run
(2) Create an instance object of the above class. method
(3) Create a thread that runs this instance. .
(4) Start running the instance using the start method.
Exampl The output
e
435
Creating Threads
2.3 Thread states
•We need to look at the various
states that a thread can be in and
how a thread might move from
one state to another.
•A thread is in one of five states
at any moment in time:
(1) initial state;
(2) runnable state;
(3) running state;
(4) blocked state;
(5) finished state.
43
6
Movement from one state to another is governed by:
(1)a number of methods from Thread class and the Object
class
(2)the operating system and other external factors.
Note the following in the figure:
•A thread is put into the initial state by means of it being
created using new.
•Thread t1= new Thread(); <<< it is in initial state
•Thread is a class in Java
•t1.start() <<<<< it is in Runnable state
•the start method moves the thread into the runnable
state. This does not mean that it will run immediately (there
may be another thread that is being run by the CPU)
•At certain times during the execution of a program that
contains threads, the Java system will have a look at all the
runnable threads and will select one to execute.
•Only the thread that is actually executing is said to be in
the running state. When a particular thread is chosen, its
run method is invoked and the thread can begin to execute
the code. It is now in the running state.
•t1.run() <<< is invoked by the scheduler and CPU
•When a running state finishes executing, it moves into the
finished state.
437
Creating Threads
• However, the thread may run out of its
allotted CPU time.
440
Creating Threads
• The important concept at this stage is that a Java program may involve a
number of threads, some of which are runnable and ready to be
executed by a processor and others that are unable to proceed because
they are blocked.
• On a single-processor machine only one thread can actually be running
at a time. The Java system has a component known as the scheduler
that makes decisions about which thread to run next.
442
Exercise
•(a) What are the two ways to define threads?
•(b) When a thread is executing, does it continue executing until it gets to
the end of its code?
•(c) How do you tell the system that you want to set a thread in running?
•ANSWERS .................................................................................................
...........
•(a) Threads can be defined by extending the Thread class or by
implementing the Runnable interface.
•(b) No, in all likelihood the thread will have access to the CPU for only a
short part of its execution before it is stopped and another thread is given
an opportunity to run.
•(c) After creating an instance of a threaded class, you invoke the start
method.
443
Exercise
•(a) When would you typically want to define a thread by implementing
Runnable rather than extending Thread?
•(b) How do you define, create and start a thread using Runnable?
•ANSWERS....................................................................................................
........
•(a) There are many occasions when a threaded class will inherit from
another class: for example, JFrame. As Java does not allow multiple
inheritance it is useful to be able to implement an interface to create a
thread. Remember, Java allows a class to implement any number of
interfaces but to extend only one other class.
•(b) The thread class is defined by implementing the interface Runnable
and the single method in the interface – run. You then create an instance
of this threaded class and pass this instance to the Thread constructor to
create a new threaded object. This can then be treated as any other
threaded object and can be started by invoking the start method. 444
Exercise
• (a) What is the difference between a thread in the blocked state and one
in the runnable state?
• (b) how do you explain the following
WhoamI t1 = new WhoamI("tota"); // initaile state
t1.start(); // <<<<< start state
t1.run(); <<<<<<<<<<<<<<<<<yes but out of the Thread mechanism
Who is responsible to invoke run() method
OS and scheduler
• ANSWERS.................................................................................................
...........
• (a) A runnable thread is fully ready to run once it is chosen by the
scheduler. On the other hand, a thread in the blocked state is definitely
not ready to run because
– it is waiting for something to happen.
– It may be waiting either for an I/O event to happen or because the wait
method has been invoked. 445