Cse 205 All Java Slides

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

Transcript of Cse 205 All Java Slides

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 1/260

Java Introduction

• The Java programming language wascreated by Sun Microsystems, Inc.

• It was introduced in 1995 and it'spopularity has grown quickly since

• It is an object-oriented language

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 2/260

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) alwayscontains a method called main 

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 3/260

3

Java Program Structure

 public class MyProgram  

{

// comments about the class

class header

class body

Comments can be placed almost anywhere

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 4/260

4

Java Program Structure

 public class MyProgram  

{

 public static void main (String[] args) 

{

// comments about the class

// comments about the method 

method headermethod body

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 5/260

5

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 */

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 6/260

6

Java Identifiers

• An identifier can be made up of letters, digits,the underscore character ( _ ), and the dollarsign

• 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, suchas

 – title case for class names - Lincoln 

 – upper case for constants - MAXIMUM 

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 7/260

7

Reserved Words

• The Java reserved words:abstract

 boolean

 break

 bytecase

catch

char

class

const

continuedefault

do

double

else

extends

false

finalfinally

float

for

goto

if

implementsimport

instanceof

int

interface

long

native

newnull

 package

 private

 protected 

 public

returnshort

static

strictfp

super

switch

synchronized 

thisthrow

throws

transient

true

try

void volatile

 while

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 8/260

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 t

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 9/260

Visibility Levels for attributes:

Public +Private – Protected #

Ex.  –address: String#idNumber: int

Multiplicity

1 one and only one0..1 zero or oneM..N from M to N (natural numbers)* from zero to any positive integers0..* from zero to any positive integers1..* from one to any positive integers

Example: One to many associationFor one bank, there are many customers.

1 *

Bank Customer

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 10/260

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.

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 methodscan be added to Teacher and Student).

Person

Teacher

Student

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 11/260

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 cla

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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 12/260

Transition from a Class Diagram to a class in JAVA

Class Diagram

Student

-name: String = “?” -address: String = “?” -idNumber: int = 0

+toString(): String+submitHW(): boolean

Student.java _____________________________________ 

 public class Student{

private String name;private String address;private int idNumber;

 //Constructorpublic Student(){

name = new String(“?”); address = new String(“?”); idNumber = 0;

}

public String toString(){

 //to be filled by a programer

Note: the parameters of each method might notbe present and in that case, a programmer needs tofill them.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 13/260

Object Diagrams

An Object Diagram consists of one or more instantiated objects.

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

The attributes shown with their current value 

Example:

Class Diagram

Coin

-face:int

+flip():void+setFace(int):void

coin1:Coin

face=0

coin2:Coin

face=1

Object Diagram

coin1 and coin2 are instances ofthe class Coin.

Coin coin1 = new Coin();

coin1.setFace(0);

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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 14/260

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 theint corresponding to the value stored in the parameter string. Since it is static, it can be calledwith 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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 15/260

Inheritance-- to derive a new class from an existing class.

In stead of repeating similar data/method definitions in several classes, we can definewith 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 kwill need instance data tail and legs, we can define them in another class called “Anim

let Cat, Dog, and Raccoon classes inherit from it.

Animalint tail;int legs;

Cat Dog Raccoon

Here the Animal class is called “parent class ”, “super class ”, or “base class ” 

The classes Cat, Dog, and Raccoon are called “child class ” or “sub class ”. The child classes will inherit the methods and data defined for the parentclass.

However, child classes do not inherit private variablesand methods. They can inherit public variables and methods.Making instance data (variables) public violatesEncapsulation. There is another visibility modifier called“ protected” . Protected variables and methods canbe 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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 16/260

Visibility Modifiers

public -- inherited, can be accessed from anywhere (we use + for UML class diagramsprivate – not inherited, can be accessed only within its class (we use – for UML class diprotected – 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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 17/260

public class Car extends Vehicle

{

 // class contents

}

Vehicle

Car

If we want the class Car to inherit the class Vehicle, we use the followingsyntax (using the reserved word “extends”): 

-Constructors are not inherited: A child’s constructor is responsible for calling its parent’s 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 t

public String toString(){

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 18/260

Super reference-- refer to the parent class

Example:

 // Parent classpublic class Book{protected int pages;

public Book(int numPages){

pages = numPages;}

public String toString()

{return (“The number of pages: “ + pages); 

}}

 // Child classpublic class Dictionary extends Book{private int definitions;

public Dictionary(int numPages, int num

{super (numPages); // calls Parent’ co

 definitions = numDefn;

}

public String toString(){

return (“The number of definitions: “

+ definitions + “ \ n” + super.toString( ) );

// calls Parent’s toString method }

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 19/260

Java supports single inheritancei.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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 20/260

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 object’s class and a hash val

-equals(Object arg) – returns true if two object references refer to the same object.

Abstract classes

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 21/260

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 tfrom 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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 22/260

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 ossible if ob 1 does not contain a Com uter ob ect.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 23/260

Polymorphism

A polymorphic referenceis a reference variable that can refer to different types of objects at different points in ti

 Polymorphic references are resolved at run-time, not during compilation.

Animal

Mammal

Dog

move()

move()

move()

Example: Suppose that we have the following inheritance, the class Dog

inherits from the class Mammal, and the class Mammal inherits fromthe class Animal.

Animal[] animalList = new Animal[3];

animalList[0] = new Animal();

animalList[1] = new Mammal();animalList[2] = new Dog();

for (int i=0; i <= 2; i++){

animalList[i].move();

}

The left line refers to different definition

of the move method for each i.

animalList[0].move() refers to move() ofAnimal class.animalList[1].move() refers to move() ofMammal class.

This part is polymorphic.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 24/260

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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 25/260

Example5: using javax.swing.Timer class. A yellow circle will bebouncing inside of an applet. When it hits a wall, it bounces 45 degreesso that it won’t 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();}

}

// D h i l i h l i

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 26/260

 // Represents the primary panel for the Reboundapplet.

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 theanimation. //-----------------------------------------------------------------public ReboundPanel (){

timer = new Timer(DELAY, newReboundListener());

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 appletclass.

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 applet’s 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();}

}}

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 27/260

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 anExample:

--------------------------------------------------------------------------------------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 / denominatAt this point, the program is terminated and the next line is never executed.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 28/260

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 exce

// finally clause is used to manage resources or to guarantee that particular parts}

The catch clause may be omitted when the finally clause is used, and vice versa. Mor

Throws clause

The appropriate exception is appended to the header of a method definition where the

Example:

public static void main (String[] args) throws IOException{

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 29/260

Example:-----------------------------------------------------------------------------------import java.util.Scanner;

public class ProductCodes {public static void main (String[] args) {

String code;char zone;int district, valid = 0, banned = 0;

Scanner input = new Scanner(System.in);System.out.print ("Enter product code (XXX to quit): ");code =input.next();

while (!code.equals ("XXX")){

try {zone = code.charAt(9);district = Integer.parseInt(code.substring(3, 7));valid++;if (zone == 'R' && district > 2000)

banned++;}

If the string “code” does not have enough

charAt and substring can throw StringInd

 If the substring of “code” contains a non-dMethod parserInt can throw NumberForm 

How do we know which methods throw ewhich exception a method throws? – Seeand description of each method.

For instance, see the method “parseInt” o

It throws NumberFormatException.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 30/260

There are checked and unchecked exceptions:

Checked exceptions – must be caught by a method (try & catch ) or be listed in the thro Unchecked exceptions – should not be caught and requires no throws clause.

Only unchecked exception in Java are objects of type Runti 

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 31/260

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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 32/260

 //Using the Scanner class, we have thefollowing in a program:

 //------------------------------------------------------------------------------------import java.util.Scanner;

public class lab1{public static void main (String[] args){Scanner in = new

Scanner(System.in);String line = in.next();

while (line.equals("QUIT") == false){System.out.println(line);

line = in.next();}}

}

InputStreamReader converts the originalcharacter stream.

With BufferedReader, we can use readLi

“isr” and “stdin” are variables. 

The method readLine() throws IOExceptherefore we need to use either throw clThis method reads a line by a line ever

 //---------------------------------------------------------------------------------------- //Now we read from a keyboard without using the Scanner class: //----------------------------------------------------------------------------------------import java.io.*;

public class lab2

{public static void main (String[] args) throws IOException{InputStreamReader isr = new InputStreamReader(System.in);BufferedReader stdin = new BufferedReader(isr);

String line = stdin.readLine();" "

These programs keep reading keyboard input untilthe string “QUIT” is entered. 

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 33/260

33

Designing Classes

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 34/260

34

Classes – introduction

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

EncapsulationThe variables contained in an object should be modified only withinthe object.

Visibility modifiers/Access SpecifiersThey are used to declare classes, methods, and variables to definetheir accessibility .

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

Accessor methods

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 35/260

35

Accessor methodsAn accessor method can be defined to access private variable in the classsince 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;

}}

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 36/260

36

The toString methods

-It is a method that takes no parameter and returns a String.

-A returned string usually contains information on instance variablesof its class.

-Each class has a default toString method that contains its class objectname and hash number.

-When an object is used with System.out.print or println method,its toString method will be called.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 37/260

37

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;}

} // end of the class Customer

Output of this program:

CustomerId: 1Balance: 100.0CustomerId: 1Balance: 100.0

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

Constructor methods

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 38/260

38

Constructor methodsA 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;

}}

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 39/260

39

Method OverloadingThe 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;

}

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 40/260

40

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.

Th thi f

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 41/260

41

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 yetequivalent 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 variablethis.accountNum = accountNum; //accountNum on right hand side is a local

}}

Static modifiers

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 42/260

42

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 forall others.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 43/260

43

Coin

-face:int-count: static int

+flip()

coin1:Coin

face=0count=2

coin2:Coin

face=1count=2

Class coin1 and coin2 are instances of the class Coin.

They must have the same value because count is static

Non static variablecan have differentvalues

We can create other classes besides the class that contains

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 44/260

44

Drive class/program (Test class/program) containsa main method.

public class Example1{public static void main(String[] args){

Customer customer1; // declarationcustomer1 = new Customer(); // instantiation

customer1.setCustId(12345);System.out.println(customer1.getCustId());

Customer customer2 = new Customer();System.out.println(customer2.getCustId());

}}

public class Customer{

private int custId;private double balance;

public Customer() // first constructor{custId = 0;balance = 0.0;

}

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

public int getCustId() // accessor method{

return custId;}

} // end of the class Customer

Customer.java

We can create other classes besides the class that containsa main method.

public class Customer

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 45/260

45

Drive class/program (Test class/program) containsa main method.

Example1.java

public class Example1

{public static void main(String[] args){

Customer customer1; // declarationcustomer1 = new Customer(); // instantiation

customer1.setBalance(1000.0);

System.out.println(customer1.getCustId());

Customer customer2 = new Customer(2, 500.0);System.out.println(customer2.getBalance());

}}

The Example1 class created an object of Customer.

p{

private int custId;private double balance;

public Customer() // first constructor{custId = 0;balance = 0.0;

} //second constructorpublic Customer(int id, double balance){custId = id;this.balance = balance // this reference is used to distinguish

 // instance variable and local variable}

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

public int getCustId() // accessor method{return custId;

}public void setBalance(double balance2) // mutator method{

balance = balance2;}

public double getBalance() // accessor method

{return balance;

}public String toString(){String result = "CustomerId: " + custId

+ "\nBalance: " + balance;return result;}

} // end of the class Customer

Example1Customer

Createsan object

Customer.jav

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 46/260

Software Engineering

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 47/260

47

What is Software Engineering about?

An attempt to produce a repeatable process for thedevelopmentand management of software projects. The quality

of the

software is a direct result of the process we followto create it

1. Cost Estimation1. Time2. Money3. resources

2. Division of project work 

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 48/260

Specifications for improving the softwaredevelopment process:

• SEI CMM (Software Engineering Institute

Capability Maturity Model)

• ISO 9001:2000

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 49/260

49

The Software Life Cycle

• The overall life cycle of a program includesuse and maintenance:

UseDevelopment

Maintenance

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 50/260

50

Development vs. Maintenance

Use andMaintenance

Development

De elopment and Maintenance

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 51/260

51

Development and MaintenanceEffort

Development Maintenance

Development Maintenance

Small increases in development effort canreduce maintenance effort

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 52/260

52

The Build-and-Fix Approach

Writeprogram

Modifyprogram

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

Repeat until everything is fixed

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 53/260

Software Development Models

A Software Development model is an organized approach tocreate quality software

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 54/260

54

The Waterfall Model

Establishrequirements

Create

design

Implementcode

Test

systemDeploy

An Iterative Development

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 55/260

55

An Iterative DevelopmentProcess

Establishrequirements

Createdesign

Implementcode

Testsystem Deplo

y

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 56/260

56

Testing Techniques

• Generally, the goal of testing is to finderrors

• Often it is called defect testing 

• A good test uncovers problems in a

program

• A test case includes

 – a set of inputs

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 57/260

57

White-Box Testing

• White-box testing also is referred to asglass-box testing  

• It focuses on the internal logic such as theimplementation of a method

• Statement coverage guarantees that allstatements in a method are executed

• Condition coverage guarantees that allaths throu h a method are executed

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 58/260

58

Black-Box Testing

• Black-box testing maps a set of specificinputs to a set of expected outputs

• An equivalence category is a collection ofinput sets

• Two input sets belong to the sameequivalence category if there is reason tobelieve that if one works, it will work for theother

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 59/260

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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 60/260

Walkthrough

• A meeting in which several peoplecarefully review a design/ sections of codeto see if the design satisfies requirement

or the implementation represent thedesign.

• A design or an implementation may beevaluated during a walkthrough 

• The oal of a walkthrou h is to identif

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 61/260

61

Prototypes

• A prototype is a program created toexplore a particular concept

• Prototyping is more useful, time-effective,and cost-effective than merely acting onan assumption that later may backfire

• Usually a prototype is created tocommunicate to the client:

 – a particular task

Prototypes

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 62/260

Prototypes

• We have

 – Throw-away prototypes

 – Evolutionary prototypes

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 63/260

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 beincorporated into final systems

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 64/260

Evolutionary Prototypes

• Because it is designed more carefully, anevolutionary prototype can be incorporatedinto the final system

• Evolutionary prototypes provide a doublebenefit, but at a higher cost

Evolutionary Development

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 65/260

65

Evolutionary DevelopmentModel

• Evolutionary development divides thedesign process into

 – architectural design - primary classes and

interaction – detailed design - specific classes, methods,

and algorithms

• Each refinement cycle focuses on oneaspect of the system

An Evolutionary Development

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 66/260

66

An Evolutionary DevelopmentModel

Establishrequirements

Architectural design

Establishrefinementscope

Unit andintegrationtest

Implementation

System test

Identifyclasses &objects

Identifyrelationships

Detaileddesign

Object-oriented programming is well suited to this approach 

Inheritance

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 67/260

-- to derive a new class from an existing class.

In stead of repeating similar data/method definitions in several classes, we can definewith 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 kwill need instance data tail and legs, we can define them in another class called “Anim

let Cat, Dog, and Raccoon classes inherit from it.

Animalint tail;int legs;

Cat Dog Raccoon

Here the Animal class is called “parent class ”, “super class ”, or “base class ” 

The classes Cat, Dog, and Raccoon are called “child class ” or “sub class ”. The child classes will inherit the methods and data defined for the parentclass.

However, child classes do not inherit private variablesand methods. They can inherit public variables and methods.Making instance data (variables) public violates

Encapsulation. There is another visibility modifier called“ protected” . Protected variables and methods canbe 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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 68/260

public -- inherited, can be accessed from anywhere (we use + for UML class diagramsprivate – not inherited, can be accessed only within its class (we use – for UML class diprotected – 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.

V hi lIf we want the class Car to inherit the class Vehicle, we use the following

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 69/260

public class Car extends Vehicle

{

 // class contents

}

Vehicle

Car

syntax (using the reserved word “extends”): 

-Constructors are not inherited: A child’s constructor is responsible for calling its parent’s 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 t

public String toString(){

Super reference

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 70/260

p-- refer to the parent class

Example:

 // Parent classpublic class Book{protected int pages;

public Book(int numPages){

pages = numPages;}

public String toString()

{ return (“The number of pages: “ + pages); }

}

 // Child classpublic class Dictionary extends Book{private int definitions;

public Dictionary(int numPages, int num

{ super (numPages); // calls Parent’ co

 definitions = numDefn;

}

public String toString(){

return (“The number of definitions: “

+ definitions + “ \ n” + super.toString( ) );

// calls Parent’s toString method 

}

Java supports single inheritance

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 71/260

Java supports single inheritancei.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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 72/260

-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 object’s class and a hash val

-equals(Object arg) – returns true if two object references refer to the same object.

Abstract classes

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 73/260

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 tfrom 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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 74/260

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 ossible if ob 1 does not contain a Com uter ob ect.

Polymorphism

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 75/260

o y o p s

A polymorphic referenceis a reference variable that can refer to different types of objects at different points in ti

 Polymorphic references are resolved at run-time, not during compilation.

Animal

Mammal

Dog

move()

move()

move()

Example: Suppose that we have the following inheritance, the class Doginherits from the class Mammal, and the class Mammal inherits fromthe class Animal.

Animal[] animalList = new Animal[3];

animalList[0] = new Animal();

animalList[1] = new Mammal();animalList[2] = new Dog();

for (int i=0; i <= 2; i++){

animalList[i].move();

}

The left line refers to different definitionof the move method for each i.

animalList[0].move() refers to move() ofAnimal class.animalList[1].move() refers to move() ofMammal class.

This part is polymorphic.

Layout Managers

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 76/260

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 FlowLayoutThis program using FlowLayout organizes three buttonsin the following manner

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 77/260

import javax.swing.*; // to use Japplet, JButtonimport java.awt.*; // to import FlowLayout manager

 // and Container

public class AppletFlow extends JApplet{public void init(){

Container content = getContentPane();

 // to use FlowLayout to add componentscontent.setLayout(new FlowLayout());

 // create three buttonsJButton button1 = new JButton("Button1");JButton button2 = new JButton("Button2");JButton button3 = new JButton("Button3");

 // add three buttons to the content pane of JApplet objectcontent.add(button1);content.add(button2);content.add(button3);

setSize(270,70);}

}

in the following manner.

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

An Example of Applet using BorderLayout

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 78/260

import javax.swing.*; // to use Japplet, JButtonimport java.awt.*; // to import BorderLayout manager

public class AppletBorder extends JApplet{

public void init(){

Container content = getContentPane();

 // to use BorderLayout to add componentscontent.setLayout(new BorderLayout());

 // create five buttonsJButton 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 objectcontent.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 GridLayoutIt will fill the first row from left to right first, then fill the second

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 79/260

import javax.swing.*; // to use Japplet, JButtonimport java.awt.*; // to import GridLayout manager

public class AppletGrid extends JApplet{

public void init(){

Container content = getContentPane();

 // 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 objectcontent.add(button1);

content.add(button2);content.add(button3);content.add(button4);content.add(button5);

setSize(270,70);}

}

row, and so on. Here we have only five components to add, so thlast slot is empty and it is showing its background color – gray,the default color for the content pane.

An Example of Applet using BoxLayoutimport javax.swing.*; // to use Japplet, JButtonimport java.awt.*; // to import BoxLayout manager

 // create an rigid area between button 4 and button 5content add(Box createRigidArea(new Dimension(0 20)));

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 80/260

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 buttonsJButton 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 verticallycontent.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 sizecontent.add(Box.createVerticalGlue());content.add(button3);content.add(button4);

content.add(Box.createRigidArea(new Dimension(0,20)));content.add(button5);

setSize(70,270);}

}

If a user shrinks the height ofthe applet, the area betweenbutton2 and 3 also shrinkswhile the areas between button12 and between button 4 and 5 stasame.

JPanel (defined in javax.swing package)

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 81/260

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 centerseem to be organized using GridLayout.

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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 82/260

public class Nested extends JApplet{public void init(){Container content = getContentPane();

 // create six buttonsJButton 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 panel2panel2.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 everythingsetSize(200,200);

}}

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

Then, create another JPanel object to organize everythinusing BorderLayout.

At the center, panel2 contains panel1 that contains

button1 and button2.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 83/260

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.

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

public class ExamplePanel extends JPanel

We can separate the organization of components into another classand keep the applet class concise.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 84/260

public class ExamplePanel extends JPanel{public ExamplePanel(){ // create six buttonsJButton 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");

 // panel to contain two buttonsJPanel panel1 = new JPanel();panel1.setLayout(new GridLayout(2,1));

panel1.add(button1);panel1.add(button2);

 // panel to contain all componentsJPanel 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 contentpane

setLayout(new BorderLayout());add(panel2); // by default, it adds it at its center

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

import javax.swing.*;

import java.awt.*;

public class Applet2 extends JApplet{public void init(){

Container content = getContentPane();

 // An ExamplePanel objects contains all components

ExamplePanel panel = new ExamplePanel();

content.add(panel);

setSize(400,400);}

}

Note that there are many ways of separating them into two ormore classes as you may see in the examples of the textbook.

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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 85/260

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 componentsExamplePanel 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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 86/260

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 87/260

Aliases

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 88/260

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 student2the address of student1, and they become aliases. After this assignment, if we make ato instance data of one object, the change is also seen in the other object that is an alithat we made a change.

So if we do:

student2.setLastName(“Smith”); 

Then the object student1 will also have the last name “Smith”. 

student1

student2

address1

address2

before

After becomingaliases.

Passing objects as parameters

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 89/260

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

 Example:

public class ParameterPassing{public static void main (String[] args)

{ParameterTester tester = new ParameterTester();

int a1 = 111;Num a2 = new Num (222);Num a3 = new Num (333);

tester.changeValues (a1, a2, a3);}

}

public class ParameterTester{

public void changeValues (int f1, Num f2,

{ f1 = 999;f2.setValue(888);f3 = new Num (777);

}

}

public class Num

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 90/260

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 changeValff t 1 Th bj t 2 i d t th l “222” d h 2 d t

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 91/260

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 theThe 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 wo

f3 is given a different address from the one a3 has, thus any change made to f3 after taffect a3 in the main method.

Nested/Inner Classes

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 92/260

 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 o

containing it. A nested class can access all instance data and methods of the class co 

-- 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 

NestedClass 

InterfacesA Java interface is a collection of abstract methods and constants

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 93/260

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 b Example: The following is a definition of the interface Doable

public interface Doable{

public final int COUNT = 1;public void doThis(); // abstract methodpublic int doThat(String name); // abstract method

}After defining the interface Doable, we can make a class to implement the interface Do 

public class CanDo implements Doable{

public void doThis(){ // put some definition for this method}public int doThat(String name)

{

Doable.java

CanDo.java

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 94/260

Doable

+count:int=1

+doThis():void +doThat(String):int 

CanDo

Constants in an interface cannotbe declared with private or prote

Notes:Interface cannot be instantiated

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 95/260

-- Interface cannot be instantiated.-- A class that implements an interface must define a definition for each abstract methoOtherwise 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 nam public class Class1 implements Interface1, Interface2, Interface3{ // some content

}

Note that these interfaces cannot have a same constant name with different types ora same method name with a same signature with different return types.

The Comparable interface

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 96/260

The Comparable interface is defined in the java.lang package and it contains only onmethod, compareTo , which takes an object as a parameter and returns an integer. An

that implements the Comparable interface needs to define compareTo method andtheir 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(It depends on the type of the object that reference points to at the moment of invocati

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 97/260

A polymorphic reference

is a reference variable that can refer to different types of objects at different pointsin time.

Polymorphic references are resolved at run-time, not during compilation.

Example:

public interface Speaker{public void speak();

}

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

guest = new Dog(); // valid

( p yp j p -The child interface inherits all abstract methods of the parent.-Class hierarchies and interface hierarchies are distinct (they do not overlap.)

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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 98/260

guest = new Dog();guest.talk(); causes a compiler error.

We can do:

guest = new Person();((Person) guest).talk();

Speaker

+speak():void 

DogPerson

+talk():void

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 99/260

GUI(Graphical User

Interfaces)

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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 100/260

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 clasin packages such as javax swing and java awt

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 101/260

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)

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 102/260

GUI Class Hierarchy (Swing)

Dimension

Font

FontMetrics

Component 

Graphics

Object Color

Container

Panel Applet

Frame

Dialog

Window

 JComponent 

JApplet

JFrame

JDialog

Swing Components

in the javax.swing package

Lightweight

Heavyweight

Classes in the java.awtpackage

1

 LayoutManager  

*

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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 103/260

are used to contain other components.

JFrame: the container that holds other Swing user-interface components in Java Graphical applicIt 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 andJApplet is defined in javax.swing package. You need to create a class that extendsJApplet to create a Swing based Java applet. Such class will not contain a main methoInstead it contains applet purpose methods such as init(), start(), stop(), and destroy().applet will be displayed with a html file or appletviewer.

JDialog/JOptionPane: a popup window or message box generally used as a temporary window treceive information from a user or provide notification that an event has occurred.

A dialog box is a temporary graphical window that pops up.

JComponent .

JCh kB M It

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 104/260

JButton

JMenuItem

JCheckBoxMenuItem

 AbstractButton

 JComponent 

JMenu

JRadioButtonMenuItem

JToggleButton JCheckBox

JRadioButton

JComboBox

JInternalFrame JLayeredPane

JList JMenuBar JOptionPane

JPopupMenu

JProgressBar

JPane

JFileChooser

JScrollBar JScrollPane

JSeparator

JSplitPane

JSlider

JTabbedPane

JTable

JTableHeader

JTextField JTextComponent 

JEditorPane

JTextArea

JToolBar

JToolTip

JTree

JRootPane

JPanel

JPasswordField

JColorChooser

JLabel

AWT package

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 105/260

AWT packageAWTEvent

Font

FontMetrics

Component

Graphics

Object Color

Canvas

Button

TextComponent

Label

List

CheckBoxGroup

CheckBox

Choice

Container Panel Applet

Frame

Dialog FileDialog

Window

TextField

TextArea

MenuComponent MenuItem

MenuBar

Menu

Scrollbar

 LayoutManager 

An Example of JFrame:

Compiling and executing the Java program on the leftwill pop the following window It contains a button in it

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 106/260

import javax.swing.*; // to use JFrame and JButtonimport java.awt.Container;

public class Frame1

{public static void main(String[] args){ // create a JFrame objectJFrame 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 terminatedframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 // create a buttonJButton button1 = new JButton("Button1");

 // add the button to the content pane of the JFrame objectContainer content = frame.getContentPane();content.add(button1);

frame.setSize(200, 100); // width is 200 pixels, height is 100 pixelsframe.setVisible(true); // make this JFrame object visible

}}

will pop the following window. It contains a button in it.

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 doframe.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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 107/260

pp y p y g p

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 ina 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

start

leave the page

stop

destroy

init

return to the page

after init

exit

reload enters web page

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:

j A l t2 j

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 108/260

public class Applet2 extends JApplet{public void init(){

 // create a buttonJButton button1 = new JButton("Button1");

 // add the button to the content pane of this appletgetContentPane().add(button1);

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

}

}

 javac Applet2.java

2. Create an html file, say “Applet2.html”, with the following conte

 _________________________________________ <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 orNetscape.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)

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 109/260

-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 webbrowser.

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 localfiles.)

- Applets are not allowed to run any programs on the browser’s computer. 

- Applets are not allowed to establish connections between the user’s 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 w 

//********************************************************************

// EvenOdd.java

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 110/260

// j

// 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 whicthe dialog is displayed. Herethe dialog pops independently.

Color class (defined in java.awt package)

-An object of the Color class represents a color

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 111/260

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 suchdefined 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 //The following program will show all possible

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 112/260

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 orDialogInput

fontStyle : Font.PLAIN(0), Font.BOLD(1), Font.ITALIC(2) and

Font.BOLD + Font.ITALIC (3)

fontSize : can be any positive integerOne example: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);

 //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.getLocalGraphicsEnvironment();String [ ] fontNames =e.getAvailableFontFamilyNames();

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

}}

JButton class (defined in javax.swing package)

-An object of the JButton class is a button that a user can push.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 113/260

j p

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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 114/260

j p g

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 hadwith 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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 115/260

j p p g

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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 116/260

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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 117/260

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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 118/260

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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 119/260

Note that when we have multiple JCheckBox objects, they can be checked independently whether othercheck 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 adde

Network and World Wide Web, bytecode

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 120/260

A network is two or more computers that are connected

so that data and resources can be shared.

Point to Point connection

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 121/260

-Each computer in a network could be directly connected to

every other computer in the network

-Adding a computer requires a new communication line foreach computer already in the network

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

Single Communication Line

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 122/260

-Adding a new computer to the network is relatively easy

-Network traffic must take turns using the line, which introduces d -Often information is broken down in parts, called packets ,

which are sent to the receiving machine and then reassembled

LAN(Local Area Networks)

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 123/260

-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 obuilding

LAN 

WAN(Wide Area Networks)

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 124/260

-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 oftenconnects groups in different countries

LAN 

LAN 

The Internet

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 125/260

-The Internet is a WAN which spans the entire planet

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

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

The World Wide Web

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 126/260

The World Wide Web allows many different types of information to be access

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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 127/260

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 machi

Java is considered to be architecture-neutral  

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 128/260

Java sourcecode 

Machine

code 

Javabytecode 

Javainterpreter 

Bytecodecompiler 

Java

compiler 

Local Computer

Across the Internet usiHTML

Remote Computer

Web Browser

Java Interpreter

 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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 129/260

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 implementsKeyListener 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:

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 130/260

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 Desription

VK_HOME Home keyVK_END End keyVK_DOWN Down arrow keyVK_UP Up arrow keyVK_LEFT Left arrow keyVK_RIGHT 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:

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 131/260

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 component’s top level ancestor become the focused window.

 //This method needs to be defined to draw in this panelpublic void paintComponent(Graphics page){super.paintComponent(page);

page.setColor(currentColor);

import javax.swing.JApplet;

public class KeyDemo extends JApplet

KeyDemo.java file

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 132/260

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 blackcurrentChar = 'A'; //default character is 'A'

addKeyListener (new Listener1()); //this panel listens tokeys

setBackground(Color.white);

 //This method needs to be called for this panel to listento keys

 //When panel listens to other things, and go back tolisten

 //to keys, this method needs to be called again.requestFocus();

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 keyspublic boolean isFocusable(){

return true;}

 //Listener1 class received the key pressed by a userprivate 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 userrepaint(); // call paintComponent method indirectly

}} // end of Key Listener

} // end of Key Panel Class

KeyPanel.java file

public class KeyDemo extends JApplet{public void init(){KeyPanel keyPanel = new KeyPanel();

getContentPane().add(keyPanel);setSize (400, 400);

}}

Algorithms

An algorithm is a sequence of computational steps that transform some input into som

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 133/260

g q p p pIt 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 cor find an item that equals to X (the element that we are searching for).

public int linearSearch(int[] A, int x){ constant time to executefor (int i=0; i<A.length, i++) C1{if (A[i] = = x ) C2

return i; C3}

return ( –1); // 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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 134/260

 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 execu(T(n) grows proportionally to n. ) And when n gets very large, constant c2 has a very s 

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

Then we say that T(n) = O(g(n)). This means that a*g(n) is an upper bound of T(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:

n

a*g(n)

T(n)

c

When n gets larger (greatwe can find a positive consuch that T(n) <= a*g(n)

Ω-notation (Omega-notation)  – lower bound

Similarly, we can define a lower bound for each running time.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 135/260

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.A list needs to be sorted before a binary search (pre condition)

Binary Search Using iterative

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 136/260

-A list needs to be sorted before a binary search (pre-condition).

Example: Search for x = 11

-5 –2 7 9 11 12 20 31 x > 9, so x is in right half segment.

11 12 20 31 x < 12, so x is in left quarter segment

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

If x is found, it returns the indotherwise it returns –1.

public static int binIter(int[] nu{int n = num.length;if (x>num[n-1] || x<num[0])return -1; // x is not fo

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

while (i<j)

{k = (int) Math.floor((i+j)/(

 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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 137/260

Se ect o So t go t

It sorts a list of values by successively putting particular values (the smallest value amon 

Example:

3 9 6 1 2 Find the smallest (1), and exchange so that the smalle 

1 9 6 3 2 Find the second smallest (2), and exchange so that th

 

1 2 6 3 9 Find the third smallest (3), and exchange

1 2 3 6 9 Find the fourth smallest. The fourth smallest is already

1 2 3 6 9

  //----------------------------------------------------------------- // Sorts the specified array of integers using the selection

This line compares two valueHow many comparison are dalgorithm? Let n be the lengt

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 138/260

p y g g // sort algorithm. //-----------------------------------------------------------------

public static void selectionSort (int[] numbers){

int min, temp;

for (int index = 0; index < numbers.length-1; index++){

min = index;for (int scan = index+1; scan < numbers.length; scan++)

if (numbers[scan] < numbers[min])min = scan;

 // Swap the valuestemp = numbers[min];numbers[min] = numbers[index];numbers[index] = temp;

}}

algorithm? Let n be the lengt When index = 0,scan goes from 1 to n-1, thus

When index = 1,scan goes from 2 to n-1, thus

….. 

When index = n-2,scan foes from n-1 to n-1, 1 it The total number of iterations

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

 We look at the fastest growin 

Thus we say:

A Graphical User Interfaces (GUI) is created with at least three kinds of objects inorder to receive user input and process it.

-components (e g buttons textfields)

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 139/260

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 formalrelationship between the generator and listener.

-- Define what happens in response to each event of interest.

Event 

Generator Listener

This object may generate an event It waits for and responds to an even

When an event occurs, the generatorcalls theappropriate method of the listener,passing an object that describes theevent.

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

To receive user input from a button, we create a class that implemActionListener interface where the method actionPerformed isdefined. In the actionPerformed method we specify what kind ofactions to take in case a button is pushed.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 140/260

import javax.swing.*;

public class PushCounter extends JApplet{

private int pushes; //declared as instance variables so that it can be usedprivate JLabel label; // in more than one method.private JButton push;

 // it initializes and arranges components in the appletpublic void init(){

pushes = 0;

push = new JButton ("Push Me!"); //using an object of ButtonListener, the button listens to an eventpush.addActionListener (new ButtonListener());

label = new JLabel ("Pushes: " + pushes);

Container cp = getContentPane();cp.setLayout (new FlowLayout());cp.add (push);cp.add (label);setSize (300, 35);

}

 //ButtonListener class represents a listener for button push (action) eventsprivate class ButtonListener implements ActionListener{ //It updates the counter when the button is pushed.public void actionPerformed (ActionEvent event){

pushes++;label.setText("Pushes: " + pushes);

}}

}

p

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

A GUI Example using JLabel and JTextField:

 // Fahrenheit.java modified from Lewis/Loftus textbook

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

 // FahrenheitGUI.java modified from Lewis/Loftus textbook

import java.awt.*;import java.awt.event.*; //to use ActionListener and ActionEventimport javax.swing.*;

public class FahrenheitGUI extends JPanel{

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 141/260

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);

}}

{private JLabel inputLabel, outputLabel, resultLabel;private JTextField fahrenheit;

 // constructor arranges components using a layoutpublic 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 liste

 setLayout(new FlowLayout());

add (inputLabel);add (fahrenheit);add (outputLabel);add (resultLabel);

}

 // TempListener class represents an action listener for the temperature text fielprivate 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 user enter a temperature in Fahrenheit,and it will covert it to temp in Celsius.

A GUI Example using JCheckBox:

 // StyleOptions.java--modified from Lewis/Loftus textbook // Demonstrates the use of check boxes.

import javax.swing.*;

 // StyleGUI.java-- modified from Lewis/Loftus textbookimport javax.swing.*;import java.awt.*;import java.awt.event.*; //to use ItemListener and ItemEvent

public class StyleGUI extends JPanel{pri ate final int FONT SIZE 36

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 142/260

public class StyleOptions extends JApplet{

public void init()

{StyleGUI gui = new StyleGUI();getContentPane().add (gui);setSize(300,100);

}}

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 thesaying 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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 143/260

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);

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 144/260

p ( );

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 }f th t f th th d f th t l th t it il

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 145/260

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.

Thi b d t th ith M E t bj t

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 146/260

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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 147/260

y p p ( y ) pp

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 itsGraphics object:

 // DotsPanel1.java // Represents the primary panel for the Dots program on which the

 // 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 propertiessuper.paintComponent(page);

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 148/260

 // 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 mouseaddMouseListener (new DotsListener());

} // end of DotsPanel1 constructor

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

We construct paintComponent method, and use itsGraphics object parameter to draw shapes. We can userepaint() method to call paintComponents method indirectly,and when it is called, it erases any previously drawn shapesand re-draw what is defined in the method. Thus we need tore-draw all dots in the arraylist in this method.

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 shouldbe drawn, and it has an important visual effect on the design of GUI.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 149/260

• 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  Description Empty Border  Puts buffering space around the edge of a component, but has no visual effect.  Line Border  A simple line surrounding the component Etched Border  Creates the effect of an etched groove around a component Bevel Border  Creates the effect of a component raised above the surface or sunken below it. Titled Border  Includes a text title on or around the border.  Matte Border  Allows the size of each edge to be specified. Uses either a solid color or an image Compound Border  A combination of two borders 

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

public class BorderDemo{

 //Creates a border with a lowered beveled edgeJPanel p4 = new JPanel();p4.setBorder(BorderFactory.createLoweredBevelBorder());p4.add(new JLabel("Lowered Bevel Border"));panel add(p4);

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 150/260

{public static void main(String[] args)

{

JFrame frame = new JFrame("Border Demo");

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" lookJPanel p2 = new JPanel();p2.setBorder(BorderFactory.createEtchedBorder());

p2.add(new JLabel("Etched Border"));panel.add(p2);

 //Creates a border with a raised beveled edgeJPanel p3 = new JPanel();p3.setBorder(BorderFactory.createRaisedBevelBorder());p3.add(new JLabel("Raised Bevel Border"));panel.add(p3);

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 moreborders.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 frameframe.getContentPane().add(panel);

frame.setSize(300, 300);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setLocationRelativeTo(null);frame.setVisible(true);}}

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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 151/260

(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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 152/260

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

y=28

(x,y) = (30,28)

Cartesian coordinate system

(0,0)x

y

(x,y)

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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 153/260

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 dimenwidth 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 deby x, y width, and height. The arc starts at startAngle and extends for a distance defined by arcAngle (positive – counter cloc

 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 content’s foreground color to the specified color. 

Color getColor() – returns this graphics content’s foreground color. 

Drawing a rectangle:

 page.drawRect (50, 20, 100, 40);

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 154/260

50 

20 

100 

40 

Drawing an oval:

 page.drawOval (175, 20, 50, 80);

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 155/260

175 

20 

50 

80 

bounding

rectangle 

Drawing a line:

 page.drawLine (10, 20, 150, 45);

d Li (150 45 10 20)or

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 156/260

 page.drawLine (150, 45, 10, 20);

10 

20 

150 

45 

Drawing an arc:

 page.drawArc (175, 20, 50, 80, 30, 90);

Arc is drawn

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 157/260

175 

20 

50 

80 

bounding

rectangle 

30

Start angle90

Arc angle

 //******************************************************************** // Einstein.java // Demonstrates a basic applet. //********************************************************************

import javax.swing.JApplet;import java awt Graphics;

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 158/260

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); // squarepage.drawRect (60, 80, 225, 30); // rectanglepage.drawOval (75, 65, 20, 20); // circlepage.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 JAppletimport java.awt.*; //to use Graphics and Color classes

public class Snowman extends JApplet{

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 159/260

 //----------------------------------------------------------------- // 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); // headpage.fillOval (MID-35, TOP+35, 70, 50); // upper torsopage.fillOval (MID-50, TOP+80, 100, 60); // lower torso

page.setColor (Color.black);page.fillOval (MID-10, TOP+10, 5, 5); // left eyepage.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 armpage.drawLine (MID+25, TOP+60, MID+55, TOP+60); // right arm

page.drawLine (MID-20, TOP+5, MID+20, TOP+5); // brim of hatpage.fillRect (MID-15, TOP-20, 30, 25); // top of hat

}}

Reading/Writing Text Files

Reading Text Files: 

Instead of reading from the standard input,

import java.io.*;

public class ReadingFromFile{

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 160/260

we can read from text files using the classesFileReader and BufferedReader. 

{public static void main (String[] args){

String line, file = “input.txt"; 

try{

FileReader fr = new FileReader (file);

BufferedReader inFile = new BufferedR//Scanner inFile = new Scanner(fr); inste// line = inFile.nextLine(); see page 577

line = inFile.readLine();while (line != null)

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

}

inFile.close();

}

The parameter for the FileReader constructoris the name of a file to be read.

The constructor of FileReader can throwsFileNotFoundException if the file specified in

the parameter is not located.

It is a good practice to close the file after finishingreading it.

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 beexpanded to be more robust.

finally{

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 161/260

import java.io.*;

public class ReadingFromFile{public static void main (String[] args){String line, file = "input.txt";

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();

try{if (inFile != null)inFile.close();

}catch (IOException ex){

System.out.println(ex);}}

}}

Writing Text Files: 

We can write into text files using the classesFileWriter, BufferedWriter, and PrintWriter.

import java.io.*;

public class WriteFile

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 162/260

The FileWriter class represents a text output file.

The parameter of the FileWriter constructor is the nameof a file to be written.

The PrintWriter class provides print and println methodssimilar to the standard I/O PrintStream class.

The Buffered Writer class gives the output stream bufferingcapabilities, which makes the processing more efficient.

{public static void main (String[] args) thro{

String fileName = "test.txt";

FileWriter fw = new FileWriter (fileNamBufferedWriter bw = new BufferedWritePrintWriter outFile = new PrintWriter (b

//PrintWriter outFile = new PrintWriter(file 

for (int i=1; i <= 10; i++){

outFile.print (“The value is “ + i ); 

outFile.println ();}

outFile.close();}

}

It is a good practice to close files after writing.

In this example, the file “test.txt” will be created and have all output written in it.

Command-Line Arguments

--The signature of a main method indicates that it takes an array of String objects as a

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 163/260

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

Now we want to store an object, not just texts.We can store (write) an object information in a file, orbt i ( d) bj t f fil

import java.io.*;

public class WriteObject{

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 164/260

obtain (read) an object from a file.

Persistence – the concept that an object can exist separatefrom the executing program that creates it.

Writing Objects: 

This can be done using two classes FileOutputStream andObjectOutputStream.

The FileOutputStream takes the name of a file to write objectsinto as its parameter.

The ObjectOutputStream provides the method “writeObject” which takes an object as its parameter.

The classes whose objects are to be serialized have toimplements Serializable. The interface Serializable is definedin java.io package. The interface Serializable does not contain

any method

{public static void main (String[] args)

{FileOutputStream file = null;ObjectOutputStream outStream = null;try{file = new FileOutputStream ("computer.

outStream = new ObjectOutputStream ( 

Computer comp = new Computer();comp.setBrandName(“IBM”); 

 // Serialize this above object to a file

outStream.writeObject(comp);}

catch (NotSerializableException exception){

System.out.println("NotSerializableExc}

import java.io.*;public class Computer implements Serializable{

….. 

Reading Objects: 

The classes FileInputStream and ObjectInputStream areused to deserialize objects.

import java.io.*;

public class ReadObject{public static void main (String[]

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 165/260

The method “readObject” reads one object at time,

and return an object as a reference of the class Object.

If the object is an object of, say “Computer” class,

it needs to be cast before any method in the Computerclass is used.

p ( g[]args)

{String fileName ="computer.dat";

FileInputStream file = null;ObjectInputStream inStream

= null;

try{

file = new FileInputStream(fileName);

inStream = newObjectInputStream (file);

 // Deserialize the objectsObject obj1 =

inStream.readObject();

if (obj1 instanceof

Com uter

finally{

try{

if (inStream != null)

inStream.close();}

catch (IOException exc){

System.out.println(exc);}

The Transient modifier

If we want to exclude a data (an attribute) of some class so that it is not part of the in

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 166/260

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

By default, all the non-static variables of a serialized object are written to the objectHowever, not all non-static variables are serializable. If a class contains such non-se

 java.io.NotSerializableException will occur. We can declare such non-serializable vaNotSerializableException will not be thrown.

JList• A Jlist is a component that basically performs the same function as a combo box, but enablesthe user to choose a single value or multiple values.• To use a JList, you will need the following package

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 167/260

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 indexvoid 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 cellsampleList.setSelectionForeground(Color.pink);

• Set the background color of the selected cellsampleList.setSelectionBackground(Color.black);

•Only allows one item to be sleected each timeSampleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

 //This program demonstates event handling with a JListobject

import java.awt.*;import javax.swing.*;import javax.swing.event.*;i t j til *

 //set the foreground & background color of the selected cellcountryList.setSelectionForeground(Color.pink);countryList.setSelectionBackground(Color.black);

 //set to only allow one item to be selected each timecountryList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 168/260

import java.util.*;import javax.swing.border.*; //to set up theborder

public class EventHandleJListDemo extends JApplet{

private JList countryList;private JLabel currentCountry;

 //Step 1: arranges the componentspublic void init()

{  //create a String vectorVector<String> originalList = new Vector<String>();originalList.add("United States");originalList.add("China");originalList.add("India");

 //Create a JList object from above vectorcountryList = new JList(originalList);

countryList.setBorder(BorderFactory.createEtchedBorder());

 //the country's list is in red color with a whitebackground

countryList.setForeground(Color.red);countryList.setBackground(Color.white);

ELECTION);

currentCountry = new JLabel("At begining, no country is

selected", JLabel.CENTER);

 //Step 3: Register the countryList with a CountryListListenercountryList.addListSelectionListener (newCountryListListener());

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 implementsthe interfaceprivate class CountryListListener implementsListSelectionListener{

 //implement the abstact method insideListSelectionListener

public void valueChanged(ListSelectionEvent event){ //Display which country is selected

currentCountry.setText((String)countryList.getSelectedValue());

}

} //end of CountryListListener

Visual effect of above sample program

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 169/260

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 dd h i i l li d

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 170/260

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 optionat time.

Th t b i t t JC b B O i t t f h i fi t d

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 171/260

There are two basic ways to create a JComboBox. One is to create an array of choices first andcreate 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 userusing 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 wayto the one for JButton. A class that implements ActionListenerinterface needs to be created, and the actionPerformed method needsto be defined:

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 172/260

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 li Example:

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 173/260

3 9 6 1 2 9 should be inserted after 3 – no change

3 9 6 1 2 6 should be inserted between 3 and 9

3 6 9 1 2 1 should be inserted before 3

1 3 6 9 2 2 should be inserted between 1 and 3

1 2 3 6 9

The complexity of the insertion sort algorithm is order of n 2 

 

 //----------------------------------------------------------------- // Sorts the specified array of integers using the insertion

Comparisons are done in this line.A similar computation to the one forselection sort results into:

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 174/260

 // sort algorithm.

 //-----------------------------------------------------------------public static void insertionSort (int[] numbers){

for (int index = 1; index < numbers.length; index++){

int key = numbers[index];

int position = index;

 // shift larger values to the rightwhile (position > 0 && numbers[position-1] > key){

numbers[position] = numbers[position-1];

position--;}

numbers[position] = key;}

}

Best Case – when an input array isalready sorted - O(n)

Worst Case – when an input array is inthe reverse order - O(n 2 )

We consider the worst case for its upperbound,So the insertion sort algorithm is O(n 2 )

The Comparable interface

The Comparable interface is defined in the java.lang package and it contains only onmethod compareTo which takes an object as a parameter and returns an integer An

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 175/260

method, compareTo , which takes an object as a parameter and returns an integer. Anthat 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 order

public int compareTo (Object other)

{

int result;

Recursion

We suppose that you have seen iterative methods in the prerequisite courses. Methodsor do-while loops are considered to be iterative . Often we can compute the same resultIn some cases, using recursion enables you to give a natural, straight forward, simple sdifficult to solve

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 176/260

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. Thwhere it does not call itself.

Recursion should have:- recursive case(s)

base case s non recursive art sto in condition

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

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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 177/260

g p ( ) p g(here the variable is “result”) 

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

for (int i=2; i<=n; i++)

result = result + i; //in this line, “result” on the right hand side is the old value//and the “result on the left hand side if the new value cont

return result;}

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

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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 178/260

Iterative case: sum(k) = sum(k-1) + k for k >= 2

(This means that, assuming that we have already computed the sum up to k-1, we can c The second line is recursive since you see the same function in both sides of the equati Based on the above observation, we have the following recursive method to compute th

Recursive method

 // assume that n >= 1public static int sum(int n)

{int result;if (n == 1) // base case

result = 1;else //recursive case for n >= 2

result = sum(n-1) + n;

return result;}

main

sum

sum

sum

sum

sum(4)is invoked

sum(3)is invoked

sum(2)is invoked

sum(1)is invoked

sum(1)=1 is returned

sum(2)= sum(1) + 2=2+1is re

sum(3)= sum(2) + 3=3+3is returne

sum(4)= sum(3) + 4=4+6is returned

public static void main(String[] args){int result = sum(4);

}

This method can be called from a main method as:

Observe that the sum using a recursive method can be computed in two passes.

going down to the base case then going up!

n=1

n=2

n=3

n=4

We can also observe from the mathematical recursive function that:

Sum(4) = sum(3) + 4

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 179/260

= ((sum(2) + 3 ) + 4

= (((sum(1) + 2) + 3) + 4)= ((( 1 + 2) + 3) + 4) <- reached the base case= (( 3 + 3) + 4)= (6 + 4)= 10

Iterative methodRecursive method

Now you can see these two methods side by side. They compute the exactly same rethe other is recursive.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 180/260

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

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

return result;}

 // assume that i >= 1public static int sum(int i){

int result;if (i == 1) // base case

result = 1;

else //recursive case for i >= 2result = sum(i-1) + i;

return result;}

How to construct a recursive method:

1. Identify your sub-problem. i.e., the same problem as the original problem, but on a sub 

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 thIf 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 our base case s

Indirect Recursion

Example:For the methods m1, m2, and m3.m1 invokes m2 which invokes m2 which invokes m1

m1

invokesinvoke

s

m2 m3

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 181/260

m1 invokes m2, which invokes m2, which invokes m1.

--It is difficult to trace and debug.

invokesm2 m3

Sorting using RecursionMerge Sort 

Merge Sort uses Divide and Conquer approach. It divides elements evenly and invokeelements.

3 62 9

2 3 6 9

6 3 92

6 39 2

6 3 9 2 Dividing process

Merging process

public static void mergeSort(int[] num, int start, int end){ //base case is when start == end, does nothingif (start < end) //recursive case{

The method “mergeSort” splits an array i

subarrays and invokes itself on them.(“start” is the starting index and “end” is t

 

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 182/260

{

int mid = (int) Math.floor((double) (start+end)/(2.0));

mergeSort(num,start,mid);mergeSort(num,mid+1,end);merge(num, start, mid, end);

}

}

The method “merge” merges two subarra

array without disturbing their order.

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

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 3 4 7 10 12

1 2 3 4 5 6 7 9 10 12 13 14

public static void merge(int[] num, int start, int mid, int end){

int n1 = mid-start+1; //get the length of the first half subarrayint n2 = end-mid; //get the length of the second half subarrayint[] left = new int[n1];

 // copy the rest of the subarray thatif ( i == n1){while (k <= end)

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 183/260

t[] e t e t[ ];int[] right = new int[n2];

 //i is used for the array "left", j for "right", k for "num"int i, j, k;

 // copy the elements in the array "num" to the arrays // "left" and "right"for (i=0; i<n1; i++)

left[i] = num[start+i];

for (j=0; j<n2; j++)right[j] = num[mid+1+j];

i=0; j=0;k=start;while (i < n1 && j < n2) //merge left and right into "num"{

if (left[i] < right[j])

{

num[k] = right[j];k++;

 j++;}

}else if (j == n2)

{while (k <= end){

num[k] = left[i];k++;i++;

}}

}

Binary Search using Recursion:

public static int binSearch(int[] num, int x){i t l th

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 184/260

int n = num.length;

if (n == 0 || x > num[n-1] || x < num[0])return -1; // x is not foundelsereturn binRec(num,x,0,n-1);

}

public static int binRec(int[] num, int x, int i, int j){ //base casesif (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-arrai l th l t i th l t b i ll l t i th fi t b

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 185/260

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 greateequals to a pivot value. There are several ways to pick a pivot value, but one way is topick 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, andthe 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-arrayon). At the end, we will have a sorted array.

 //The quickSort method calls partition method to partition //the array, then call itself recursively on the two sub //arrays that were divided by the partition method.

public static void quickSort(int[] elements int from int to)

 //The partition method re-arrange the array so that // the pivot (first element of the array) are grouped //of the array, and all elements >= the pivot are gro//end of the array. The returned index j will be wher//divided when the partitioning process is over.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 186/260

public static void quickSort(int[] elements, int from, int to)

{ if ( from < to ){int p = partition(elements, from, to);quickSort(elements, from, p);quickSort(elements, p+1, to);

}} //end of quickSort method

//divided when the partitioning process is over.public static int partition(int[] elements, int from, int t

{int pivot = elements[from];int i = from -1;int j = to + 1;

while (i < j ) // until i and j cross each other{i++;

 //move i towards right until we find an elementwhile (elements[i] < pivot)

i++;

 j--; //move j towards left until we find an element swhile (elements[j] > pivot)

 j--;

//we swap the two elements

Example of partition:

Pivot is set to the first element, in this case 4.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 187/260

4 3 7 9 5 6 1 8 2i -> <- j

“i” keeps increasing until it finds an element that is greater than or equals to the pivot v

“j” keeps decreasing until it finds an element that is smaller than or equals to the pivot

4 3 7 9 5 6 1 8 2i j i finds 4 and j finds 2

Then we swap these two values:

2 3 7 9 5 6 1 8 4i 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 )

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 188/260

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

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 inin every partition process.In this case, its running time is computed in almost same way as that of the Merge SHowever, the constant/ coefficient of Quick Sort running time is much smaller than thafaster than Merge Sort in most cases.

One possible average case might be when an array is partitioned into a sub-array withwith 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)

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 189/260

(Note, this meaning is different from those associated with static modifier)

-A dynamic data structure grows and shrinks as required by the information it containsexample: linked lists

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 

Consider an object that contains a reference to another object of the same type:

class Node{

String name;Node pointer;

}

studentJohn Smith

40725

3.58

This can construct a linked list 

 A variable “students”

the address of the obcontaining informatio

 “John Smith” 

Deleting an entry from a linked list:

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 190/260

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();

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 191/260

y y y ()….. 

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 itNote 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: 

Some method implementation of Linked ListNote: You need to be careful in boundary cases such as operations at the beginning and the end of a list.

 //This Linked List class shows how some of its commonly

 // Returns the first element in the linked list.

public Object getFirst(){

if (first == null){N S hEl E i

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 192/260

 //used methods are implemented.

 // A linked list is a sequence of nodes with efficient // element insertion and removal. // This class contains a subset of the methods of the // standard java.util.LinkedList class.

import java.util.NoSuchElementException;

public class LinkedList{ //nested class to represent a nodeprivate class Node{

public Object data;public Node next;

}

 //only instance variable that points to the first node.

NoSuchElementException ex

= new NoSuchElementEthrow ex;

}else

return first.data;}

 // Removes the first element in the linked lipublic Object removeFirst(){

if (first == null){NoSuchElementException ex

= new NoSuchElementthrow ex;

}else{

 // Adds an element to the front of the linked list.public void addFirst(Object element){ //create a new nodeNode newNode = new Node();

 // Tests if there is an element after the iter

public boolean hasNext(){

if (position == null) //not traversed yet{

if (first != null) return true;

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 193/260

()newNode.data = element;

newNode.next = first; //change the first reference to the new node.first = newNode;

}

 // Returns an iterator for iterating through this list.public ListIterator listIterator(){

return new LinkedListIterator();}

 //nested class to define its iteratorprivate class LinkedListIterator implements ListIterator{

private Node position; //current positionprivate Node previous; //it is used for remove() method

// Constructs an iterator that oints to the front

( ) ;else return false;

}else{

if (position.next != null) return true;else return false;

}} // Moves the iterator past the next eleme// the traversed element's data.public Object next(){

if (!hasNext()) {NoSuchElementException ex =new NoSuchElementE

throw ex;}

else {

revious osition // Remember for

// Adds an element after the iterator position // and moves the iterator to point to // the inserted element.public void add(Object element){

 // Removes the last traversed element. This metho

// only be called after a call to the next() method.public void remove(){if (previous == position) //not after next() is call

{

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 194/260

if (position == null) //never traversed yet

{addFirst(element);position = first;

}else{ //making a new node to addNode newNode = new Node();newNode.data = element;newNode.next = position.next;

 //change the link to insert the new node

position.next = newNode; //move the position forward to the new nodeposition = newNode;

} //this means that we cannot call remove() //right after add()

previous position;

{IllegalStateException ex = new IllegalStateEthrow ex;

}else{if (position == first)

removeFirst():elseprevious.next = position.next; //removing

 //stepping back //this also means that remove() cannot be calposition = previous;

}} // Sets the last traversed element to a different valpublic void set(Object element){if (position == null) {

NoSuchElementExce tion ex new NoSuch

 // 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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 195/260

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 Ob ect element ;

LinkedListItera

tor

position:Node

ListIterator

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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 196/260

LinkedList

-first:Node

+LinkedList()

+getFirst(): Object+removeFirst(): Object+addFirst(Object):void+listIterator(): ListIterator

Node

+data:Object

+next:Node

-position:Node

-previous:Node

+LinkedListIterator()+hasNext():boolean+next():Object+add(Object):void

+remove():void+set(Object):void

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

Example:

Using the LinkedList and ListIterator classes we discussed in class,the following output show how a linked list behaves:

public class LinkedListTester{

 //This method prints out the contentpublic static void printList(LinkedLis{

ListIterator iterator = list1.listIterString result = "{ ";

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 197/260

{public static void main(String[] args){

LinkedList list1 = new LinkedList();ListIterator iterator = list1.listIterator();

iterator.add("A");

printList(list1);iterator.add("B");printList(list1);iterator.add("C");printList(list1);

iterator = list1.listIterator();iterator.next();iterator.add("D");printList(list1);iterator.next();iterator.add("E");

rintList list1

g { ;while (iterator.hasNext())

result += iterator.next() + " ";result += "}";System.out.println(result);

}}

Output:{ A }{ A B }{ A B C }{ A D B C }

{ A D B E C }{ D B E C }{ D E C }

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.)

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 198/260

Comparison between ArrayList and Linked List:

Efficiency of operations of ArrayList and LinkedList

---------------------------------------------------------------Operation ArrayList LinkedList---------------------------------------------------------------Access O(1) O(n)

Add/Remove O(n) O(1) -- assuming that the iterator is already in the right posit

an element

-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.  – 

Linked List Variations:Doubly Linked Lists 

- It may be convenient to implement a list with next and previous references. 

class Node{

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 199/260

{

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 fr class List1{

N d fi t l t li

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 200/260

Node first, last;

} firstlast

list

Garbage Collector

When we remove a node from a linked list, the memory used for that node should beso that it can be used to store other data. Such memory can be collected by the garb

The Java virtual machine contains a garbage collector that periodically reclaims obje

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 201/260

g g p y j You can also run a garbage collector using a code such as follows:

 //Runtime class is in java.lang packagepublic static void runGarbageCollector()

{

 // run garbage collector until no more memory freed up

 //getRunTime()turns the runtime object associated with the current Java applicaRuntime 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 oper

 

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 202/260

-The set of operations defines the interface to the ADT

Stacks

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 203/260

• A stack is a data structure in which access isonly 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 thebottom, you have to remove the ones on top.

• This is called LIFO - Last-in/First-out

 java.util.Stack

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 204/260

• Provides the stack class• Constructor

• isEmpty or empty

• peek - get the top item withoutremoving it

• pop - remove the top item

• push - push a new item onto thestack

• size - the number of items in astack

Our StackPush T Push I Push N

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 205/260

Push T

T T

I

Push I

T

I

N

Push N

Pop N

T

I

Pop I

T

Pop T

Evaluating ArithmeticExpressions

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 206/260

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 ArithmeticExpressions using a Stack

Let’s use 2 stacks

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 207/260

p g

( ( (1 + 2) / 3) * (6 - 4) )

Let s use 2 stacks 

One storing numbers the other the

operations 

1 +

2

Read 1, + , 2

Then we hit aRightparenthesis soevaluate stack

3

Evaluating ArithmeticExpressions using a Stack

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 208/260

p g

( ( (1 + 2) / 3) * (6 - 4) )

33

Read 3, / 

Then we hit aRightparenthesis soevaluate stack

1

Evaluating ArithmeticExpressions using a Stack

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 209/260

( ( (1 + 2) / 3) * (6 - 4) )

Read *, 6, -, 4

Then we hit aRightparenthesis soevaluate stack

1 *

6

4

-

1 *

2

Hit anotherRightparenthesisso evaluatestack

We get

2 * 1 = 2 

Implementation ofa Stack

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 210/260

• A stack can be implemented using anarray or a linked list

 – Using an array, elements are pushed andpopped from the back end of the array

 – Using a linked list, elements are added(pushed) to the head of the list and alsoremoved from the head of the list when

popped.

On Your Own

(1) What is the output (2) What are some

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 211/260

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()); 

Exceptions that could bethrown in our example ofevaluating arithmeticexpressions with the 2stacks?

(3) Could we use a

stack to match

parenthesis? How?

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 212/260

LIFO -Last-in/ First-OutData Structure

Queues

R b i

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 213/260

• A queue is a datastructure of ordereditems where items

are added to therear (in the orderthat they areentered and

removed from thefront.)

Remember inClass - we lined people upinto a queue and the first

person in line received theirproject back first! (FIFO)

Queue Example

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 214/260

• The first person in lineat a bank is served firstand so on. People areserved on in respect to

their position in line.• At the bakery, you pull anumber out of themachine that distributesnumbers in order on a

first-come, first servebasis. When yournumber in the queue iscalled – it is your turn!

FIFO – First-In/First-Out

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 215/260

• A queue is a FIFOdata structure

 – Adding an item is

called “enqueue”• (Entering the queue)

 – Removing an item iscalled “dequeue” 

• (Removing from thequeue)

First-In/First-Out

Comparing a Stack andQueue Pop – 

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 216/260

A A A A

Push A PushB PushC

B B B

C

p

Removes C

Front Back

Insert AA

getFront – Removes A

B

Insert CA

B

B C

Insert BA C

Enqueue/Dequeue

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 217/260

• remove – removesthe front item fromthe queue

(dequeue)• offer – adds a new

item to the rear ofthe queue

(enqueue)

Palindrome EvaluationUsing a Stack and Queue

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 218/260

• A palindrome is a word that readsidentical forwards and backwards

• Examples

 – Radar

 – Sees

 – Bib

• Whatever we read in and out ofour stack and queue should output

identical results from both thestack and queue!

Palindrome Examplewith a Stack and Queue

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 219/260

• Assume that we have push and inserted thecharacters onto our stack and queue

• while(!q.empty()){

if(q.remove() != s.pop() )

mismatches ++;}

if(mismatches == 0)

System.out.println(“Yeah palindrome!”); 

elseSystem.out.println(“That’s not a palindrome.”); 

QueueLinked List Implementation

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 220/260

• There are “manyNodes”

representing thenumber of nodes

• The head is the front of

the queue (where itemsare removed)

• The rear (tail) is the endof the queue where the

items are added)

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 221/260

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.It is called a LIFO (Last-In, First-Out) data structure.Stacks are often drawn vertically.

pop

push

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 222/260

Some operations in a stack:Object push(Object item) – adds an item to the top of the stack, and returns itObject pop( ) – removes an item from the top of the stack and returns itObject peek( ) – retrieves the top item without removing itboolean 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{

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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 223/260

{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());

[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 frIt is called a FIFO (First-In, First-Out) data structure.

Some operations on a queue:

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 224/260

-enqueue  – add an item to the rear of the queue-dequeue – remove an item from, the front of the queue

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 boundepeek() - Retrieves, but does not remove, the head of this queue, returning null if this que

It returns the peeked element.remove() - Retrieves and removes the head of this queue. It returns the removed elemen 

LinkedList class implements Queue interface,As well as:

enqueuedequeue

 //Queue example using Linked List

import java.util.LinkedList;

public class QueueTester2{

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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 225/260

public static void main(String[] args){

LinkedList list = new LinkedList();

list.offer("A");list.offer("B");

list.offer("C");list.offer("D");

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());

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

Applications of Stacks: Postfix Expression

• Infix notation

 – The operator is written between the operands

• Prefix or Polish notation

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 226/260

 – 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 orderrequired for computation

Example:

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 227/260

Table 17-1 Infix expressions and their equivalent postfix expressions

Algorithm to evaluate postfix expressions 1. Scan the expression from left to right2. When an operator is found, back up to get the required number of operands3. Perform the operation4. 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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 228/260

{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 p Pre-order Traversal:

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 229/260

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 != null)

leftNode.preorderPrint();Here the output will be “G D B A C F E K I H J M L “  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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 230/260

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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 231/260

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 vand any element in the left sub tree is smaller than (or equals to ) the value of the nodThus those elements need to be compared such as numbers or strings.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 232/260

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 insorted order.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 233/260

233

15

6

3 7

18

17

4

9

13

20

2

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

• 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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 234/260

234

15

6 18

Example: Search for k = 4

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 235/260

235

3 7 17

4

9

13

20

2

Insert key = 13

15

6 18

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 236/260

236

3 7 17

4

9

13

20

2 13

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 nodesmissing 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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 237/260

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 

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 238/260

•A heap content can be physically stored in an array (or arrayList) because of the firs 

20 75 43 84 90 57 71 93 91 96

0 1 2 3 4 5 6 7 8 9

For an element at the index i of the array,

20 75 43 84 90 57 71 93 91 96

0 1 2 3 4 5 6 7 8 9

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 239/260

The index of its left child is: 2*i + 1The 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=2

i=3

i=7 i=8 i=9

i=4

i=5 i=6

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

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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 240/260

p p p y q p p y

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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 241/260

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)

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 242/260

Compare the added element to its parent.If the parent is larger than the new element,

then swap themElse

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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 243/260

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)

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 244/260

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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 245/260

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 lastelement 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 lastelement 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 extractingthe 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 nodesin the one level above. Then we keep going up to the node in the above leveluntil we call fixHeap on the root.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 246/260

The fixHeap method:---------------------------------------------------------------Repeat the following until both childrenare 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.

ElseDONE!

3. If it is not done, go back to the step 1, with the node’s 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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 247/260

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 R t th f ll i til it hild d ll h th b tt f th h

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 248/260

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)

27

12

10

22 13 7 33

Example: Building a max-heap

27

12

10

80 31 7 33

swap

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 249/260

80 24 31

27

12

10

22 31 7 33

80 24 13

22 24 13

swap

swap

27

12

33

80 31 7 10

22 24 13

swap

Next page

80

12

33

27 31 7 10

swap

31

80

33

27 12 7 10

swap

Continuing from the previous page.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 250/260

22 24 13

12

80

33

27 31 7 10

22 24 13

swap

22 24 13swap

31

80

33

27 13 7 10

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 integerspublic HeapSorter(int[] anArray){

a = anArray;}

// Sorts the array managed by this heap sorter

 // Ensures the heap property for a subtree, provided its children already fulfill the heap propert// @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 fixedprivate void fixHeap(int rootIndex, int lastIndex){

int rootValue = a[rootIndex]; //Remove root

 // Promote children while they are larger than the rootint index = rootIndex;boolean more = true;while (more){

int childIndex getLeftChildIndex(index);

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 251/260

 // 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 nodefor (int i = (n - 1) / 2; i >= 0; i--)

fixHeap(i, n);while (n > 0){

swap(0, n);

n--;fixHeap(0, n);

}}

int childIndex = getLeftChildIndex(index);if (childIndex <= lastIndex){ // Use right child instead if it is largerint rightChildIndex = getRightChildIndex(index);if (rightChildIndex <= lastIndex && a[rightChildIndex] > a[childIndex]){

childIndex = rightChildIndex;}

if (a[childIndex] > rootValue){ // Promote childa[index] = a[childIndex];index = childIndex;

}else{ // Root value is larger than both childrenmore = false;

}

}else{ // No childrenmore = false;

}}

 // Store root value in vacant slota[index] = rootValue;

}

  // Swaps two entries of the array.

 // @param i the first position to swap // @param j the second position to swapprivate 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

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 252/260

 // @param index the index of a node in this heap // @return the index of the left child of the given nodeprivate 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 nodeprivate 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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 253/260

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 lastelement 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 lastelement 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 extractingthe 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 nodesin the one level above. Then we keep going up to the node in the above leveluntil we call fixHeap on the root.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 254/260

The fixHeap method:---------------------------------------------------------------Repeat the following until both childrenare 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.

ElseDONE!

3. If it is not done, go back to the step 1, with the node’s 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.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 255/260

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:

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 256/260

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)

27 

12 

10 

22  13  7  33 

Example: Building a max-heap

27 

12 

10 

80  31  7  33 

swap

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 257/260

80 24  31 

27 

12 

10 

22  31  7  33 

80 24  13 

22 24  13 

swap

swap

27 

12 

33 

80  31  7  10 

22 24  13 

swap

Next page

80 

12 

33 

27  31  7  10 

swap

31 

80 

33 

27  12  7  10 

swap

Continuing from the previous page.

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 258/260

22 24  13 

12 

80 

33 

27  31  7  10 

22 24  13 

swap

22 24  13 swap

31 

80 

33 

27  13  7  10 

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 integerspublic HeapSorter(int[] anArray){

a = anArray;}

 // Sorts the array managed by this heap sorter.

 // Ensures the heap property for a subtree, provided its children already fulfill the heap propert// @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 fixedprivate void fixHeap(int rootIndex, int lastIndex){

int rootValue = a[rootIndex]; //Remove root

 // Promote children while they are larger than the rootint index = rootIndex;boolean more = true;while (more){

int childIndex = getLeftChildIndex(index);if ( hildI d l tI d )

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 259/260

y g y ppublic void sort(){

int n = a.length - 1; //for each node that has at least one child nodefor (int i = (n - 1) / 2; i >= 0; i--)

fixHeap(i, n);while (n > 0){

swap(0, n);

n--;fixHeap(0, n);}

}

g ( );if (childIndex <= lastIndex){ // Use right child instead if it is largerint rightChildIndex = getRightChildIndex(index);if (rightChildIndex <= lastIndex && a[rightChildIndex] > a[childIndex]){

childIndex = rightChildIndex;}

if (a[childIndex] > rootValue){ // Promote childa[index] = a[childIndex];index = childIndex;

}else{ // Root value is larger than both childrenmore = false;

}

}else{ // No childrenmore = false;

}}

 // Store root value in vacant slota[index] = rootValue;

}

   // Swaps two entries of the array.

 // @param i the first position to swap // @param j the second position to swapprivate 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// @ t th i d f th l ft hild f th i d

8/4/2019 Cse 205 All Java Slides

http://slidepdf.com/reader/full/cse-205-all-java-slides 260/260

@p p // @return the index of the left child of the given nodeprivate 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 nodeprivate static int getRightChildIndex(int index){

return 2 * index + 2;}

}