Advanced Programming
Advanced Programming
Dilla Campus
Department of Information Technology
Lecture 1:
Introduction to Java
Contents
✓Introduction
✓Data types, Variables and Keywords
✓Control Structures
✓Methods and Arrays
2
Introduction
What is java?
• Java is a general purpose, concurrent, class based, object oriented
programming language.
• Java as an object-oriented language was designed from the outset
to be platform independent, robust, and secure.
3
Java Characteristics
✓ Java is simple in that it retains much familiar syntax of C++.
✓ It is strongly typed. This means that every thing must have a
data type.
✓ Java performs its own memory management avoiding the
memory leaks that plague programs written in languages
like C and C++.
✓ Java is completely object oriented.
✓ Java is multi-threaded, allowing a program to do more than
one thing at a time.
✓ Network-Savvy: extensive library of routines for coping
with TCP/IP protocols like HTTP and FTP.
✓ Secure and Robust: Java is intended for writing programs
that are reliable and secure in a variety of ways.
✓ Portable and architecture neutral. 4
The Java language Specifications, API, JDK
and IDE
• Java language Specifications: a technical specifications of the language
that includes the syntax and semantics of the language.
• API (Application Program Interface): Contains predefined classes and
interfaces for developing java programs.
Three editions of java API
– J2SE: Java 2 Standard Edition
– J2EE: Java 2 Enterprise Edition
– J2ME: Java 2 Micro Edition
• JDK(Java Development Toolkit): Consists of a set of programs for
developing and testing java programs each of which is invoked from a
command line .
Three major java development tools
– Jbulider
– NetBeans
– Eclipse 5
Java Application Vs Applet
• Java can be used to create two types of programs: applications and applets.
• Application: is a stand alone program that runs on your computer, under the
operating system of your computer.
6
Getting Started with Java Programming
7
Creating , Compiling and Executing a Java
program. Create/Modify Source code
Source Code
Bytecode
Run Bytecode
e.g.java Welcome
Result
8
The Java Virtual Machine (JVM) and Byte code
• Earlier programming languages are platform dependent, meaning they
only run on a predefined software or hardware.
• Java compiles the java source code, not into some particular machine
code, but into a machine code (byte code), for a hypothetical machine,
and is what is downloaded into the local machine.
• But the byte codes are not the native machine code of the local
computer, so we need a program in the local machine (called the
interpreter) that reads, the byte codes, interprets what operation have to
be carried out on what data and carries them out.
9
Steps to create a Java application:
1. Using any text editor, write Java application source code.
2. Compile the Java source code. When this is done, the Java
compiler creates a byte-code file.
10
A Simple Application
Example 1:
//This application program prints Welcome to Java!
message on the console window.
public class Welcome
{
public static void main(String[] args)
{
System.out.println("Welcome to Java!");
}
} 11
Remarks
• Every java program must have at least one class
• In order to run a class, the class must contain a method named main
Commands on a command prompt to Compile and Execute
✓ javac Welcome.java // compile
✓ java Welcome // run or execute
✓ output:...
12
Anatomy of a Java Program
• A java program contains:
– Comments
– Reserved words
– Package
– Modifiers
– Statements
– Blocks
– Classes
– Methods
– The main method
13
Comments
• Preceded by two slashes (//) in a line, or enclosed
between /* and */ in one or multiple lines.
Reserved Words
• Reserved words or keywords are words that have a
specific meaning to the compiler and cannot be
used for other purposes in the program.
Example,
class, public, static, and void.
14
Packages
• A group of predefined classes
Example
• JOptionPane is in javax.swing package i.e it
is imported to a program using import
statement.
• java. lang package is imported implicitly in
every java program, eg. System class is not
imported b/c it is in this package
15
Modifiers
• Reserved words that specify the properties of the data,
methods, and classes and how they can be used.
• Ex. public and static, private, final, abstract, and protected.
Statements
• Represents an action or a sequence of actions.
• Eg.: System.out.println("Welcome to Java!") is a statement to
display the greeting "Welcome to Java!"
• Should end with a semicolon (;).
Block
• A pair of braces in a program forms a block that groups
components of a program.
16
Classes
• The essential Java construct that serves as a template or blueprint for
objects.
Methods
• A collection of statements that performs a sequence of operations.
Main Method
• The main method provides the control of program flow.
• The Java interpreter executes the application by invoking the main
method.
• The main method looks like this:
18
• The syntax for declaring a variable is
datatype variableName;
Eg:
int count;
double radius;
double interestRate;
• Variables often have initial values.
Eg. int count=1;
19
Constants Variables
• Represents permanent data that never changes.
20
Character and String Data Type
Character data type:
– Used to represent a single character
– A character literal is enclosed in single quotation
marks.
Eg. char letter=‘A’;
String Data type
– Represent a string of character
– A predefined class in java library
– It is known as reference type
Eg. Sting message =“Welcome to Java”
21
Programming errors
• Categorized into three types
1. Syntax Errors
• Occur during compilation
• Result from errors in code construction, such as mistyping a keyword,
omitting some necessary punctuation, or using an opening brace
without a corresponding closing brace.
• Usually easy to detect, b/c the compiler tells you where they are and
what caused them.
2. Runtime Errors
• Cause a program to terminate abnormally.
• Occur while a program is running if the environment detects an
operation that is impossible to carry out.
– Eg. Input errors 22
3. Logical Errors
• Logic errors occur when a program does not perform the way it was
intended to.
• Finding logic errors, can be very challenging
• Logic errors are called bugs. The process of finding and correcting
errors is called debugging.
• Can hand-trace the program i.e this approach might work for a short,
simple program.
• Debugger utility : the most effective approach for large, and complex
program.
23
Control Structures
• Control structures are a way to alter the natural sequence of execution
in a Java program.
• They act as “direction signals” to control the path a program takes.
• The process of performing one statement after another is called the flow
of execution or flow of control.
• Control structures include:
» Block statements
» Decision statements
» Loops
24
Decision Statements
• The control statements that allow alternative actions based up
on conditions that are evaluated at run time are generally
called decision or selection statements.
• These include if and switch statements.
If Statements
• A simple if statement executes an action if and only if the
condition is true.
• The syntax:
if (boolean-expression)
{
statement(s);
}
25
26
If … Else Statement
• To take alternative actions when the condition is false, you can use a n
if… else statement.
• The actions that a if…else statement specifies differ based on whether
the condition is true or false.
• The syntax:
if (boolean-expression)
{
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
27
28
Nested if Statements
• The nested if statement can be used to implement multiple alternatives.
Eg. if (score >= 90.0)
grade = 'A';
else if (score >= 80.0)
grade = 'B';
else if (score >= 70.0)
grade = 'C';
else if (score >= 60.0)
grade = 'D';
else
grade = 'F';
29
Switch Statements
• Java provides it to handle multiple conditions efficiently,
replace the nested if statement.
• The syntax:
switch (switch-expression)
{
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
...
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
30
Loops
• Some most useful program use data objects that contain
sequences of numbered elements.
• These sequences are easily processed by iteration statement
blocks. Such programming statements are called loops, because
the flow of execution “loops back” to the beginning of the block.
The while Loop
• The syntax:
while (condition)
{
// Loop body
Statement(s);
}
31
32
The do-while Loop
• The do-while loop is a variation of the while loop.
• Syntax :
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
• Executes the loop body first, then checks the loop-
continuation-condition to determine whether to continue or
terminate the loop.
33
34
The for Loop
• A for loop can be used to simplify the proceeding loop:
35
36
Methods
• The syntax for defining a method is as follows:
37
38
• If a method returns a value, it is called a value returning
method, otherwise it is a void method.
• Formal parameters : variables defined in the method header.
• Actual parameter or argument, when a method is invoked, it’s
value passed as a parameter..
• In order for a value-returning method to return a result, a
return statement using the keyword return is required. .
• Methods can be used to reduce redundant code and enable
code reuse.
Overloading Methods
• Two methods have the same name but different parameter lists
within one class.
39
Array Basics
• Used to store a collection of data,
• A collection of variables of the same type.
Declaring Array Variables
• Syntax
dataType[] arrayName;
• For example, declares a variable myList that references an
array of double data type elements.
double[] myList;
40
Creating Arrays
• After an array variable is declared, you can create an array by
using the new operator with the following syntax:
41
• Here is an example:
arrayName[index] = value;
• When an array is created, its elements are assigned the
default value of 0 for the numeric primitive data types,
'\u0000' for char types, and false for Boolean types
• Each element in the array is represented using the following
syntax, known as an indexed variable:
arrayName[index];
42a
43
Array Initializers
• Combines in one statement declaring an array, creating an array,
and initializing, using the following syntax:
44
For-each Loops
• Java supports a convenient for loop, known as a for-each loop or
enhanced for loop, which enables to traverse the array
sequentially without using an index variable.
Syntax
for (elementType element: arrayRefVar)
{
// Process the element
}
45
• Eg, the following code displays all the elements in the array
myList:
46
Passing Arrays to Methods
• Java uses pass-by-value to pass arguments to a method.
47
Infolink University College
Dilla Campus
Department of Information Technology
Lecture 2:
Object Oriented Programming with Java
48
Contents
✓Classes and Objects
✓Inheritance and Polymorphism
✓Abstract Class and Interface
49
Introduction
• Java combines the power of procedural
language and object oriented language.
• Procedural language : data and operations on
the data is separate -> required sending data to
methods.
Object-Oriented programming:
• Involves programming using objects
• place data and the operations that pertained to
them within a single entity called an object.
50
Object Oriented Programming
• Object orientation is a set of tools and methods that enable
software engineers to build reliable, user friendly,
maintainable, well documented, reusable software systems
that fulfills the requirements of its users.
• Object-orientation provides a new view of computation.
– A software system is seen as a community of objects that
cooperate with each other by passing messages in solving a
problem.
• At the heart of object-oriented programming, instead of
tasks we find objects – entities that:
– have behaviors,
– hold information, and
– can interact with one another.
51
Object Oriented Programming
• An object-oriented programming language
provides support for the following object-oriented
concepts:
– Objects
– Classes
– Inheritance
– Polymorphism
– Abstraction
– Modularity
– Encapsulation
52
Defining Classes for Objects
An object:
• represents an entity in the real world that can
be distinctly identified.
• has a unique identity, state, and behavior
• an instance of a class. You can create many
instances of a class.
Eg, a student, a desk, a circle, a button
• Data fields : represent state of an object (also
known as its properties or attributes)
53
• Methods: the behavior of an object (also known as
its actions) .
• Invoke a method on an object:- asking the object
to perform an action.
A class is a template, blue print, or contract that
defines what an object’s data fields and methods
will be.
• two classes can put into one file, but only one
class in the file can be a public class.
• The public class must have the same name as
the file name.
54
Specifying a Class
• A class is a way to bind the data and its associated functions
(methods) together.
• It allows the data to be hidden.
• Generally class specification has two parts.
– Class declaration:- Describes the type and scope of its members.
– Class function definition:- Describes how the class functions are
implemented.
• The basic form of a class definition is:
modifier class Class_Name [extends Class_Name] [implements Interface]
{
[Variable declaration;]
[Method declaration;]
} 55
A class can contain any of the following variable types
• Local variables . Variables defined inside
methods, constructors or blocks.
• Instance variables . Instance variables are
variables within a class but outside any
method. It is instantiated when the class is
loaded.
• Class variables . Variables declared with in a
class, outside any method, with the static
keyword.
56
• Figure 1. shows a class named Circle and its three
objects.
57
• The body of a class contains declarations of variables and
methods (functions).
• The variables and methods (functions) are also called members.
• A class has three kinds of members:
– Fields: that specify the kind of data that the objects hold.
– Methods: that specify the operations that the objects can perform.
– Constructors: that specify how the objects are to be created.
• Private members can be accessed only from with in the class.
• Public members can be accessed from outside the class also.
• Private members can be accessed by the member functions of
that class. However, public members can be accessed from
outside the class.
• This type of binding the data and functions into a single unit is
called data encapsulation. 58
Constructing Objects Using Constructors
Constructors : are a special kind of method.
They have three peculiarities:
– have the same name as the class itself.
– do not have a return type—not even void.
– invoked using the new operator when an object is
created.
– play the role of initializing objects.
• Like regular methods, constructors can be
overloaded i.e. a class can have more than
one constructor. 59
Creating an Object:
• The declaration of class does not define any objects of
that class, but only specifies what they will contain.
• Once a class has been declared, we can create
variables of that type by using the class name.
• There are three steps when creating an object from a
class:
– Declaration . A variable declaration with a variable name
with an object type.
– Instantiation . The 'new' key word is used to create the
object.
– Initialization . The 'new' keyword is followed by a call to
a constructor. This call initializes the new object. 60
• The basic form of object creation and instantiation
is:
Example:
student Stud1 = new student(117);
creates the object Stud1 of type student as an
instance of the class student.
• It is like the declaration of variables of any base
types. The memory is allocated to an object at this
stage.
61
• Every class has a constructor. If we do not
explicitly write a constructor for a class the
java compiler builds a default constructor
for that class.
• The constructor is denoted as:
ClassName(parameterName: parameterType)
Eg.
• new Circle1() creates an object with radius
1.0
• new Circle1(25) creates an object with
radius 25
62
63
Default constructor: A class may be defined
without constructors.
64
Accessing an Object’s Data and Methods
• After an object is created, its data can be accessed
and its methods invoked using the dot operator (.),
also known as the object member access operator.
objectRefVar.dataField
– references a data field in the object.
objectRefVar.method(arguments)
– invokes a method on the object
• Examples
– myCircle.radius references the radius in myCircle, and
– myCircle.getArea() invokes the getArea method on
myCircle.
65
• Anonymous object: an object can be created
without explicitly assigning it to a variable, if
the object does not need to be referenced later.
Eg. new Circle();
Example:
System.out.println("Area is " + new Circle(5).getArea());
66
• Garbage collection :The Java runtime system
detects garbage and automatically reclaims the
space it occupies.
• The JVM will automatically collect the space if
the object is not referenced by any reference
variable.
67
Visibility Modifiers
• Public visibility modifier for classes, methods,
and data fields to denote that they can be
accessed from any other classes.
• If no visibility modifier is used, then by default
the classes, methods, and data fields are
accessible by any class in the same package.
• This is known as package-private or package-
access.
• The private modifier makes methods and data
fields accessible only from within its own class.
68
Note
• In most cases, the constructor should be public.
• However, if you want to prohibit the user from
creating an instance of a class, use a private
constructor.
private Math() {
}
• To prevent data from being tampered with and
to make the class easy to maintain, declare data
fields private.
• Java uses exactly one mode of passing
arguments: pass-by-value.
69
Array of Objects
• We can also create arrays of objects.
• For example, the following statement declares and
creates an array of ten Circle objects:
Circle[] circleArray = new Circle[10];
• To initialize the circleArray, you can use a for loop
like this one:
for (int i = 0; i < circleArray.length; i++) {
circleArray[i] = new Circle();
}
• In an array of objects, an element of the array
contains a reference to an object.
70
• An array of objects is actually an array of reference
variables. So, invoking circleArray[1].getArea()
involves two levels of referencing, as shown in
Figure 8.18.
circleArray references the entire array.
circleArray[1] references a Circle object.
71
The this keyword
• The this keyword gives us a way to refer to the
object that invokes an instance method within the
code of the instance method.
• The line this.i = i means “assign the value of
parameter i to the data field i of the calling object.”
• The keyword this refers to the object that invokes
the instance method set i, as shown in Figure
below.
72
The keyword this refers to the calling
object that invokes the method
78
Inheritance (cont)
• Although a subclass includes all of
the members of its superclass, it // A's j is not accessible here.
cannot access those members of class B extends A {
the superclass that have been int total;
declared as private. For example, void sum() {
consider the following simple class total = i + j;
hierarchy: // ERROR, j is not accessible here
Example : }
// Create a superclass. }
class Access {
class A {
public static void main(String args[]){
int i; // public by default B subOb = new B();
private int j; // private to A subOb.setij(10, 12);
void setij(int x, int y) { subOb.sum();
i = x; System.out.println("Total is " +
subOb.total);
j = y; }
} } 79
Inheritance (cont)
• This program will not compile because the reference to j inside
the sum( ) method of B causes an access violation. Since j is
declared as private, it is only accessible by other members of its
own class. Subclasses have no access to it.
• A class member that has been declared as private will remain
private to its class. It is not accessible by any code outside its
class, including subclasses.
80
Using super Keyword
• Whenever a subclass needs to refer to its immediate superclass, it
can do so by use of the keyword super.
• Super has two general forms. The first calls the superclass’
constructor. The second is used to access a member of the
superclass that has been hidden by a member of a subclass.
Using super-Use 1
• A subclass can call a constructor method defined by its
superclass by use of the following form of super:
super(parameter-list);
• Here, parameter-list specifies any parameters needed by the
constructor in the superclass. super( ) must always be the first
statement executed inside a subclass’ constructor.
81
Using super-Use 2
• The second form of super acts somewhat like this, except that it
always refers to the superclass of the subclass in which it is used.
This usage has the following general form:
super.member
• Here, member can be either a method or an instance variable.
• This second form of super is most applicable to situations in which
member names of a subclass hide members by the same name in
the superclass. Consider this simple class hierarchy:
82
Creating a Multilevel Hierarchy
• Up to this point, we have been using simple class hierarchies that
consist of only a superclass and a subclass. However, you can
build hierarchies that contain as many layers of inheritance as you
like.
• When this type of situation occurs, each subclass inherits all of the
traits found in all of its superclasses. In this case, C inherits all
aspects of B and A.
83
When Constructors Are Called
• When a class hierarchy is created, in what order are the
constructors for the classes that make up the hierarchy called?
• For example, given a subclass called B and a superclass called A,
is A’s constructor called before B’s, or vice versa?
• The answer is that in a class hierarchy, constructors are called in
order of derivation, from superclass to subclass.
• Further, since super( ) must be the first statement executed in a
subclass’ constructor, this order is the same whether or not
super() is used. If super( ) is not used, then the default or
parameterless constructor of each superclass will be executed.
Eg:-
84
When Constructors Are Called (cont)
// Demonstrate when constructors are called.
// Create a super class. • The output from this program is
class A { shown here:
A() { Inside A’s constructor
System.out.println("Inside A's constructor.");
} Inside B’s constructor
} Inside C’s constructor
// Create a subclass by extending class A. • As you can see, the constructors
class B extends A { are called in order of derivation. If
B() { you think about it, it makes sense
System.out.println("Inside B's constructor.");
}
that constructors are executed in
}
order of derivation. Because a
// Create another subclass by extending B. superclass has no knowledge of
class C extends B { any subclass, any initialization it
C() { needs to perform is separate
System.out.println("Inside C's constructor."); from and possibly prerequisite to
} any initialization performed by
} the subclass. Therefore, it must
class CallingCons { be executed first.
public static void main(String args[]) {
C c = new C();
}
}
Polymorphism 85
Polymorphism
• Polymorphism means one name, many forms.
• Polymorphism manifests itself by having multiple methods all
with the same name, but slightly different functionality.
86
Method Overriding
• In a class hierarchy, when a method in a subclass has the same
name and type signature as a method in its superclass, then the
method in the subclass is said to override the method in the
superclass.
87
Method Overriding (cont)
class B extends A {
// Method overriding. int k;
class A { B(int a, int b, int c) {
int i, j; super(a, b);
A(int a, int b) { k = c;
}
i = a;
// display k – this overrides show() in A
j = b;
void show() {
}
System.out.println("k: " + k);
void show() { // display i and j }
System.out.println("i and j: " + i + " " + j); }
} class Override {
} public static void main(String args[]) {
What would you do if you want to B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
call the superclass version of show( ).
}
} 88
Method Overriding (cont)
// Methods with differing type // Create a subclass by extending class A.
//signatures are overloaded – not class B extends A {
// overridden. int k;
class A { B(int a, int b, int c) {
super(a, b);
int i, j;
k = c;
A(int a, int b) { }
i = a; void show(String msg) {// overload show()
j = b; System.out.println(msg + k);
} }
// display i and j }
void show() { class Override {
System.out.println("i and j: " + i + " “+public
j); static void main(String args[]) {
} B subOb = new B(1, 2, 3);
} subOb.show("This is k: "); //calls show() in B
subOb.show(); // this calls show() in A
}
}
89
Method Overriding (cont)
Using final with Inheritance
• The keyword final has three uses. First, it can be used to create the
equivalent of a named constant. The other two uses of final apply
to inheritance.
91
Second Use : Using final to Prevent Inheritance
• Sometimes you will want to prevent a class from being inherited.
To do this, precede the class declaration with final.
• Declaring a class as final implicitly declares all of its methods as
final, too.
Example on Second Use
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
• As the comments imply, it is illegal for B to inherit A since A is
declared as final.
Abstract Classes 92
Abstract Classes
• Abstraction refers to the ability to make a class abstract in OOP.
• An abstract class is one that cannot be instantiated.
– All other functionality of the class still exists, and its fields, methods, and
constructors are all accessed in the same manner.
– You just cannot create an instance of the abstract class.
• Use the abstract keyword to declare an abstract class.
• The keyword appears in the class declaration somewhere before
the class keyword.
Example:
Notice that nothing is different in this Employee class. The class is
now abstract, but it still has two fields, one methods, and one
constructor.
93
public abstract class Employee {
private String name;
private String jobTitle;
public Employee(String name, String jobTitle) {
this.name = name;
this. jobTitle = jobTitle;
}
public void getEmployee(){
System.out.println(“Employee Info”);
System.out.println(“Name : ” + name + “ JobTitle : ” +
jobTitle);
}
}
• Now if you would try as follows:
94
public class AbstractDemo {
public static void main(String [] args) {
Employee e = new Employee(“Selamawit", “Secretary”);
}
}
• When you would compile above class then you would get following
error: Employee is abstract; cannot be instantiated
95
Extending Abstract Classes
• We can extend Employee class in normal way as follows:
97
Abstract Methods
• If you want a class to contain a particular method but you want
the actual implementation of that method to be determined by
child classes, you can declare the method in the parent class as
abstract.
• The abstract keyword is also used to declare a method as abstract.
• An abstract methods consist of a method signature, but no
method body.
• Abstract method would have no definition, and its signature is
followed by a semicolon, not curly braces.
• To declare an abstract method, use this general form:
abstract type name(parameter-list);
• As you can see, no method body is present.
98
Abstract Methods (cont)
• Any class that contains one or more abstract methods must also
be declared abstract. There can be no objects of an abstract class
• Also, you cannot declare abstract constructors, or abstract static
methods.
• Any subclass of an abstract class must either implement all of the
abstract methods in the superclass, or be itself declared abstract.
• Declaring a method as abstract has two results:
– The class must also be declared abstract. If a class contains an
abstract method, the class must be abstract as well.
– Any child class must either override the abstract method or
declare itself abstract.
Interfaces 99
Interfaces
• An interface is a collection of abstract methods.
• Unless the class that implements the interface is abstract, all the
methods of the interface need to be defined in the class.
• In Java, a class can inherit from only one class but it can implement
more than one interface.
100
Interfaces
• Interfaces is very useful in cases where you need the
implementation to be interchangeable.
• Apart from that an interface is very useful when the
implementation changes frequently.
• Interface can be used to define a generic template and then one or
more abstract classes to define partial implementations of the
interface.
• Interfaces just specify the method declaration and can contain
properties.
• If a class that implements an interface does not define all the
methods of the interface, then it must be declared abstract and the
method definitions must be provided by the subclass that extends
the abstract class.
• In addition to this an interfaces can inherit other interfaces.
101
Interfaces(cont)
• An interface is similar to a class in the following ways:
1. An interface can contain any number of methods.
2. An interface is written in a file with a .java extension, with the
name of the interface matching the name of the file.
3. The bytecode of an interface appears in a .class file.
• However, an interface is different from a class in several ways, including:
1. You cannot instantiate an interface.
2. An interface does not contain any constructors.
3. All of the methods in an interface are abstract.
4. An interface cannot contain instance fields. The only fields that can
appear in an interface must be declared both static and final.
5. An interface is not extended by a class; it is implemented by a class.
6. An interface can extend multiple interfaces.
102
Declaring Interfaces
• The interface keyword is used to declare an interface.
• Access to the data and code is tightly controlled by an interface.
• Let us look at an example
public interface NameOfInterface {
//Any number of final, static fields
//Any number of abstract method declarations
}
• Interfaces have the following properties:
– An interface is implicitly abstract. You do not need to use
the abstract keyword when declaring an interface.
– Each method in an interface is also implicitly abstract, so the
abstract keyword is not needed.
– Methods in an interface are implicitly public.
103
Implementing Interfaces
• When a class implements an interface, you can think of the class as
signing a contract, agreeing to perform the specific behaviors of
the interface.
• If a class does not perform all the behaviors of the interface, the
class must declare itself as abstract.
• A class uses the implements keyword to implement an interface.
• Implementing an interface allows a class to become more formal
about the behavior it promises to provide.
• Interfaces form a contract between the class and the outside world,
and this contract is enforced at build time by the compiler.
• If your class claims to implement an interface, all methods defined
by that interface must appear in its source code before the class will
successfully compile.
104
• The general form of a class that includes the implements clause looks
like this:
modifier class classname [extends superclass] [implements interface
[interface...]
{
// class-body
}
• Here, modifier is either public or not used.
• If a class implements more than one interface, the interfaces are
separated with a comma.
• If a class implements two interfaces that declare the same method, then
the same method will be used by clients of either interface.
• The methods that implement an interface must be declared public.
• Also, the type signature of the implementing method must match
exactly the type signature specified in the interface definition.
105
Example(cont):
interface Animal {
public void eat();
public void travel();
}
public class Mammal implements Animal{
Output will be:
public void eat(){
System.out.println("Mammal eats");
} Mammal eats
public void travel(){ Mammal travels
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
Mammal m = new Mammal();
m.eat();
m.travel();
}
}
106
Interfaces (cont)
• When overriding methods defined in interfaces there are several
rules to be followed:
1. The signature of the interface method and the same return
type or subtype should be maintained when overriding the
methods.
2. An implementation class itself can be abstract and if so
interface methods need not be implemented.
• When implementing interfaces there are several rules:
1. A class can extend only one class, but can implement many
interface.
2. An interface itself can extend another interface.
107
Extending Interfaces
• An interface can extend another interface, similarly to the way
that a class can extend another class.
• The extends keyword is used to extend an interface, and the child
interface inherits the methods of the parent interface.
• The following Sports interface is extended by Hockey and
Football interfaces.
Extending Multiple Interfaces:
• A Java class can only extend one parent class. Multiple
inheritance is not allowed. Interfaces are not classes, however, and
an interface can extend more than one parent interface.
• The extends keyword is used once, and the parent interfaces are
declared in a comma-separated list.
• For example, if the Hockey interface extended both Sports and
Event, it would be declared as:
public interface Hockey extends Sports, Event
108
What is the difference between an Interface and an Abstract class?
• There are quite a big difference between an interface and an abstract class, even
though both look similar.
– Interface definition begins with a keyword interface so it is of type interface
– Abstract classes are declared with the abstract keyword so it is of type class
– Interface has no implementation, but they have to be implemented.
– Abstract class’s methods can have implementations and they have to be extended.
– Interfaces can only have method declaration (implicitly public and abstract) and
fields (implicitly public static)
– Abstract class’s methods can’t have implementation only when declared abstract.
– Interface can inherit more than one interfaces
– Abstract class can implement more than one interfaces, but can inherit only one class
– Abstract class must override all abstract method and may override virtual methods
– Interface can be used when the implementation is changing
– Abstract class can be used to provide some default behavior for a base class.
– Interface makes implementation interchangeable
– Interface increase security by hiding the implementation
– Abstract class can be used when implementing framework
– Abstract classes are an excellent way to create planned inheritance hierarchies and
also to use as non-leaf classes in class hierarchies.
109
What is the difference between a Class and an Interface?
• A class and an interface are two different types (conceptually).
110
QUESTION:
IF AN OBJECT IS ALSO A COLLECTION OF VARIABLES AND
METHODS, HOW DO THEY DIFFER FROM CLASSES?
Answer:
No memory is allocated when a class is created. Memory allocation
happens only when the actual instances of a class(the objects) are
created.
111
Infolink University College
Dilla Campus
Department of Information Technology
Lecture 3:
Java AWT and Swing
112
Contents
✓ Concepts of AWT and Swing
✓ Frame, label, Button, TextField, ComboBox,…
✓ JFrame, JLabel, JButton, JtextField, JComboBox,…
✓ Event Handling
✓ Sources
✓ Listeners
113
Abstract Window Toolkit (AWT)
• The Abstract Window Toolkit (AWT) is a GUI toolkit designed to work
across multiple platforms.
• Event-driven: the window is displayed, and when things happen, an
event handler is called. Generally, the default event handler is to do
nothing.
• A graphical user interface is built of graphical elements called
components.
• Typical components include items such as buttons, scrollbars, and text
fields.
• Components allow the user to interact with the program and provide the
user with visual feedback about the state of the program.
• Must import java.awt.* and java.awt.event.*
114
General Layout of AWT
Swing
115
What are Components?
• A component is an object having a graphical representation that can be
displayed on the screen like checkboxes, menus, windows, buttons, text
fields, applets, and more.
• A container is a special component that can hold other components like
panels, windows, applets, frames.
• Functionality of most GUI components derive from the Component
and Container classes.
• Represents something that has a position and a size and can be painted
on the screen as well as receive input events.
• This is an abstract class and may not be instantiated.
Some important methods:
• public void paint(Graphics g);
• public void show( );
• public void addComponentListener(ComponentListener l )
• Various routines to set fonts, handle mouse events, etc.
116
Top Level Windows
• Window: A top-level window that has no border.
• Frame: A top-level window that has a border and can also have an
associated MenuBar.
117
Important I/O Components
• Button: A push button.
• Canvas: General-purpose component that lets you paint or trap input
events from the user. It can be used to create graphics.
• Checkbox: A component that has an "on" or "off" state. You can place
Checkboxes in a group that allows at most 1 box to be checked.
• Choice: A component that allows the selection of one of a group of
choices. Takes up little screen space.
• Label: A component that displays a static string at a certain location.
• List: A scrolling list of strings. Allows one or several items to be
selected.
• TextArea: Multiple line text components that allows viewing and
editing.
• TextField: A single-line text component that can be used to build forms.
118
Where to declare components
• Components are typically declared in one of several places:
119
Eg1:
import java.awt.*;
public class Hello extends Frame {
private Label text;
public Hello() // constructor
{
// create a label containing "Hello World!", with the text
centered
text = new Label("Hello World!", Label.CENTER);
f.add(b);
f.pack();
f.setVisible(true);
}
public class MyListener implements ActionListener{
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "you clicked me "); //from Swing
}
}
} 121
Eg3: Frame f = new Frame();
f.addWindowListener(new
import java.awt.*; WindowAdapter(){
public void windowClosing(WindowEvent we)
import java.awt.event.*; {
public class GUI3 System.exit(0); //close the window
{ }
static TextField tf = new TextField(12); });
static int count = 0; Panel p = new Panel();
p.setLayout(new FlowLayout());
public static void main(String[] args) { p.add(but); p.add(tf);
Button but = new Button("Press Me"); f.add(p);
but.addActionListener(new f.pack();
ActionListener() { f.setVisible(true);
public void }
actionPerformed(ActionEvent ev) { }
count++;
tf.setText("clicked " + count);
}
});
122
123
WHAT IS SWING?
• Swing is Java's GUI(graphical user interface) library
• Swing is created to provide a more sophisticated set of GUI components than
the Abstract Windows Toolkit (AWT)
• You MUST import the following packages to use swing:
import javax.swing.*;
• Java Swing consists of:
– Pluggable Look and feel – means each picture shows the same program but with a
different look and feel
– Java 2D
• javax.swing and java.awt together offer a complete API for Java applications to
operate graphical devices and create GUI.
124
WHAT IS SWING?
The Swing package contains following sub packages:
• javax.swing - Provides a set of "lightweight“ components that, to the
maximum degree possible, work the same on all platforms.
• javax.swing.border - Provides classes and interfaces for drawing specialized
borders around a Swing component.
• javax.swing.colorchooser - Contains classes and interfaces used by the
JColorChooser component.
• javax.swing.event - Provides support for events fired by Swing components.
• javax.swing.filechooser - Contains classes and interfaces used by the
JFileChooser component.
• javax.swing.plaf - Provides one interface and many abstract classes that
Swing uses to provide its pluggable look and feel capabilities.
• javax.swing.plaf.basic - Provides user interface objects built according to the
Basic look and feel.
125
WHAT IS SWING?
• javax.swing.plaf.metal - Provides user interface objects built according to the
Java look and feel (once codenamed Metal), which is the default look and feel.
• javax.swing.plaf.multi - Provides user interface objects that combine two or
more look and feels.
• javax.swing.plaf.synth - Provides user interface objects for a skinnable look and
feel in which all painting is delegated.
• javax.swing.table - Provides classes and interfaces for dealing with JTable.
• javax.swing.text - Provides classes and interfaces that deal with editable and
non-editable text components.
• javax.swing.text.html - Provides the class HTMLEditorKit and supporting
classes for creating HTML text editors.
• javax.swing.text.html.parser - Provides the default HTML parser, along with
support classes.
• javax.swing.text.rtf - Provides a class (RTFEditorKit) for creating Rich Text
Format text editors.
• javax.swing.tree - Provides classes and interfaces for dealing with JTree.
• javax.swing.undo - Allows developers to provide support for undo/redo in
applications such as text editors.
126
Why Swing?
• Better, more flexible GUIs.
• Faster. Uses “lightweight components”
• Automatic keyboard navigation
• Easy scrolling
• Easy tooltips
• Mnemonics
• General attempt to compete with MFC
• Can set custom look-and-feel
127
Swing Components
• Usually start with ‘J’:
• All components are lightweight (written in Java) except:
– Japplet
– Jframe
– Jwindow
– Jdialog
• AWT components have Swing analogs
AWT to Swing Mappings
• Almost all map by prepending a ‘J’
Examples:
– Button -> Jbutton
– Panel -> Jpanel
– List -> Jlist
Exceptions:
– Checkbox -> JCheckBox (note case change)
– Choice -> JComboBox
128
Some New Components
• Jtree
– Creates a tree, whose nodes can be expanded.
• Jtable
– Used to display tables (for instance, those obtained from databases)
• Tooltips
– Use setToolTipText to install a tooltip.
– Works for any JComponent.
Jbutton b = new Jbutton( "Quit" );
b.setToolTipText("Press to quit");
• JPopupMenu
– Appears when you right-click on a component
• JOptionPane
– Contains static methods that pop up a modal dialog.
– Commonly used methods are:
showMessageDialog( )
showConfirmDialog( )
showInputDialog( )
129
• Borders
– Use setBorder to set borders for a JComponent.
– Available borders include
• TitledBorder
• EtchedBorder
• LineBorder
• MatteBorder
• BevelBorder
• SoftBevelBorder
• CompoundBorder
– In package javax.swing.border
130
• Sliders
– Sliders are implemented with the Jslider class.
– Important methods:
JSlider( int orient, int low, int high, int val );
void setValue( int val );
int getValue( );
void setPaintTicks( boolean makeTicks );
void setMajorTickSpacing( int n );
void setMinorTickSpacing( int n );
ChangeListener interface handles slider
events. Must implement stateChanged
method.
– Note: this interface is in package javax.swing.event.
131
• Progress Bars
– JProgressBar displays data in relative fashion from empty (default
value=0) to full (default value=100).
– Interesting methods
double getPercentComplete( );
int getValue( );
void setValue( int val );
• Scrolling
– Use a JScrollPane to wrap any Component.
– Scrolling will be automatically done.
– Example:
JPanel p = new JPanel( );
JList list = new JList( );
for( int i = 0; i < 100; i++ )
list.addItem( "" + i );
p.add( new JScrollPane( list ) );
132
• Other Stuff (There's Lots)
– JFileChooser: supports file selection
– JPasswordField: hides input
– HTML-aware: Can do simple HTML formatting and display
– JTextPane: text editor that supports formatting, images, word
wrap
– …
Implementing a Swing GUI
– Import javax.swing.*, java.io.*, java.awt.*
– Make a specific class to do GUI functions
– Specify all the GUI functions/components in the class’s constructor
(or methods / classes called by the constructor)
– Run the GUI by instantiating the class in the class’s main method
133
Anatomy of an Application GUI
GUI Internal structure
JFrame JFrame
JPanel
containers
JPanel
JButton
JButton JLabel
JLabel
134
Anatomy of a JFrame
title bar
minimize
maximize
close
135
Eg1:
import javax.swing.*;
public class HelloWorldSwing {
public static void main(String[] args) {
// let’s create a frame object and give some title
JFrame frame = new JFrame("HelloWorldSwing");
// let’s have a label
JLabel label = new JLabel("Hello World");
//let’s add the label to the frame we have created above
frame.getContentPane().add(label);
//this is the operation to do when the window is closed.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//pack() causes a window to be sized to fit the preferred
//size and layouts of its sub-components
frame.pack();
// let’s make the frame to be visible
frame.setVisible(true);
}
}
136
Eg2
public class Trials {
static JButton b = new JButton("Click me");
public static void main(String[] a){
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Trials t = new Trials();
b.addActionListener(t.new MyListener());
f.add(b);
f.pack();
f.setVisible(true);
}
public class MyListener implements ActionListener{
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "you clicked me ");
}
}
}
137
Eg3: JFrame f = new JFrame();
import javax.swing.*;
import java.awt.*; f.setDefaultCloseOperation(JFrame.EXIT_
import javax.swing.event.*; ON_CLOSE);
import java.awt.event.*; JPanel p = new JPanel();
public class GUI2 p.setLayout(new FlowLayout());
{ p.add(but); p.add(tf);
static JTextField tf = new JTextField(12); f.add(p);
static int count = 0; f.pack();
public static void main(String[] args) { f.setVisible(true);
JButton but = new JButton("Press Me"); }
but.addActionListener(new
ActionListener() { }
public void
actionPerformed(ActionEvent ev) {
count++;
tf.setText("clicked " + count);
}
});
138
Swing Vs. AWT
• Concepts are all the same.
• AWT is more portable Swing is better looking
• AWT lays out inconsistently on different OSs)
• Most old AWT is easily translated: Add J in front of the class names
• AWT Uses peer components of the OS; heavyweight components
• Swing has easy-to-use new stuff including tooltips, mnemonics, borders,
JOptionPane.
• Swing 99% java; lightweight components
• Swing lays out consistently on all OSs
• Swing uses AWT event handling
• Unlike AWT components, Swing components are not implemented by
platform-specific code. Instead they are written entirely in Java and
therefore are platform-independent. The term "lightweight" is used to
describe such an element.
139
Swing Vs. AWT
• Swing provides replacements for most of the AWT components, although
many AWT non-component classes remain in use.
• Upward compatibility is assured in almost all cases; an AWT continues to
work in Java.
• Mixing both Swing and AWT components in the same interface can
produce errors, so one has to make a decision about which to use.
• Swing advantages
• Swing is faster.
• Swing is more complete.
• Swing is being actively improved.
• AWT advantages
• AWT is supported on older, as well as newer, browsers so Applets
written in AWT will run on more browsers.
• The Java Micro-Edition, which is used for phones, TV settop boxes,
PDAs, etc, uses AWT, not Swing.
140
What Is Layout?
• A layout is a set of rules that defines how graphical components should be
positioned in a container.
• Layouts tell Java where to put components in containers.
• Every panel (and other container) has a default layout.
• Each layout has its own way to resize components to fit the layout.
There two ways to position a component in a container:
1. Using a predefined layout and allowing the layout to decide where to
position the component.
• This is a soft way of positioning a component. If the container changes its size, the
component's position will be adjusted.
• But you may not able to get precisely where you want to component to be.
2. Specifying the position of the component using the container's
coordinates.
• This is a hard way of positioning a component.
• You can get precisely where you want the component to be. But if the container
changes its size, the component's position will not be adjusted.
141
142
Events - Introduction
• Events come from User Controls
• Events are actions usually triggered by the system user such as clicking a
button; however, events can also be triggered by the actions of objects.
• For example, buttons, menus, sliders, mouse clicks, ... all generate events
when the user does something with them.
• Every Input Control (Button, Slider, ...) Needs an Event Listener
• If you want a control to do something when the user alters the control, you
must have a listener.
• import Statements: To use events, you must import :-
• import java.awt.*;
AWT
• import java.awt.event.*;
• import javax.swing.*;
• import javax.swing.event.*; Swing
143
Listeners
• A listener is called when the user does something to the user
interface that causes an event.
Button listener example
• After a button is created, you will add a listener to it.
Eg,
b.addActionListener(listener_object);
144
Event Handling
• One of the key concepts in GUI programming is Event Handling.
• Something (Mouse click / Key press, Menu Selection, Timer expiring,
Network message received) happens. These would be all Event Sources.
• Some GUI components might care about one of these things happening
and need to react to it.
• These components would register themselves with the Event Source, so
the source would tell them when something happens. These are the Event
Listeners.
Event Basics
• All Events are objects of Event Classes.
• All Event Classes derive from EventObject.
• When an Event occurs, Java sends a message to all registered Event
Listeners from the Event source (this actually was a change, the old AWT
event model would send it out to everyone).
145
Event Handling in Java
Act that results in the event Listener type
User clicks a button, presses Return while ActionListener
typing in a text field, or chooses a menu item
User closes a frame (main window) WindowListener
ButtonTest() //constructor
{
theField=new JTextField(20);
actionButton=new JButton(“Set Text Field”);
this.add(theField); // add components to ourself (we’re a panel)
this.add(actionButton);
actionButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
theField.setText(“JButton was pressed”);
}
});
149
}}
Other Listener Classes
• So far, we’ve only dealt with ActionListeners, which only have 1
method defined, actionPerformed.
• Some Event classes have multiple methods defined, for instance,
WindowListener, which looks like
public interface WindowListener {
void windowOpened(WindowEvent e);
void windowClosing(WindowEvent e);
void windowClosed(WindowEvent e);
void windowIconified(WindowEvent e);
void windowDeIconified(WindowEvent e);
void windowActivated(WindowEvent e);
void windowDeActivated(WindowEvent e);
}
Reading Assignment:
Adapter Classes
150
Types of Event
• Java makes a useful distinction between two types of events. low-level
events and semantic events.
• A semantic event is something like a user clicking a button.
ActionEvents are semantic events.
• A low-level event is something like a key being pressed, or a mouse
moving.
• Semantic Events are built upon low level events and are handled for
you.
154
Infolink University College
Dilla Campus
Department of Information Technology
Lecture 4:
Exception Handling and I/O
Contents
• Exceptions and Assertions
• Streams and File I/O
156
Programming Errors
We learned that there are three categories of errors:
– Syntax errors: arise because the rules of the language
have not been followed. They are detected by the
compiler
– Runtime errors: occur while the program is running if
the environment detects an operation that is impossible
to carry out.
– Logic errors: occur when a program doesn't perform the
way it was intended to.
157
Introduction
– Users have high expectations for the code we produce.
– Checked exceptions are inherited from the core Java class Exception.
They represent exceptions that are frequently considered “non fatal”
to program execution
– Unchecked exceptions represent error conditions that are considered
“fatal” to program execution.
– You do not have to do anything with an unchecked exception. Your
program will terminate with an appropriate error message.
163
Exceptions
• Examples:
– Checked exceptions include errors such as “array index out of
bounds”, “file not found” and “number format conversion”.
– Unchecked exceptions include errors such as “null pointer”.
165
Exception Handler
Exception
"thrown" here
Thrown exception matched against first
set of exception handlers
Exception
handler
If it fails to match, it is matched against
next set of handlers, etc.
Exception
handler
166
Terminology
– Thrown exception – an exception that has occurred
– Stack trace
– Throw point – initial point at which the exception occurs, top row
of call chain
167
Coding Exceptions
• Try-Catch Mechanism
– Wherever your code may trigger an exception, the normal code logic
is placed inside a block of code starting with the “try” keyword.
– After the try block, the code to handle the exception should it arise is
placed in a block of code starting with the “catch” keyword.
• Finally blocks can be used for operations that must happen no matter what
(i.e. cleanup operations such as closing a file)
168
Coding Exceptions
• Example
try
{
… //normal program code
}
catch(Exception e)
{
… //exception handling code
}
finally
{
… //normal program code
}
169
Java Exception Hierarchy
– Class Throwable, superclass of Exception
171
Code Example
import java.io.*;
public class ExcepTest
{
public static void main(String args[]){
try
{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
} Output:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block 172
Summary
– Exceptions are a powerful error handling mechanism.
– Exceptions in Java are built into the language.
– Exceptions can be handled by the programmer (try-catch), or
handled by the Java environment (throws).
Assertions
– An assertion is a Java statement that enables you to assert an
assumption about your program. An assertion contains a Boolean
expression that should be true during program execution.
Assertions can be used to assure program correctness and avoid
logic errors.
Reading Assignment:
Assertions
Streams and I/O173
I/O Overview
– I/O = Input/Output
• permanent copy
174
Streams
– Streams are sequences of data.
– Stream: an object that either delivers data to its destination (screen,
file, etc.) or that takes data from a source (keyboard, file, etc.)
• it acts as a buffer between the data source and destination
– Input stream: a stream that provides input to a program
• System.in is an input stream
– Output stream: a stream that accepts output from a program
• System.out is an output stream
– A stream connects a program to an I/O object
• System.out connects a program to the screen
• System.in connects a program to the keyboard
175
Binary Vs. Text Files
• All data and programs are ultimately just zeros and ones
• Text files: the bits represent printable characters
– for example, Java source files are text files
– so is any file created with a "text editor“
– Text files are more readable by humans
• Binary files: the bits represent other types of encoded information,
such as executable instructions or numeric data
– these files are easily read by the computer but not humans
177
Text File Output
• To open a text file for output: connect a text file to a stream for
writing
PrintWriter outputStream =
new PrintWriter(new FileOutputStream("out.txt"));
• print
• format
• flush: write buffered output to disk
• close: close the PrintWriter stream (and file)
179
Example
public static void main(String[] args)
{
PrintWriter outputStream = null;
try
{
outputStream = new PrintWriter(new
FileOutputStream("out.txt"));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file out.txt. “
+ e.getMessage());
System.exit(0);
}
180
System.out.println("Enter three lines of text:");
String line = null;
int count;
for (count = 1; count <= 3; count++)
{
line = keyboard.nextLine();
outputStream.println(count + " " + line);
}
outputStream.close();
System.out.println("... written to out.txt.");
}
181
Overwriting a File
• Opening an output file creates an empty file
• Opening an output file creates a new file if it does not already exist
• Opening an output file that already exists eliminates the old file and creates a new, empty one
- data in the original file is lost
• To add/append to a file instead of replacing it, use a different constructor for
outputStream = new PrintWriter(new FileOutputStream("out.txt", true));
Closing a File
• An output file should be closed when you are done writing to it.
• Use the close method of the class PrintWriter (BufferedReader also has a close
method).
• For example, to close the file opened in the previous example:
outputStream.close();
• If a program ends normally it will close any files that are open.
182
Text File Input
• To open a text file for input: connect a text file to a stream for reading
• For example:
183
Methods for BufferedReader
• readLine: read a line into a String
– import java.util.*
• read returns -1 when it tries to read beyond the end of a text file
188
Reading in int
Scanner inFile = new Scanner(new File(“in.txt"));
int number;
while (inFile.hasInt())
{
number = inFile.nextInt();
// …
}
Reading in lines of characters
Scanner inFile = new Scanner(new File(“in.txt"));
String line;
while (inFile.hasNextLine())
{
line = inFile.nextLine();
// …
} 189
BufferedReader vs Scanner
(parsing primitive types)
• Scanner
• BufferedReader
190
BufferedReader vs Scanner
(Checking End of File/Stream (EOF))
• BufferedReader
– readLine() returns null
– read() returns -1
• Scanner
– nextLine() throws exception
– needs hasNextLine() to check first
– nextInt(), hasNextInt(), …
191
Opening a New Output File
• The file name is given as a String
– file name rules are determined by your operating system
• Opening an output file takes two steps
1. Create a FileOutputStream object associated with the file
name String
2. Connect the FileOutputStream to an
ObjectOutputStream object
• This can be done in one line of code
• To open a file named numbers.dat:
ObjectOutputStream outputStream =
new ObjectOutputStream(
new FileOutputStream("numbers.dat"));
192
• Writing a Character to a File
– just cast the character to an int
– For example, to write the character 'A' to the file opened previously:
outputStream.writeChar((int) 'A');
– Or, just use the automatic conversion from char to int
• Writing a boolean Value to a File
• boolean values can be either of two values, true or false
• For example, to write the boolean value false to the output file:
outputStream.writeBoolean(false);
• Writing Strings to a File:
• Use the writeUTF method to output a value of type String
– there is no writeString method
• UTF stands for Unicode Text Format
– a special version of Unicode
193
Opening a New Input File
• Similar to opening an output file, but replace "output" with "input"
ObjectInputStream inStream =
new ObjectInputStream (new FileInputStream("numbers.dat"));
194
Summary
• Text files contain strings of printable characters; they look intelligible to
humans when opened in a text editor.
• Binary files contain numbers or data in non-printable codes; they look
unintelligible to humans when opened in a text editor.
• Java can process both binary and text files, but binary files are more
common when doing file I/O.
• The class ObjectOutputStream is used to write output to a binary
file.
• The class ObjectInputStream is used to read input from a binary
file.
• Always check for the end of the file when reading from a file. The way
you check for end-of-file depends on the method you use to read from
the file.
• A file name can be read from the keyboard into a String variable and
the variable used in place of a file name.
• The class File has methods to test if a file exists and if it is read- and/or
write-enabled.
• Serializable class objects can be written to a binary file.
195
Infolink University College
Dilla Campus
Department of Information Technology
Lecture 5:
Networking in Java
Contents
• Introduction
– Sockets, ports, URLs
• Socket Programming with TCP
• Socket Programming with UDP
• Some Important Methods
197
Introduction
– Java provides a number of built-in networking capabilities that make
it easy to develop Internet-based and web-based applications.
– The term network programming refers to writing programs that
execute across multiple devices (computers), in which the devices
are all connected to each other using a network.
– Through the classes in java.net Java programs can use TCP or UDP
to communicate over the Internet.
– Through classes from java.net, Java offers
• Stream-based communications that enable applications to view networking as
streams of data as if it were file I/O. (TCP)
• Packet-based communications for transmitting individual packets of
information—commonly used to transmit data images, audio and video over the
Internet. (UDP)
198
Introduction (contd)
• Socket - connecting to other computers
– Is simply a software construct that represents one endpoint of a
connection.
– A socket is a host-local, application-created, OS-controlled
interface (a “door”) into which application process can both send
and receive messages to/from another application process.
– When connecting to another computer you use a ‘socket’.
– When opening a file you uniquely identify it by its file name.
– When connecting to a computer you uniquely identify it with its IP
number.
– There are two types of Sockets:
199
Introduction (contd)
Stream Socket
– With stream sockets, a process establishes a connection to another
process.
– While the connection is in place, data flows between the processes in
continuous streams.
– Stream sockets are said to provide a connection-oriented service.
– The protocol used for transmission is the popular TCP (Transmission
Control Protocol).
Datagram Socket
– With datagram sockets, individual packets of information are
transmitted.
– The protocol uses—UDP, the User Datagram Protocol—is a
connectionless service and does not guarantee that packets arrive in
any particular order.. 200
• Ports - connecting to programs on other computer over
a network
– Using a unique number we can identify a computer to
connect to
• However, computers have many programs running on them
• We identify which program to communicate with by using a
port number.
• Common networking programs (such as telnet, ftp and WWW
services) are always on the same port. These ports are called
“well known”.
• Telnet is on port 23, FTP on port 21, WWW services are on
port 80, etc.
201
Socket-programming using TCP
Socket: a door between application process and end-end-transport
protocol (UDP or TCP)
TCP service: reliable transfer of bytes from one process to another
controlled by
controlled by process application
application process
developer
developer socket socket
TCP with TCP with controlled by
controlled by
buffers, operating
operating buffers, internet variables system
system variables
host or host or
server server
202
Socket programming with TCP
Client must contact server
• server process must first be running
• server must have created socket (door) that welcomes client’s
contact
Client contacts server by:
• creating client-local TCP socket
• specifying IP address, port number of server process
• When client creates socket: client TCP establishes connection to
server TCP
• When contacted by client, server TCP creates new socket for server
process to communicate with client
– allows server to talk with multiple clients
– source port numbers used to distinguish clients
203
Client/server socket interaction: TCP
Server (running on hostid) Client
create socket,
port=x, for
incoming request:
welcomeSocket =
ServerSocket()
write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
clientSocket
204
Socket programming with TCP
Example client-server app:
1) client reads line from standard input (inFromUser
stream) , sends to server via socket (outToServer
stream)
2) server reads line from socket
3) server converts line to uppercase, sends back to client
4) client reads, prints modified line from socket
(inFromServer stream)
205
Example: Java client (TCP)
import java.io.*;
import java.net.*;
class TCPClient {
sentence = inFromUser.readLine();
Send line
to server outToServer.writeBytes(sentence + '\n');
clientSocket.close();
}
}
207
Example: Java server (TCP)
import java.io.*;
import java.net.*;
class TCPServer {
208
Example: Java server (TCP)
Create output
stream, attached
DataOutputStream outToClient =
to socket
new DataOutputStream(connectionSocket.getOutputStream());
Read in line
from socket clientSentence = inFromClient.readLine();
209
Socket programming with UDP
UDP: no “connection” between client and server
• no handshaking
• sender explicitly attaches IP address and port of
destination to each packet
• server must extract IP address, port of sender from
received packet
UDP: transmitted data may be received out of order, or
lost
210
Client/server socket interaction: UDP
Server (running on hostid) Client
write reply to
serverSocket
specifying read datagram from
client address, clientSocket
port number close
clientSocket
211
Example: Java client (UDP)
import java.io.*;
import java.net.*;
class UDPClient {
public static void main(String args[]) throws Exception
Create {
input stream
BufferedReader inFromUser =
Create new BufferedReader(new InputStreamReader(System.in));
client socket
DatagramSocket clientSocket = new DatagramSocket();
Translate
hostname to IP InetAddress IPAddress = InetAddress.getByName("hostname");
address using DNS
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String modifiedSentence =
new String(receivePacket.getData());
213
Example: Java server (UDP)
import java.io.*;
import java.net.*;
class UDPServer {
public static void main(String args[]) throws Exception
Create {
datagram socket
at port 9876 DatagramSocket serverSocket = new DatagramSocket(9876);
while(true)
{
Create space for
received datagram DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
Receive serverSocket.receive(receivePacket);
datagram
214
Example: Java server (UDP)
String sentence = new String(receivePacket.getData());
Get IP addr
port #, of InetAddress IPAddress = receivePacket.getAddress();
sender
int port = receivePacket.getPort();
sendData = capitalizedSentence.getBytes();
Create datagram
to send to client DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
port);
Write out
datagram serverSocket.send(sendPacket);
to socket }
}
} End of while loop,
loop back and wait for
another datagram
215
Example - Client
class Client {
public static void main(String args[]) {
try {
Socket skt = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream()));
System.out.print("Received string: '");
while (!in.ready()) {}
System.out.println(in.readLine()); // Read one line and output it
System.out.print("'\n");
in.close();
}
catch(Exception e) {
System.out.print("Oops! It didn't work!\n");
}
}
}
216
Example - Server
import java.lang.*;
import java.io.*;
import java.net.*;
class Server {
public static void main(String args[]) {
String data = "This is a test msg";
try {
ServerSocket srvr = new ServerSocket(1234);
Socket skt = srvr.accept();
System.out.print("Server has connected!\n");
PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
System.out.print("Sending string: '" + data + "'\n");
out.print(data);
out.close(); skt.close(); srvr.close();
}
catch(Exception e) {
System.out.print("Oops! It didn't work!\n");
}
}
}
217
218
Socket Methods
public ServerSocket(int port) throws IOException
Attempts to create a server socket bound to the specified port. An exception
occurs if the port is already bound by another application.
public ServerSocket(int port, int backlog) throws IOException
Similar to the previous constructor, the backlog parameter specifies how many
incoming clients to store in a wait queue.
public ServerSocket(int port, int backlog, InetAddress address) throws
IOException
Similar to the previous constructor, the InetAddress parameter specifies the local
IP address to bind to. The InetAddress is used for servers that may have multiple
IP addresses, allowing the server to specify which of its IP addresses to accept
client requests on
public ServerSocket() throws IOException
Creates an unbound server socket. When using this constructor, use the bind()
method when you are ready to bind the server socket
219
Socket Methods (contd)
public int getLocalPort()
Returns the port that the server socket is listening on. This method is useful if you
passed in 0 as the port number in a constructor and let the server find a port for you.
Lecture 6:
JDBC
Contents
• Overview of JDBC
• JDBC Drivers
• Statements and Prepared Statements
• Connecting to a Database
224
Overview of JDBC
– JDBC is a specification that provides a complete set of interfaces
and classes that allows for portable access to an underlying
database.
– Using JDBC you can send SQL statements to almost any relational
database.
– JDBC is a Java API for executing SQL statements and supports
basic SQL functionality.
– It provides RDBMS access by allowing you to embed SQL inside
Java code.
– The JDBC library includes APIs for each of the tasks commonly
associated with database usage:
• Making a connection to a database
• Creating SQL or MySQL statements
• Executing that SQL or MySQL queries in the database
• Viewing & Modifying the resulting records
225
Overview of JDBC (contd)
– The JDBC Classes and Interfaces are in the java.sql package
What does JDBC do?
• Establish a connection with a database
• Send SQL statements
• Process the results
Steps in using JDBC
1. Load the JDBC driver
2. Define the Connection URL
3. Establish the Connection
4. Create a Statement object
5. Execute a query
6. Process the results
7. Close the connection
226
JDBC Model
How It Works
– Java code calls JDBC library
– JDBC loads a driver
– Driver talks to a particular database
– An application can work with several databases by using all
corresponding drivers
– Ideal: can change database engines without changing any
application code (not always in practice)
227
JDBC Model (cont)
– JDBC consists of two parts:
• The JDBC API
• JDBC Driver Manager, which
communicates with vendor-
specific drivers that interact
with the database
228
JDBC Model(cont)
Oracle
Driver
Oracle
DB2
Network
MySQL
Driver
MySQL
229
JDBC Driver Types
– JDBC drivers implement the defined interfaces
in the JDBC API for interacting with your
database server.
– For example, using JDBC drivers enable you to
open database connections and to interact with it
by sending SQL or database commands then
receiving results with Java.
– The Java.sql package contains various classes
with their behaviors defined and their actual
implementaions are done in third-party drivers.
Third party vendors implements the
java.sql.Driver interface in their database driver.
230
JDBC Driver Types(cont)
Type Description
java.sql.package
java.sql.DriverManager
(JDBC library)
4. Connection
supplied by
Driver for MySQL Driver for Oracle DriverManager is
databases databases used by
application to talk
How JDBC establishes a JDBC through
connection between your the driver to the
MySQL
code and a database database.
DB
JDBC Programming Steps
233
Primary JDBC classes
– Java classes used for JDBC
• DriverManager: used to load the class which is the driver for a
specific database.
• Connection: the database connection interface.
• Statement: An SQL statement to be executed on the
connection.
• ResultSet: The set of results that are returned by a query.
• DataSource: interface can be used for any object that can be
used as a database connection.
234
JDBC - Statements
– Once a connection is obtained we can interact
with the database.
– The JDBC Statement, CallableStatement, and
PreparedStatement interfaces define the methods
and properties that enable you to send SQL
commands and receive data from your database.
– They also define methods that help bridge data
type differences between Java and SQL data types
used in a database.
235
JDBC - Statements
Interfaces Recommended Use
241
Some Popular JDBC Drivers
RDBMS JDBC Driver Name
Driver Name : com.mysql.jdbc.Driver
MySQL Database URL format:
jdbc:mysql//hostname/databaseName
Driver Name : oracle.jdbc.driver.OracleDriver
Oracle Database URL format:
jdbc:oracle:thin@hostname:portnumber:databaseName
Driver Name : com.ibm.db2.jdbc.net.DB2Driver
DB2 Database URL format:
jdbc:db2:hostname:portnumber/databaseName
Driver Name : com.jdbc.odbc.JdbcOdbcDriver
Access Database URL format:
jdbc:odbc:databaseName
Driver Name : com.org.derby.jdbc.ClintDriver
Java DB Database URL format:
jdbc:derby:databaseName
JDBC - Result Sets
– The SQL statements that read data from a database query return the
data in a result set.
– The rows that satisfy a particular query are called the result set.
– A user can access the data in a result set using a cursor one row at
a time from top to bottom
– The java.sql.ResultSet interface represents the result set of a
database query.
– A ResultSet object maintains a cursor that points to the current row
in the result set.
– ResultSet interface methods can be broken down into three
categories:
• Navigational methods: used to move the cursor around.
• Get methods: used to view the data in the columns of the current row being
pointed to by the cursor.
• Update methods: used to update the data in the columns of the current row.
The updates can then be updated in the underlying database as well. 243
JDBC - Result Sets
– JDBC provides following connection methods to create
statements with desired ResultSet:
1. createStatement(int RSType, int RSConcurrency);
2. prepareStatement(String SQL, int RSType, int RSConcurrency);
3. prepareCall(String sql, int RSType, int RSConcurrency);
– The first argument indicate the type of a ResultSet object and the
second argument is one of two ResultSet constants for specifying
whether a result set is read-only or updatable.
244
JDBC - Result Sets
Type of ResultSet:
• The possible RSType are given below, If you do not specify any ResultSet type,
you will automatically get one that is TYPE_FORWARD_ONLY.
Type Description
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set.
245
JDBC - Result Sets
Concurrency of ResultSet:
• The possible RSConcurrency are given below, If you do not specify any
Concurrency type, you will automatically get one that is CONCUR_READ_ONLY.
Concurrency Description
• getMaxRows/setMaxRows
– Maximum number of rows a ResultSet may contain
– Unless explicitly set, the number of rows is unlimited
251
JDBC - Result Sets
Updating a Result Set:
• The ResultSet interface contains a collection of update methods for updating the
data of a result set.
• As with the get methods, there are two update methods for each data type:
1. One that takes in a column name.
2. One that takes in a column index.
• For example, to update a String column of the current row of a result set, you
would use one of the following updateString() methods:
252
JDBC - Result Sets
Updating a Result Set:
• There are update methods for the eight primitive data types, as well as String, Object,
URL, and the SQL data types in the java.sql package.
• Updating a row in the result set changes the columns of the current row in the
ResultSet object, but not in the underlying database. To update your changes to the
row in the database, you need to invoke one of the following methods.
S.N. Methods & Description
public void updateRow()
1
Updates the current row by updating the corresponding row in the database.
public void deleteRow()
2
Deletes the current row from the database
public void refreshRow()
3
Refreshes the data in the result set to reflect any recent changes in the database.
public void cancelRowUpdates()
4
Cancels any updates made on the current row.
public void insertRow()
5 Inserts a row into the database. This method can only be invoked when the cursor is pointing to
the insert row.
253
Infolink University College
Dilla Campus
Department of Information Technology
Lecture 7:
Remote Method Invocation(RMI)
Contents
• Overview of RMI
• The RMI Registry
• The Remote Interface
• Implementing RMI
255
• Consider the following program organization:
method call
SomeClass AnotherClass
returned object
computer 1 computer 2
257
Marshalling Parameters
258
RMI and Other Technologies
– CORBA (Common Object Request Broker Architecture)
was used for a long time.
– Microsoft supported CORBA, then COM, now .NET
– Remote Procedure Call (RPC)
– RMI is purely Java-specific
– Java to Java communications only
– As a result, RMI is much simpler than CORBA
259
The General RMI Architecture
Remote Machine
– The server must first bind its
bind
name to the registry RMI Server
Registry
– The client lookup the server skeleton
260
The Stub and Skeleton
call
skeleton
Stub
RMI Client RMI Server
return
264
Terminology
– A remote object is an object on another computer
– The client object is the object making the request (sending a
message to the other object)
– The server object is the object receiving the request
– As usual, “client” and “server” can easily trade roles (each
can make requests of the other)
– The rmiregistry is a special server that looks up objects by
name
– rmic is a special compiler for creating stub (client) and
skeleton (server) classes
265
Processes
– For RMI, you need to be running three processes
• The Client
• The Server
• The Object Registry, rmiregistry, which is like a DNS
service for objects
– You also need TCP/IP active
266
Remote Interfaces and Class
• A Remote class has two parts:
– The interface (used by both client and server):
• Must be public
• Must extend the interface java.rmi.Remote
• Every method in the interface must declare that it throws
java.rmi.RemoteException (other exceptions may also be
thrown)
– The class itself (used only by the server):
• Must implement the Remote interface
• Should extend java.rmi.server.UnicastRemoteObject
• May have locally accessible methods that are not in its
Remote interface
267
Security
• It isn’t safe for the client to use somebody else’s
code on some random server
– System.setSecurityManager(new RMISecurityManager());
– The security policy of RMISecurityManager is the same as
that of the default SecurityManager
– Your client program should use a more conservative
security manager than the default
268
The Server Class
• The class that defines the server object should
extend UnicastRemoteObject
– This makes a connection with exactly one other
computer
• The server class needs to register its server object:
– String url = "rmi://" + host + ":" + port + "/" +
objectName;
– Naming.rebind(url, object);
• Every remotely available method must throw a
RemoteException (because connections can fail)
269
Steps for Developing an RMI System
1. Define the remote interface
2. Develop the remote object by implementing the remote
interface.
3. Develop the client program.
4. Compile the Java source files.
5. Generate the client stubs and server skeletons.
6. Start the RMI registry.
7. Start the remote server objects.
8. Run the client
Example 1
270
Hello world server: interface
• import java.rmi.*;
271
Hello world server: class
• import java.rmi.*;
import java.rmi.server.*;
Example 2
277
Step 1: Defining the Remote Interface
• To create an RMI application, the first step is the
defining of a remote interface between the client
and server objects.
/* SampleServer.java */
import java.rmi.*;
/* SampleServerImpl.java */
public int sum(int a,int b) throws RemoteException
{
return a + b;
}
}
• The server must bind its name to the registry, the client
will look up the server name.
• Use java.rmi.Naming class to bind the server name to
registry.
280
Step 2: Develop the remote object and its interface
/* SampleServerImpl.java */
public static void main(String args[])
{
try
{
System.setSecurityManager(new RMISecurityManager());
//set the security manager
System.out.println("Server waiting.....");
}
catch (java.net.MalformedURLException me) {
System.out.println("Malformed URL: " + me.toString()); }
catch (RemoteException re) {
System.out.println("Remote exception: " + re.toString()); }
}
281
Step 3: Develop the client program
• In order for the client object to invoke methods on the server, it must
first look up the name of server in the registry. You use the
java.rmi.Naming class to lookup the server name.
• The server name is specified as URL in the from (
rmi://host:port/name )
• Default RMI port is 1099.
• The name specified in the URL must exactly match the name that
the server has bound to the registry. In this example, the name is
“SAMPLE-SERVER”
• The remote method invocation is programmed using the remote
interface name (remoteObject) as prefix and the remote method
name (sum) as suffix.
282
Step 3: Develop the client program
import java.rmi.*;
import java.rmi.server.*;
public class SampleClient
{
public static void main(String[] args)
{
// set the security manager for the client
System.setSecurityManager(new RMISecurityManager());
//get the remote object from the registry
try
{
System.out.println("Security Manager loaded");
String url = "//localhost/SAMPLE-SERVER";
SampleServer remoteObject = (SampleServer)Naming.lookup(url);
System.out.println("Got remote object");
System.out.println(" 1 + 2 = " + remoteObject.sum(1,2) );
}
catch (RemoteException exc) {
System.out.println("Error in lookup: " + exc.toString()); }
catch (java.net.MalformedURLException exc) {
System.out.println("Malformed URL: " + exc.toString()); }
catch (java.rmi.NotBoundException exc) {
System.out.println("NotBound: " + exc.toString());
}
}
}
283
Step 4 & 5: Compile the Java source files & Generate the
client stubs and server skeletons
• Once the interface is completed, you need to
generate stubs and skeleton code.
284
Step 6: Start the RMI registry
• The RMI applications need install to Registry. And the
Registry must start manual by call rmiregisty.
• The rmiregistry us uses port 1099 by default.
• You can also bind rmiregistry to a different port by
indicating the new port number as : rmiregistry <new
port>
285
Steps 7 & 8: Start the remote server objects & Run the client
286
Infolink University College
Dilla Campus
Department of Information Technology
Lecture 8:
Threads
Contents
• Introductions to threads
• Creating a Thread
• Thread Scheduling
• Synchronization
• The Object Monitor
288
What are Threads?
– Processes – are independently running programs that are
isolated from each other.
– Threading - is a facility to allow multiple activities to coexist
within a single process.
– Java is the first programming language to explicitly
include threading within the language itself.
– Threads are sometimes referred to as lightweight processes.
– Like processes, threads are independent, concurrent paths of
execution through a program, and each thread has its own
stack, its own program counter, and its own local variables.
– However, threads within a process are less insulated from each
other than separate processes are.
– They share memory, file handles, and other per-process state.
289
What are Threads? (contd)
– A process can support multiple threads, which appear to execute
simultaneously and asynchronously to each other.
– More than one thread (program) run simultaneously is known as
multithreading (multiprogramming).
– Multiple threads within a process share the same memory address
space, which means they have access to the same variables and
objects, and they allocate objects from the same heap.
– Every Java program has at least one thread -- the main thread.
– The JVM also creates other threads that are mostly invisible to you
– for example: threads associated with garbage collection and other
JVM housekeeping tasks.
– Other facilities create threads too, such as the AWT (Abstract
Windowing Toolkit) or Swing UI toolkits, servlet containers,
application servers, and RMI (Remote Method Invocation). 290
Why Use Threads?
– Some of the reasons for using threads are that
they can help to:
• Make the UI more responsive
• Take advantage of multiprocessor systems
• Simplify modeling
• Perform asynchronous or background processing
• Allow multiple client connections simultaneously
• Maintain responsiveness of an application during a
long running task
• Speed up tasks when multiple processors available
291
Thread Risks
– While the Java thread facility is very easy to use, there are
several risks you should try to avoid when you create
multithreaded programs.
• When multiple threads access the same data item, make
sure that they coordinate their access to a shared data so
that both see a consistent.
• The Java language provides two keywords for this
purpose: synchronized and volatile.
• If you are going to use synchronization to protect access
to shared variables, you must make sure to use it
everywhere in your program where the variable is
accessed.
292
Thread Life Cycle
– A thread can be in one of several possible states through out its life.
1. Newborn State
– When we create a thread it will be in Newborn State.
– The thread is just created still its not running.
– We can move it to running mode by invoking the start() method
and it can be killed by using stop() method.
2. Runnable State
– It means that thread is now ready for running and its waiting to give
control.
– We can move control to another thread by yield() method.
293
Thread Life Cycle (contd)
3. Running State
– It means thread is in its execution mode because the control of CPU
is given to that particular thread.
– It can move in three different situation from running mode.
4. Blocked State
– A thread is called in Blocked State when it is not allowed to
entering in Runnable State or Running State.
– It happens when thread is in waiting, suspended or in sleeping
mode.
5. Dead State
– When a thread is completed executing its run() method the life
cycle of that particular thread is end.
– We can kill thread by invoking stop() method for that particular
294
thread and send it to be in Dead State.
Thread Life Cycle(contd)
295
Thread Methods
void start()
– Creates a new thread and makes it runnable
– This method can be called only once
void run()
– The new thread begins its life inside this method
void stop()
– The thread is being terminated
void yield()
– Causes the currently executing thread object to temporarily pause
and allow other threads to execute
– Allow only threads of the same priority to run
void sleep(int m) or sleep(int m, int n)
– The thread sleeps for m milliseconds, plus n nanoseconds
Creating Threads 296
Creating Thread
– We can create thread in java with two different ways.
1. Extending the Thread Class.
2. Implements Runnable interface.
Example 1:
//A program to find out the thread used by JVM to execute the statements.
class FirstDemo {
public static void main(String[] args) {
System.out.println("Let's find current thread.. ");
Thread th=Thread.currentThread();
System.out.println("Current thread is: "+th);
System.out.println("Thread name is: "+th.getName());
System.out.println("Thread priority is: "+th.getPriority());
Let's find current thread..
System.out.println("Thread is alive: "+th.isAlive());
Current thread is: Thread[main,5,main]
} Thread name is: main
} Thread priority is: 5
Thread is alive: true 297
Creating Thread(contd)
1. Extending the Thread class:
– In this method one normal class extends the inbuilt class thread
and override its run() method with the code required by that
particular thread.
– Here we are going to extend class java.lang.Thread.
• Create one class which extends the thread class.
• Override the run method and put lines of code inside
thread method that will be perform by thread.
• Create an object of class which we created with extending
the thread class and call the start() method to execute the
thread.
298
Creating Thread(contd)
• Example: MyThread.
Class MyThread extends Thread
{
………………..
………………..
}
• Implementing the run() method
public void run()
{
……… // Thread code here
}
• Starting new Thread
MyThread aTh = new MyThread(); // instantiates a new
aTh.start(); // invokes run() method
299
Creating Thread(contd)
Example One:
public class ThreadDemo extends Thread{
public static void main(String[] a) {
ThreadDemo t = new ThreadDemo ();
t.start();
System.out.println("Hello world! - From the main program.");
}
public void run() {
System.out.println("Hello world! - From a thread.");
try {
sleep(1000*60*60);
} catch (InterruptedException e) {
System.out.println("Interrupted.");
}
}
Output:
} Hello world! - From the main program.
300
Hello world! - From a thread.
Creating Thread(contd)
• A couple of things you should know about this program:
❑This program will run (actually sleep) for about one hour, after
printing those messages. So you may need to press Ctrl-C to
terminate the program.
❑There will be actually two threads running in this program. The
first one is the main thread executing all the statement in the
main() method. The second one is a sub-thread launched by the
t.start() statement.
❑Notice the order of the messages printed out on the console. It
tells us that the sub-thread took a little bit longer to run its first
statement, after it has been launched by the main thread.
❑A multi-threading program will not terminate until all its threads
has reached the end of their execution.
❑The run() method in the Thread is empty, so if you want a
thread to do some work, you need to override the run() 301
method.
Creating Thread(contd)
import java.lang.Thread;
class A extends Thread{
public void run(){
System.out.println("Thread A");
for(int i=1;i<=5;i++){
System.out.println("From thread A i = " + i);
}
System.out.println("Exit from A");
}}
class B extends Thread {
public void run(){
System.out.println("Thread B");
for(int i=1;i<=5;i++){
System.out.println("From thread B i = " + i);
}
System.out.println("Exit from B"); 302
}}
Creating Thread(contd)
public class Demo {
public static void main(String[] args) {
new A().start();//creating A class thread object and calling run method
new B().start();//creating B class thread object and calling run method
System.out.println("End of main thread");
}
} Thread A
From thread A i = 1
From thread A i = 2
From thread A i = 3
• Running the same program will yield different From thread A i = 4
From thread A i = 5
output though our program code is same. Exit from A
End of main thread
• It happens in thread program because they are Thread B
running concurrently on their own. From thread B i = 1
From thread B i = 2
• Threads are running independently of one From thread B i = 3
From thread B i = 4
another and each executes whenever it has a From thread B i = 5
chance. Exit from B 303
Creating Thread(contd)
2) Implementing the Runnable interface:
– In this method we have one interface named runnable and we
implements this interface for implementing a thread.
• Create one class which implements runnable interface.
• Override the run() method and put some line of code for that
particular thread.
• Now create an object of inbuilt thread class and create an object
of class that implements runnable interface.
• Give the reference of object to thread object by passing an
argument (argument must be the object of class which
implements the runnable interface) while creating a thread
object.
• Call the start() method to run the thread.
304
Creating Thread(contd)
Example One:
class ThreadRun implements Runnable {
public static void main(String[] a) {
ThreadRun r = new ThreadRun();
Thread t = new Thread(r);
t.start();
System.out.println("Hello world! - From the main program.");
}
public void run() {
System.out.println("Hello world! - From a thread.");
try {
Thread.sleep(1000*60*60);
} catch (InterruptedException e) {
System.out.println("Interrupted.");
} Output:
Hello world! - From the main program.
}} Hello world! - From a thread. 305
Creating Thread(contd)
• Note that:
❑ The program behaves the same way as the previous program
ThreadDemo which is created using thread objects with thread sub
classes
❑ The Thread object t is created with the special Thread constructor,
which takes a Runnable object as input..
❑ Since our class is not extending the Thread class any more, we need to
call the sleep() explicitly by prefixing the class name: Thread.
• May be you are wondering why we need the second way of creating a
new thread, which seems to be less straight forward than the first way?
The answer is that Java classes can not be extended from two different
base classes. So if you are in a situation where you want to create a new
class by extending an existing class to inherit some nice features of that
class, and you also want to make the new class executable as a thread, you
have to use the second way to implement the "Runnable" interface in your
new class. 306
Creating Thread(contd)
Example Two: Output
End of main Thread
class X implements Runnable {
Inside X thread
public void run() { From xthread i = 1
System.out.println("Inside X thread"); From xthread i = 2
for(int i=1;i<=10;i++) { From xthread i = 3
From xthread i = 4
System.out.println("From xthread i = " +i);
From xthread i = 5
} From xthread i = 6
System.out.println("Exit from X"); From xthread i = 7
}} From xthread i = 8
From xthread i = 9
public class Demo{
From xthread i = 10
public static void main(String[] args) { Exit from X
X x1 = new X(); //class object
//creating thread object and giving reference of class object to thread
object
Thread xthread = new Thread(x1);
xthread.start();
System.out.println("End of main Thread");
}}
307
Extending Thread vs. Implementing
Runnable Interface
–•
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
–E
•xtending the Thread class
• Easier to implement
• Your class can no longer extend any other class
308
The Thread Class: Constructor
309
The Thread Class: Constants
• Contains fields for priority values
310
What You Should Know
– A thread doesn't actually begin to execute until another thread
calls the start() method on the Thread object for the new
thread.
– A thread will end in one of three ways:
• The thread comes to the end of its run() method.
• The thread throws an Exception or Error that is not
caught.
• Another thread calls one of the deprecated stop() methods.
– When all the threads within a Java program complete, the
program exits.
– The Thread API contains a method for waiting for another
thread to complete: the join() method.
311
Thread Priority
– Each java thread has its own priority which decides the order of
thread to be schedule.
– The threads of equal priority will be given same treatment by java
scheduler. And they will follow the FCFS (First Come First Serve)
algorithm.
– User can also set the priority of thread by using the setPriority()
method as follow:
ThreadName.setPriority(int Number);
– Here the number is integer value between 1 to 10, Here 1 is
minimum priority 10 is maximum priority.
– The Thread class defines few priority constants:
– MIN_PRIORITY = 1
– NORM_PRIORITY = 5
– MAX_PRIORITY = 10
– In any Thread the default priority is NORM_PRIORITY
312
Thread Scheduling
Scheduling
– Except when using Thread.join() and Object.wait(), the
timing of thread scheduling and execution is
nondeterministic.
– If two threads are running at the same time and neither is
waiting, you must assume that between any two
instructions, other threads may be running and modifying
program variables.
– If your thread will be accessing data that may be visible to
other threads, such as data referenced directly or indirectly
from static fields (global variables), you must use
synchronization to ensure data consistency.
313
Sleeping
– The Thread API includes a sleep() method, which will cause
the current thread to go into a wait state until the specified
amount of time has elapsed or until the thread is interrupted by
another thread calling Thread.interrupt() on the current
thread's Thread object.
• When the specified time elapses, the thread again becomes
runnable and goes back onto the scheduler's queue of runnable
threads.
• If a thread is interrupted by a call to Thread.interrupt(), the
sleeping thread will throw an InterruptedException so that the
thread will know that it was awakened by an interrupt and won't
have to check to see if the timer expired.
– The Thread.yield() method is like Thread.sleep(), but instead
of sleeping, it simply pauses the current thread momentarily
so that other threads can run.
– In most implementations, threads with lower priority will not
run when a thread of higher priority calls Thread.yield(). 314
Daemon Threads
– It’s mentioned that a Java program exits when all of its threads have
completed, but this is not exactly correct.
• What about the hidden system threads, such as the garbage collection
thread and others created by the JVM? We have no way of stopping
these. If those threads are running, how does any Java program ever
exit?
– These system threads are called daemon threads. A Java program
actually exits when all its non-daemon threads have completed.
– Any thread can become a daemon thread.
• You can indicate a thread is a daemon thread by calling the
Thread.setDaemon() method.
• You might want to use daemon threads for background threads that
you create in your programs, such as timer threads or other deferred
event threads, which are only useful while there are other non-
315
daemon threads running.
Sharing variables
– For multiple threads to be useful in a program, they have to
have some way to communicate or share their results with each
other.
– The simplest way for threads to share their results is to use
shared variables.
– They should also use synchronization to ensure that values are
propagated correctly from one thread to another and to prevent
threads from seeing inconsistent intermediate results while
another thread is updating several related data items.
316
Thread Synchronization
Race condition & How to Solve it
–R
•ace conditions occur when multiple, asynchronously
executing threads access the same object (called a shared
resource) returning unexpected (wrong) results
–E
•xample: Threads often need to share a common resource
i.e. a file, with 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
Method one An Unsynchronized Example
class PrintStringsThread implements public void run() {
Runnable { System.out.print(this.str1);
Thread thread; try {
String str1, str2; java.lang.Thread.sleep(2000);
PrintStringsThread(String str1, String }catch (InterruptedException ie) { }
str2) { System.out.println(this.str2);
this.str1 = str1; }
this.str2 = str2; }
thread = new java.lang.Thread(this); public class RaceConditionDemo{
thread.start(); public static void main(String[] args) {
} new PrintStringsThread("Hello ",
“comps.");
new PrintStringsThread("How are ",
"you?");
new PrintStringsThread("Thank you ",
"very much!");
}}
An Unsynchronized Example
Sample outputs:
Hello How are Thank you comps. Hello How are Thank you you?
you? very much!
very much! comps.
Hello How are Thank you comps. Hello Thank you How are comps.
very much! very much!
you? you?
Unsynchronized Example
– The biggest problem of allowing multiple threads sharing the same
data set is that one operation in one thread could collide with
another operation in another threads on the same data. When this
happens, the result is un-desirable.
– Let's use a bank application program as an example. Assuming that
the program has multiple threads running, with each thread
connecting one ATM system, and you have a saving account in the
bank with $100.00, now you and your friend are going to two
different ATMs at about the same time, and trying to withdraw
$50.00 from your account, what do you think it will happen?
– If the threads are running independently, the following could
happen:
– Both you and your friend will receive $50.00 each, and your account will still have
$50.00. The bank could lose $50.00.
– The solution to this problem is synchronization.
Synchronization: Locking an Object
–•
Synchronization is needed in a multi-threading
application to ensure that one thread is updating a shared
data other threads wait and get the updated value.
– Synchronization uses a lock to represent the shared data
to allow each thread to use the lock status to
Synchronize with each other.
– Synchronization code block is a unit of code in a thread
that requires synchronization on a particular lock.
– More synchronization locks or longer synchronization
code blocks slow down application performance.
Synchronization: Locking an Object
• Synchronization is a programming technique that involves 3 elements:
❑Lock: An object with two states: locked and unlocked.
❑Synchronized Block: A block of statements that is
associated with a lock.
❑Synchronization Rule: When a synchronized block is
encountered in a thread of execution, the associated
lock will be checked.
❑If the lock is locked, the execution will be stopped until the
lock is unlocked. If the lock is unlocked, the lock will be locked,
and the synchronized block of statements will be executed.
When the execution reaches the end of the synchronized
block, the lock will be unlocked. With this rule, two
synchronized blocks associated with same lock will never be
executed at the same time.
How Java Supports Synchronization?
– Instead of let the programmers to design their own locks,
manage the synchronization blocks, and apply the
synchronization rules, Java offers a synchronization
monitor on each instance of the Object class, so it can be
used as a synchronization lock. Since all classes are sub
classes of Object, all objects in Java can be used as
synchronization locks.
– Java also offers three ways to define synchronized
blocks.
How Java Supports Synchronization?
Way 1) Synchronized Class Method:
class class_name {
static synchronized return_type method_name() {
//statement block
}
}
• All the statements in the method become the
synchronized block, and the class object is the lock.
How Java Supports Synchronization?
Way 2) Synchronized Instance Method:
class class_name {
synchronized return_type method_name() {
//statement block
}
}
• All the statements in the method become the
synchronized block, and the instance object is the lock.
How Java Supports Synchronization?
Way 3) Synchronized Statement:
class class_name {
return_type method_name() {
synchronized (object) {
statement block
}
}
}
• All the statements specified in the parentheses of the synchronized
statement become the synchronized block, and the object
specified in the statement is the lock.
How Java Supports Synchronization?
• For example, the following code defines two synchronized blocks.
Both are associated with the same lock, the instance object.
class class_name {
type method_name() {
synchronized (this) {
statement block 1
}
}
synchronized type method_name() {
statement block 2
}
}
• Block 1 will never be executed at the same time as block 2.
Deposit as a Synchronized method
• Assume we have a method called deposit in Account class. So here is
how to make it synchronized.
class Account {
int balance=0;