Vous êtes sur la page 1sur 260

Java Introduction

The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since It is an object-oriented language

Java Program Structure


In the Java programming language:
A program is made up of one or more classes A class can contain one or more methods and some data (variables and constants) A method contains program statements

A Java application (not applet) always contains a method called main

Java Program Structure


// comments about the class public class MyProgram { class header

class body

Comments can be placed almost anywhere }

Java Program Structure


// comments about the class public class MyProgram { // comments about the method

public static void main (String[] args) { method body } }

method header

Comments in Java Programs


// this comment runs to the end of the line /* this comment runs to the terminating symbol, even across line breaks */

*/

/** this is a comment

Java Identifiers
An identifier can be made up of letters, digits, the underscore character ( _ ), and the dollar sign Identifiers cannot begin with a digit Java is case sensitive - Total, total, and TOTAL are different identifiers By convention, Java programmers use different case styles for different types of identifiers, such as title case for class names - Lincoln upper case for constants - MAXIMUM
6

Reserved Words
The Java reserved words:
abstract boolean break byte case catch char class const continue default do double else extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while

UML (Unified Modeling Language)


UML is used -to document the object-oriented development process -to design object-oriented programs UML diagrams are used to visualize relationship among classes and objects. Examples of UML diagrams Class diagrams, Object diagrams, and Use Case diagrams

Class Diagrams
A class diagram consists of one or more classes, each with sections for the class name, Attributes (instance variables in Java), and methods, and describes relationship between classes.

Class Name

Attributes

variableName:type = initial value

Methods

methodName(parameterType):return ty

Visibility Levels for attributes: Public + Private Protected # Ex. address: String #idNumber: int

Multiplicity 1 0..1 M..N * 0..* 1..* one and only one zero or one from M to N (natural numbers) from zero to any positive integers from zero to any positive integers from one to any positive integers

Example: One to many association For one bank, there are many customers. Bank

Customer

Aggregations (relationships)

Car

Engine

name: Engine

The class Engine is a part of the class Car. The class Car has an Engine. The class Engine is used to define some attributes in the class Car. Person

Generalization/Inheritance (relationships)
The class Teacher and Student inherit from the class Person. i.e., the class Teacher and Student will have all attributes and methods that the class Person has (and more attributes and methods can be added to Teacher and Student). Teache r Studen t

Relationships between classes:

Association it can be used as a default relationship if the exact relationship is unknown. In our textbook, it is used when an object of one class is a local variable in a method of another clas In a UML class diagram, a solid straight line between two classes is used.

Aggregation An object of one class is a part of another class. In our textbook, it is used when an object of one class is an instance variable of another class. In a UML class diagram, a solid straight line together with a diamond shape is used.

Inheritance A class inherits instance variables and methods from another class. In a UML class diagram, a solid line with a triangle shape is used.

Transition from a Class Diagram to a class in JAVA

Class Diagram
Student

Student.java ______________________________________ public class Student { private String name; private String address; private int idNumber;

-name: String = ? -address: String = ? -idNumber: int = 0 +toString(): String +submitHW(): boolean

//Constructor public Student() { name = new String(?); address = new String(?); idNumber = 0; } Note: the parameters of each method might not public String be present and in that case, a programmer needs to toString() { fill them. //to be filled by a programer

Object Diagrams
An Object Diagram consists of one or more instantiated objects.

The name of a specific object in addition to the class name


The attributes shown with their current value

objectName: C

Example:
Class Diagram Object Diagram coin1 and coin2 are instances of the class Coin.

Co in -face:int
+flip():void +setFace(int):void

coin1:Coin
face=0

Coin coin1 = new Coin(); coin1.setFace(0);

coin2:Coin
face= 1

Coin coin2 = new Coin(); coin2.setFace(1);

Wrapper Classes
A wrapper class represents a particular primitive data type. (primitive data types int, double, char, boolean, and so on)
They are defined in the java.lang package. Instead of declaring an integer as primitive data as:

int number1 = 45;


We can declare it as an object of the Integer (wrapper) class. Integer number1 = new Integer(45);

For instance, the method doubleValue() returns the value of this integer as double. The class Integer also has static methods such as parseInt(String str) that returns the int corresponding to the value stored in the parameter string. Since it is static, it can be called with the class name (without instantiating an obejct) as:

int num = Integer.parseInt(11);


Then num will contain the integer 11.

Also see other wrapper classes such as Double. (e.g., double num2 = Double.parseDouble(3.21

Inheritance
-- to

derive a new class from an existing class.

In stead of repeating similar data/method definitions in several classes, we can define with the common instance data/methods, and let other classes inherit these data/meth

For instance, if we are trying to define Cat class, Dog class, and Raccoon class and kn will need instance data tail and legs, we can define them in another class called Anima let Cat, Dog, and Raccoon classes inherit from it.
Here the Animal class is called parent class, super class, or base class Animal The classes Cat, Dog, and Raccoon are called child class or sub class. int tail; int parent The child classes will inherit the methods and data defined for thelegs; class. However, child classes do not inherit private variables Raccoon and methods. They can inherit public variables and Cat methods. Dog Making instance data (variables) public violates Encapsulation. There is another visibility modifier called protected. Protected variables and methods can be inherited by child classes, but not as accessible as public.

If you plan to have a class inherited by other classes, its data should be declared as

Visibility Modifiers

public -- inherited, can be accessed from anywhere (we use + for UML class diagrams) private not inherited, can be accessed only within its class (we use for UML class dia protected inherited, can be accessed by any class in the same package (we use # for UML class diagrams) none (if no modifier is used) can be accessed and inherited in the same package. Note: Constructors are not inherited.

If we want the class Car to inherit the class Vehicle, we use the following Vehicl syntax (using the reserved word extends): e public class Car extends Vehicle { // class contents

Car } -Constructors are not inherited: A childs constructor is responsible for calling its parents constructor. For this purpose, we use super reference.
public class Car extends Vehicle { public Car(String name) { super(name); // this line calls the constructor of the parent class // and this needs to be the first line in the constructor. } }

The super reference can be used to reference other variables and methods defined in th public String toString() {

Super reference
-- refer to the parent class Example: // Parent class public class Book { protected int pages; public Book(int numPages) { pages = numPages; } // Child class public class Dictionary extends Book { private int definitions;

public Dictionary(int numPages, int numD { super (numPages); // calls Parent con definitions = numDefn; }

public String toString() { public String toString() return (The number of pages: + pages); { } return (The number of definitions: } + definitions + \n + super.toString( ) ); // calls Parents toString method }

Java supports single inheritance i.e., a derived class can have only one parent class (direct parent, not ancestors)
Multiple inheritance can be simulated using interfaces.

Example:
public class Student implements Comparable, Iterator, .

Overriding Methods
A child class can override (redefine) the definition of an inherited method. (The new method must have the same signature AND the return type.) A method with the final modifier cannot be overridden. The final modifier makes variables constant. For instance, final int number = 1; The value of number cannot be modified.

The Object class


-The Object class is a special class defined in the java.lang package. -All classes are derived from the Object class. Here is some methods defined in the Object class:

-toString( ) returns a string that contains the name of the objects class and a hash valu -equals(Object arg) returns true if two object references refer to the same object.

Abstract classes
An abstract class cannot be instantiated and contains one or more abstract methods (no definition body). -- can contain methods that are not abstract. (unlike Interfaces) -- can contain data declarations other than constants. (unlike Interfaces) An abstract method is a method header without a method body. It cannot be final or static because there is no definition and it should be changed later.

-- It is possible to derive an abstract class from a non abstract parent class. -- If a child class of an abstract class does not give a definition for every abstract method t from its parent, the child class is also considered abstract.

Example: The following class contains an abstract method pay, thus it should be declare class. public abstract class StaffMember // class is declared with abstract { protected String name; public StaffMember( ) { // some content

Type Conversion Widening conversion assigning a predecessor object to an ancestor reference.

Example: the following is a valid operation. (the Computer class is a predecessor of th

Object obj1; Computer comp1 = new Computer(); obj1 = comp1;


The following is also valid: Object obj1 = new Computer(); Narrowing conversion assigning an ancestor object to a predecessor reference. This operation requires a cast. Example: Object obj1 = new Computer(); Computer comp1 = new Computer(); comp1 = (Computer) obj1; Of course, this is not possible if obj1 does not contain a Computer object.

Polymorphism

A polymorphic reference is a reference variable that can refer to different types of objects at different points in tim Polymorphic references are resolved at run-time, not during compilation.

Animal Example: Suppose that we have the following inheritance, the class Dog inherits from the class Mammal, and the class Mammal inherits from move() the class Animal. Animal[] animalList = new Animal[3]; Mammal animalList[0] = new Animal(); The left line refers to different definition of animalList[1] = new Mammal(); the move method for each i. move() animalList[2] = new Dog(); animalList[0].move() refers to move() of Animal class. for (int i=0; i <= 2; i++) animalList[1].move() refers to move() ofDog { Mammal class. animalList[i].move(); This part is polymorphic. } move()

Timer class (defined in javax.swing package)


We can use javax.swing.Timer class to allow a thread to be created and at a time interval. An object of Timer class can be created using the following constructor: Timer(int m, ActionListener listener) creates a timer that generates an action event at regular interval (m milliseconds), specified by the first parameter. The event will be handled by the specified listener. (It creates a Timer that will notify its listener very m milliseconds.) Some methods in javax.swing.Timer class: public void addActionListener(ActionListener listener) --- constructor method add listener where an action to be performed after a delay should be defined. public void start() start the timer, causing it to generate action events. public void stop() stops the timer, causing it to stop generating action event. public void setDelay(int delay) sets the delay of the timer. public boolean isRunning() return true if the timer is running

Example5: using javax.swing.Timer class. A yellow circle will be bouncing inside of an applet. When it hits a wall, it bounces 45 degrees so that it wont disappear from the applet. //************************************************ // Rebound.java modified from Lewis/Loftus textbook. // Demonstrates an animation and the use of the Timer class. //************************************************ import javax.swing.*; public class Rebound extends JApplet { private ReboundPanel panel; public void init() { panel = new ReboundPanel(); getContentPane().add (panel); } // Starts the animation when the applet is started. public void start () { panel.getTimer().start(); } // Stops the animation when the applet is stopped. public void stop () { panel.getTimer().stop(); } }

// Represents the primary panel for the Rebound applet. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ReboundPanel extends JPanel { private final int DIAMETER = 35; private final int DELAY = 20; private Timer timer; private int x, y, moveX, moveY; //----------------------------------------------------------------// Sets up the applet, including the timer for the animation. //----------------------------------------------------------------public ReboundPanel () { timer = new Timer(DELAY, new ReboundListener()); timer.start(); x = 0; y = 40; moveX = moveY = 3; setBackground (Color.black); setPreferredSize (new Dimension(300, 100)); } // accessor method of timer to be used in the applet class. public Timer getTimer() { }

// Draws the circle in the current location. public void paintComponent (Graphics page) { super.paintComponent (page); page.setColor(Color.yellow); page.fillOval(x,y,DIAMETER, DIAMETER); } // Represents the action listener for the timer. private class ReboundListener implements ActionListener { // Updates the position of the image and possibly the direction // of movement whenever the timer fires an action event. public void actionPerformed (ActionEvent event) { x += moveX; y += moveY; //if the circle hits the applets boundary, //it changes its direction. if (x <= 0 || x >= getSize().getWidth()-DIAMETER) moveX = moveX * -1; if (y <= 0 || y >= getSize().getHeight()-DIAMETER) moveY = moveY * -1; repaint(); }

Exceptions

An Exception is an object that describes an unusual or erroneous situation.

-If an exception is ignored by the program, the program will terminate and produce an a Example:

-------------------------------------------------------------------------------------public class DividingByZero { //----------------------------------------------------------------// Deliberately divides by zero to produce an exception. //----------------------------------------------------------------public static void main (String[] args) { int numerator = 10; int denominator = 0; System.out.println (numerator / denominator);

System.out.println ("This text will not be printed."); The call stack trace: indicating where the exception occurred. } This exception was produced by the line System.out.println (numerator / denominato } At this point, the program is terminated and the next line is never executed.

We can avoid the termination of a program caused by an exception by using: try statements.
Try statements

try {
// the line that throws the exception is included here } catch ( //put the exception object produced in try, e.g., IOException ) {

} finally { // the statements inside of finally are always executed whether there was an excep Throws clause clause is used to manage resources or to guarantee that particular parts o // finally } The appropriate exception is appended to the header of a method definition where the e

Example: clause may be omitted when the finally clause is used, and vice versa. More The catch public static void main (String[] args) throws IOException {

Example: ----------------------------------------------------------------------------------import java.util.Scanner; If the string code does not have enough charAt and substring can throw StringInde public class ProductCodes { public static void main (String[] args) { If the substring of code contains a non-d String code; Method parserInt can throw NumberForma char zone; int district, valid = 0, banned = 0;

Scanner input = new Scanner(System.in); How do "); System.out.print ("Enter product code (XXX to quit):we know which methods throw ex which exception a method throws? See code =input.next(); and description of each method. while (!code.equals ("XXX")) For instance, see the method parseInt o { It throws NumberFormatException. try { zone = code.charAt(9); district = Integer.parseInt(code.substring(3, 7)); valid++; if (zone == 'R' && district > 2000) banned++; }

There are checked and unchecked exceptions:

Checked exceptions must be caught by a method (try & catch) or be listed in the throw Unchecked exceptions should not be caught and requires no throws clause. Only unchecked exception in Java are objects of type Runtim

I/O Streams

A stream is a sequence of bytes that flow from a source to a destination. The I/O streams can be categorized in three ways:

-Input streams -Output streams


-Character streams deal with text data -Byte streams deal with byte data -Data streams a source or destination -Processing streams alters or manages information in the stream

Three standard I/O streams: -standard input --- System.in -standard output --- System.out -standard error --- System.err

//Using the Scanner class, we have the following in a program: //----------------------------------------------------------------------------------import java.util.Scanner;

These programs keep reading keyboard input until the string QUIT is entered.

public class lab1 { public static void main (String[] args) { Scanner in = new //---------------------------------------------------------------------------------------Scanner(System.in); //Now we read from in.next(); String line = a keyboard without using the Scanner class: //---------------------------------------------------------------------------------------- converts the original while (line.equals("QUIT") == false) InputStreamReader import java.io.*; { character stream. System.out.println(line); public class lab2 line = in.next(); { } public static void main (String[] args) throws IOException } With BufferedReader, we can use readLin The method readLine() throws IOExcept }{ therefore we need InputStreamReader isr = new InputStreamReader(System.in); to use either throw cla This BufferedReader stdin = new BufferedReader(isr);method reads a line by a line every isr and stdin are variables. String line = stdin.readLine();

Designing Classes

33

Classes introduction A class is a blue print of an object. A class consists of some data (attributes) and methods.

Encapsulation The variables contained in an object should be modified only within the object. Visibility modifiers/Access Specifiers They are used to declare classes, methods, and variables to define their accessibility .

public it can be accessed from anywhere (including outside of the class) private it can only be accessed from inside the class.

34

Accessor methods An accessor method can be defined to access private variable in the class since private data cannot be accessed from outside of the class. Mutator methods A mutator method can be defined to modify private variable in the class. public class Example1 { private int number1; //Accessor method for the variable number1 public int getNumber1() { return number1; } //Mutator method for the variable number1 public void setNumber1(int numberFromOutside) { number1 = numberFromOutside; } }
35

The toString methods -It is a method that takes no parameter and returns a String. -A returned string usually contains information on instance variables of its class. -Each class has a default toString method that contains its class object name and hash number. -When an object is used with System.out.print or println method, its toString method will be called.

36

public class Example { public static void main(String[] args) { Customer customer1 = new Customer(); System.out.println(customer1.toString()); // line1 System.out.println(customer1); // line 2 } }

public class Customer { private int custId; private double balance; public Customer() { custId = 1; balance = 100.0; } public String toString() { String result = "CustomerId: " + custId + "\nBalance: " + balance; return result; }

Output of this program: CustomerId: 1 Balance: 100.0 CustomerId: 1 Balance: 100.0

} // end of the class Customer

Line1 and line2 produce the same output. When printing an object, its toString() method is automatically called.

37

Constructor methods A constructor is a special method that is used to create a new object.
Programmers do not have to define a constructor for a class. Each class has a default constructor. -It has to have the same name as the class -It does not have return type, not even void -It can be used to set the initial values of instance variables public class Customer { private int customerId; private double balance; public Customer( ) //Constructor { customerId = 0; balance = 0.0; } }
38

Method Overloading The process of using the same method for multiple methods. The signature -- the number, type, and order of the parameters The signature of a method must be unique. Example: We can have two definitions for the method calc:

public int calc(int num1, int num2) { int sum = num1 + num2; return sum; }
public int calc(int num1, int num2, int num3) { int sum = num1 + num2 + num3; return sum; }
39

Instance Variables vs. Local Variables Instance variables variables declared at a class level. They are used by all methods in that class. Local variables variables declared in a method. They are used only in that method.

40

The this reference The this reference refers to the instance variables of the object. This approach eliminates the need to come up with a different yet equivalent name. Example: The following two methods have the same result. public class Example2 { private int accountNum; public void setAccountNum1(int account) { accountNum = account; } public void setAccountNum2(int accountNum) { //this.accountNum is an instance variable this.accountNum = accountNum; //accountNum on right hand side is a local } }
41

Static modifiers -it associates a variable or method with the class rather than an object. (there are static variables and static methods) -it is invoked by the system without creating an object. Static Methods cannot reference non-static instance variables. - can reference static variables or local variables. Static Variables also called class variables All objects created from the class share access to the static variable. Changing the value of a static variable in one object changes it for all others.

42

Class Coi n -face:int -count: static int +flip()

coin1 and coin2 are instances of the class Coin. coin1:Coin face=0 count=2 Non static variable can have different coin2:Coin values face=1 count=2

They must have the same value because count is static

43

We can create other classes besides the class that contains a main method. Customer.java
public class Customer { private int custId; private double balance; public Customer() // first constructor { custId = 0; balance = 0.0; }

Drive class/program (Test class/program) contains a main method.

public class Example1 { public static void main(String[] args) { Customer customer1; // declaration customer1 = new Customer(); // instantiation customer1.setCustId(12345); System.out.println(customer1.getCustId()); Customer customer2 = new Customer(); System.out.println(customer2.getCustId()); } }

public void setCustId(int id) // mutator method { custId = id; }


public int getCustId() // accessor method { return custId; } } // end of the class Customer

44

Drive class/program (Test class/program) contains a main method. Example1.java

public class Customer { private int custId; private double balance;

Customer.java

public Customer() // first constructor { custId = 0; balance = 0.0; public class Example1 } { //second constructor public Customer(int id, double balance) public static void main(String[] args) { { custId = id; Customer customer1; // declaration this.balance = balance // this reference is used to distinguish // instance variable and local variable customer1 = new Customer(); // instantiation } public void setCustId(int id) // mutator method { customer1.setBalance(1000.0); custId = id; System.out.println(customer1.getCustId()); } public int getCustId() // accessor method Customer customer2 = new Customer(2, 500.0); { return custId; System.out.println(customer2.getBalance()); } public void setBalance(double balance2) // mutator method } { } balance = balance2; } // accessor method The Example1 class created an object of Customer. public double getBalance() { return balance; } public String toString() { String result = "CustomerId: " + custId + "\nBalance: " + balance; Example1 return result; Customer } Creates } // end of the class Customer

an object

45

Software Engineering

What is Software Engineering about?


An attempt to produce a repeatable process for the development and management of software projects. The quality of the software is a direct result of the process we follow to create it

1. Cost Estimation
1. Time 2. Money 3. resources

2. Division of project work

47

Specifications for improving the software development process: SEI CMM (Software Engineering Institute Capability Maturity Model) ISO 9001:2000

The Software Life Cycle


The overall life cycle of a program includes use and maintenance:
Development
Use

Maintenance

49

Development vs. Maintenance


Development

Use and Maintenance

50

Development and Maintenance Effort


Development Maintenance

Development

Maintenance

Small increases in development effort can reduce maintenance effort

51

The Build-and-Fix Approach


Repeat until everything is fixed

Write program

Modify program

Too many programmers follow a build-and-fix approach They write a program and modify it until it is functional, without regard to system design
52

Software Development Models


A Software Development model is an organized approach to create quality software

The Waterfall Model


Establish requirements Create design

Implement code
Test system

Deplo y

54

An Iterative Development Process


Establish requirements
Create design Implement code Test system

Deplo y

55

Testing Techniques
Generally, the goal of testing is to find errors Often it is called defect testing A good test uncovers problems in a program A test case includes
a set of inputs
56

White-Box Testing
White-box testing also is referred to as glass-box testing It focuses on the internal logic such as the implementation of a method Statement coverage guarantees that all statements in a method are executed Condition coverage guarantees that all paths through a method are executed
57

Black-Box Testing
Black-box testing maps a set of specific inputs to a set of expected outputs An equivalence category is a collection of input sets Two input sets belong to the same equivalence category if there is reason to believe that if one works, it will work for the other 58

Example of Black Box Testing


Consider a method whose purpose is to validate that a particular integer value is in the range 0 an 99, inclusive. There are three equivalence categories in this case: values below 0, values in the range of 0 and 99, and values above 99. Black-box testing dictates that we use test values that surround and fall on the boundaries, as well as some general values from the equivalence categories. Therefore, a set of black-box test cases for this situation might be: -500, -1, 0, 1, 50, 98, 99, 100, and 500.

Walkthrough
A meeting in which several people carefully review a design/ sections of code to see if the design satisfies requirement or the implementation represent the design. A design or an implementation may be evaluated during a walkthrough

The goal of a walkthrough is to identify

Prototypes
A prototype is a program created to explore a particular concept

Prototyping is more useful, time-effective, and cost-effective than merely acting on an assumption that later may backfire
Usually a prototype is created to communicate to the client:
a particular task
61

Prototypes
We have
Throw-away prototypes Evolutionary prototypes

Throw-away Prototypes
A quick and dirty prototype to test an idea or a concept is called a throw-away prototype Throw-away prototypes should not be incorporated into final systems

Evolutionary Prototypes
Because it is designed more carefully, an evolutionary prototype can be incorporated into the final system Evolutionary prototypes provide a double benefit, but at a higher cost

Evolutionary Development Model


Evolutionary development divides the design process into
architectural design - primary classes and interaction detailed design - specific classes, methods, and algorithms

Each refinement cycle focuses on one aspect of the system


65

An Evolutionary Development Model


Establish requirement s Architectur al design Establish refinement scope System test

Unit and integration test

Identify classes & objects

Implementatio n

Identify relationship s

Detailed design

Object-oriented programming is well suited to this approach

66

Inheritance
-- to

derive a new class from an existing class.

In stead of repeating similar data/method definitions in several classes, we can define with the common instance data/methods, and let other classes inherit these data/meth

For instance, if we are trying to define Cat class, Dog class, and Raccoon class and kn will need instance data tail and legs, we can define them in another class called Anima let Cat, Dog, and Raccoon classes inherit from it.
Here the Animal class is called parent class, super class, or base class Animal The classes Cat, Dog, and Raccoon are called child class or sub class. int tail; int parent The child classes will inherit the methods and data defined for thelegs; class. However, child classes do not inherit private variables Raccoon and methods. They can inherit public variables and Cat methods. Dog Making instance data (variables) public violates Encapsulation. There is another visibility modifier called protected. Protected variables and methods can be inherited by child classes, but not as accessible as public.

If you plan to have a class inherited by other classes, its data should be declared as

Visibility Modifiers

public -- inherited, can be accessed from anywhere (we use + for UML class diagrams) private not inherited, can be accessed only within its class (we use for UML class dia protected inherited, can be accessed by any class in the same package (we use # for UML class diagrams) none (if no modifier is used) can be accessed and inherited in the same package. Note: Constructors are not inherited.

If we want the class Car to inherit the class Vehicle, we use the following Vehicl syntax (using the reserved word extends): e public class Car extends Vehicle { // class contents

Car } -Constructors are not inherited: A childs constructor is responsible for calling its parents constructor. For this purpose, we use super reference.
public class Car extends Vehicle { public Car(String name) { super(name); // this line calls the constructor of the parent class // and this needs to be the first line in the constructor. } }

The super reference can be used to reference other variables and methods defined in th public String toString() {

Super reference
-- refer to the parent class Example: // Parent class public class Book { protected int pages; public Book(int numPages) { pages = numPages; } // Child class public class Dictionary extends Book { private int definitions;

public Dictionary(int numPages, int numD { super (numPages); // calls Parent con definitions = numDefn; }

public String toString() { public String toString() return (The number of pages: + pages); { } return (The number of definitions: } + definitions + \n + super.toString( ) ); // calls Parents toString method }

Java supports single inheritance i.e., a derived class can have only one parent class (direct parent, not ancestors)
Multiple inheritance can be simulated using interfaces.

Example:
public class Student implements Comparable, Iterator, .

Overriding Methods
A child class can override (redefine) the definition of an inherited method. (The new method must have the same signature AND the return type.) A method with the final modifier cannot be overridden. The final modifier makes variables constant. For instance, final int number = 1; The value of number cannot be modified.

The Object class


-The Object class is a special class defined in the java.lang package. -All classes are derived from the Object class. Here is some methods defined in the Object class:

-toString( ) returns a string that contains the name of the objects class and a hash valu -equals(Object arg) returns true if two object references refer to the same object.

Abstract classes
An abstract class cannot be instantiated and contains one or more abstract methods (no definition body). -- can contain methods that are not abstract. (unlike Interfaces) -- can contain data declarations other than constants. (unlike Interfaces) An abstract method is a method header without a method body. It cannot be final or static because there is no definition and it should be changed later.

-- It is possible to derive an abstract class from a non abstract parent class. -- If a child class of an abstract class does not give a definition for every abstract method t from its parent, the child class is also considered abstract.

Example: The following class contains an abstract method pay, thus it should be declare class. public abstract class StaffMember // class is declared with abstract { protected String name; public StaffMember( ) { // some content

Type Conversion Widening conversion assigning a predecessor object to an ancestor reference.

Example: the following is a valid operation. (the Computer class is a predecessor of th

Object obj1; Computer comp1 = new Computer(); obj1 = comp1;


The following is also valid: Object obj1 = new Computer(); Narrowing conversion assigning an ancestor object to a predecessor reference. This operation requires a cast. Example: Object obj1 = new Computer(); Computer comp1 = new Computer(); comp1 = (Computer) obj1; Of course, this is not possible if obj1 does not contain a Computer object.

Polymorphism

A polymorphic reference is a reference variable that can refer to different types of objects at different points in tim Polymorphic references are resolved at run-time, not during compilation.

Animal Example: Suppose that we have the following inheritance, the class Dog inherits from the class Mammal, and the class Mammal inherits from move() the class Animal. Animal[] animalList = new Animal[3]; Mammal animalList[0] = new Animal(); The left line refers to different definition of animalList[1] = new Mammal(); the move method for each i. move() animalList[2] = new Dog(); animalList[0].move() refers to move() of Animal class. for (int i=0; i <= 2; i++) animalList[1].move() refers to move() ofDog { Mammal class. animalList[i].move(); This part is polymorphic. } move()

Layout Managers
Once we start adding more than one component to a container, we need to consider how we organize/arrange them. For this purpose, we can use layout managers. A layout manager is an object that determines the manner in which components are arranged in a container. Here is a list of commonly used layout managers: (they are defined in java.awt package.) BorderLayout it organizes components into five areas (North, South, East, West, and Center). FlowLayout it organizes components from left to right, starting new rows as necessary. GridLayout it organizes components into a grid of rows and columns BoxLayout it organizes components into a single row or a single column. CardLayout it organizes components into one such that only one is visible at any time. GridBagLayout it organizes components into a grid of cells, allowing components to span more than one cell.

An Example of Applet using FlowLayout


import javax.swing.*; // to use Japplet, JButton import java.awt.*; // to import FlowLayout manager // and Container public class AppletFlow extends JApplet { public void init() { Container content = getContentPane(); // to use FlowLayout to add components content.setLayout(new FlowLayout()); // create three buttons JButton button1 = new JButton("Button1"); JButton button2 = new JButton("Button2"); JButton button3 = new JButton("Button3"); // add three buttons to the content pane of JApplet object content.add(button1); content.add(button2); content.add(button3);

This program using FlowLayout organizes three buttons in the following manner.

If a user narrows the size of the applet, any component that did not fit in the first row will appear in the next row and so on.

setSize(270,70);
} }

An Example of Applet using BorderLayout


import javax.swing.*; // to use Japplet, JButton import java.awt.*; // to import BorderLayout manager public class AppletBorder extends JApplet { public void init() { Container content = getContentPane();

// to use BorderLayout to add components content.setLayout(new BorderLayout());


// create five buttons JButton button1 = new JButton("Button1"); JButton button2 = new JButton("Button2"); JButton button3 = new JButton("Button3"); JButton button4 = new JButton("Button4"); JButton button5 = new JButton("Button5"); // add five buttons to the content pane of JApplet object content.add(button1, BorderLayout.CENTER); content.add(button2, BorderLayout.NORTH); content.add(button3, BorderLayout.SOUTH); content.add(button4, BorderLayout.WEST); content.add(button5, BorderLayout.EAST); setSize(270,70); } }

An Example of Applet using GridLayout


import javax.swing.*; // to use Japplet, JButton import java.awt.*; // to import GridLayout manager public class AppletGrid extends JApplet { public void init() { Container content = getContentPane();

It will fill the first row from left to right first, then fill the second row, and so on. Here we have only five components to add, so the last slot is empty and it is showing its background color gray, the default color for the content pane.

// to use GridLayout to add components // by specifying its number of rows (2) and columns (3) content.setLayout(new GridLayout(2,3));
// create five buttons JButton button1 = new JButton("Button1"); JButton button2 = new JButton("Button2"); JButton button3 = new JButton("Button3"); JButton button4 = new JButton("Button4"); JButton button5 = new JButton("Button5"); // add five buttons to the content pane of JApplet object content.add(button1); content.add(button2); content.add(button3); content.add(button4); content.add(button5); setSize(270,70); } }

An Example of Applet using BoxLayout


import javax.swing.*; // to use Japplet, JButton import java.awt.*; // to import BoxLayout manager public class AppletBox extends JApplet { public void init() { Container content = getContentPane(); // to use BoxLayout to add components vertically(Y_AXIS) // The first parameter is the container that needs to be laid out, // in this case, it is the content pane of the JApplet. content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); // create five buttons JButton button1 = new JButton("Button1"); JButton button2 = new JButton("Button2"); JButton button3 = new JButton("Button3"); JButton button4 = new JButton("Button4"); JButton button5 = new JButton("Button5"); // add five buttons vertically content.add(button1); // create an rigid area between button 1 and button 2 content.add(Box.createRigidArea(new Dimension(0,10))); content.add(button2); // create a glue between button2 and button3. Glue area changes its size content.add(Box.createVerticalGlue()); content.add(button3); content.add(button4);

// create an rigid area between button 4 and button 5 content.add(Box.createRigidArea(new Dimension(0,20))); content.add(button5); setSize(70,270); } }

If a user shrinks the height of the applet, the area between button2 and 3 also shrinks while the areas between button1 a 2 and between button 4 and 5 stay same.

JPanel (defined in javax.swing package) If we want to combine more than one layout manager, we can use JPanel. JPanel is a container that holds user-interface components. -- JPanel can be nested, i.e., A JPanel object can contain another JPanel object. -- JPanel cannot be displayed by itself. It must be contained in a container such as JFrame and JApplet. For instance, the following applet seems to be using BorderLayout, but button1 and button2 in the center seem to be organized using GridLayout.

import javax.swing.*; import java.awt.*; public class Nested extends JApplet { public void init() { Container content = getContentPane(); // create six buttons JButton button1 = new JButton("Button1"); JButton button2 = new JButton("Button2"); JButton button3 = new JButton("Button3"); JButton button4 = new JButton("Button4"); JButton button5 = new JButton("Button5"); JButton button6 = new JButton("Button6"); JPanel panel1 = new JPanel(); panel1.setLayout(new GridLayout(2,1)); panel1.add(button1); panel1.add(button2); JPanel panel2 = new JPanel(); panel2.setLayout(new BorderLayout()); // add five buttons to panel2 panel2.add(button3, BorderLayout.NORTH); panel2.add(button4, BorderLayout.SOUTH); panel2.add(button5, BorderLayout.WEST); panel2.add(button6, BorderLayout.EAST); panel2.add(panel1, BorderLayout.CENTER); content.add(panel2); // content pane contains panel2 that contains everything setSize(200,200);

First, we create a JPanel object to organize button1 and 2 using GridLayout.

Then, create another JPanel object to organize everythin using BorderLayout.

At the center, panel2 contains panel1 that contains button1 and button2.

}
}

Note that the default layout manager of content pane is BorderLayout, and with add method, a component is added to its center. The default layout manager of JPanel is FlowLayout.

We can separate the organization of components into another class and keep the applet class concise. public class ExamplePanel extends JPanel Note that there are many ways of separating them into two or { more classes as you may see in the examples of the textbook. public ExamplePanel() { // create six buttons import javax.swing.*; JButton button1 = new JButton("Button1"); import java.awt.*; JButton button2 = new JButton("Button2"); JButton button3 = new JButton("Button3"); public class Applet2 extends JApplet JButton button4 = new JButton("Button4"); { JButton button5 = new JButton("Button5"); public void init() JButton button6 = new JButton("Button6"); { Container content = getContentPane(); // panel to contain two buttons JPanel panel1 = new JPanel(); // An ExamplePanel objects contains all components panel1.setLayout(new GridLayout(2,1)); ExamplePanel panel = new ExamplePanel(); panel1.add(button1); panel1.add(button2); content.add(panel); setSize(400,400); } } // panel to contain all components JPanel panel2 = new JPanel(); panel2.setLayout(new BorderLayout()); panel2.add(button3, BorderLayout.NORTH); panel2.add(button4, BorderLayout.SOUTH); panel2.add(button5, BorderLayout.WEST); panel2.add(button6, BorderLayout.EAST); panel2.add(panel1, BorderLayout.CENTER); // use the same layout (BorderLayout) as content pane setLayout(new BorderLayout()); add(panel2); // by default, it adds it at its center

import javax.swing.*; import java.awt.*;

} // end of constructor } // end of ExamplePanel class

ExamplePanel.java file in the previous page can be used with the following driver class to create an application instead of an applet.

import javax.swing.*; import java.awt.*; public class Application2 { public static void main(String[] args) { JFrame frame = new JFrame("Application2"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container content = frame.getContentPane();

// An ExamplePanel objects contains all components ExamplePanel panel = new ExamplePanel();


content.add(panel); frame.setSize(400,400); frame.setVisible(true); }

The following shows how a complicated appearance of a GUI program can be made by combining several layouts.

Aliases
When two objects share a same address, we say that they are aliases of each other. Example: Student student1 = new Student(); Student student2 = new Student(); student1 = student2; // making them aliases of each other

When we make an assignment such as above for two objects, the address of student2 the address of student1, and they become aliases. After this assignment, if we make an to instance data of one object, the change is also seen in the other object that is an alia address1 that we made a change. So if we do: before student1 student2.setLastName(Smith); After becoming aliases. address2 Then the object student1 will also have the last name Smith. student2

Passing objects as parameters

When an object (not primitive data) is passed as a parameter for a method, say method1 its address is passed. Thus if we make any value changes to instance data of the object those changes will be reflected in the object in the method from where method1 was cal
Example:

public class ParameterTester public class ParameterPassing { { public void changeValues (int f1, Num f2, N public static void main (String[] args) { { f1 = 999; ParameterTester tester = new ParameterTester(); f2.setValue(888); f3 = new Num (777); int a1 = 111; Num a2 = new Num (222); } Num a3 = new Num (333); }

tester.changeValues (a1, a2, a3);


} }

public class Num { private int num; public Num(int number) { num = number; } public void setValue(int number) { num = number; } }

Since a1 is a primitive data, any change that was made to f1 in the method changeValu affects a1. The object a2 was assigned to the value 222 and when a2 was passed to method, a2 and f2 became aliases, so the change made to f2 will be seen in a2 in the The object a3 was assigned to the value 333 and when a3 was passed to changeVal a3 and f3 became aliases. However when f3 was re-instantiated with the reserved wor f3 is given a different address from the one a3 has, thus any change made to f3 after th affect a3 in the main method.

Nested/Inner Classes

A class can be defined inside of another class and it is called a nested class (or an in

In general, a nested class is defined with private visibility so that it can be accessed on containing it. A nested class can access all instance data and methods of the class con

-- A nested class produces a separate bytecode file. -- If a nested class called Inside is declared in an outer class called Outside, two bytecode files will be produced: Outside.class Outside$Inside.class
public class Outside { private int num; private Inside obj; .. private class Inside { private double num2; . }

Enclosing Class

Nested Class

Interfaces
A Java interface is a collection of abstract methods and constants.

An abstract method is a method header without a method body. Abstract methods cannot be final or static (because there is no definition, needs to be Example: The following is a definition of the interface Doable

public interface Doable { Doable.java public final int COUNT = 1; public void doThis(); // abstract method public int doThat(String name); // abstract method } After defining the interface Doable, we can make a class to implement the interface Doa public class CanDo implements Doable { public void doThis() { // put some definition for this method } public int doThat(String name) {

CanDo.java

Doable +count:int=1 +doThis():void +doThat(String):int

Constants in an interface cannot be declared with private or protec

CanDo

Notes: -- Interface cannot be instantiated. -- A class that implements an interface must define a definition for each abstract method Otherwise the class should be declared as abstract. -- A class that implements an interface can implements other methods as well. -- A class can implement multiple interfaces using commas between the interface name
public class Class1 implements Interface1, Interface2, Interface3 { // some content } Note that these interfaces cannot have a same constant name with different types or a same method name with a same signature with different return types.

The Comparable interface

The Comparable interface is defined in the java.lang package and it contains only one method, compareTo, which takes an object as a parameter and returns an integer. Any that implements the Comparable interface needs to define compareTo method and their instantiated objects become something that can be compared.
// Person.java // Represents a Person. public class Person implements Comparable { private String firstName, lastName, phone; // Sets up this Person with the specified information. public Person (String first, String last, String telephone) { firstName = first; lastName = last; phone = telephone; } // Uses both last and first names to determine lexical ordering. public int compareTo (Object other) { int result; if (lastName.equals(((Person)other).lastName)) result = firstName.compareTo(((Person)other).firstName); else result = lastName.compareTo(((Person)other).lastName); return result; } }

Interface Hierarchies
-The child interface inherits all abstract methods of the parent. -Class hierarchies and interface hierarchies are distinct (they do not overlap.) A polymorphic reference is a reference variable that can refer to different types of objects at different points in time. Polymorphic references are resolved at run-time, not during compilation. Example: public interface Speaker { public void speak(); }

(It depends on the type of the object that reference points to at the moment of invocatio

And suppose that the class Person implements Speaker and the class Dog implements Speaker guest; guest = new Person(); // valid guest.speak(); // calls speak method of the class Person guest = new Dog(); // valid

If we add a new method talk() in the class Person, then


guest = new Dog(); guest.talk(); causes a compiler error. We can do: guest = new Person(); ((Person) guest).talk(); Speaker

+speak():void

Person

Dog

+talk():void

GUI (Graphical User Interfaces)

Taking a user input using a console (a user might enter an invalid input such as a number ou Range or a string containing non-digit characters):

Taking a user input using Applet (a user is forced to choose among 0 through 7):

Making a Java program to generate a GUI is accomplished by using pre-defined class in packages such as javax.swing and java.awt.

Swing is a comprehensive solution to developing graphical use interfaces. There are more than 250 classes.

GUI Class Hierarchy (Swing)


Dimension Font FontMetrics Object Color Graphics Component
* LayoutManager 1 Classes in the java.awt package Heavyweight

Panel

Applet

JApplet

Container

Window

Frame Dialog

JFrame JDialog

JComponent

Swing Components in the javax.swing package

Lightweight

JFrame, JApplet, and JDialog are heavy weight container classes that can be displayed alone an are used to contain other components.

JFrame: the container that holds other Swing user-interface components in Java Graphical applica It can be used in a Java program with a main method (Applications).

JApplet: It is a subclass of the Applet class. Applet is defined in java.applet package and JApplet is defined in javax.swing package. You need to create a class that extends JApplet to create a Swing based Java applet. Such class will not contain a main method Instead it contains applet purpose methods such as init(), start(), stop(), and destroy(). T applet will be displayed with a html file or appletviewer.

JDialog/JOptionPane: a popup window or message box generally used as a temporary window to receive information from a user or provide notification that an event has occurred.
A dialog box is a temporary graphical window that pops up.

JComponent
JCheckBoxMenuItem JMenuItem JMenu JRadioButtonMenuItem JCheckBox JRadioButton

AbstractButton

JButton
JToggleButton

JComponent
JTextComponent

JEditorPane JTextField JTextArea JPasswordField

JLabel

JList

JComboBox JFileChooser

JMenuBar

JPanel

JOptionPane

JScrollBar

JScrollPane

JTabbedPane

JPopupMenu JProgressBar JInternalFrame

JSeparator JToolBar JToolTip

JSlider JSplitPane JLayeredPane

JRootPane JTable JTableHeader

JPane JTree JColorChooser

AWT package
AWTEvent Font FontMetrics Object Color Graphics Component Container Button Label
TextComponent

Panel Window

Applet Frame Dialog FileDialog

TextField

List Choice CheckBox

TextArea

LayoutManager

CheckBoxGroup Canvas
MenuComponent

MenuItem MenuBar

Menu

Scrollbar

An Example of JFrame:
Compiling and executing the Java program on the left will pop the following window. It contains a button in it. import javax.swing.*; // to use JFrame and JButton import java.awt.Container; public class Frame1 { public static void main(String[] args) { // create a JFrame object JFrame frame = new JFrame("Testing Frame"); // when a user click the close button at the upper left corner, // the window will close and the program will be terminated frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create a button JButton button1 = new JButton("Button1"); // add the button to the content pane of the JFrame object Container content = frame.getContentPane(); content.add(button1); frame.setSize(200, 100); // width is 200 pixels, height is 100 pixels frame.setVisible(true); // make this JFrame object visible } } These two lines can be done in one line as: frame.getContentPane().add(button1); as it is seen in the textbook.

Instead we can also do frame.show(); as they do in the textbook.

Applets
An applet is executed by Web browser so some methods are specifically designed with that concept in mind. public void init() Initializes the applet. Called just after the applet is loaded. public void start() Starts the applet. Called just after the applet is made active (every time the web page is visited).

public void stop() Stops the applet. Called just after the applet is made inactive (when the page containing the applet becomes inac public void destroy() Destroys the applet. Called when the browser is exited. Also, the default constructor can be created to be called by the browser when the Web page containing this applet is initially loaded

reload

enters web page

init after init return to the page start exit leave the page stop

destroy

An Example of JApplet:
import javax.swing.*; // to use JApplet and JButton

How to execute an applet program: 1. This class can be compiled as usual: javac Applet2.java

public class Applet2 extends JApplet { public void init() { // create a button JButton button1 = new JButton("Button1"); // add the button to the content pane of this applet getContentPane().add(button1);

// set its width to 300 pixels and the height to 100 pixels setSize(300, 100);
} }

2. Create an html file, say Applet2.html, with the following conten _________________________________________ <HTML> <HEAD> <TITLE>Applet 2</TITLE> </HEAD> <BODY> <applet code="Applet2.class" width=300 height=100> </applet> </BODY> </HTML> ---------------------------------------------3. You can view this html file using a web browser such as IE or Netscape. You can also use appletviewer. In a console, type appletviewer Applet2.html -In the TextPad, choose Tool, then choose Run Java Applet or press Ctrl-3 (press control key and 3 at the same time). -In the jGrasp, choose Run, then choose Run as Applet.

Applications (using JFrame) vs. Applets (JApplet)


-A Java application is a stand-alone program with a main method. -A Java applet is a program that is intended to be transported over the Web and executed using a web browser. Similarities Since they both are subclasses of the Container class, all the user interface components, layout managers, and event-handling features are the same for both classes. Differences Applications are invoked by the Java interpreter, and applets are invoked by the Web browser. Applets have security restrictions Web browser creates graphical environment for applets, GUI applications are placed in a frame. Security Restrictions on Applets (not to damage the system on which the browser is running): -Applets are not allowed to read from, or write to, the file system of the computer viewing the applets. (Note that a new security protocol allows you to use a security policy file to grant applets access to local files.) -Applets are not allowed to run any programs on the browsers computer. -Applets are not allowed to establish connections between the users computer and another computer except with the server where the applets are stored.

An Example of JOptionPane: -- JOptionPane has several static methods that pop up a temporary wi
//******************************************************************** // EvenOdd.java // Demonstrates the use of the JOptionPane class. //******************************************************************** import javax.swing.JOptionPane; public class EvenOdd { //----------------------------------------------------------------// Determines if the value input by the user is even or odd. //----------------------------------------------------------------public static void main (String[] args) { String numStr, result; int num, again; do { numStr = JOptionPane.showInputDialog ("Enter an integer: "); num = Integer.parseInt(numStr); result = "That number is " + ((num%2 == 0) ? "even" : "odd"); JOptionPane.showMessageDialog (null, result); again = JOptionPane.showConfirmDialog (null, "Do Another?"); } while (again == JOptionPane.YES_OPTION); } }

The parent component in which the dialog is displayed. Here the dialog pops independently.

Color class (defined in java.awt package)

-An object of the Color class represents a color. -It can be defined by RGB (red, green, and blue) value. There are also pre-defined colors such a defined in the Color class. Each of RGB value varies between 0 and 255. ( 8bits)
Object Color.black Color.blue Color.cyan Color.orange Color.white Color.yellow RGB Value 0, 0, 0 0, 0, 255 0, 255, 255 255, 200, 0 255, 255, 255 255, 255, 0

There are foreground color and background color. Foreground color color used to draw shapes or strings. If comp is a component object, we can set foreground color as follows: comp.setForeground(Color.red); To set background color: comp.setBackground(Color.blue);

The Font Class


-You can create a font using the java.awt.Font class - You can set fonts for the components by using the setFont method in the Component class - The constructor for Font is:
Public Font(String fontName, int fontStyle, int fontSize) fontName : SansSerif, Serif, Monospaced, Dialog or DialogInput fontStyle : Font.PLAIN(0), Font.BOLD(1), Font.ITALIC(2) and Font.BOLD + Font.ITALIC (3) fontSize : can be any positive integer
//The following program will show all possible //fonts in your system FindSystemFont.java import java.awt.*; public class FindSystemFont { public static void main(String[ ] args) { GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnviro nment(); String [ ] fontNames = e.getAvailableFontFamilyNames();

One example:

for(int i = 0; i < fontNames.length; i++) System.out.println(fontNames[i]);


} }

Font font1 = new Font(SansSerif, Font.BOLD, 12); Font font2 = new Font(Serif, Font.BOLD + Font.ITALIC, 16); JButton okButton = new JButton(OK); JLabel saying = new JLabel(A new saying); okButton.setFont(font1); saying.setFont(font2);

JButton class (defined in javax.swing package)


-An object of the JButton class is a button that a user can push. It can be instantiated as: JButton button1 = new JButton(Button 1); where Button 1 is the string shown in the button in this case.

JLabel class (defined in javax.swing package)


-An object of the JLabel class is a component that shows a string. It can be instantiated as: JLabel label1 = new JLabel(Example); where Example is the string shown in this case. To change the text string, we can use setText method as: label1.setText(changing text); Note: Instead of using setText method, if label1 is re-instantiated with a new string, it loses any link it had with other components/panels before. To get the text string in it, we can use getText method as: String text = label1.getText();

JTextField class (defined in javax.swing package)


-An object of the JTextField class is a component that can take an input string from a user. It can be instantiated as: JTextField field1 = new JTextField(5); where 5 is a number of columns (width) of this text field. To set the shown text string in the text field, we can use setText method as: field1.setText(changing text); To get the text string that a user entered, we can use getText method as: String text = field1.getText();

JTextArea class (defined in javax.swing package)


-An object of the JTextArea class is a component that can take an input string from a user. It is similar to JTextField (both are child classes of JTextComponent), but it can have a longer height. It can be instantiated as: JTextArea area1 = new JTextArea(); There are several constructors. Some examples are: JTextArea area1 = new JTextArea(rows, columns); // specify the width and height of the area JTextArea area1 = new JTextArea(string); // specify the initial shown string

To set the shown text string in the text area, we can use setText method as:
area1.setText(changing text); To get the text string that a user entered, we can use getText method as: String text = area1.getText(); We can append a string to what it contained: area1.append(additional string); We can use the text area to display strings, but not to take any user input: area1.setEditable(false);

JTabbedPane class (defined in javax.swing package)


-An object of the JTabbedPane class can have several tabs with panels or components. It can be instantiated as: JTabbedPane tPane1 = new JTabbedPane(); Suppose that we have component objects comp1 and comp2. If we want to add them with tabs Component1 and Component2, we can add them as: tPanel.addTab(Component1, comp1); tPanel.addTab(Component2, comp2);

JScrollPane class (defined in javax.swing package)


-Using the JScrollPane, we can add scrolls to a component. Suppose comp is a component or a panel, and when it has more content that it can display with its size, and we want to add scrolls to it, we can do the following: JScrollPane sPane = new JScrollPane(comp);

JCheckBox class (defined in javax.swing package)


-An object of the JCheckBox is a component that shows a check box that user can check or uncheck. Note that when we have multiple JCheckBox objects, they can be checked independently whether other check boxes are checked or not. It can be instantiated as: JCheckBox box1, box2; box1 = new JCheckBox(String to be Shown); box2 = new JCheckBox(Next Choice); To check if the check box is checked or not, you can use isSelected( ) method that returns true or false: if (box1.isSelected() == true) { .. } You can add it to a JPanel object as: JPanel panel1 = new JPanel(); panel1.add(box1); panel1.add(box2);

Then retrieve them later as: JCheckBox box = (JCheckBox) panel1.getComponent(0); // the component at 0 is the first one that was added

Network and World Wide Web, bytecode


A network is two or more computers that are connected so that data and resources can be shared.

Point to Point connection


-Each computer in a network could be directly connected to every other computer in the network
-Adding a computer requires a new communication line for each computer already in the network

-This technique is not practical for more than a few close machin

Single Communication Line


-Adding a new computer to the network is relatively easy

-Network traffic must take turns using the line, which introduces de
-Often information is broken down in parts, called packets, which are sent to the receiving machine and then reassembled

LAN(Local Area Networks)


-A Local-Area Network (LAN) covers a small distance and a small number of computers

-A LAN often connects the machines in a single room or building

LAN

WAN(Wide Area Networks)


-A Wide-Area Network (WAN) connects two or more LANs, often over long distances
-A LAN usually is owned by one organization, but a WAN often connects groups in different countries

LAN

LAN

The Internet
-The Internet is a WAN which spans the entire planet

-It started as a United States government project, sponsored by the Advanced Research Projects Agency (ARPA) - originally it was called the ARPANET

-Less than 600 computers were connected to the Internet in 1983 by the year 2000 there were over 10 million

The World Wide Web

The World Wide Web allows many different types of information to be accesse using a common interface A browser is a program which accesses and presents information

text, graphics, video, sound, audio, executable programs

Web documents are often defined using the HyperText Markup Language (HT Information on the Web is found using a Uniform Resource Locator (URL): http://www.lycos.com http://www.villanova.edu/webinfo/domains.html ftp://java.sun.com/applets/animation.zip A URL indicates a protocol (http), a domain, and possibly specific documents

Java Translation
The Java compiler translates Java source code into
a special representation called bytecode Java bytecode is not the machine language for any traditional

Another software tool, called an interpreter, translates bytecod into machine language and executes it

Therefore the Java compiler is not tied to any particular machin Java is considered to be architecture-neutral

Java source code

Java bytecode

Across the Internet usin HTML

Java compiler
Java interpreter

Bytecode compiler
Machine code

Web Browser Java Interpreter

Local Computer

Remote Computer

Key Listener interface -- defined in java.awt.event package.


If we want to obtain a user input through a key in a keyboard, we need to create a listener object of a class that implements KeyListener interface. To define what should happen for each key event, a method of KeyListener should be defined.

Methods in KeyListener interface: void keyPressed(KeyEvent event) called when a key is pressed. Void keyReleased(KeyEvent event) called when a key is released. void keyTyped(KeyEvent event) called when a key is pressed and then released.

Key Event class: (java.awt.event package)


Some method in Key Event class: char getKeyChar(): returns the character of a key a user pressed, released, or typed: int getKeyCode(): returns the code number of a key a user pressed, released, or typed:

Examples:
char characterEntered = event.getKeyChar(); // event is a KeyEvent object int code = event.getKeyCode(); // even is a KeyEvent object Some key constants defined in the KeyEvent class:

Constants
VK_HOME VK_END VK_DOWN VK_UP VK_LEFT VK_RIGHT

Desription
Home key End key Down arrow key Up arrow key Left arrow key Right arrow key

Example: if (event.getKeyCode() == KeyEvent.VK_UP) // if the key a user chooses is the up arrow key { . }

To add a key listener class, we use addKeyListener method. Example: panel.addKeyListener(new Listener1()); Some steps to be done in the panel that listens to keys: 1. boolean isFocusable() This method returns whether this component (panel) can be focused. In the component (panel) that listens to keys, this method needs to be overridden to enable keyboard focus. 2. void requestFocus() This method requests that this component (panel) get the input focus, and that this components top level ancestor become the focused window.

KeyDemo.java file
import javax.swing.JApplet; public class KeyDemo extends JApplet { public void init() { KeyPanel keyPanel = new KeyPanel(); getContentPane().add(keyPanel); setSize (400, 400); } }

//This method needs to be defined to draw in this panel public void paintComponent(Graphics page) { super.paintComponent(page); page.setColor(currentColor); page.setFont(new Font("TimesRoman", Font.PLAIN, 24)); //draw the string at the location (200, 200) page.drawString(String.valueOf(currentChar), 200, 200); } /** Override this method to enable keyboard focus */ // This method should be defined in the panel to listen to keys public boolean isFocusable() { return true; } //Listener1 class received the key pressed by a user private class Listener1 implements KeyListener { public void keyReleased(KeyEvent e) {} public void keyTyped(KeyEvent e) {} public void keyPressed(KeyEvent e) { currentChar = e.getKeyChar(); //get a letter(key) pressed by a user repaint(); // call paintComponent method indirectly } } // end of Key Listener } // end of Key Panel Class

KeyPanel.java file
import java.awt.*; import javax.swing.*; import java.awt.event.*; // to use listener interfaces public class KeyPanel extends JPanel { private Color currentColor; private char currentChar; public KeyPanel() { currentColor = Color.black; //default color is black currentChar = 'A'; //default character is 'A'

addKeyListener (new Listener1()); //this panel listens to keys


setBackground(Color.white); //This method needs to be called for this panel to listen to keys //When panel listens to other things, and go back to listen //to keys, this method needs to be called again. requestFocus();

Algorithms

An algorithm is a sequence of computational steps that transform some input into some It is a tool for solving a well-defined computational problem. Examples of such problems --- searching, sorting

Searching Linear Search Algorithm

-- looks sequentially at each element of a given collection of elements until we either co or find an item that equals to X (the element that we are searching for). public int linearSearch(int[] A, int x) { for (int i=0; i<A.length, i++) { if (A[i] = = x ) return i; } return (1);

constant time to execute C1 C2 C3

// returns 1 when the element is not found

C4

O-notation -- upper bound

The (worst case) running time of the linear search can be expressed as a function of n T(n) = c1 * n + c2

where c1 and c2 are positive constants.

Intuitively, we can see that when n, input size, gets larger, the time that takes to execut a*g(n) (T(n) grows proportionally to n. ) And when n gets very large, constant c2 has a very sm We say that the complexity of the linear search is O(n), but here is a formal definition of O (pronounced as big-Oh) notation. Definition of O-notation: If there exist positive constants a and c such that T(n) <= a*g(n) for all n larger than c c

T(n)

When n gets larger (greate we can bound of T(n). Then we say that T(n) = O(g(n)). This means that a*g(n) is an upper find a positive con such that T(n) <= a*g(n) For the linear search, g(n) = n. Note that there is more than one such function g(n). For instance it is correct to say that:

-notation (Omega-notation) lower bound Similarly, we can define a lower bound for each running time. If there exist positive constants b and c such that

T(n) >= b* g(n) for all n larger than c


Then we say that T(n) = ( g(n) ) (big Omega) where g is a function of n. Thus g(n) is a lower bound of the running time T(n).

-notation (Theta-notation) If T(n) = O( g(n) ) and T(n) = ( g(n) ), Then we say that: T(n) = ( g(n) ) Thus the function g represents a tight bound for T(n).

Example:

Binary Search Algorithm

-It is used to look up a word in a dictionary or a name in a phone book. -It uses Divide and Conquer approach. Binary Search Using iterative m -A list needs to be sorted before a binary search (pre-condition). found, it returns the inde If x is otherwise it returns 1. Example: Search for x = 11 -5 2 7 9 11 12 20 31 11 12 20 31

public static int binIter(int[] num { x > 9, so x is in right half segment.n = num.length; int if (x>num[n-1] || x<num[0]) x < 12, so x is in left quarter segment -1; return // x is not fo

11 12

x == 11. We found x.

The complexity of Binary Search Algorithm is order of log n where n is the number of elements to search from

int i = 0; int j = n-1; int k;

while (i<j) { k = (int) Math.floor((i+j)/(2 if (x<=num[k]) j = k; else i = k+1;

Sorting

--the process of arranging a list of items into a particular order.


Selection Sort Algorithm

It sorts a list of values by successively putting particular values (the smallest value among Example: 3 9 6 1 2

Find the smallest (1), and exchange so that the smalle

Find the second smallest (2), and exchange so that the

6 3

Find the third smallest (3), and exchange

Find the fourth smallest. The fourth smallest is already

3 6

This line compares two values //----------------------------------------------------------------How many comparison are do // Sorts the specified array of integers using the selection algorithm? Let n be the length // sort algorithm. //----------------------------------------------------------------When index = 0, public static void selectionSort (int[] numbers) scan goes from 1 to n-1, thus { int min, temp; When index = 1, scan goes from 2 to n-1, thus

for (int index = 0; index < numbers.length-1; index++) { .. min = index; for (int scan = index+1; scan < numbers.length; scan++) index = n-2, When if (numbers[scan] < numbers[min]) scan foes from n-1 to n-1, 1 it min = scan; // Swap the values temp = numbers[min]; numbers[min] = numbers[index]; numbers[index] = temp; } } The total number of iterations

(n-1)+(n-2)+1 = (n-1)n/2 =(1/2)n2-(1/2

We look at the fastest growing Thus we say:

A Graphical User Interfaces (GUI) is created with at least three kinds of objects in order to receive user input and process it. -components
(e.g., buttons, textfields) -listeners waits for events to occur -events (e.g., a button is pushed, a mouse is moved) An Event is an object that represents some activity to which we may want to respond.

To create a GUI program:


-- Define and set up the components -- Create a listener object by writing a class that implements a particular listener interface. (The Java standard class library contains several interfaces that corresponds to particular event categories.) -- After creating the listener, we add the listener to the component that might generate the event to set up a formal relationship between the generator and listener. -- Define what happens in response to each event of interest.

Event
When an event occurs, the generator calls the appropriate method of the listener, passing an object that describes the event.

Generator
This object may generate an event

Listener

It waits for and responds to an event

A GUI Example using JButton and ActionListener:


// PushCounter.java--modified from Lewis/Loftus textbook import java.awt.*; import java.awt.event.*; //to use ActionListener and ActionEvent import javax.swing.*; public class PushCounter extends JApplet { private int pushes; //declared as instance variables so that it can be used private JLabel label; // in more than one method. private JButton push; // it initializes and arranges components in the applet public void init() { pushes = 0; push = new JButton ("Push Me!"); //using an object of ButtonListener, the button listens to an event push.addActionListener (new ButtonListener()); label = new JLabel ("Pushes: " + pushes); Container cp = getContentPane(); cp.setLayout (new FlowLayout()); cp.add (push); cp.add (label); setSize (300, 35); }

To receive user input from a button, we create a class that implem ActionListener interface where the method actionPerformed is defined. In the actionPerformed method we specify what kind of actions to take in case a button is pushed.

When a user pushes the Push Me button, it will increments the number shown next to the label Pushes.

A component object to listen A listener object An event object

//ButtonListener class represents a listener for button push (action) events private class ButtonListener implements ActionListener { //It updates the counter when the button is pushed. public void actionPerformed (ActionEvent event) { pushes++; label.setText("Pushes: " + pushes); } } }

// FahrenheitGUI.java

modified from Lewis/Loftus textbook

A GUI Example using JLabel and JTextField:


// Fahrenheit.java import javax.swing.*; import java.awt.*; public class Fahrenheit extends JApplet { // Creates and displays the temperature converter GUI. public void init() { FahrenheitGUI gui = new FahrenheitGUI(); Container content = getContentPane(); content.add(gui); setSize(300,75); } } modified from Lewis/Loftus textbook

import java.awt.*; import java.awt.event.*; //to use ActionListener and ActionEvent import javax.swing.*; public class FahrenheitGUI extends JPanel { private JLabel inputLabel, outputLabel, resultLabel; private JTextField fahrenheit; // constructor arranges components using a layout public FahrenheitGUI() { inputLabel = new JLabel ("Enter Fahrenheit temperature:"); outputLabel = new JLabel ("Temperature in Celsius: "); resultLabel = new JLabel ("---");

fahrenheit = new JTextField (5); fahrenheit.addActionListener (new TempListener()); //make the textfield listen setLayout(new FlowLayout()); add (inputLabel); add (fahrenheit); add (outputLabel); add (resultLabel); }

A user enter a temperature in Fahrenheit, and it will covert it to temp in Celsius.

// TempListener class represents an action listener for the temperature text field private class TempListener implements ActionListener { // Performs the conversion when the enter key is pressed in the text field. public void actionPerformed (ActionEvent event) { String text = fahrenheit.getText(); int fahrenheitTemp = Integer.parseInt (text); int celciusTemp = (fahrenheitTemp-32) * 5/9; resultLabel.setText (Integer.toString (celciusTemp)); } }

A GUI Example using JCheckBox:


// StyleOptions.java--modified from Lewis/Loftus textbook // Demonstrates the use of check boxes. import javax.swing.*; public class StyleOptions extends JApplet { public void init() { StyleGUI gui = new StyleGUI(); getContentPane().add (gui); setSize(300,100); } }

// StyleGUI.java-- modified from Lewis/Loftus textbook import javax.swing.*; import java.awt.*; import java.awt.event.*; //to use ItemListener and ItemEvent public class StyleGUI extends JPanel { private final int FONT_SIZE = 36; private JLabel saying; private JCheckBox bold, italic; // constructor arranges a label and some check boxes that control the style of the label's font. public StyleGUI() { saying = new JLabel ("Say it with style!"); saying.setFont (new Font ("Helvetica", Font.PLAIN, FONT_SIZE)); bold = new JCheckBox ("Bold"); italic = new JCheckBox ("Italic"); StyleListener listener = new StyleListener(); bold.addItemListener (listener); italic.addItemListener (listener); add (saying); add (bold); add (italic); } // StyleListener class represents the listener for both check boxes. private class StyleListener implements ItemListener { // Updates the style of the label font style. public void itemStateChanged (ItemEvent event) { int style = Font.PLAIN; if (bold.isSelected()) style = Font.BOLD; if (italic.isSelected()) style += Font.ITALIC; saying.setFont(new Font ("Helvetica", style, FONT_SIZE)); } } }

A user can check Bold or Italic check box to make the saying with each style.

Mouse Listener and Mouse Motion Listener -- defined in java.awt.event package.


If we want to obtain a user input through a mouse, we need to create an object of a listener class that implements MouseListener interface or MouseMotionListener interface. To define what should happen for each mouse event, a method of MouseLister or MouseMotionListener should be defined.

Methods in MouseListener interface: void mousePressed(MouseEvent event) a mouse button is pressed down. void mouseReleased(MouseEvent event) a mouse button is released.

void mouseClicked(MouseEvent event) a mouse button is pressed down and released without moving the mouse in between.
void mouseEntered(MouseEvent event) a mouse pointer is moved onto (over) a component. void mouseExited(MouseEvent event) a mouse pointer is moved out of a component.

Methods in MouseMotionListener interface: void mouseMoved(MouseEvent event) a mouse is moved. void mouseDragged(MouseEvent event) a mouse is moved while the mouse button is pressed down.

To add a listener object that implements MouseListener interface a component, addMouseListener() method is used as: component.addMouseListener(listener); To add a listener object that implements MouseMotionListener interface to a component, addMouseMotionListener() method is used as: component.addMouseMotionListener(listener);

Adapter classes (MouseAdapter class and MouseMotionAdapter class):


Suppose a class Listener1 needs to be defined to implements MouseListener interface. Even if we want to use only one method, say mousePressed method, we need to provide a definition with { and } for the rest of the methods for that class so that it compiles. For example:

public class Listener1 implements MouseListener { private int count = 0; public void mousePressed(MouseEvent event) { count++; } public void mouseClicked(MouseEvent event) {} public void mouseReleased(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} }
Instead of using MouseListener interface, we can make a class inherit from MouseAdapter class. MouseAdapter class implements the MouseListener interface and contains empty definitions for all methods of MouseListener.

public class Listener1 extends MouseAdapter { private int count = 0; public void mousePressed(MouseEvent event) { count++; } }
For MouseMotionListener, we have MouseMotionAdapter class.

The Point class -- defined in java.awt package.


An object of the Point class represents the (x,y) coordinate of a given point in two dimensional space. This can be used together with MouseEvent objects as: Suppose that event is a MouseEvent object. Then,

public void mousePressed(MouseEvent event) { Point pt = event.getPoint(); System.out.println(X-coordinate is: + pt.x + and Y-coordinate is: + pt.y); }
Here we can obtain the coordinate of the point where a user pressed using a mouse. A Point object has x and y as its public variables, so we can access them directly.

An Example using MouseListener and Graphics


In this example, we use MouseListener to check the location of the panel where a user pressed using a mouse, then we draw a green dot at that location. The background of this panel is black. It counts how many times a user pressed the panel (or how many dots are drawn so far). Here we see two approaches.

Approach we can define paint or paintComponent method and use its Graphics object parameter to draw shapes.

//******************************************* // Dots1.java // Demonstrates mouse events and drawing on a panel. //******************************************* import javax.swing.JApplet; public class Dots1 extends JApplet { public void init() { getContentPane().add (new DotsPanel1()); setSize(300,200); } }

Approach - defining paintComponent method to obtain its Graphics object: // DotsPanel1.java // Represents the primary panel for the Dots program on which the // dots are drawn. import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class DotsPanel1 extends JPanel { private final int RADIUS = 6; private ArrayList pointList; private int count; public DotsPanel1() { setBackground (Color.black); count = 0; pointList = new ArrayList(); // this panel class listens to a mouse addMouseListener (new DotsListener()); } // end of DotsPanel1 constructor We construct paintComponent method, and use its Graphics object parameter to draw shapes. We can use repaint() method to call paintComponents method indirectly, and when it is called, it erases any previously drawn shapes and re-draw what is defined in the method. Thus we need to re-draw all dots in the arraylist in this method.

// Draws all of the dots stored in the list. public void paintComponent (Graphics page) { // use paintComponent method of its parent class // to have all graphics properties super.paintComponent(page); page.setColor (Color.green); for (int i=0; i<pointList.size() ; i++) { Point drawPoint = (Point) pointList.get(i); page.fillOval (drawPoint.x - RADIUS, drawPoint.y - RADIUS, RADIUS * 2, RADIUS * 2); } page.drawString ("Count: " + count, 5, 15); } //end of paintComponent method // DotsListener class represents the listener for mouse events. private class DotsListener implements MouseListener { // Adds the current point to the list of points and redraws // whenever the mouse button is pressed. public void mousePressed (MouseEvent event) { pointList.add (event.getPoint()); count++; repaint(); // this calls paintComponent method indirectly }

// Provide empty definitions for unused event methods. public void mouseClicked (MouseEvent event) {} public void mouseReleased (MouseEvent event) {} public void mouseEntered (MouseEvent event) {} public void mouseExited (MouseEvent event) {} } // end of DotsListener class } // end of DotsPanel1 class

Borders Java provides the ability to put a border around any swing components. A border is not a component itself, but rather defines how the edge of a component should be drawn, and it has an important visual effect on the design of GUI. In order to use a border, you should put the following code on top of your program.
import javax.swing.border.*;

To set a border, you write, for example


Jcomponet_name.setBorder(BorderFactory.createEtchedBorder());

Border Empty Border Line Border Etched Border Bevel Border

Description Puts buffering space around the edge of a component, but has no visual effect. A simple line surrounding the component Creates the effect of an etched groove around a component Creates the effect of a component raised above the surface or sunken below it.

Titled Border
Matte Border Compound Border

Includes a text title on or around the border.


Allows the size of each edge to be specified. Uses either a solid color or an image A combination of two borders

import java.awt.*; import javax.swing.*; import javax.swing.border.*; public class BorderDemo { public static void main(String[] args) { JFrame frame = new JFrame("Border Demo");

//Creates a border with a lowered beveled edge JPanel p4 = new JPanel(); p4.setBorder(BorderFactory.createLoweredBevelBorder()) ; p4.add(new JLabel("Lowered Bevel Border")); panel.add(p4); //Creates a new title border JPanel p5 = new JPanel(); p5.setBorder(BorderFactory.createTitledBorder("Title")); p5.add(new JLabel("Titled Border")); panel.add(p5); //A compound border is a combination of two or more borders. JPanel p6 = new JPanel(); Border b1 = BorderFactory.createLineBorder(Color.blue, 2); Border b2 = BorderFactory.createRaisedBevelBorder(); p6.setBorder(BorderFactory.createCompoundBorder(b1, b2)); p6.add(new JLabel("Compound Border")); panel.add(p6); //add panel onto the frame frame.getContentPane().add(panel); frame.setSize(300, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E); frame.setLocationRelativeTo(null); frame.setVisible(true); } }

JPanel panel = new JPanel(); panel.setLayout(new GridLayout(0, 2, 5, 10));

panel.setBorder(BorderFactory.createEmptyBorder(8,8,8,8)); //Creates a line border with the specified color and width JPanel p1 = new JPanel(); p1.setBorder(BorderFactory.createLineBorder(Color.red, 3)); p1.add(new JLabel("Line Border")); panel.add(p1); //Creates a border with an "etched" look JPanel p2 = new JPanel(); p2.setBorder(BorderFactory.createEtchedBorder()); p2.add(new JLabel("Etched Border")); panel.add(p2); //Creates a border with a raised beveled edge JPanel p3 = new JPanel(); p3.setBorder(BorderFactory.createRaisedBevelBorder()); p3.add(new JLabel("Raised Bevel Border")); panel.add(p3);

Visual effect of different borders (Running result of above sample program)

Graphics class -- defined in java.awt (abstract windowing toolkit) package

-It is used to draw shapes, lines, and strings.

Paint method in JApplet


public void paint(Graphics page) { } The paint method is invoked automatically whenever the graphic elements of the applet need to be painted to the screen.

Coordinate Systems
Graphic system (0,0) x = 30 (x,y) y=28 (x,y) = (30,28) (0,0) x y Cartesian coordinate system

Some methods of the Graphics class: void drawRect(int x, int y, int width, int height) paints a rectangle with upper left cornet (x,y) and dimensions width and height. void fillRect(int x, int y, int width, int height) same as drawRect, but with inside filled with a foreground color.

void drawOval(int x, int y, int width, int height) paints an oval bounded by the rectangle with an upper left cornet of (x,y) and dimens width and height. void fillOval(int x, int y, int width, int height) same as drawOval, but with inside filled with a foreground color.

void drawLine(int x1, int y1, int x2, int y2) paints a line from point (x1,y1) and point (x2,y2).
void drawString(String str, int x, int y) paints the character string at point (x,y), extending to the right.

void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) paints an arc along the oval bounded by the rectangle def by x, y width, and height. The arc starts at startAngle and extends for a distance defined by arcAngle (positive counter clock void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) same as drawArc, but with inside filled with a foreground color. void setColor(Color color) sets this graphics contents foreground color to the specified color. Color getColor() returns this graphics contents foreground color.

Drawing a rectangle: page.drawRect (50, 20, 100, 40);

50

20 40

100

Drawing an oval: page.drawOval (175, 20, 50, 80);

175

20

80

bounding rectangle
Y 50

Drawing a line:
page.drawLine (10, 20, 150, 45); or page.drawLine (150, 45, 10, 20);

10

150

20

45

Drawing an arc: page.drawArc (175, 20, 50, 80, 30, 90);


Arc is drawn

175

20
90 30

Arc angle Start angle

80

bounding rectangle
Y 50

//******************************************************************** // Einstein.java // Demonstrates a basic applet. //******************************************************************** import javax.swing.JApplet; import java.awt.Graphics; public class Einstein extends JApplet { //----------------------------------------------------------------// Draws a quotation by Albert Einstein among some shapes. //----------------------------------------------------------------public void paint (Graphics page) { page.drawRect (50, 50, 40, 40); // square page.drawRect (60, 80, 225, 30); // rectangle page.drawOval (75, 65, 20, 20); // circle page.drawLine (35, 60, 100, 120); // line page.drawString ("Out of clutter, find simplicity.", 110, 70); page.drawString ("-- Albert Einstein", 130, 100);

}
}

// Snowman.java // Demonstrates basic drawing methods and the use of color. import javax.swing.*; //to use JApplet import java.awt.*; //to use Graphics and Color classes public class Snowman extends JApplet { //----------------------------------------------------------------// Draws a snowman. //----------------------------------------------------------------public void paint (Graphics page) { final int MID = 150; final int TOP = 50; setBackground (Color.cyan); page.setColor (Color.blue); page.fillRect (0, 175, 300, 50); // ground page.setColor (Color.yellow); page.fillOval (-40, -40, 80, 80); // sun page.setColor (Color.white); page.fillOval (MID-20, TOP, 40, 40); // head page.fillOval (MID-35, TOP+35, 70, 50); // upper torso page.fillOval (MID-50, TOP+80, 100, 60); // lower torso page.setColor (Color.black); page.fillOval (MID-10, TOP+10, 5, 5); // left eye page.fillOval (MID+5, TOP+10, 5, 5); // right eye

page.drawArc (MID-10, TOP+20, 20, 10, 190, 160); // smile


page.drawLine (MID-25, TOP+60, MID-50, TOP+40); // left arm page.drawLine (MID+25, TOP+60, MID+55, TOP+60); // right arm page.drawLine (MID-20, TOP+5, MID+20, TOP+5); // brim of hat page.fillRect (MID-15, TOP-20, 30, 25); // top of hat } }

Reading/Writing Text Files


Reading Text Files:

import java.io.*;

public class ReadingFromFile Instead of reading from the standard input,{ we can read from text files using the classes public static void main (String[] args) FileReader and BufferedReader. { The parameter for the FileReader constructor String line, file = input.txt"; is the name of a file to be read. try The constructor of FileReader can throws { FileNotFoundException if the file specified in FileReader fr = new FileReader (file); the parameter is not located. BufferedReader inFile = new BufferedRe //Scanner inFile = new Scanner(fr); instea It is a good practice to close the file after finishing = inFile.nextLine(); see page 577 // line reading it. line = inFile.readLine(); while (line != null) { System.out.println(line); line = inFile.readLine(); } inFile.close(); }

Note that the previous code can be done a little more formally as follows. All other examples are rather simplified in this notes, but it can be finally expanded to be more robust. { try import java.io.*; { if (inFile != null) public class ReadingFromFile inFile.close(); { } public static void main (String[] args) catch (IOException ex) { { String line, file = "input.txt"; System.out.println(ex); FileReader fr = null; } BufferedReader inFile = null; } try } { } fr = new FileReader (file); inFile = new BufferedReader (fr);

line = inFile.readLine(); while (line != null) { System.out.println(line); line = inFile.readLine();

Writing Text Files:

import java.io.*;

We can write into text files using the classes FileWriter, BufferedWriter, and PrintWriter. public class WriteFile { The FileWriter class represents a text output file. public static void main (String[] args) throw The parameter of the FileWriter constructor is the name { of a file to be written. String fileName = "test.txt";

The PrintWriter class provides print and println methods fw = new FileWriter (fileName FileWriter similar to the standard I/O PrintStream class. BufferedWriter bw = new BufferedWriter PrintWriter outFile = new PrintWriter (bw The Buffered Writer class gives the output stream bufferingoutFile = new PrintWriter(fileN //PrintWriter It is a good practice to close files after writing. efficient. capabilities, which makes the processing more for (int i=1; i <= 10; i++) In this example, the file test.txt will be created{ and have all output written in it. outFile.print (The value is + i ); outFile.println (); } outFile.close(); } }

Command-Line Arguments

--The signature of a main method indicates that it takes an array of String objects as a For instance, if we have the following command to execute a program:

java Example1 input1.txt my1.txt test


Then in the following program args[0] contains input1.txt, args[1] contains my1.txt, and args[2] contains test and so on. public class Example1 { public static void main (String[] args) throws IOException { FileReader fr = new FileReader (args[0]); BufferedReader inFile = new BufferedReader (fr); FileWriter fw = new FileWriter (args[1]); BufferedWriter bw = new BufferedWriter (fw); PrintWriter outFile = new PrintWriter (bw);

Object Serialization

import java.io.*;

Now we want to store an object, not just texts. public class WriteObject We can store (write) an object information in a file, or { obtain (read) an object from a file. public static void main (String[] args) { Persistence the concept that an object can exist separate FileOutputStream file = null; from the executing program that creates it. ObjectOutputStream outStream = null; try Writing Objects: { This can be done using two classes FileOutputStream and file = new FileOutputStream ("computer.d ObjectOutputStream. outStream = new ObjectOutputStream (f The FileOutputStream takes the name of a file to write objects Computer comp = new Computer(); into as its parameter. comp.setBrandName(IBM);

The ObjectOutputStream provides the method writeObject // Serialize this above object to a file which takes an object as its parameter. outStream.writeObject(comp); import java.io.*; } public class Computer implements Serializable catch to The{ classes whose objects are to be serialized have(NotSerializableException exception) { implements Serializable. The interface Serializable is defined .. in java.io package. The interface Serializable doesSystem.out.println("NotSerializableExce not contain } any method.

import java.io.*;
Reading Objects:

public class ReadObject The classes FileInputStream and ObjectInputStream are { used to deserialize objects. public static void main (String[] args) The method readObject reads one object at{time, and return an object as a reference of the class Object. String fileName = "computer.dat"; If the object is an object of, say Computer class, FileInputStream file = null; it needs to be cast before any method in the Computer ObjectInputStream inStream class is used. = null; try { finally file = new FileInputStream { (fileName); try inStream = new { ObjectInputStream (file); if (inStream != null)
inStream.close(); } catch (IOException exc) { System.out.println(exc); } // Deserialize the objects Object obj1 = inStream.readObject();

if (obj1 instanceof Computer)

The Transient modifier

If we want to exclude a data (an attribute) of some class so that it is not part of the inf we can declare such data with the transient modifier:

private transient int password;

The above variable (data), when the object in which it is contained is serialized, will n

By default, all the non-static variables of a serialized object are written to the object s However, not all non-static variables are serializable. If a class contains such non-ser java.io.NotSerializableException will occur. We can declare such non-serializable var NotSerializableException will not be thrown.

JList A Jlist is a component that basically performs the same function as a combo box, but enables the user to choose a single value or multiple values. To use a JList, you will need the following package
import javax.swing.*; Import javax.swing.event.*;

Common methods in JList class


JList( ) JList(Object[] items) //create a JList from an Array JList(Vector<?> listData) //create a JList from a Vector int getSelectedIndex() //return the index of the first selected item Object getSelectedValue() //returns the first selected item in the list void setSelectedIndex(int index) //select the cell at the specified index void setVisibleRowCount(int count) //set the preferred number of visible rows displayed without a scrollbar (default is 8) To set the foreground color of the selected cell sampleList.setSelectionForeground(Color.pink); Set the background color of the selected cell sampleList.setSelectionBackground(Color.black); Only allows one item to be sleected each time SampleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

//This program demonstates event handling with a JList object import java.awt.*; import javax.swing.*; import javax.swing.event.*; import java.util.*; import javax.swing.border.*; border

//set the foreground & background color of the selected cell countryList.setSelectionForeground(Color.pink); countryList.setSelectionBackground(Color.black); //set to only allow one item to be selected each time countryList.setSelectionMode(ListSelectionModel.SINGLE_S ELECTION);

//to set up the

currentCountry = new JLabel("At begining, no country is selected", JLabel.CENTER); //Step 3: Register the countryList with a CountryListListener countryList.addListSelectionListener (new CountryListListener()); Container cp = getContentPane(); cp.setLayout (new GridLayout(2,1)); cp.add(currentCountry); cp.add (countryList); setSize (300, 300); } //Step 2: Create a CountryListListener class that implements the interface private class CountryListListener implements ListSelectionListener { //implement the abstact method inside ListSelectionListener public void valueChanged(ListSelectionEvent event) { //Display which country is selected currentCountry.setText((String) countryList.getSelectedValue()); } } //end of CountryListListener

public class EventHandleJListDemo extends JApplet { private JList countryList; private JLabel currentCountry;
//Step 1: arranges the components public void init() { //create a String vector Vector<String> originalList = new Vector<String>(); originalList.add("United States"); originalList.add("China"); originalList.add("India"); //Create a JList object from above vector countryList = new JList(originalList); countryList.setBorder(BorderFactory.createEtchedBorder ()); //the country's list is in red color with a white background countryList.setForeground(Color.red); countryList.setBackground(Color.white);

Visual effect of above sample program

JSplitPane class (defined in javax.swing package)


-An object of the JSplitPane class is a pane split vertical direction or horizontal direction. Suppose that we have component objects comp1 and comp2. If we want to add them using vertical split, we can do: JSplitPane sPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, comp1, comp2);

JComboBox class (defined in javax.swing package)


-An object of the JComboBox is a component that shows a list of choices and user can choose one option at time. There are two basic ways to create a JComboBox. One is to create an array of choices first and create a JComboBox using it. The other is to create an empty JComboBox and add items one by one: Example1: String[] letters = {A, B, C, D, E}; JComboBox combo = new JComboBox(letters); Example2:

JComboBox combo = new JComboBox(); combo.addItem(A); combo.addItem(B); combo.addItem(C); combo.addItem(D); combo.addItem(E); Once it is created, we can check which one is selected by a user using following methods:
combo.getSelectedIndex() -- returns an index (integer) of the selected item. combo.getSelectedItem() -- returns a selected object.

A Listener for a JComboBox can be constructed in a similar way to the one for JButton. A class that implements ActionListener interface needs to be created, and the actionPerformed method needs to be defined:
private class ComboListener implements ActionListener { public void actionPerformed(ActionEvent event) { if (combo.getSelectedIndex() == 0) label.setText(A was chosen); else if (combo.getSelectedIndex() == 1) label.setText(B was chosen); //Etc. } }

Insertion Sort Algorithm

--It sorts a list of values by repetitively inserting a particular value into a subset of the lis Example: 3 9 6 1 2 9 should be inserted after 3 no change

6 should be inserted between 3 and 9

9 1

1 should be inserted before 3

2 should be inserted between 1 and 3

3 6

The complexity of the insertion sort algorithm is order of n2

Comparisons are done in this line. A similar //-----------------------------------------------------------------computation to the one for selection sort results into: // Sorts the specified array of integers using the insertion
// sort algorithm. //----------------------------------------------------------------- when an input array is Best Case public static void insertionSort (int[] numbers) already sorted - O(n) { for (int index = 1; index < numbers.length; index++) when an input array is in Worst Case { the reverse order - O(n2) int key = numbers[index]; int position = index; We consider the worst case for its upper bound, // shift larger values to the right So the insertion sort algorithm is O(n2) while (position > 0 && numbers[position-1] > key) { numbers[position] = numbers[position-1]; position--; } numbers[position] = key; } }

The Comparable interface

The Comparable interface is defined in the java.lang package and it contains only one method, compareTo, which takes an object as a parameter and returns an integer. Any that implements the Comparable interface needs to define compareTo method and their instantiated objects become something that can be compared. // Person.java: Represents a Person. public class Person implements Comparable { private String firstName, lastName, phone;

// Sets up this Person with the specified information. public Person (String first, String last, String telephone) { firstName = first; lastName = last; phone = telephone; }

// Uses both last and first names to determine lexical orderi public int compareTo (Object other) { int result;

Recursion

We suppose that you have seen iterative methods in the prerequisite courses. Methods u or do-while loops are considered to be iterative. Often we can compute the same result u In some cases, using recursion enables you to give a natural, straight forward, simple so difficult to solve.
What is a recursive method? -A method that invokes itself (direct recursion)

Example: public void methodA() { methodA(); }

Of course the methodA keeps calling itself and this will generate an infinite recursion. Thu where it does not call itself. Recursion should have: - recursive case(s) - base case(s) (non-recursive part, stopping condition)

Example: For a given positive integer n (i.e., n = 1, 2, 3, 4, ), the method sum is defined by: sum

Using a loop (iterative), this can be computed using a variable that shows the accumula (here the variable is result)

public static int sum(int n) { int result = 1;


for (int i=2; i<=n; i++) result = result + i; return result; }

//in this line, result on the right hand side is the old value o //and the result on the left hand side if the new value conta

By observing the pattern from the previous page, we can formulate the recursion:

Base case: sum(1) = 1 for n=1

Iterative case: sum(k) = sum(k-1) + k for k >= 2 (This means that, assuming that we have already computed the sum up to n=1 we can co k-1,

The secondmethodrecursive since you see the same function in both sides n=2 equatio of the Recursive line is

n=3 Based on the that n >= 1 // assume above observation, we have the following recursive method to compute the public static int sum(int n) main n=4 { sum(4)= sum(3) + 4=4+6is returned sum(4) int result; if (n == 1) // base case is invoked sum sum(3)= sum(2) + 3=3+3is returned result = 1; sum(3) else //recursive case for n >= 2 is invokedsum result = sum(n-1) + n; sum(2)= sum(1) + 2=2+1is re sum(2) This method can be called from a main method as: is invokedsum return void main(String[] args) public staticresult; sum(1)=1 is returned { } sum(1) int result = sum(4); is invoked sum } Observe that the sum using a recursive method can be computed in two passes. going down to the base case, then going up!

We can also observe from the mathematical recursive function that: Sum(4) = sum(3) + 4 = ((sum(2) + 3 ) + 4 = (((sum(1) + 2) + 3) + 4) = ((( 1 + 2) + 3) + 4) = (( 3 + 3) + 4) = (6 + 4) = 10

<- reached the base case

Now you can see these two methods side by side. They compute the exactly same res the other is recursive. Iterative method public static int sum(int n) { int result = 1; for (int i=2; i<=n; i++) result = result + i; Recursive method // assume that i >= 1 public static int sum(int i) { int result; if (i == 1) // base case result = 1; else //recursive case for i >= 2 result = sum(i-1) + i;

return result; How to construct a recursive method: }

return result; 1. Identify your sub-problem. i.e., the same problem as the original problem, but on a subs } 2. Think how you can use a solution of the sub-problem to solve the original problem.

With the above example, the original problem is to compute the sum from 1 to n, and th If we had the sum from 1 to (n-1), then we just need to add n to it to get the sum from 1 3. Also consider your base case(s).

Indirect Recursion

m1

invokes Example: invokes For the methods m1, m2, and m3. m2 m3 m1 invokes m2, which invokes m2, which invokes m1. invokes Sorting using Recursion --It is difficult to trace and debug. Merge Sort Merge Sort uses Divide and Conquer approach. It divides elements evenly and invokes elements. 6392 Dividing process
63 6 36 2369 3 92 9 29

2
Merging process

public static void mergeSort(int[] num, int start, int end) The method mergeSort splits an array in { subarrays and invokes itself on them. //base case is when start == end, does nothing (start is the starting index and end is th if (start < end) //recursive case { The method merge merges two subarray int mid = (int) Math.floor((double) (start+end)/(2.0)); array without disturbing their order. mergeSort(num,start,mid); mergeSort(num,mid+1,end); merge(num, start, mid, end);

} The mergeSort method invokes merge method described in the next page. } The merge method merges two sorted subarrays into one. 2 5 6 9 13 14 1 1 3 4 7 10 12 2 3 4 5 6 7 9 10 12 13 14

The complexity of Merge Sort Algorithm is n log n. Therefore Merge Sort is more effic Selection Sort and Insertion Sort in their w

public static void merge(int[] num, int start, int mid, int end) // copy the rest of the subarray that d { if ( i == n1) int n1 = mid-start+1; //get the length of the first half subarray { int n2 = end-mid; //get the length of the second half subarray while (k <= end) int[] left = new int[n1]; { int[] right = new int[n2]; num[k] = right[j]; k++; //i is used for the array "left", j for "right", k for "num" j++; int i, j, k; } // copy the elements in the array "num" to the arrays} else if (j == n2) // "left" and "right" { for (i=0; i<n1; i++) while (k <= end) left[i] = num[start+i]; { num[k] = left[i]; for (j=0; j<n2; j++) k++; right[j] = num[mid+1+j]; i++; } i=0; } j=0; } k=start; while (i < n1 && j < n2) //merge left and right into "num" { if (left[i] <= right[j])

Binary Search using Recursion:

public static int binSearch(int[] num, int x) { int n = num.length;


if (n == 0 || x > num[n-1] || x < num[0]) return -1; // x is not found else return binRec(num,x,0,n-1); } public static int binRec(int[] num, int x, int i, int j) { //base cases if (i==j && num[i]==x) return i; // x is found else if (i==j && num[i]!=x) return -1; // x is not found int k = (int) Math.floor((i+j)/(2.0)); //recursive cases

Quick Sort algorithm

The quick sort uses the strategy of divide and conquer like merge sort. Its idea is to rearrange the element in the range so that no element in the first sub-array is larger than any element in the last sub-array. i.e., all elements in the first sub-array are smaller or equals to a pivot value, and all elements in the last sub-array are greater equals to a pivot value. There are several ways to pick a pivot value, but one way is to pick the first element of a given array. If we have an array containing:

{5 3 2 6 4 1 3 7}
And if we use 5 (the first element of this array) as a pivot to partition, we can arrange it into two sub arrays as: {3 3 2 1 4} {6 5 7} (this can be viewed as one array {3 3 2 1 4 6 5 7})

The first sub-array contains elements smaller or equals to 5, and the second sub-array contains elements greater or equals to 5.

We can repeat the similar partitioning process on two sub arrays (to get four sub-arrays on). At the end, we will have a sorted array.

//The partition method re-arrange the array so that a //The quickSort method calls partition method to partition // the two (first //the array, then call itself recursively on the pivotsub element of the array) are grouped a //of the array, //arrays that were divided by the partition method. and all elements >= the pivot are gro //end of the array. The returned index j will be where //divided when to) public static void quickSort(int[] elements, int from, int the partitioning process is over. public static int partition(int[] elements, int from, int to { { if ( from < to ) int pivot = elements[from]; { int p = partition(elements, from, to); int i = from -1; int j = to + 1; quickSort(elements, from, p); quickSort(elements, p+1, to); } } //end of quickSort method

while (i < j ) // until i and j cross each other { i++; //move i towards right until we find an element g while (elements[i] < pivot) i++;

j--; //move j towards left until we find an element sm while (elements[j] > pivot) j--; //we swap the two elements

Example of partition: Pivot is set to the first element, in this case 4.

4 3 7 9 5 6 1 8 2

i ->

<- j

i keeps increasing until it finds an element that is greater than or equals to the pivot va j keeps decreasing until it finds an element that is smaller than or equals to the pivot v

4 3 7 9 5 6 1 8 2 i j Then we swap these two values:

i finds 4 and j finds 2

2 3 7 9 5 6 1 8 4 i j
Repeat this process until i and j cross each other. (repeat FIND and SWAP) FIND

Running Time Analysis of QuickSort

Worst Case running time: O( n2 )

Worst Cases occur when the array is re-arranged into one sub-array containing only on the rest of elements in every partition process. This generates an extreme split and re

Average and Best Case running time: O( n log (n) )

The best case occurs when the array is re-arranged into two same (or almost same in in every partition process. In this case, its running time is computed in almost same way as that of the Merge So However, the constant/ coefficient of Quick Sort running time is much smaller than that faster than Merge Sort in most cases.

One possible average case might be when an array is partitioned into a sub-array with with the length of of the original one.

Data Structures Static vs. Dynamic Structures -A static data structure has a fixed size example: arrays (Note, this meaning is different from those associated with static modifier)

-A dynamic data structure grows and shrinks as required by the information it contains student example: linked lists John Smith 40725 3.58 An object reference is a variable that stores the address of an object. A reference is also called a pointer. Object references can be used to create links between objects
Linked Lists

A variable students the address of Consider an object that contains a reference to another object of the same type: the ob containing information John Smith class Node { String name; Node pointer; } This can construct a linked list

Deleting an entry from a linked list:

Inserting an entry into a linked list:

Using Iterator in the ArrayList We can use the iterator of an ArrayList object to traverse it (without using any index). ArrayList arraylist1 = new ArrayList(); .. Iterator iterator1 = arraylist1.iterator(); while (iterator1.hasNext()) { System.out.println(iterator.next()); }

Here, we use iterator.next() to access each element in the array list. Since a linked list does not have any index to trace each element, we need to use an ite Note that the above loop is equivalent to:

for (int i=0; i<arraylist1.size(); i++) { System.out.println(arraylist1.get(i)); }


We can also use for each loop as follows:

// Returns the first element in the linked list. public Object Note: You need to be careful in boundary cases such as getFirst() operations at the beginning and the end of a { list. if (first == null) { //This Linked List class shows how some of its commonly NoSuchElementException ex //used methods are implemented. = new NoSuchElementE throw ex; // A linked list is a sequence of nodes with efficient } // element insertion and removal. else // This class contains a subset of the methods of the return first.data; // standard java.util.LinkedList class. } import java.util.NoSuchElementException; // Removes the first element in the linked lis public Object removeFirst() public class LinkedList { { if (first == null) //nested class to represent a node { private class Node NoSuchElementException ex { = new NoSuchElementE public Object data; throw ex; public Node next; } } else { //only instance variable that points to the first node.
Some method implementation of Linked List

// Tests if there is an element after the itera // Adds an element to the front of the linked list. public boolean hasNext() public void addFirst(Object element) { { if (position == null) //not traversed yet //create a new node { Node newNode = new Node(); if (first != null) return true; newNode.data = element; else return false; newNode.next = first; } //change the first reference to the new node. else first = newNode; { } if (position.next != null) return true; else return false; // Returns an iterator for iterating through this list. } public ListIterator listIterator() } { // Moves the iterator past the next elemen return new LinkedListIterator(); // the traversed element's data. } public Object next() { //nested class to define its iterator if (!hasNext()) { private class LinkedListIterator implements ListIterator NoSuchElementException ex = { new NoSuchElementE private Node position; //current position throw ex; private Node previous; //it is used for remove() method } else { // Constructs an iterator that points to the front previous = position; // Remember for r

// Removes the last traversed element. This method // Adds an element after the iterator position be called after a call to the next() method. // only // and moves the iterator to point to public void remove() // the inserted element. { public void add(Object element) if (previous == position) //not after next() is calle { { if (position == null) //never traversed yet IllegalStateException ex = new IllegalStateEx { throw ex; addFirst(element); } position = first; else } { else if (position == first) { removeFirst(): //making a new node to add else Node newNode = new Node(); previous.next = position.next; //removing newNode.data = element; //stepping back newNode.next = position.next; //this also means that remove() cannot be cal //change the link to insert the new node position = previous; position.next = newNode; } //move the position forward to the new node } position = newNode; // Sets the last traversed element to a different valu } public void set(Object element) //this means that we cannot call remove() { //right after add() if (position == null) { previous = position; NoSuchElementException ex = new NoSuchE

// The ListIterator interface allows access of a position in a linked list. // This interface contains a subset of the methods of the // standard java.util.ListIterator interface. The methods for // backward traversal are not included. public interface ListIterator { //Move Moves the iterator past the next element. Object next(); // Tests if there is an element after the iterator position. boolean hasNext(); // Adds an element before the iterator position // and moves the iterator past the inserted element. void add(Object element);

// Removes the last traversed element. This method may // only be called after a call to the next() method. void remove(); // Sets the last traversed element to a different value. void set(Object element);

UML class diagram representing the classes/interface used in the last 4 slide pages:

LinkedListIterator -position:Node -previous:Node LinkedList -first:Node +LinkedList() +getFirst(): Object +removeFirst(): Object +addFirst(Object):void +listIterator(): ListIterator +LinkedListIterator() +hasNext():boolean +next():Object +add(Object):void +remove():void +set(Object):void Node +data:Object +next:Node

ListIterator

+hasNext():boolean +next():Object +add(Object):void +remove():void +set(Object):void

Example: Using the LinkedList and ListIterator classes we discussed in class, prints out the content o //This method the following output show how a linked list behaves: public static void printList(LinkedList { public class LinkedListTester ListIterator iterator = list1.listItera { String result = "{ "; public static void main(String[] args) while (iterator.hasNext()) { result += iterator.next() + " "; LinkedList list1 = new LinkedList(); result += "}"; ListIterator iterator = list1.listIterator(); System.out.println(result); } iterator.add("A"); } printList(list1); iterator.add("B"); Output: printList(list1); {A} iterator.add("C"); {AB} printList(list1); {ABC} {ADBC} iterator = list1.listIterator(); {ADBEC} iterator.next(); {DBEC} iterator.add("D"); {DEC} printList(list1); iterator.next(); iterator.add("E"); printList(list1);

We have Linked List class in java.util package. (but it is important to have some idea of how it is implemented as a programmer. We need to know how efficient to do each operation using it.)

Comparison between ArrayList and Linked List:

Efficiency of operations of ArrayList and LinkedList


--------------------------------------------------------------Operation ArrayList LinkedList --------------------------------------------------------------Access O(1) O(n) Add/Remove an element O(n)

O(1) -- assuming that the iterator is already in the right posit

-In ArrayList, we can access any element by specifying its index in constant time. O(1 -In LinkedList, we need to go through n/2 elements on average to get to an element. O

Linked List Variations: Doubly Linked Lists

-It may be convenient to implement a list with next and previous references. class Node { Object data; Node next, previous; }

Circular Linked Lists

-A linked list in which the last node points to the first node.

LinkedLists with a reference to the rear node as well as the referent to the front node.

It may also be convenient to use a separate header node with references to both the fro class List1 { Node first, last; }

list
first last

Garbage Collector

When we remove a node from a linked list, the memory used for that node should be r so that it can be used to store other data. Such memory can be collected by the garba The Java virtual machine contains a garbage collector that periodically reclaims objec You can also run a garbage collector using a code such as follows: //Runtime class is in java.lang package public static void runGarbageCollector() { // run garbage collector until no more memory freed up

//getRunTime()turns the runtime object associated with the current Java applicat Runtime runtime1 = Runtime.getRuntime();

//freeMemory() returns the amount of free memory in the Java Virtual Machine. long freeMemory = runtime1.freeMemory(); long oldFreeMemory; do { System.out.println("free memory: " + freeMemory); oldFreeMemory = freeMemory;

Abstract Data Types:

-An abstract data type (ADT) is an organized collection of information and a set of opera -The set of operations defines the interface to the ADT

Stacks
A stack is a data structure in which access is only allowed from one end. Imagine the candy Pez dispensers
You insert and remove candy from the same end. The first piece in is the last piece out.

You have a stack of books - to get to the bottom, you have to remove the ones on top. This is called LIFO - Last-in/First-out

java.util.Stack
Provides the stack class Constructor isEmpty or empty peek - get the top item without removing it pop - remove the top item push - push a new item onto the stack size - the number of items in a stack

Our Stack
Push T Push I Push N N I I

T
Pop N

T Pop I

T
Pop T

I T T

Evaluating Arithmetic Expressions with a Stack


Lets assume that the parentheses match up ( (1 + 2)/3) * (6 - 4) ) ( (3 / 3) * (6-4) ) ( 1 * (6 - 4) ) ( 1 * (2 ) ) 1* 2 =2

Evaluating Arithmetic Expressions using a Stack stacks Lets use 2


( ( (1 + 2) / 3) * (6 - 4) )
One storing numbers the other the operations

Read 1, + , 2
Then we hit a Right parenthesis so evaluate stack

2
1 + 3

Evaluating Arithmetic Expressions using a Stack


( ( (1 + 2) / 3) * (6 - 4) )
Read 3, / Then we hit a Right parenthesis so evaluate stack

3
3 1

Evaluating Arithmetic Expressions using a Stack


( ( (1 + 2) / 3) * (6 - 4) )
Read *, 6, -, 4 Then we hit a Right parenthesis so evaluate stack

Hit another Right parenthesis so evaluate stack

We get 2*1= *

6
1

2
1

Implementation of a Stack
A stack can be implemented using an array or a linked list
Using an array, elements are pushed and popped from the back end of the array Using a linked list, elements are added (pushed) to the head of the list and also removed from the head of the list when popped.

On Your Own
(1) What is the output
Stack Letters = new Stack(); Letters.push(A); Letters.push(B); System.out.println(Letters.pop()) ; Letters.push(C); Letters.push(D); System.out.println(Letters.pop()) ; System.out.println(Letters.pop()) ; System.out.println(Letters.pop()) ;

(2) What are some


Exceptions that could be thrown in our example of evaluating arithmetic expressions with the 2 stacks?

(3) Could we use a


stack to match parenthesis? How?

LIFO Last-in/ First-Out Data Structure

Queues
A queue is a data structure of ordered items where items are added to the rear (in the order that they are entered and removed from the front.)
Remember in Class - we lined people up into a queue and the first person in line received their project back first! (FIFO)

Queue Example
The first person in line at a bank is served first and so on. People are served on in respect to their position in line. At the bakery, you pull a number out of the machine that distributes numbers in order on a first-come, first serve basis. When your number in the queue is called it is your turn!

FIFO First-In/First-Out
A queue is a FIFO data structure
Adding an item is called enqueue
(Entering the queue)
First-In/First-Out

Removing an item is called dequeue


(Removing from the queue)

Push A

Comparing a Stack and Queue Pop


Push B Push C
C B B A B A

Removes C

Front
A

Back Insert A
A B C

Insert C

A B

Insert B

getFront Removes A

Enqueue/Dequeue
remove removes the front item from the queue (dequeue) offer adds a new item to the rear of the queue (enqueue)

Palindrome Evaluation Using a Stack and Queue


A palindrome is a word that reads identical forwards and backwards Examples
Radar Sees Bib

Whatever we read in and out of our stack and queue should output identical results from both the stack and queue!

Palindrome Example with a Stack and Queue


Assume that we have push and inserted the characters onto our stack and queue while(!q.empty()){ if(q.remove() != s.pop() ) mismatches ++; } if(mismatches == 0) System.out.println(Yeah palindrome!); else System.out.println(Thats not a palindrome.);

Queue Linked List Implementation


There are manyNodes representing the number of nodes The head is the front of the queue (where items are removed) The rear (tail) is the end of the queue where the items are added)

First-In/First-Out

Data Structure

Stacks

(Stack class in java.util package, it extends Vector class)

A stack adds items only to the top of the list and removes them from the top. push pop It is called a LIFO (Last-In, First-Out) data structure. Stacks are often drawn vertically. Some operations in a stack: Object push(Object item) adds an item to the top of the stack, and returns it Object pop( ) removes an item from the top of the stack and returns it Object peek( ) retrieves the top item without removing it boolean empty() returns true if the stack is empty, false otherwise

int size() returns the number of elements

A stack can be used to - reverse a string - check matching parentheses

//Example import java.util.Stack;

public class StackTester2 { public static void main(String[] args) { Stack test = new Stack(); test.push("A"); test.push("B"); test.push("C"); test.push("D"); System.out.println(test.toString()); System.out.println(test.peek()); System.out.println(test.toString()); System.out.println(test.pop()); test.push("E"); System.out.println(test.toString()); test.push("F"); System.out.println(test.toString()); System.out.println(test.pop());

/** output [A, B, C, D] D [A, B, C, D] D [A, B, C, E] [A, B, C, E, F] F [A, B, C, E, G] G [A, B, C, E, G] **/

Queues

A queue is similar to a list but adds items only to the end of the list and removes them fro It is called a FIFO (First-In, First-Out) data structure. Some operations on a queue: -enqueue add an item to the rear of the queue -dequeue remove an item from, the front of the queue dequeue

enqueue

We have Queue interface in java.util package.

Abstract methods: boolean offer(obj) - Inserts the specified element into this queue, if possible. It returns tru (for bounded peek() - Retrieves, but does not remove, the head of this queue, returning null if this queu It returns the peeked element. remove() - Retrieves and removes the head of this queue. It returns the removed element

LinkedList class implements Queue interface, As well as:

//Queue example using Linked List import java.util.LinkedList;

public class QueueTester2 { public static void main(String[] args) { LinkedList list = new LinkedList();
list.offer("A"); list.offer("B"); list.offer("C"); list.offer("D");

/** output [A, B, C, D] A [A, B, C, D] A [B, C, D, E] [B, C, D, E, F] B [C, D, E, F, G] C [C, D, E, F, G] **/

System.out.println(list.toString()); System.out.println(list.peek()); System.out.println(list.toString()); System.out.println(list.remove()); list.offer("E"); System.out.println(list.toString()); list.offer("F"); System.out.println(list.toString()); System.out.println(list.remove());

Applications of Stacks: Postfix Expression Infix notation


The operator is written between the operands

Prefix or Polish notation


Operators are written before the operands Does not require parentheses

Reverse Polish or postfix notation


Operators follow the operands Has the advantage that the operators appear in the order required for computation

Example:

Table 17-1 Infix expressions and their equivalent postfix expressions


Algorithm to evaluate postfix expressions

1. 2. 3. 4.

Scan the expression from left to right When an operator is found, back up to get the required number of operands Perform the operation Continue processing the expression

Tree data structures

Data can be stored in a tree format, such as binary trees. A node for binary trees can be defined as follows: class Node { Object data; Node rightNode; Node leftNode; } Here the letters A, B, C, D, E, F, G, and H are stored in a binary tree data structure.

228

Tree Traversals

How can we process or go through all nodes in a tree? We will look at three types of traversals, pre-order traversals, in-order traversals, and po Pre-order Traversal: The root is processed previous to its two sub-trees. For a non-empty tree: Step1: Process the root. Step2: Process the nodes in the left sub-tree with a recursive call. Step3: Process the nodes in the right sub-tree with a recursive call.

//The following preorderPrint method prints the data from each node //at or below this node of the binary tree. //Assume that this method is defined in the Node class in the previous page. public void preorderPrint() { System.out.print(data + ); if (leftNode != will Here the outputnull) be G D B A C F E K I H J M L leftNode.preorderPrint();

229

In-order Traversal: The root is processed in between the processing of its two sub-trees. For a non-empty tree: Step1: Process the nodes in the left sub-tree with a recursive call. Step2: Process the root. Step3: Process the nodes in the right sub-tree with a recursive call.

//The following inorderPrint method prints the data from each node //using in-order. //Assume that this method is defined in the Node class in the previous page. public void inorderPrint() { if (leftNode != null) leftNode.inorderPrint(); System.out.print(data + ); if (rightNode != null) rightNode.inorderPrint(); } Here the output will be A B C D E F G H I J K L M

230

Post-order Traversal: The root is processed after processing its two sub-trees. For a non-empty tree: Step1: Process the nodes in the left sub-tree with a recursive call. Step2: Process the nodes in the right sub-tree with a recursive call. Step3: Process the root.

//The following postorderPrint method prints the data from each node //using post-order. //Assume that this method is defined in the Node class in the previous page. public void postorderPrint() { if (leftNode != null) leftNode.postorderPrint(); if (rightNode != null) rightNode.postorderPrint(); System.out.print(data + ); Here the output will be A C B E F D H J I L M K G }

231

Binary Search Trees:

The binary search property is that any element in the right sub tree is larger than the va and any element in the left sub tree is smaller than (or equals to ) the value of the node Thus those elements need to be compared such as numbers or strings.

Searching operation can be more efficient in a tree data structure than a linear list.

232

Inorder-Print/Traversal: prints out all the key in a binary search tree in sorted order.

15
6 3 2 4 9 7 13 17 18 20

2,3,4,6,7,9,13,15,17,18,20

233

The successor of a node x is the node with the smallest key greater than x. The predecessor of a node x is the node with the greater key smaller than x.

234

Example: Search for k = 4

15 6 3 2 4 9 7 13 17 18 20

235

Insert key = 13

15 6 3 2 4 9 7 13 17 13 18 20

236

Heaps
A heap or min-heap (max-heap) is a binary tree with two special properties: 1. A heap is almost complete: all nodes are filled in, except the last level may have some nodes missing toward the right. 2. The tree fulfills the heap property: all nodes store values that are at most as small (large) as the values stored in their descendants. It is easy to see that the heap property ensures that the smallest element is stored in the root.

Example of an almost complete tree:

An example of a heap

A heap content can be physically stored in an array (or arrayList) because of the firs 0 1 2 3 4 5 6 7 8 9

20 75 43 84 90 57 71 93 91 96

20 75 43 84 90 57 71 93 91 96
For an element at the index i of the array, The index of its left child is: 2*i + 1 The index of its right child is: 2*i + 2 The index of its parent is: the integer part of (i-1)/2

Using these formula, we can find the children or the parent of a node in the array.

i=0

i=1 i=4 i=3 i=5 i=9

i=2

For example, for the node at the index = 3, the left child is 2*3+1=7 the right child is 2*3+2=8 the parent is: (3-1)/2 = 1

i=6

i=7

i=8

A priority queue collects elements, each of which has a priority. Elements are retrieved according to their priority. New items can be inserted in any order, but the item with the highest priority is removed first. example: A collection of work requests, some of which many be more urgent than others. A heap can be used to represent a priority queue because of its 2nd property. The element at the root position has the smallest value, so it can be viewed as having the highest priority. It is easy to find the element with the highest priority in a heap.

We will be looking at three operations: -Inserting a new element into a heap -Extracting (Deleting) the root of a heap -Sort an array using a heap (Heap Sort)

1. Inserting an element into a heap Example: Inserting a new element with 60.

Insertion steps: Step1: Insert a new element as the last element in the heap (array). (This makes the 1st property of the heap hold.) Step2: Repeat the following until we are done or reach the top of the heap (no parent) Compare the added element to its parent. If the parent is larger than the new element, then swap them Else DONE! (This makes the 2nd property of the heap hold.)
Efficiency of Insertion: -Step1 takes a constant time: O(1) -In each comparison and swapping in the step 2 using an array or an arraylist takes a constant time. Step 2 can be repeated at most the height of the heap. If we have n elements in a heap, the height of the heap is O( log n) -- same idea as binary search This total running time of Insertion is: O(1) + O(1) * O(log n) = O( log n). It is O(log n).

2. Extracting the root node from a heap

Extraction (Removing) steps: Step1: Extract the root element. Step2: Remove the last element in the heap (array) and set it as the root. (This makes the 1st property of the heap hold.) Step3: Repeat the following until we are done or reach the bottom of the heap (no child) Compare the new root element to its children. If at least one of the children is smaller than the new root, then swap it with the smaller value child element, Else DONE! (This makes the 2nd property of the heap hold.)
Efficiency of Extraction of the root: -Step1 and Step2 take a constant time: O(1) -In each comparison and swapping in the step 3 using an array or an arraylist takes a constant time. Step 3 can be repeated at most the height of the heap. If we have n elements in a heap, the height of the heap is O( log n) -- same idea as binary search This total running time of Deletion of the root is: O(1) + O(1) * O(log n) = O( log n). It is O(log n).

3. HeapSort
We can use a heap to sort an array. Here we use a max-heap instead of a min-heap.

The main idea: Build a heap from an array. With a max-heap, we can extract the root to get the largest value, and put it aside (put it as the last element of the array by swapping the root and the last element.) Then we continue to extract the next root (the second largest value, and put it as the second last element of the array. After doing this for n-1 times (where n is the number of elements in the initial heap), we will have a sorted (ascending order) array. To have a descending order array, we can use a min-heap.

Since sorting an array means to sort any array, first we need to build a heap before we start extracting the roots.

Turning a tree into a max-heap. (Building a max-heap from an array)


For each node that has a child node, we call fixHeap method. We do this starting the node in the lowest level first, then we do for nodes in the one level above. Then we keep going up to the node in the above level until we call fixHeap on the root.

The fixHeap method: --------------------------------------------------------------Repeat the following until both children are smaller or we reach the bottom of the tree. 1. we compare the node and its children. 2. If at least one of the children is larger than the node, then swap it with the larger child. Else DONE! 3. If it is not done, go back to the step 1, with the nodes new location. ----------------------------------------------------------------

Turning a tree into a max-heap. (Building a max-heap from an array)

First we call fixHeap on each node in the second lowest level.

Then we call fixHeap on each node in the third lowest level

Then we call fixHeap on the root.

Heap Sort summary: (using a max-heap)


1. Build a heap from a given array. 1.1. For each node with at least one child node (i.e., not leaves), starting with the ones in the lowest level and ending with the root (bottom-up order), call the fixHeap (Heapify) method: 1.1.1 Repeat the following until its child nodes are smaller or reach the bottom of the heap: Compare the node and its children. If at least one child is larger than the node, then swap the node with the larger child node. Else, DONE. 2. Extract the root for n-1 times where n is the number of elements in the heap (array).

for (int i=0; i < n-1; i++) Extract the root and swap it with the element at the (n-1-i)-th position of the array. Adjust the tree so that the heap property holds for every extraction.

Worst case running time of Heap Sort: O(n log n)

Example: Building a max-heap 12 27 22 80 24 13 31 7


swap

12 27 10 7 33
swap

10 33 22 80 24

31 13

12 27
swap

12 10
swap

27 31 7

33 10

22 24

31 13

33

80

80

22

24

13
Next page

Continuing from the previous page.

swap

12 33 7 10 22 31

80 33

80 27 22 24 31 13

27
24

12
13

7
swap

10

80 80 31 12
swap

33 7 10

33 27 13 7 10

27 22 24

31 13

22

24

12
DONE!

/** This class applies the heapsort algorithm to sort an array. */ public class HeapSorter { private int[] a;

// Constructs a heap sorter that sorts a given array. // @param anArray an array of integers public HeapSorter(int[] anArray) { a = anArray; }
// Sorts the array managed by this heap sorter. public void sort() { int n = a.length - 1; //for each node that has at least one child node for (int i = (n - 1) / 2; i >= 0; i--) fixHeap(i, n); while (n > 0) { swap(0, n); n--; fixHeap(0, n); } }

// Ensures the heap property for a subtree, provided its children already fulfill the heap property // @param rootIndex the index of the subtree to be fixed // @param lastIndex the last valid index of the tree that contains the subtree to be fixed private void fixHeap(int rootIndex, int lastIndex) { int rootValue = a[rootIndex]; //Remove root // Promote children while they are larger than the root int index = rootIndex; boolean more = true; while (more) { int childIndex = getLeftChildIndex(index); if (childIndex <= lastIndex) { // Use right child instead if it is larger int rightChildIndex = getRightChildIndex(index); if (rightChildIndex <= lastIndex && a[rightChildIndex] > a[childIndex]) { childIndex = rightChildIndex; }

if (a[childIndex] > rootValue) { // Promote child a[index] = a[childIndex]; index = childIndex; } else { // Root value is larger than both children more = false; }
} else { // No children more = false; } } // Store root value in vacant slot a[index] = rootValue; }

// Swaps two entries of the array. // @param i the first position to swap // @param j the second position to swap private void swap(int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } // Returns the index of the left child. // @param index the index of a node in this heap // @return the index of the left child of the given node private static int getLeftChildIndex(int index) { return 2 * index + 1; } // Returns the index of the right child. // @param index the index of a node in this heap // @return the index of the right child of the given node private static int getRightChildIndex(int index) { return 2 * index + 2; } }

3. HeapSort
We can use a heap to sort an array. Here we use a max-heap instead of a min-heap.

The main idea: Build a heap from an array. With a max-heap, we can extract the root to get the largest value, and put it aside (put it as the last element of the array by swapping the root and the last element.) Then we continue to extract the next root (the second largest value, and put it as the second last element of the array. After doing this for n-1 times (where n is the number of elements in the initial heap), we will have a sorted (ascending order) array. To have a descending order array, we can use a min-heap.

Since sorting an array means to sort any array, first we need to build a heap before we start extracting the roots.

Turning a tree into a max-heap. (Building a max-heap from an array)


For each node that has a child node, we call fixHeap method. We do this starting the node in the lowest level first, then we do for nodes in the one level above. Then we keep going up to the node in the above level until we call fixHeap on the root.

The fixHeap method: --------------------------------------------------------------Repeat the following until both children are smaller or we reach the bottom of the tree. 1. we compare the node and its children. 2. If at least one of the children is larger than the node, then swap it with the larger child. Else DONE! 3. If it is not done, go back to the step 1, with the nodes new location. ----------------------------------------------------------------

Turning a tree into a max-heap. (Building a max-heap from an array)

First we call fixHeap on each node in the second lowest level.

Then we call fixHeap on each node in the third lowest level

Then we call fixHeap on the root.

Heap Sort summary: (using a max-heap)


1. Build a heap from a given array. 1.1. For each node with at least one child node (i.e., not leaves), starting with the ones in the lowest level and ending with the root (bottom-up order), call the fixHeap (Heapify) method: 1.1.1 Repeat the following until its child nodes are smaller or reach the bottom of the heap: Compare the node and its children. If at least one child is larger than the node, then swap the node with the larger child node. Else, DONE. 2. Extract the root for n-1 times where n is the number of elements in the heap (array).

for (int i=0; i < n-1; i++) Extract the root and swap it with the element at the (n-1-i)-th position of the array. Adjust the tree so that the heap property holds for every extraction.

Worst case running time of Heap Sort: O(n log n)

Example: Building a max-heap 12 12

27

10

27

10
swap

22

13

7
swap

33

80

31

33

80

24

31

22

24

13

12 27
swap

12

27

10

33

swap

22

31

33

80

31

10

80

24

13

22

24

13
Next page

Continuing from the previous page.

80 12
swap

31 80 33

33

27
27 31 7 10

12

7
swap

10

22 22 24 13

24

13

80 80 31 12
swap

33

33 27 13 7 10

27

31

10 22 24 12

22

24

13

DONE!

/** This class applies the heapsort algorithm to sort an array. */ public class HeapSorter { private int[] a;

// Constructs a heap sorter that sorts a given array. // @param anArray an array of integers public HeapSorter(int[] anArray) { a = anArray; }
// Sorts the array managed by this heap sorter. public void sort() { int n = a.length - 1; //for each node that has at least one child node for (int i = (n - 1) / 2; i >= 0; i--) fixHeap(i, n); while (n > 0) { swap(0, n); n--; fixHeap(0, n); } }

// Ensures the heap property for a subtree, provided its children already fulfill the heap property // @param rootIndex the index of the subtree to be fixed // @param lastIndex the last valid index of the tree that contains the subtree to be fixed private void fixHeap(int rootIndex, int lastIndex) { int rootValue = a[rootIndex]; //Remove root // Promote children while they are larger than the root int index = rootIndex; boolean more = true; while (more) { int childIndex = getLeftChildIndex(index); if (childIndex <= lastIndex) { // Use right child instead if it is larger int rightChildIndex = getRightChildIndex(index); if (rightChildIndex <= lastIndex && a[rightChildIndex] > a[childIndex]) { childIndex = rightChildIndex; }

if (a[childIndex] > rootValue) { // Promote child a[index] = a[childIndex]; index = childIndex; } else { // Root value is larger than both children more = false; }
} else { // No children more = false; } } // Store root value in vacant slot a[index] = rootValue; }

// Swaps two entries of the array. // @param i the first position to swap // @param j the second position to swap private void swap(int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } // Returns the index of the left child. // @param index the index of a node in this heap // @return the index of the left child of the given node private static int getLeftChildIndex(int index) { return 2 * index + 1; } // Returns the index of the right child. // @param index the index of a node in this heap // @return the index of the right child of the given node private static int getRightChildIndex(int index) { return 2 * index + 2; } }

Vous aimerez peut-être aussi