Académique Documents
Professionnel Documents
Culture Documents
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
class body
method header
*/
Java Identifiers
An identifier can be made up of letters, digits, the underscore character ( _ ), and the dollar sign Identifiers cannot begin with a digit Java is case sensitive - Total, total, and TOTAL are different identifiers By convention, Java programmers use different case styles for different types of identifiers, such as title case for class names - Lincoln upper case for constants - MAXIMUM
6
Reserved Words
The Java reserved words:
abstract boolean break byte case catch char class const continue default do double else extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while
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
Methods
methodName(parameterType):return ty
Visibility Levels for attributes: Public + Private Protected # Ex. address: String #idNumber: int
Multiplicity 1 0..1 M..N * 0..* 1..* one and only one zero or one from M to N (natural numbers) from zero to any positive integers from zero to any positive integers from one to any positive integers
Example: One to many association For one bank, there are many customers. Bank
Customer
Aggregations (relationships)
Car
Engine
name: Engine
The class Engine is a part of the class Car. The class Car has an Engine. The class Engine is used to define some attributes in the class Car. Person
Generalization/Inheritance (relationships)
The class Teacher and Student inherit from the class Person. i.e., the class Teacher and Student will have all attributes and methods that the class Person has (and more attributes and methods can be added to Teacher and Student). Teache r Studen t
Association it can be used as a default relationship if the exact relationship is unknown. In our textbook, it is used when an object of one class is a local variable in a method of another clas In a UML class diagram, a solid straight line between two classes is used.
Aggregation An object of one class is a part of another class. In our textbook, it is used when an object of one class is an instance variable of another class. In a UML class diagram, a solid straight line together with a diamond shape is used.
Inheritance A class inherits instance variables and methods from another class. In a UML class diagram, a solid line with a triangle shape is used.
Class Diagram
Student
Student.java ______________________________________ public class Student { private String name; private String address; private int idNumber;
-name: String = ? -address: String = ? -idNumber: int = 0 +toString(): String +submitHW(): boolean
//Constructor public Student() { name = new String(?); address = new String(?); idNumber = 0; } Note: the parameters of each method might not public String be present and in that case, a programmer needs to toString() { fill them. //to be filled by a programer
Object Diagrams
An Object Diagram consists of one or more instantiated objects.
objectName: C
Example:
Class Diagram Object Diagram coin1 and coin2 are instances of the class Coin.
Co in -face:int
+flip():void +setFace(int):void
coin1:Coin
face=0
coin2:Coin
face= 1
Wrapper Classes
A wrapper class represents a particular primitive data type. (primitive data types int, double, char, boolean, and so on)
They are defined in the java.lang package. Instead of declaring an integer as primitive data as:
For instance, the method doubleValue() returns the value of this integer as double. The class Integer also has static methods such as parseInt(String str) that returns the int corresponding to the value stored in the parameter string. Since it is static, it can be called with the class name (without instantiating an obejct) as:
Also see other wrapper classes such as Double. (e.g., double num2 = Double.parseDouble(3.21
Inheritance
-- to
In stead of repeating similar data/method definitions in several classes, we can define with the common instance data/methods, and let other classes inherit these data/meth
For instance, if we are trying to define Cat class, Dog class, and Raccoon class and kn will need instance data tail and legs, we can define them in another class called Anima let Cat, Dog, and Raccoon classes inherit from it.
Here the Animal class is called parent class, super class, or base class Animal The classes Cat, Dog, and Raccoon are called child class or sub class. int tail; int parent The child classes will inherit the methods and data defined for thelegs; class. However, child classes do not inherit private variables Raccoon and methods. They can inherit public variables and Cat methods. Dog Making instance data (variables) public violates Encapsulation. There is another visibility modifier called protected. Protected variables and methods can be inherited by child classes, but not as accessible as public.
If you plan to have a class inherited by other classes, its data should be declared as
Visibility Modifiers
public -- inherited, can be accessed from anywhere (we use + for UML class diagrams) private not inherited, can be accessed only within its class (we use for UML class dia protected inherited, can be accessed by any class in the same package (we use # for UML class diagrams) none (if no modifier is used) can be accessed and inherited in the same package. Note: Constructors are not inherited.
If we want the class Car to inherit the class Vehicle, we use the following Vehicl syntax (using the reserved word extends): e public class Car extends Vehicle { // class contents
Car } -Constructors are not inherited: A childs constructor is responsible for calling its parents constructor. For this purpose, we use super reference.
public class Car extends Vehicle { public Car(String name) { super(name); // this line calls the constructor of the parent class // and this needs to be the first line in the constructor. } }
The super reference can be used to reference other variables and methods defined in th public String toString() {
Super reference
-- refer to the parent class Example: // Parent class public class Book { protected int pages; public Book(int numPages) { pages = numPages; } // Child class public class Dictionary extends Book { private int definitions;
public Dictionary(int numPages, int numD { super (numPages); // calls Parent con definitions = numDefn; }
public String toString() { public String toString() return (The number of pages: + pages); { } return (The number of definitions: } + definitions + \n + super.toString( ) ); // calls Parents toString method }
Java supports single inheritance i.e., a derived class can have only one parent class (direct parent, not ancestors)
Multiple inheritance can be simulated using interfaces.
Example:
public class Student implements Comparable, Iterator, .
Overriding Methods
A child class can override (redefine) the definition of an inherited method. (The new method must have the same signature AND the return type.) A method with the final modifier cannot be overridden. The final modifier makes variables constant. For instance, final int number = 1; The value of number cannot be modified.
-toString( ) returns a string that contains the name of the objects class and a hash valu -equals(Object arg) returns true if two object references refer to the same object.
Abstract classes
An abstract class cannot be instantiated and contains one or more abstract methods (no definition body). -- can contain methods that are not abstract. (unlike Interfaces) -- can contain data declarations other than constants. (unlike Interfaces) An abstract method is a method header without a method body. It cannot be final or static because there is no definition and it should be changed later.
-- It is possible to derive an abstract class from a non abstract parent class. -- If a child class of an abstract class does not give a definition for every abstract method t from its parent, the child class is also considered abstract.
Example: The following class contains an abstract method pay, thus it should be declare class. public abstract class StaffMember // class is declared with abstract { protected String name; public StaffMember( ) { // some content
Polymorphism
A polymorphic reference is a reference variable that can refer to different types of objects at different points in tim Polymorphic references are resolved at run-time, not during compilation.
Animal Example: Suppose that we have the following inheritance, the class Dog inherits from the class Mammal, and the class Mammal inherits from move() the class Animal. Animal[] animalList = new Animal[3]; Mammal animalList[0] = new Animal(); The left line refers to different definition of animalList[1] = new Mammal(); the move method for each i. move() animalList[2] = new Dog(); animalList[0].move() refers to move() of Animal class. for (int i=0; i <= 2; i++) animalList[1].move() refers to move() ofDog { Mammal class. animalList[i].move(); This part is polymorphic. } move()
Example5: using javax.swing.Timer class. A yellow circle will be bouncing inside of an applet. When it hits a wall, it bounces 45 degrees so that it wont disappear from the applet. //************************************************ // Rebound.java modified from Lewis/Loftus textbook. // Demonstrates an animation and the use of the Timer class. //************************************************ import javax.swing.*; public class Rebound extends JApplet { private ReboundPanel panel; public void init() { panel = new ReboundPanel(); getContentPane().add (panel); } // Starts the animation when the applet is started. public void start () { panel.getTimer().start(); } // Stops the animation when the applet is stopped. public void stop () { panel.getTimer().stop(); } }
// Represents the primary panel for the Rebound applet. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ReboundPanel extends JPanel { private final int DIAMETER = 35; private final int DELAY = 20; private Timer timer; private int x, y, moveX, moveY; //----------------------------------------------------------------// Sets up the applet, including the timer for the animation. //----------------------------------------------------------------public ReboundPanel () { timer = new Timer(DELAY, new ReboundListener()); timer.start(); x = 0; y = 40; moveX = moveY = 3; setBackground (Color.black); setPreferredSize (new Dimension(300, 100)); } // accessor method of timer to be used in the applet class. public Timer getTimer() { }
// Draws the circle in the current location. public void paintComponent (Graphics page) { super.paintComponent (page); page.setColor(Color.yellow); page.fillOval(x,y,DIAMETER, DIAMETER); } // Represents the action listener for the timer. private class ReboundListener implements ActionListener { // Updates the position of the image and possibly the direction // of movement whenever the timer fires an action event. public void actionPerformed (ActionEvent event) { x += moveX; y += moveY; //if the circle hits the applets boundary, //it changes its direction. if (x <= 0 || x >= getSize().getWidth()-DIAMETER) moveX = moveX * -1; if (y <= 0 || y >= getSize().getHeight()-DIAMETER) moveY = moveY * -1; repaint(); }
Exceptions
-If an exception is ignored by the program, the program will terminate and produce an a Example:
-------------------------------------------------------------------------------------public class DividingByZero { //----------------------------------------------------------------// Deliberately divides by zero to produce an exception. //----------------------------------------------------------------public static void main (String[] args) { int numerator = 10; int denominator = 0; System.out.println (numerator / denominator);
System.out.println ("This text will not be printed."); The call stack trace: indicating where the exception occurred. } This exception was produced by the line System.out.println (numerator / denominato } At this point, the program is terminated and the next line is never executed.
We can avoid the termination of a program caused by an exception by using: try statements.
Try statements
try {
// the line that throws the exception is included here } catch ( //put the exception object produced in try, e.g., IOException ) {
} finally { // the statements inside of finally are always executed whether there was an excep Throws clause clause is used to manage resources or to guarantee that particular parts o // finally } The appropriate exception is appended to the header of a method definition where the e
Example: clause may be omitted when the finally clause is used, and vice versa. More The catch public static void main (String[] args) throws IOException {
Example: ----------------------------------------------------------------------------------import java.util.Scanner; If the string code does not have enough charAt and substring can throw StringInde public class ProductCodes { public static void main (String[] args) { If the substring of code contains a non-d String code; Method parserInt can throw NumberForma char zone; int district, valid = 0, banned = 0;
Scanner input = new Scanner(System.in); How do "); System.out.print ("Enter product code (XXX to quit):we know which methods throw ex which exception a method throws? See code =input.next(); and description of each method. while (!code.equals ("XXX")) For instance, see the method parseInt o { It throws NumberFormatException. try { zone = code.charAt(9); district = Integer.parseInt(code.substring(3, 7)); valid++; if (zone == 'R' && district > 2000) banned++; }
Checked exceptions must be caught by a method (try & catch) or be listed in the throw Unchecked exceptions should not be caught and requires no throws clause. Only unchecked exception in Java are objects of type Runtim
I/O Streams
A stream is a sequence of bytes that flow from a source to a destination. The I/O streams can be categorized in three ways:
Three standard I/O streams: -standard input --- System.in -standard output --- System.out -standard error --- System.err
//Using the Scanner class, we have the following in a program: //----------------------------------------------------------------------------------import java.util.Scanner;
These programs keep reading keyboard input until the string QUIT is entered.
public class lab1 { public static void main (String[] args) { Scanner in = new //---------------------------------------------------------------------------------------Scanner(System.in); //Now we read from in.next(); String line = a keyboard without using the Scanner class: //---------------------------------------------------------------------------------------- converts the original while (line.equals("QUIT") == false) InputStreamReader import java.io.*; { character stream. System.out.println(line); public class lab2 line = in.next(); { } public static void main (String[] args) throws IOException } With BufferedReader, we can use readLin The method readLine() throws IOExcept }{ therefore we need InputStreamReader isr = new InputStreamReader(System.in); to use either throw cla This BufferedReader stdin = new BufferedReader(isr);method reads a line by a line every isr and stdin are variables. String line = stdin.readLine();
Designing Classes
33
Classes introduction A class is a blue print of an object. A class consists of some data (attributes) and methods.
Encapsulation The variables contained in an object should be modified only within the object. Visibility modifiers/Access Specifiers They are used to declare classes, methods, and variables to define their accessibility .
public it can be accessed from anywhere (including outside of the class) private it can only be accessed from inside the class.
34
Accessor methods An accessor method can be defined to access private variable in the class since private data cannot be accessed from outside of the class. Mutator methods A mutator method can be defined to modify private variable in the class. public class Example1 { private int number1; //Accessor method for the variable number1 public int getNumber1() { return number1; } //Mutator method for the variable number1 public void setNumber1(int numberFromOutside) { number1 = numberFromOutside; } }
35
The toString methods -It is a method that takes no parameter and returns a String. -A returned string usually contains information on instance variables of its class. -Each class has a default toString method that contains its class object name and hash number. -When an object is used with System.out.print or println method, its toString method will be called.
36
public class Example { public static void main(String[] args) { Customer customer1 = new Customer(); System.out.println(customer1.toString()); // line1 System.out.println(customer1); // line 2 } }
public class Customer { private int custId; private double balance; public Customer() { custId = 1; balance = 100.0; } public String toString() { String result = "CustomerId: " + custId + "\nBalance: " + balance; return result; }
Line1 and line2 produce the same output. When printing an object, its toString() method is automatically called.
37
Constructor methods A constructor is a special method that is used to create a new object.
Programmers do not have to define a constructor for a class. Each class has a default constructor. -It has to have the same name as the class -It does not have return type, not even void -It can be used to set the initial values of instance variables public class Customer { private int customerId; private double balance; public Customer( ) //Constructor { customerId = 0; balance = 0.0; } }
38
Method Overloading The process of using the same method for multiple methods. The signature -- the number, type, and order of the parameters The signature of a method must be unique. Example: We can have two definitions for the method calc:
public int calc(int num1, int num2) { int sum = num1 + num2; return sum; }
public int calc(int num1, int num2, int num3) { int sum = num1 + num2 + num3; return sum; }
39
Instance Variables vs. Local Variables Instance variables variables declared at a class level. They are used by all methods in that class. Local variables variables declared in a method. They are used only in that method.
40
The this reference The this reference refers to the instance variables of the object. This approach eliminates the need to come up with a different yet equivalent name. Example: The following two methods have the same result. public class Example2 { private int accountNum; public void setAccountNum1(int account) { accountNum = account; } public void setAccountNum2(int accountNum) { //this.accountNum is an instance variable this.accountNum = accountNum; //accountNum on right hand side is a local } }
41
Static modifiers -it associates a variable or method with the class rather than an object. (there are static variables and static methods) -it is invoked by the system without creating an object. Static Methods cannot reference non-static instance variables. - can reference static variables or local variables. Static Variables also called class variables All objects created from the class share access to the static variable. Changing the value of a static variable in one object changes it for all others.
42
coin1 and coin2 are instances of the class Coin. coin1:Coin face=0 count=2 Non static variable can have different coin2:Coin values face=1 count=2
43
We can create other classes besides the class that contains a main method. Customer.java
public class Customer { private int custId; private double balance; public Customer() // first constructor { custId = 0; balance = 0.0; }
public class Example1 { public static void main(String[] args) { Customer customer1; // declaration customer1 = new Customer(); // instantiation customer1.setCustId(12345); System.out.println(customer1.getCustId()); Customer customer2 = new Customer(); System.out.println(customer2.getCustId()); } }
44
Customer.java
public Customer() // first constructor { custId = 0; balance = 0.0; public class Example1 } { //second constructor public Customer(int id, double balance) public static void main(String[] args) { { custId = id; Customer customer1; // declaration this.balance = balance // this reference is used to distinguish // instance variable and local variable customer1 = new Customer(); // instantiation } public void setCustId(int id) // mutator method { customer1.setBalance(1000.0); custId = id; System.out.println(customer1.getCustId()); } public int getCustId() // accessor method Customer customer2 = new Customer(2, 500.0); { return custId; System.out.println(customer2.getBalance()); } public void setBalance(double balance2) // mutator method } { } balance = balance2; } // accessor method The Example1 class created an object of Customer. public double getBalance() { return balance; } public String toString() { String result = "CustomerId: " + custId + "\nBalance: " + balance; Example1 return result; Customer } Creates } // end of the class Customer
an object
45
Software Engineering
1. Cost Estimation
1. Time 2. Money 3. resources
47
Specifications for improving the software development process: SEI CMM (Software Engineering Institute Capability Maturity Model) ISO 9001:2000
Maintenance
49
50
Development
Maintenance
51
Write program
Modify program
Too many programmers follow a build-and-fix approach They write a program and modify it until it is functional, without regard to system design
52
Implement code
Test system
Deplo y
54
Deplo y
55
Testing Techniques
Generally, the goal of testing is to find errors Often it is called defect testing A good test uncovers problems in a program A test case includes
a set of inputs
56
White-Box Testing
White-box testing also is referred to as glass-box testing It focuses on the internal logic such as the implementation of a method Statement coverage guarantees that all statements in a method are executed Condition coverage guarantees that all paths through a method are executed
57
Black-Box Testing
Black-box testing maps a set of specific inputs to a set of expected outputs An equivalence category is a collection of input sets Two input sets belong to the same equivalence category if there is reason to believe that if one works, it will work for the other 58
Walkthrough
A meeting in which several people carefully review a design/ sections of code to see if the design satisfies requirement or the implementation represent the design. A design or an implementation may be evaluated during a walkthrough
Prototypes
A prototype is a program created to explore a particular concept
Prototyping is more useful, time-effective, and cost-effective than merely acting on an assumption that later may backfire
Usually a prototype is created to communicate to the client:
a particular task
61
Prototypes
We have
Throw-away prototypes Evolutionary prototypes
Throw-away Prototypes
A quick and dirty prototype to test an idea or a concept is called a throw-away prototype Throw-away prototypes should not be incorporated into final systems
Evolutionary Prototypes
Because it is designed more carefully, an evolutionary prototype can be incorporated into the final system Evolutionary prototypes provide a double benefit, but at a higher cost
Implementatio n
Identify relationship s
Detailed design
66
Inheritance
-- to
In stead of repeating similar data/method definitions in several classes, we can define with the common instance data/methods, and let other classes inherit these data/meth
For instance, if we are trying to define Cat class, Dog class, and Raccoon class and kn will need instance data tail and legs, we can define them in another class called Anima let Cat, Dog, and Raccoon classes inherit from it.
Here the Animal class is called parent class, super class, or base class Animal The classes Cat, Dog, and Raccoon are called child class or sub class. int tail; int parent The child classes will inherit the methods and data defined for thelegs; class. However, child classes do not inherit private variables Raccoon and methods. They can inherit public variables and Cat methods. Dog Making instance data (variables) public violates Encapsulation. There is another visibility modifier called protected. Protected variables and methods can be inherited by child classes, but not as accessible as public.
If you plan to have a class inherited by other classes, its data should be declared as
Visibility Modifiers
public -- inherited, can be accessed from anywhere (we use + for UML class diagrams) private not inherited, can be accessed only within its class (we use for UML class dia protected inherited, can be accessed by any class in the same package (we use # for UML class diagrams) none (if no modifier is used) can be accessed and inherited in the same package. Note: Constructors are not inherited.
If we want the class Car to inherit the class Vehicle, we use the following Vehicl syntax (using the reserved word extends): e public class Car extends Vehicle { // class contents
Car } -Constructors are not inherited: A childs constructor is responsible for calling its parents constructor. For this purpose, we use super reference.
public class Car extends Vehicle { public Car(String name) { super(name); // this line calls the constructor of the parent class // and this needs to be the first line in the constructor. } }
The super reference can be used to reference other variables and methods defined in th public String toString() {
Super reference
-- refer to the parent class Example: // Parent class public class Book { protected int pages; public Book(int numPages) { pages = numPages; } // Child class public class Dictionary extends Book { private int definitions;
public Dictionary(int numPages, int numD { super (numPages); // calls Parent con definitions = numDefn; }
public String toString() { public String toString() return (The number of pages: + pages); { } return (The number of definitions: } + definitions + \n + super.toString( ) ); // calls Parents toString method }
Java supports single inheritance i.e., a derived class can have only one parent class (direct parent, not ancestors)
Multiple inheritance can be simulated using interfaces.
Example:
public class Student implements Comparable, Iterator, .
Overriding Methods
A child class can override (redefine) the definition of an inherited method. (The new method must have the same signature AND the return type.) A method with the final modifier cannot be overridden. The final modifier makes variables constant. For instance, final int number = 1; The value of number cannot be modified.
-toString( ) returns a string that contains the name of the objects class and a hash valu -equals(Object arg) returns true if two object references refer to the same object.
Abstract classes
An abstract class cannot be instantiated and contains one or more abstract methods (no definition body). -- can contain methods that are not abstract. (unlike Interfaces) -- can contain data declarations other than constants. (unlike Interfaces) An abstract method is a method header without a method body. It cannot be final or static because there is no definition and it should be changed later.
-- It is possible to derive an abstract class from a non abstract parent class. -- If a child class of an abstract class does not give a definition for every abstract method t from its parent, the child class is also considered abstract.
Example: The following class contains an abstract method pay, thus it should be declare class. public abstract class StaffMember // class is declared with abstract { protected String name; public StaffMember( ) { // some content
Polymorphism
A polymorphic reference is a reference variable that can refer to different types of objects at different points in tim Polymorphic references are resolved at run-time, not during compilation.
Animal Example: Suppose that we have the following inheritance, the class Dog inherits from the class Mammal, and the class Mammal inherits from move() the class Animal. Animal[] animalList = new Animal[3]; Mammal animalList[0] = new Animal(); The left line refers to different definition of animalList[1] = new Mammal(); the move method for each i. move() animalList[2] = new Dog(); animalList[0].move() refers to move() of Animal class. for (int i=0; i <= 2; i++) animalList[1].move() refers to move() ofDog { Mammal class. animalList[i].move(); This part is polymorphic. } move()
Layout Managers
Once we start adding more than one component to a container, we need to consider how we organize/arrange them. For this purpose, we can use layout managers. A layout manager is an object that determines the manner in which components are arranged in a container. Here is a list of commonly used layout managers: (they are defined in java.awt package.) BorderLayout it organizes components into five areas (North, South, East, West, and Center). FlowLayout it organizes components from left to right, starting new rows as necessary. GridLayout it organizes components into a grid of rows and columns BoxLayout it organizes components into a single row or a single column. CardLayout it organizes components into one such that only one is visible at any time. GridBagLayout it organizes components into a grid of cells, allowing components to span more than one cell.
This program using FlowLayout organizes three buttons in the following manner.
If a user narrows the size of the applet, any component that did not fit in the first row will appear in the next row and so on.
setSize(270,70);
} }
It will fill the first row from left to right first, then fill the second row, and so on. Here we have only five components to add, so the last slot is empty and it is showing its background color gray, the default color for the content pane.
// to use GridLayout to add components // by specifying its number of rows (2) and columns (3) content.setLayout(new GridLayout(2,3));
// create five buttons JButton button1 = new JButton("Button1"); JButton button2 = new JButton("Button2"); JButton button3 = new JButton("Button3"); JButton button4 = new JButton("Button4"); JButton button5 = new JButton("Button5"); // add five buttons to the content pane of JApplet object content.add(button1); content.add(button2); content.add(button3); content.add(button4); content.add(button5); setSize(270,70); } }
// create an rigid area between button 4 and button 5 content.add(Box.createRigidArea(new Dimension(0,20))); content.add(button5); setSize(70,270); } }
If a user shrinks the height of the applet, the area between button2 and 3 also shrinks while the areas between button1 a 2 and between button 4 and 5 stay same.
JPanel (defined in javax.swing package) If we want to combine more than one layout manager, we can use JPanel. JPanel is a container that holds user-interface components. -- JPanel can be nested, i.e., A JPanel object can contain another JPanel object. -- JPanel cannot be displayed by itself. It must be contained in a container such as JFrame and JApplet. For instance, the following applet seems to be using BorderLayout, but button1 and button2 in the center seem to be organized using GridLayout.
import javax.swing.*; import java.awt.*; public class Nested extends JApplet { public void init() { Container content = getContentPane(); // create six buttons JButton button1 = new JButton("Button1"); JButton button2 = new JButton("Button2"); JButton button3 = new JButton("Button3"); JButton button4 = new JButton("Button4"); JButton button5 = new JButton("Button5"); JButton button6 = new JButton("Button6"); JPanel panel1 = new JPanel(); panel1.setLayout(new GridLayout(2,1)); panel1.add(button1); panel1.add(button2); JPanel panel2 = new JPanel(); panel2.setLayout(new BorderLayout()); // add five buttons to panel2 panel2.add(button3, BorderLayout.NORTH); panel2.add(button4, BorderLayout.SOUTH); panel2.add(button5, BorderLayout.WEST); panel2.add(button6, BorderLayout.EAST); panel2.add(panel1, BorderLayout.CENTER); content.add(panel2); // content pane contains panel2 that contains everything setSize(200,200);
At the center, panel2 contains panel1 that contains button1 and button2.
}
}
Note that the default layout manager of content pane is BorderLayout, and with add method, a component is added to its center. The default layout manager of JPanel is FlowLayout.
We can separate the organization of components into another class and keep the applet class concise. public class ExamplePanel extends JPanel Note that there are many ways of separating them into two or { more classes as you may see in the examples of the textbook. public ExamplePanel() { // create six buttons import javax.swing.*; JButton button1 = new JButton("Button1"); import java.awt.*; JButton button2 = new JButton("Button2"); JButton button3 = new JButton("Button3"); public class Applet2 extends JApplet JButton button4 = new JButton("Button4"); { JButton button5 = new JButton("Button5"); public void init() JButton button6 = new JButton("Button6"); { Container content = getContentPane(); // panel to contain two buttons JPanel panel1 = new JPanel(); // An ExamplePanel objects contains all components panel1.setLayout(new GridLayout(2,1)); ExamplePanel panel = new ExamplePanel(); panel1.add(button1); panel1.add(button2); content.add(panel); setSize(400,400); } } // panel to contain all components JPanel panel2 = new JPanel(); panel2.setLayout(new BorderLayout()); panel2.add(button3, BorderLayout.NORTH); panel2.add(button4, BorderLayout.SOUTH); panel2.add(button5, BorderLayout.WEST); panel2.add(button6, BorderLayout.EAST); panel2.add(panel1, BorderLayout.CENTER); // use the same layout (BorderLayout) as content pane setLayout(new BorderLayout()); add(panel2); // by default, it adds it at its center
ExamplePanel.java file in the previous page can be used with the following driver class to create an application instead of an applet.
import javax.swing.*; import java.awt.*; public class Application2 { public static void main(String[] args) { JFrame frame = new JFrame("Application2"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container content = frame.getContentPane();
The following shows how a complicated appearance of a GUI program can be made by combining several layouts.
Aliases
When two objects share a same address, we say that they are aliases of each other. Example: Student student1 = new Student(); Student student2 = new Student(); student1 = student2; // making them aliases of each other
When we make an assignment such as above for two objects, the address of student2 the address of student1, and they become aliases. After this assignment, if we make an to instance data of one object, the change is also seen in the other object that is an alia address1 that we made a change. So if we do: before student1 student2.setLastName(Smith); After becoming aliases. address2 Then the object student1 will also have the last name Smith. student2
When an object (not primitive data) is passed as a parameter for a method, say method1 its address is passed. Thus if we make any value changes to instance data of the object those changes will be reflected in the object in the method from where method1 was cal
Example:
public class ParameterTester public class ParameterPassing { { public void changeValues (int f1, Num f2, N public static void main (String[] args) { { f1 = 999; ParameterTester tester = new ParameterTester(); f2.setValue(888); f3 = new Num (777); int a1 = 111; Num a2 = new Num (222); } Num a3 = new Num (333); }
public class Num { private int num; public Num(int number) { num = number; } public void setValue(int number) { num = number; } }
Since a1 is a primitive data, any change that was made to f1 in the method changeValu affects a1. The object a2 was assigned to the value 222 and when a2 was passed to method, a2 and f2 became aliases, so the change made to f2 will be seen in a2 in the The object a3 was assigned to the value 333 and when a3 was passed to changeVal a3 and f3 became aliases. However when f3 was re-instantiated with the reserved wor f3 is given a different address from the one a3 has, thus any change made to f3 after th affect a3 in the main method.
Nested/Inner Classes
A class can be defined inside of another class and it is called a nested class (or an in
In general, a nested class is defined with private visibility so that it can be accessed on containing it. A nested class can access all instance data and methods of the class con
-- A nested class produces a separate bytecode file. -- If a nested class called Inside is declared in an outer class called Outside, two bytecode files will be produced: Outside.class Outside$Inside.class
public class Outside { private int num; private Inside obj; .. private class Inside { private double num2; . }
Enclosing Class
Nested Class
Interfaces
A Java interface is a collection of abstract methods and constants.
An abstract method is a method header without a method body. Abstract methods cannot be final or static (because there is no definition, needs to be Example: The following is a definition of the interface Doable
public interface Doable { Doable.java public final int COUNT = 1; public void doThis(); // abstract method public int doThat(String name); // abstract method } After defining the interface Doable, we can make a class to implement the interface Doa public class CanDo implements Doable { public void doThis() { // put some definition for this method } public int doThat(String name) {
CanDo.java
CanDo
Notes: -- Interface cannot be instantiated. -- A class that implements an interface must define a definition for each abstract method Otherwise the class should be declared as abstract. -- A class that implements an interface can implements other methods as well. -- A class can implement multiple interfaces using commas between the interface name
public class Class1 implements Interface1, Interface2, Interface3 { // some content } Note that these interfaces cannot have a same constant name with different types or a same method name with a same signature with different return types.
The Comparable interface is defined in the java.lang package and it contains only one method, compareTo, which takes an object as a parameter and returns an integer. Any that implements the Comparable interface needs to define compareTo method and their instantiated objects become something that can be compared.
// Person.java // Represents a Person. public class Person implements Comparable { private String firstName, lastName, phone; // Sets up this Person with the specified information. public Person (String first, String last, String telephone) { firstName = first; lastName = last; phone = telephone; } // Uses both last and first names to determine lexical ordering. public int compareTo (Object other) { int result; if (lastName.equals(((Person)other).lastName)) result = firstName.compareTo(((Person)other).firstName); else result = lastName.compareTo(((Person)other).lastName); return result; } }
Interface Hierarchies
-The child interface inherits all abstract methods of the parent. -Class hierarchies and interface hierarchies are distinct (they do not overlap.) A polymorphic reference is a reference variable that can refer to different types of objects at different points in time. Polymorphic references are resolved at run-time, not during compilation. Example: public interface Speaker { public void speak(); }
(It depends on the type of the object that reference points to at the moment of invocatio
And suppose that the class Person implements Speaker and the class Dog implements Speaker guest; guest = new Person(); // valid guest.speak(); // calls speak method of the class Person guest = new Dog(); // valid
+speak():void
Person
Dog
+talk():void
Taking a user input using a console (a user might enter an invalid input such as a number ou Range or a string containing non-digit characters):
Taking a user input using Applet (a user is forced to choose among 0 through 7):
Making a Java program to generate a GUI is accomplished by using pre-defined class in packages such as javax.swing and java.awt.
Swing is a comprehensive solution to developing graphical use interfaces. There are more than 250 classes.
Panel
Applet
JApplet
Container
Window
Frame Dialog
JFrame JDialog
JComponent
Lightweight
JFrame, JApplet, and JDialog are heavy weight container classes that can be displayed alone an are used to contain other components.
JFrame: the container that holds other Swing user-interface components in Java Graphical applica It can be used in a Java program with a main method (Applications).
JApplet: It is a subclass of the Applet class. Applet is defined in java.applet package and JApplet is defined in javax.swing package. You need to create a class that extends JApplet to create a Swing based Java applet. Such class will not contain a main method Instead it contains applet purpose methods such as init(), start(), stop(), and destroy(). T applet will be displayed with a html file or appletviewer.
JDialog/JOptionPane: a popup window or message box generally used as a temporary window to receive information from a user or provide notification that an event has occurred.
A dialog box is a temporary graphical window that pops up.
JComponent
JCheckBoxMenuItem JMenuItem JMenu JRadioButtonMenuItem JCheckBox JRadioButton
AbstractButton
JButton
JToggleButton
JComponent
JTextComponent
JLabel
JList
JComboBox JFileChooser
JMenuBar
JPanel
JOptionPane
JScrollBar
JScrollPane
JTabbedPane
AWT package
AWTEvent Font FontMetrics Object Color Graphics Component Container Button Label
TextComponent
Panel Window
TextField
TextArea
LayoutManager
CheckBoxGroup Canvas
MenuComponent
MenuItem MenuBar
Menu
Scrollbar
An Example of JFrame:
Compiling and executing the Java program on the left will pop the following window. It contains a button in it. import javax.swing.*; // to use JFrame and JButton import java.awt.Container; public class Frame1 { public static void main(String[] args) { // create a JFrame object JFrame frame = new JFrame("Testing Frame"); // when a user click the close button at the upper left corner, // the window will close and the program will be terminated frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create a button JButton button1 = new JButton("Button1"); // add the button to the content pane of the JFrame object Container content = frame.getContentPane(); content.add(button1); frame.setSize(200, 100); // width is 200 pixels, height is 100 pixels frame.setVisible(true); // make this JFrame object visible } } These two lines can be done in one line as: frame.getContentPane().add(button1); as it is seen in the textbook.
Applets
An applet is executed by Web browser so some methods are specifically designed with that concept in mind. public void init() Initializes the applet. Called just after the applet is loaded. public void start() Starts the applet. Called just after the applet is made active (every time the web page is visited).
public void stop() Stops the applet. Called just after the applet is made inactive (when the page containing the applet becomes inac public void destroy() Destroys the applet. Called when the browser is exited. Also, the default constructor can be created to be called by the browser when the Web page containing this applet is initially loaded
reload
init after init return to the page start exit leave the page stop
destroy
An Example of JApplet:
import javax.swing.*; // to use JApplet and JButton
How to execute an applet program: 1. This class can be compiled as usual: javac Applet2.java
public class Applet2 extends JApplet { public void init() { // create a button JButton button1 = new JButton("Button1"); // add the button to the content pane of this applet getContentPane().add(button1);
// set its width to 300 pixels and the height to 100 pixels setSize(300, 100);
} }
2. Create an html file, say Applet2.html, with the following conten _________________________________________ <HTML> <HEAD> <TITLE>Applet 2</TITLE> </HEAD> <BODY> <applet code="Applet2.class" width=300 height=100> </applet> </BODY> </HTML> ---------------------------------------------3. You can view this html file using a web browser such as IE or Netscape. You can also use appletviewer. In a console, type appletviewer Applet2.html -In the TextPad, choose Tool, then choose Run Java Applet or press Ctrl-3 (press control key and 3 at the same time). -In the jGrasp, choose Run, then choose Run as Applet.
An Example of JOptionPane: -- JOptionPane has several static methods that pop up a temporary wi
//******************************************************************** // EvenOdd.java // Demonstrates the use of the JOptionPane class. //******************************************************************** import javax.swing.JOptionPane; public class EvenOdd { //----------------------------------------------------------------// Determines if the value input by the user is even or odd. //----------------------------------------------------------------public static void main (String[] args) { String numStr, result; int num, again; do { numStr = JOptionPane.showInputDialog ("Enter an integer: "); num = Integer.parseInt(numStr); result = "That number is " + ((num%2 == 0) ? "even" : "odd"); JOptionPane.showMessageDialog (null, result); again = JOptionPane.showConfirmDialog (null, "Do Another?"); } while (again == JOptionPane.YES_OPTION); } }
The parent component in which the dialog is displayed. Here the dialog pops independently.
-An object of the Color class represents a color. -It can be defined by RGB (red, green, and blue) value. There are also pre-defined colors such a defined in the Color class. Each of RGB value varies between 0 and 255. ( 8bits)
Object Color.black Color.blue Color.cyan Color.orange Color.white Color.yellow RGB Value 0, 0, 0 0, 0, 255 0, 255, 255 255, 200, 0 255, 255, 255 255, 255, 0
There are foreground color and background color. Foreground color color used to draw shapes or strings. If comp is a component object, we can set foreground color as follows: comp.setForeground(Color.red); To set background color: comp.setBackground(Color.blue);
One 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);
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);
Then retrieve them later as: JCheckBox box = (JCheckBox) panel1.getComponent(0); // the component at 0 is the first one that was added
-This technique is not practical for more than a few close machin
-Network traffic must take turns using the line, which introduces de
-Often information is broken down in parts, called packets, which are sent to the receiving machine and then reassembled
LAN
LAN
LAN
The Internet
-The Internet is a WAN which spans the entire planet
-It started as a United States government project, sponsored by the Advanced Research Projects Agency (ARPA) - originally it was called the ARPANET
-Less than 600 computers were connected to the Internet in 1983 by the year 2000 there were over 10 million
The World Wide Web allows many different types of information to be accesse using a common interface A browser is a program which accesses and presents information
Web documents are often defined using the HyperText Markup Language (HT Information on the Web is found using a Uniform Resource Locator (URL): http://www.lycos.com http://www.villanova.edu/webinfo/domains.html ftp://java.sun.com/applets/animation.zip A URL indicates a protocol (http), a domain, and possibly specific documents
Java Translation
The Java compiler translates Java source code into
a special representation called bytecode Java bytecode is not the machine language for any traditional
Another software tool, called an interpreter, translates bytecod into machine language and executes it
Therefore the Java compiler is not tied to any particular machin Java is considered to be architecture-neutral
Java bytecode
Java compiler
Java interpreter
Bytecode compiler
Machine code
Local Computer
Remote Computer
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.
Examples:
char characterEntered = event.getKeyChar(); // event is a KeyEvent object int code = event.getKeyCode(); // even is a KeyEvent object Some key constants defined in the KeyEvent class:
Constants
VK_HOME VK_END VK_DOWN VK_UP VK_LEFT VK_RIGHT
Desription
Home key End key Down arrow key Up arrow key Left arrow key Right arrow key
Example: if (event.getKeyCode() == KeyEvent.VK_UP) // if the key a user chooses is the up arrow key { . }
To add a key listener class, we use addKeyListener method. Example: panel.addKeyListener(new Listener1()); Some steps to be done in the panel that listens to keys: 1. boolean isFocusable() This method returns whether this component (panel) can be focused. In the component (panel) that listens to keys, this method needs to be overridden to enable keyboard focus. 2. void requestFocus() This method requests that this component (panel) get the input focus, and that this components top level ancestor become the focused window.
KeyDemo.java file
import javax.swing.JApplet; public class KeyDemo extends JApplet { public void init() { KeyPanel keyPanel = new KeyPanel(); getContentPane().add(keyPanel); setSize (400, 400); } }
//This method needs to be defined to draw in this panel public void paintComponent(Graphics page) { super.paintComponent(page); page.setColor(currentColor); page.setFont(new Font("TimesRoman", Font.PLAIN, 24)); //draw the string at the location (200, 200) page.drawString(String.valueOf(currentChar), 200, 200); } /** Override this method to enable keyboard focus */ // This method should be defined in the panel to listen to keys public boolean isFocusable() { return true; } //Listener1 class received the key pressed by a user private class Listener1 implements KeyListener { public void keyReleased(KeyEvent e) {} public void keyTyped(KeyEvent e) {} public void keyPressed(KeyEvent e) { currentChar = e.getKeyChar(); //get a letter(key) pressed by a user repaint(); // call paintComponent method indirectly } } // end of Key Listener } // end of Key Panel Class
KeyPanel.java file
import java.awt.*; import javax.swing.*; import java.awt.event.*; // to use listener interfaces public class KeyPanel extends JPanel { private Color currentColor; private char currentChar; public KeyPanel() { currentColor = Color.black; //default color is black currentChar = 'A'; //default character is 'A'
Algorithms
An algorithm is a sequence of computational steps that transform some input into some It is a tool for solving a well-defined computational problem. Examples of such problems --- searching, sorting
-- looks sequentially at each element of a given collection of elements until we either co or find an item that equals to X (the element that we are searching for). public int linearSearch(int[] A, int x) { for (int i=0; i<A.length, i++) { if (A[i] = = x ) return i; } return (1);
C4
The (worst case) running time of the linear search can be expressed as a function of n T(n) = c1 * n + c2
Intuitively, we can see that when n, input size, gets larger, the time that takes to execut a*g(n) (T(n) grows proportionally to n. ) And when n gets very large, constant c2 has a very sm We say that the complexity of the linear search is O(n), but here is a formal definition of O (pronounced as big-Oh) notation. Definition of O-notation: If there exist positive constants a and c such that T(n) <= a*g(n) for all n larger than c c
T(n)
When n gets larger (greate we can bound of T(n). Then we say that T(n) = O(g(n)). This means that a*g(n) is an upper find a positive con such that T(n) <= a*g(n) For the linear search, g(n) = n. Note that there is more than one such function g(n). For instance it is correct to say that:
-notation (Omega-notation) lower bound Similarly, we can define a lower bound for each running time. If there exist positive constants b and c such that
-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:
-It is used to look up a word in a dictionary or a name in a phone book. -It uses Divide and Conquer approach. Binary Search Using iterative m -A list needs to be sorted before a binary search (pre-condition). found, it returns the inde If x is otherwise it returns 1. Example: Search for x = 11 -5 2 7 9 11 12 20 31 11 12 20 31
public static int binIter(int[] num { x > 9, so x is in right half segment.n = num.length; int if (x>num[n-1] || x<num[0]) x < 12, so x is in left quarter segment -1; return // x is not fo
11 12
x == 11. We found x.
The complexity of Binary Search Algorithm is order of log n where n is the number of elements to search from
Sorting
It sorts a list of values by successively putting particular values (the smallest value among Example: 3 9 6 1 2
6 3
3 6
This line compares two values //----------------------------------------------------------------How many comparison are do // Sorts the specified array of integers using the selection algorithm? Let n be the length // sort algorithm. //----------------------------------------------------------------When index = 0, public static void selectionSort (int[] numbers) scan goes from 1 to n-1, thus { int min, temp; When index = 1, scan goes from 2 to n-1, thus
for (int index = 0; index < numbers.length-1; index++) { .. min = index; for (int scan = index+1; scan < numbers.length; scan++) index = n-2, When if (numbers[scan] < numbers[min]) scan foes from n-1 to n-1, 1 it min = scan; // Swap the values temp = numbers[min]; numbers[min] = numbers[index]; numbers[index] = temp; } } The total number of iterations
A Graphical User Interfaces (GUI) is created with at least three kinds of objects in order to receive user input and process it. -components
(e.g., buttons, textfields) -listeners waits for events to occur -events (e.g., a button is pushed, a mouse is moved) An Event is an object that represents some activity to which we may want to respond.
Event
When an event occurs, the generator calls the appropriate method of the listener, passing an object that describes the event.
Generator
This object may generate an event
Listener
To receive user input from a button, we create a class that implem ActionListener interface where the method actionPerformed is defined. In the actionPerformed method we specify what kind of actions to take in case a button is pushed.
When a user pushes the Push Me button, it will increments the number shown next to the label Pushes.
//ButtonListener class represents a listener for button push (action) events private class ButtonListener implements ActionListener { //It updates the counter when the button is pushed. public void actionPerformed (ActionEvent event) { pushes++; label.setText("Pushes: " + pushes); } } }
// FahrenheitGUI.java
import java.awt.*; import java.awt.event.*; //to use ActionListener and ActionEvent import javax.swing.*; public class FahrenheitGUI extends JPanel { private JLabel inputLabel, outputLabel, resultLabel; private JTextField fahrenheit; // constructor arranges components using a layout public FahrenheitGUI() { inputLabel = new JLabel ("Enter Fahrenheit temperature:"); outputLabel = new JLabel ("Temperature in Celsius: "); resultLabel = new JLabel ("---");
fahrenheit = new JTextField (5); fahrenheit.addActionListener (new TempListener()); //make the textfield listen setLayout(new FlowLayout()); add (inputLabel); add (fahrenheit); add (outputLabel); add (resultLabel); }
// TempListener class represents an action listener for the temperature text field private class TempListener implements ActionListener { // Performs the conversion when the enter key is pressed in the text field. public void actionPerformed (ActionEvent event) { String text = fahrenheit.getText(); int fahrenheitTemp = Integer.parseInt (text); int celciusTemp = (fahrenheitTemp-32) * 5/9; resultLabel.setText (Integer.toString (celciusTemp)); } }
// StyleGUI.java-- modified from Lewis/Loftus textbook import javax.swing.*; import java.awt.*; import java.awt.event.*; //to use ItemListener and ItemEvent public class StyleGUI extends JPanel { private final int FONT_SIZE = 36; private JLabel saying; private JCheckBox bold, italic; // constructor arranges a label and some check boxes that control the style of the label's font. public StyleGUI() { saying = new JLabel ("Say it with style!"); saying.setFont (new Font ("Helvetica", Font.PLAIN, FONT_SIZE)); bold = new JCheckBox ("Bold"); italic = new JCheckBox ("Italic"); StyleListener listener = new StyleListener(); bold.addItemListener (listener); italic.addItemListener (listener); add (saying); add (bold); add (italic); } // StyleListener class represents the listener for both check boxes. private class StyleListener implements ItemListener { // Updates the style of the label font style. public void itemStateChanged (ItemEvent event) { int style = Font.PLAIN; if (bold.isSelected()) style = Font.BOLD; if (italic.isSelected()) style += Font.ITALIC; saying.setFont(new Font ("Helvetica", style, FONT_SIZE)); } } }
A user can check Bold or Italic check box to make the saying with each style.
Methods in MouseListener interface: void mousePressed(MouseEvent event) a mouse button is pressed down. void mouseReleased(MouseEvent event) a mouse button is released.
void mouseClicked(MouseEvent event) a mouse button is pressed down and released without moving the mouse in between.
void mouseEntered(MouseEvent event) a mouse pointer is moved onto (over) a component. void mouseExited(MouseEvent event) a mouse pointer is moved out of a component.
Methods in MouseMotionListener interface: void mouseMoved(MouseEvent event) a mouse is moved. void mouseDragged(MouseEvent event) a mouse is moved while the mouse button is pressed down.
To add a listener object that implements MouseListener interface a component, addMouseListener() method is used as: component.addMouseListener(listener); To add a listener object that implements MouseMotionListener interface to a component, addMouseMotionListener() method is used as: component.addMouseMotionListener(listener);
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.
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.
Approach we can define paint or paintComponent method and use its Graphics object parameter to draw shapes.
//******************************************* // Dots1.java // Demonstrates mouse events and drawing on a panel. //******************************************* import javax.swing.JApplet; public class Dots1 extends JApplet { public void init() { getContentPane().add (new DotsPanel1()); setSize(300,200); } }
Approach - defining paintComponent method to obtain its Graphics object: // DotsPanel1.java // Represents the primary panel for the Dots program on which the // dots are drawn. import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; public class DotsPanel1 extends JPanel { private final int RADIUS = 6; private ArrayList pointList; private int count; public DotsPanel1() { setBackground (Color.black); count = 0; pointList = new ArrayList(); // this panel class listens to a mouse addMouseListener (new DotsListener()); } // end of DotsPanel1 constructor We construct paintComponent method, and use its Graphics object parameter to draw shapes. We can use repaint() method to call paintComponents method indirectly, and when it is called, it erases any previously drawn shapes and re-draw what is defined in the method. Thus we need to re-draw all dots in the arraylist in this method.
// Draws all of the dots stored in the list. public void paintComponent (Graphics page) { // use paintComponent method of its parent class // to have all graphics properties super.paintComponent(page); page.setColor (Color.green); for (int i=0; i<pointList.size() ; i++) { Point drawPoint = (Point) pointList.get(i); page.fillOval (drawPoint.x - RADIUS, drawPoint.y - RADIUS, RADIUS * 2, RADIUS * 2); } page.drawString ("Count: " + count, 5, 15); } //end of paintComponent method // DotsListener class represents the listener for mouse events. private class DotsListener implements MouseListener { // Adds the current point to the list of points and redraws // whenever the mouse button is pressed. public void mousePressed (MouseEvent event) { pointList.add (event.getPoint()); count++; repaint(); // this calls paintComponent method indirectly }
// Provide empty definitions for unused event methods. public void mouseClicked (MouseEvent event) {} public void mouseReleased (MouseEvent event) {} public void mouseEntered (MouseEvent event) {} public void mouseExited (MouseEvent event) {} } // end of DotsListener class } // end of DotsPanel1 class
Borders Java provides the ability to put a border around any swing components. A border is not a component itself, but rather defines how the edge of a component should be drawn, and it has an important visual effect on the design of GUI. In order to use a border, you should put the following code on top of your program.
import javax.swing.border.*;
Description Puts buffering space around the edge of a component, but has no visual effect. A simple line surrounding the component Creates the effect of an etched groove around a component Creates the effect of a component raised above the surface or sunken below it.
Titled Border
Matte Border Compound Border
import java.awt.*; import javax.swing.*; import javax.swing.border.*; public class BorderDemo { public static void main(String[] args) { JFrame frame = new JFrame("Border Demo");
//Creates a border with a lowered beveled edge JPanel p4 = new JPanel(); p4.setBorder(BorderFactory.createLoweredBevelBorder()) ; p4.add(new JLabel("Lowered Bevel Border")); panel.add(p4); //Creates a new title border JPanel p5 = new JPanel(); p5.setBorder(BorderFactory.createTitledBorder("Title")); p5.add(new JLabel("Titled Border")); panel.add(p5); //A compound border is a combination of two or more borders. JPanel p6 = new JPanel(); Border b1 = BorderFactory.createLineBorder(Color.blue, 2); Border b2 = BorderFactory.createRaisedBevelBorder(); p6.setBorder(BorderFactory.createCompoundBorder(b1, b2)); p6.add(new JLabel("Compound Border")); panel.add(p6); //add panel onto the frame frame.getContentPane().add(panel); frame.setSize(300, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
panel.setBorder(BorderFactory.createEmptyBorder(8,8,8,8)); //Creates a line border with the specified color and width JPanel p1 = new JPanel(); p1.setBorder(BorderFactory.createLineBorder(Color.red, 3)); p1.add(new JLabel("Line Border")); panel.add(p1); //Creates a border with an "etched" look JPanel p2 = new JPanel(); p2.setBorder(BorderFactory.createEtchedBorder()); p2.add(new JLabel("Etched Border")); panel.add(p2); //Creates a border with a raised beveled edge JPanel p3 = new JPanel(); p3.setBorder(BorderFactory.createRaisedBevelBorder()); p3.add(new JLabel("Raised Bevel Border")); panel.add(p3);
Coordinate Systems
Graphic system (0,0) x = 30 (x,y) y=28 (x,y) = (30,28) (0,0) x y Cartesian coordinate system
Some methods of the Graphics class: void drawRect(int x, int y, int width, int height) paints a rectangle with upper left cornet (x,y) and dimensions width and height. void fillRect(int x, int y, int width, int height) same as drawRect, but with inside filled with a foreground color.
void drawOval(int x, int y, int width, int height) paints an oval bounded by the rectangle with an upper left cornet of (x,y) and dimens width and height. void fillOval(int x, int y, int width, int height) same as drawOval, but with inside filled with a foreground color.
void drawLine(int x1, int y1, int x2, int y2) paints a line from point (x1,y1) and point (x2,y2).
void drawString(String str, int x, int y) paints the character string at point (x,y), extending to the right.
void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) paints an arc along the oval bounded by the rectangle def by x, y width, and height. The arc starts at startAngle and extends for a distance defined by arcAngle (positive counter clock void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) same as drawArc, but with inside filled with a foreground color. void setColor(Color color) sets this graphics contents foreground color to the specified color. Color getColor() returns this graphics contents foreground color.
50
20 40
100
175
20
80
bounding rectangle
Y 50
Drawing a line:
page.drawLine (10, 20, 150, 45); or page.drawLine (150, 45, 10, 20);
10
150
20
45
175
20
90 30
80
bounding rectangle
Y 50
//******************************************************************** // Einstein.java // Demonstrates a basic applet. //******************************************************************** import javax.swing.JApplet; import java.awt.Graphics; public class Einstein extends JApplet { //----------------------------------------------------------------// Draws a quotation by Albert Einstein among some shapes. //----------------------------------------------------------------public void paint (Graphics page) { page.drawRect (50, 50, 40, 40); // square page.drawRect (60, 80, 225, 30); // rectangle page.drawOval (75, 65, 20, 20); // circle page.drawLine (35, 60, 100, 120); // line page.drawString ("Out of clutter, find simplicity.", 110, 70); page.drawString ("-- Albert Einstein", 130, 100);
}
}
// Snowman.java // Demonstrates basic drawing methods and the use of color. import javax.swing.*; //to use JApplet import java.awt.*; //to use Graphics and Color classes public class Snowman extends JApplet { //----------------------------------------------------------------// Draws a snowman. //----------------------------------------------------------------public void paint (Graphics page) { final int MID = 150; final int TOP = 50; setBackground (Color.cyan); page.setColor (Color.blue); page.fillRect (0, 175, 300, 50); // ground page.setColor (Color.yellow); page.fillOval (-40, -40, 80, 80); // sun page.setColor (Color.white); page.fillOval (MID-20, TOP, 40, 40); // head page.fillOval (MID-35, TOP+35, 70, 50); // upper torso page.fillOval (MID-50, TOP+80, 100, 60); // lower torso page.setColor (Color.black); page.fillOval (MID-10, TOP+10, 5, 5); // left eye page.fillOval (MID+5, TOP+10, 5, 5); // right eye
import java.io.*;
public class ReadingFromFile Instead of reading from the standard input,{ we can read from text files using the classes public static void main (String[] args) FileReader and BufferedReader. { The parameter for the FileReader constructor String line, file = input.txt"; is the name of a file to be read. try The constructor of FileReader can throws { FileNotFoundException if the file specified in FileReader fr = new FileReader (file); the parameter is not located. BufferedReader inFile = new BufferedRe //Scanner inFile = new Scanner(fr); instea It is a good practice to close the file after finishing = inFile.nextLine(); see page 577 // line reading it. line = inFile.readLine(); while (line != null) { System.out.println(line); line = inFile.readLine(); } inFile.close(); }
Note that the previous code can be done a little more formally as follows. All other examples are rather simplified in this notes, but it can be finally expanded to be more robust. { try import java.io.*; { if (inFile != null) public class ReadingFromFile inFile.close(); { } public static void main (String[] args) catch (IOException ex) { { String line, file = "input.txt"; System.out.println(ex); FileReader fr = null; } BufferedReader inFile = null; } try } { } fr = new FileReader (file); inFile = new BufferedReader (fr);
import java.io.*;
We can write into text files using the classes FileWriter, BufferedWriter, and PrintWriter. public class WriteFile { The FileWriter class represents a text output file. public static void main (String[] args) throw The parameter of the FileWriter constructor is the name { of a file to be written. String fileName = "test.txt";
The PrintWriter class provides print and println methods fw = new FileWriter (fileName FileWriter similar to the standard I/O PrintStream class. BufferedWriter bw = new BufferedWriter PrintWriter outFile = new PrintWriter (bw The Buffered Writer class gives the output stream bufferingoutFile = new PrintWriter(fileN //PrintWriter It is a good practice to close files after writing. efficient. capabilities, which makes the processing more for (int i=1; i <= 10; i++) In this example, the file test.txt will be created{ and have all output written in it. outFile.print (The value is + i ); outFile.println (); } outFile.close(); } }
Command-Line Arguments
--The signature of a main method indicates that it takes an array of String objects as a For instance, if we have the following command to execute a program:
Object Serialization
import java.io.*;
Now we want to store an object, not just texts. public class WriteObject We can store (write) an object information in a file, or { obtain (read) an object from a file. public static void main (String[] args) { Persistence the concept that an object can exist separate FileOutputStream file = null; from the executing program that creates it. ObjectOutputStream outStream = null; try Writing Objects: { This can be done using two classes FileOutputStream and file = new FileOutputStream ("computer.d ObjectOutputStream. outStream = new ObjectOutputStream (f The FileOutputStream takes the name of a file to write objects Computer comp = new Computer(); into as its parameter. comp.setBrandName(IBM);
The ObjectOutputStream provides the method writeObject // Serialize this above object to a file which takes an object as its parameter. outStream.writeObject(comp); import java.io.*; } public class Computer implements Serializable catch to The{ classes whose objects are to be serialized have(NotSerializableException exception) { implements Serializable. The interface Serializable is defined .. in java.io package. The interface Serializable doesSystem.out.println("NotSerializableExce not contain } any method.
import java.io.*;
Reading Objects:
public class ReadObject The classes FileInputStream and ObjectInputStream are { used to deserialize objects. public static void main (String[] args) The method readObject reads one object at{time, and return an object as a reference of the class Object. String fileName = "computer.dat"; If the object is an object of, say Computer class, FileInputStream file = null; it needs to be cast before any method in the Computer ObjectInputStream inStream class is used. = null; try { finally file = new FileInputStream { (fileName); try inStream = new { ObjectInputStream (file); if (inStream != null)
inStream.close(); } catch (IOException exc) { System.out.println(exc); } // Deserialize the objects Object obj1 = inStream.readObject();
If we want to exclude a data (an attribute) of some class so that it is not part of the inf we can declare such data with the transient modifier:
The above variable (data), when the object in which it is contained is serialized, will n
By default, all the non-static variables of a serialized object are written to the object s However, not all non-static variables are serializable. If a class contains such non-ser java.io.NotSerializableException will occur. We can declare such non-serializable var NotSerializableException will not be thrown.
JList A Jlist is a component that basically performs the same function as a combo box, but enables the user to choose a single value or multiple values. To use a JList, you will need the following package
import javax.swing.*; Import javax.swing.event.*;
//This program demonstates event handling with a JList object import java.awt.*; import javax.swing.*; import javax.swing.event.*; import java.util.*; import javax.swing.border.*; border
//set the foreground & background color of the selected cell countryList.setSelectionForeground(Color.pink); countryList.setSelectionBackground(Color.black); //set to only allow one item to be selected each time countryList.setSelectionMode(ListSelectionModel.SINGLE_S ELECTION);
currentCountry = new JLabel("At begining, no country is selected", JLabel.CENTER); //Step 3: Register the countryList with a CountryListListener countryList.addListSelectionListener (new CountryListListener()); Container cp = getContentPane(); cp.setLayout (new GridLayout(2,1)); cp.add(currentCountry); cp.add (countryList); setSize (300, 300); } //Step 2: Create a CountryListListener class that implements the interface private class CountryListListener implements ListSelectionListener { //implement the abstact method inside ListSelectionListener public void valueChanged(ListSelectionEvent event) { //Display which country is selected currentCountry.setText((String) countryList.getSelectedValue()); } } //end of CountryListListener
public class EventHandleJListDemo extends JApplet { private JList countryList; private JLabel currentCountry;
//Step 1: arranges the components public void init() { //create a String vector Vector<String> originalList = new Vector<String>(); originalList.add("United States"); originalList.add("China"); originalList.add("India"); //Create a JList object from above vector countryList = new JList(originalList); countryList.setBorder(BorderFactory.createEtchedBorder ()); //the country's list is in red color with a white background countryList.setForeground(Color.red); countryList.setBackground(Color.white);
JComboBox combo = new JComboBox(); combo.addItem(A); combo.addItem(B); combo.addItem(C); combo.addItem(D); combo.addItem(E); Once it is created, we can check which one is selected by a user using following methods:
combo.getSelectedIndex() -- returns an index (integer) of the selected item. combo.getSelectedItem() -- returns a selected object.
A Listener for a JComboBox can be constructed in a similar way to the one for JButton. A class that implements ActionListener interface needs to be created, and the actionPerformed method needs to be defined:
private class ComboListener implements ActionListener { public void actionPerformed(ActionEvent event) { if (combo.getSelectedIndex() == 0) label.setText(A was chosen); else if (combo.getSelectedIndex() == 1) label.setText(B was chosen); //Etc. } }
--It sorts a list of values by repetitively inserting a particular value into a subset of the lis Example: 3 9 6 1 2 9 should be inserted after 3 no change
9 1
3 6
Comparisons are done in this line. A similar //-----------------------------------------------------------------computation to the one for selection sort results into: // Sorts the specified array of integers using the insertion
// sort algorithm. //----------------------------------------------------------------- when an input array is Best Case public static void insertionSort (int[] numbers) already sorted - O(n) { for (int index = 1; index < numbers.length; index++) when an input array is in Worst Case { the reverse order - O(n2) int key = numbers[index]; int position = index; We consider the worst case for its upper bound, // shift larger values to the right So the insertion sort algorithm is O(n2) while (position > 0 && numbers[position-1] > key) { numbers[position] = numbers[position-1]; position--; } numbers[position] = key; } }
The Comparable interface is defined in the java.lang package and it contains only one method, compareTo, which takes an object as a parameter and returns an integer. Any that implements the Comparable interface needs to define compareTo method and their instantiated objects become something that can be compared. // Person.java: Represents a Person. public class Person implements Comparable { private String firstName, lastName, phone;
// Sets up this Person with the specified information. public Person (String first, String last, String telephone) { firstName = first; lastName = last; phone = telephone; }
// Uses both last and first names to determine lexical orderi public int compareTo (Object other) { int result;
Recursion
We suppose that you have seen iterative methods in the prerequisite courses. Methods u or do-while loops are considered to be iterative. Often we can compute the same result u In some cases, using recursion enables you to give a natural, straight forward, simple so difficult to solve.
What is a recursive method? -A method that invokes itself (direct recursion)
Of course the methodA keeps calling itself and this will generate an infinite recursion. Thu where it does not call itself. Recursion should have: - recursive case(s) - base case(s) (non-recursive part, stopping condition)
Example: For a given positive integer n (i.e., n = 1, 2, 3, 4, ), the method sum is defined by: sum
Using a loop (iterative), this can be computed using a variable that shows the accumula (here the variable is result)
//in this line, result on the right hand side is the old value o //and the result on the left hand side if the new value conta
By observing the pattern from the previous page, we can formulate the recursion:
Iterative case: sum(k) = sum(k-1) + k for k >= 2 (This means that, assuming that we have already computed the sum up to n=1 we can co k-1,
The secondmethodrecursive since you see the same function in both sides n=2 equatio of the Recursive line is
n=3 Based on the that n >= 1 // assume above observation, we have the following recursive method to compute the public static int sum(int n) main n=4 { sum(4)= sum(3) + 4=4+6is returned sum(4) int result; if (n == 1) // base case is invoked sum sum(3)= sum(2) + 3=3+3is returned result = 1; sum(3) else //recursive case for n >= 2 is invokedsum result = sum(n-1) + n; sum(2)= sum(1) + 2=2+1is re sum(2) This method can be called from a main method as: is invokedsum return void main(String[] args) public staticresult; sum(1)=1 is returned { } sum(1) int result = sum(4); is invoked sum } Observe that the sum using a recursive method can be computed in two passes. going down to the base case, then going up!
We can also observe from the mathematical recursive function that: Sum(4) = sum(3) + 4 = ((sum(2) + 3 ) + 4 = (((sum(1) + 2) + 3) + 4) = ((( 1 + 2) + 3) + 4) = (( 3 + 3) + 4) = (6 + 4) = 10
Now you can see these two methods side by side. They compute the exactly same res the other is recursive. Iterative method public static int sum(int n) { int result = 1; for (int i=2; i<=n; i++) result = result + i; Recursive method // assume that i >= 1 public static int sum(int i) { int result; if (i == 1) // base case result = 1; else //recursive case for i >= 2 result = sum(i-1) + i;
return result; 1. Identify your sub-problem. i.e., the same problem as the original problem, but on a subs } 2. Think how you can use a solution of the sub-problem to solve the original problem.
With the above example, the original problem is to compute the sum from 1 to n, and th If we had the sum from 1 to (n-1), then we just need to add n to it to get the sum from 1 3. Also consider your base case(s).
Indirect Recursion
m1
invokes Example: invokes For the methods m1, m2, and m3. m2 m3 m1 invokes m2, which invokes m2, which invokes m1. invokes Sorting using Recursion --It is difficult to trace and debug. Merge Sort Merge Sort uses Divide and Conquer approach. It divides elements evenly and invokes elements. 6392 Dividing process
63 6 36 2369 3 92 9 29
2
Merging process
public static void mergeSort(int[] num, int start, int end) The method mergeSort splits an array in { subarrays and invokes itself on them. //base case is when start == end, does nothing (start is the starting index and end is th if (start < end) //recursive case { The method merge merges two subarray int mid = (int) Math.floor((double) (start+end)/(2.0)); array without disturbing their order. mergeSort(num,start,mid); mergeSort(num,mid+1,end); merge(num, start, mid, end);
} The mergeSort method invokes merge method described in the next page. } The merge method merges two sorted subarrays into one. 2 5 6 9 13 14 1 1 3 4 7 10 12 2 3 4 5 6 7 9 10 12 13 14
The complexity of Merge Sort Algorithm is n log n. Therefore Merge Sort is more effic Selection Sort and Insertion Sort in their w
public static void merge(int[] num, int start, int mid, int end) // copy the rest of the subarray that d { if ( i == n1) int n1 = mid-start+1; //get the length of the first half subarray { int n2 = end-mid; //get the length of the second half subarray while (k <= end) int[] left = new int[n1]; { int[] right = new int[n2]; num[k] = right[j]; k++; //i is used for the array "left", j for "right", k for "num" j++; int i, j, k; } // copy the elements in the array "num" to the arrays} else if (j == n2) // "left" and "right" { for (i=0; i<n1; i++) while (k <= end) left[i] = num[start+i]; { num[k] = left[i]; for (j=0; j<n2; j++) k++; right[j] = num[mid+1+j]; i++; } i=0; } j=0; } k=start; while (i < n1 && j < n2) //merge left and right into "num" { if (left[i] <= right[j])
The quick sort uses the strategy of divide and conquer like merge sort. Its idea is to rearrange the element in the range so that no element in the first sub-array is larger than any element in the last sub-array. i.e., all elements in the first sub-array are smaller or equals to a pivot value, and all elements in the last sub-array are greater equals to a pivot value. There are several ways to pick a pivot value, but one way is to pick the first element of a given array. If we have an array containing:
{5 3 2 6 4 1 3 7}
And if we use 5 (the first element of this array) as a pivot to partition, we can arrange it into two sub arrays as: {3 3 2 1 4} {6 5 7} (this can be viewed as one array {3 3 2 1 4 6 5 7})
The first sub-array contains elements smaller or equals to 5, and the second sub-array contains elements greater or equals to 5.
We can repeat the similar partitioning process on two sub arrays (to get four sub-arrays on). At the end, we will have a sorted array.
//The partition method re-arrange the array so that a //The quickSort method calls partition method to partition // the two (first //the array, then call itself recursively on the pivotsub element of the array) are grouped a //of the array, //arrays that were divided by the partition method. and all elements >= the pivot are gro //end of the array. The returned index j will be where //divided when to) public static void quickSort(int[] elements, int from, int the partitioning process is over. public static int partition(int[] elements, int from, int to { { if ( from < to ) int pivot = elements[from]; { int p = partition(elements, from, to); int i = from -1; int j = to + 1; quickSort(elements, from, p); quickSort(elements, p+1, to); } } //end of quickSort method
while (i < j ) // until i and j cross each other { i++; //move i towards right until we find an element g while (elements[i] < pivot) i++;
j--; //move j towards left until we find an element sm while (elements[j] > pivot) j--; //we swap the two elements
4 3 7 9 5 6 1 8 2
i ->
<- j
i keeps increasing until it finds an element that is greater than or equals to the pivot va j keeps decreasing until it finds an element that is smaller than or equals to the pivot v
2 3 7 9 5 6 1 8 4 i j
Repeat this process until i and j cross each other. (repeat FIND and SWAP) FIND
Worst Cases occur when the array is re-arranged into one sub-array containing only on the rest of elements in every partition process. This generates an extreme split and re
The best case occurs when the array is re-arranged into two same (or almost same in in every partition process. In this case, its running time is computed in almost same way as that of the Merge So However, the constant/ coefficient of Quick Sort running time is much smaller than that faster than Merge Sort in most cases.
One possible average case might be when an array is partitioned into a sub-array with with the length of of the original one.
Data Structures Static vs. Dynamic Structures -A static data structure has a fixed size example: arrays (Note, this meaning is different from those associated with static modifier)
-A dynamic data structure grows and shrinks as required by the information it contains student example: linked lists John Smith 40725 3.58 An object reference is a variable that stores the address of an object. A reference is also called a pointer. Object references can be used to create links between objects
Linked Lists
A variable students the address of Consider an object that contains a reference to another object of the same type: the ob containing information John Smith class Node { String name; Node pointer; } This can construct a linked list
Using Iterator in the ArrayList We can use the iterator of an ArrayList object to traverse it (without using any index). ArrayList arraylist1 = new ArrayList(); .. Iterator iterator1 = arraylist1.iterator(); while (iterator1.hasNext()) { System.out.println(iterator.next()); }
Here, we use iterator.next() to access each element in the array list. Since a linked list does not have any index to trace each element, we need to use an ite Note that the above loop is equivalent to:
// Returns the first element in the linked list. public Object Note: You need to be careful in boundary cases such as getFirst() operations at the beginning and the end of a { list. if (first == null) { //This Linked List class shows how some of its commonly NoSuchElementException ex //used methods are implemented. = new NoSuchElementE throw ex; // A linked list is a sequence of nodes with efficient } // element insertion and removal. else // This class contains a subset of the methods of the return first.data; // standard java.util.LinkedList class. } import java.util.NoSuchElementException; // Removes the first element in the linked lis public Object removeFirst() public class LinkedList { { if (first == null) //nested class to represent a node { private class Node NoSuchElementException ex { = new NoSuchElementE public Object data; throw ex; public Node next; } } else { //only instance variable that points to the first node.
Some method implementation of Linked List
// Tests if there is an element after the itera // Adds an element to the front of the linked list. public boolean hasNext() public void addFirst(Object element) { { if (position == null) //not traversed yet //create a new node { Node newNode = new Node(); if (first != null) return true; newNode.data = element; else return false; newNode.next = first; } //change the first reference to the new node. else first = newNode; { } if (position.next != null) return true; else return false; // Returns an iterator for iterating through this list. } public ListIterator listIterator() } { // Moves the iterator past the next elemen return new LinkedListIterator(); // the traversed element's data. } public Object next() { //nested class to define its iterator if (!hasNext()) { private class LinkedListIterator implements ListIterator NoSuchElementException ex = { new NoSuchElementE private Node position; //current position throw ex; private Node previous; //it is used for remove() method } else { // Constructs an iterator that points to the front previous = position; // Remember for r
// Removes the last traversed element. This method // Adds an element after the iterator position be called after a call to the next() method. // only // and moves the iterator to point to public void remove() // the inserted element. { public void add(Object element) if (previous == position) //not after next() is calle { { if (position == null) //never traversed yet IllegalStateException ex = new IllegalStateEx { throw ex; addFirst(element); } position = first; else } { else if (position == first) { removeFirst(): //making a new node to add else Node newNode = new Node(); previous.next = position.next; //removing newNode.data = element; //stepping back newNode.next = position.next; //this also means that remove() cannot be cal //change the link to insert the new node position = previous; position.next = newNode; } //move the position forward to the new node } position = newNode; // Sets the last traversed element to a different valu } public void set(Object element) //this means that we cannot call remove() { //right after add() if (position == null) { previous = position; NoSuchElementException ex = new NoSuchE
// The ListIterator interface allows access of a position in a linked list. // This interface contains a subset of the methods of the // standard java.util.ListIterator interface. The methods for // backward traversal are not included. public interface ListIterator { //Move Moves the iterator past the next element. Object next(); // Tests if there is an element after the iterator position. boolean hasNext(); // Adds an element before the iterator position // and moves the iterator past the inserted element. void add(Object element);
// Removes the last traversed element. This method may // only be called after a call to the next() method. void remove(); // Sets the last traversed element to a different value. void set(Object element);
UML class diagram representing the classes/interface used in the last 4 slide pages:
LinkedListIterator -position:Node -previous:Node LinkedList -first:Node +LinkedList() +getFirst(): Object +removeFirst(): Object +addFirst(Object):void +listIterator(): ListIterator +LinkedListIterator() +hasNext():boolean +next():Object +add(Object):void +remove():void +set(Object):void Node +data:Object +next:Node
ListIterator
Example: Using the LinkedList and ListIterator classes we discussed in class, prints out the content o //This method the following output show how a linked list behaves: public static void printList(LinkedList { public class LinkedListTester ListIterator iterator = list1.listItera { String result = "{ "; public static void main(String[] args) while (iterator.hasNext()) { result += iterator.next() + " "; LinkedList list1 = new LinkedList(); result += "}"; ListIterator iterator = list1.listIterator(); System.out.println(result); } iterator.add("A"); } printList(list1); iterator.add("B"); Output: printList(list1); {A} iterator.add("C"); {AB} printList(list1); {ABC} {ADBC} iterator = list1.listIterator(); {ADBEC} iterator.next(); {DBEC} iterator.add("D"); {DEC} printList(list1); iterator.next(); iterator.add("E"); printList(list1);
We have Linked List class in java.util package. (but it is important to have some idea of how it is implemented as a programmer. We need to know how efficient to do each operation using it.)
-In ArrayList, we can access any element by specifying its index in constant time. O(1 -In LinkedList, we need to go through n/2 elements on average to get to an element. O
-It may be convenient to implement a list with next and previous references. class Node { Object data; Node next, previous; }
-A linked list in which the last node points to the first node.
LinkedLists with a reference to the rear node as well as the referent to the front node.
It may also be convenient to use a separate header node with references to both the fro class List1 { Node first, last; }
list
first last
Garbage Collector
When we remove a node from a linked list, the memory used for that node should be r so that it can be used to store other data. Such memory can be collected by the garba The Java virtual machine contains a garbage collector that periodically reclaims objec You can also run a garbage collector using a code such as follows: //Runtime class is in java.lang package public static void runGarbageCollector() { // run garbage collector until no more memory freed up
//getRunTime()turns the runtime object associated with the current Java applicat Runtime runtime1 = Runtime.getRuntime();
//freeMemory() returns the amount of free memory in the Java Virtual Machine. long freeMemory = runtime1.freeMemory(); long oldFreeMemory; do { System.out.println("free memory: " + freeMemory); oldFreeMemory = freeMemory;
-An abstract data type (ADT) is an organized collection of information and a set of opera -The set of operations defines the interface to the ADT
Stacks
A stack is a data structure in which access is only allowed from one end. Imagine the candy Pez dispensers
You insert and remove candy from the same end. The first piece in is the last piece out.
You have a stack of books - to get to the bottom, you have to remove the ones on top. This is called LIFO - Last-in/First-out
java.util.Stack
Provides the stack class Constructor isEmpty or empty peek - get the top item without removing it pop - remove the top item push - push a new item onto the stack size - the number of items in a stack
Our Stack
Push T Push I Push N N I I
T
Pop N
T Pop I
T
Pop T
I T T
Read 1, + , 2
Then we hit a Right parenthesis so evaluate stack
2
1 + 3
3
3 1
We get 2*1= *
6
1
2
1
Implementation of a Stack
A stack can be implemented using an array or a linked list
Using an array, elements are pushed and popped from the back end of the array Using a linked list, elements are added (pushed) to the head of the list and also removed from the head of the list when popped.
On Your Own
(1) What is the output
Stack Letters = new Stack(); Letters.push(A); Letters.push(B); System.out.println(Letters.pop()) ; Letters.push(C); Letters.push(D); System.out.println(Letters.pop()) ; System.out.println(Letters.pop()) ; System.out.println(Letters.pop()) ;
Queues
A queue is a data structure of ordered items where items are added to the rear (in the order that they are entered and removed from the front.)
Remember in Class - we lined people up into a queue and the first person in line received their project back first! (FIFO)
Queue Example
The first person in line at a bank is served first and so on. People are served on in respect to their position in line. At the bakery, you pull a number out of the machine that distributes numbers in order on a first-come, first serve basis. When your number in the queue is called it is your turn!
FIFO First-In/First-Out
A queue is a FIFO data structure
Adding an item is called enqueue
(Entering the queue)
First-In/First-Out
Push A
Removes C
Front
A
Back Insert A
A B C
Insert C
A B
Insert B
getFront Removes A
Enqueue/Dequeue
remove removes the front item from the queue (dequeue) offer adds a new item to the rear of the queue (enqueue)
Whatever we read in and out of our stack and queue should output identical results from both the stack and queue!
First-In/First-Out
Data Structure
Stacks
A stack adds items only to the top of the list and removes them from the top. push pop It is called a LIFO (Last-In, First-Out) data structure. Stacks are often drawn vertically. Some operations in a stack: Object push(Object item) adds an item to the top of the stack, and returns it Object pop( ) removes an item from the top of the stack and returns it Object peek( ) retrieves the top item without removing it boolean empty() returns true if the stack is empty, false otherwise
public class StackTester2 { public static void main(String[] args) { Stack test = new Stack(); test.push("A"); test.push("B"); test.push("C"); test.push("D"); System.out.println(test.toString()); System.out.println(test.peek()); System.out.println(test.toString()); System.out.println(test.pop()); test.push("E"); System.out.println(test.toString()); test.push("F"); System.out.println(test.toString()); System.out.println(test.pop());
Queues
A queue is similar to a list but adds items only to the end of the list and removes them fro It is called a FIFO (First-In, First-Out) data structure. Some operations on a queue: -enqueue add an item to the rear of the queue -dequeue remove an item from, the front of the queue dequeue
enqueue
Abstract methods: boolean offer(obj) - Inserts the specified element into this queue, if possible. It returns tru (for bounded peek() - Retrieves, but does not remove, the head of this queue, returning null if this queu It returns the peeked element. remove() - Retrieves and removes the head of this queue. It returns the removed element
public class QueueTester2 { public static void main(String[] args) { LinkedList list = new LinkedList();
list.offer("A"); list.offer("B"); list.offer("C"); list.offer("D");
Example:
1. 2. 3. 4.
Scan the expression from left to right When an operator is found, back up to get the required number of operands Perform the operation Continue processing the expression
Data can be stored in a tree format, such as binary trees. A node for binary trees can be defined as follows: class Node { Object data; Node rightNode; Node leftNode; } Here the letters A, B, C, D, E, F, G, and H are stored in a binary tree data structure.
228
Tree Traversals
How can we process or go through all nodes in a tree? We will look at three types of traversals, pre-order traversals, in-order traversals, and po Pre-order Traversal: The root is processed previous to its two sub-trees. For a non-empty tree: Step1: Process the root. Step2: Process the nodes in the left sub-tree with a recursive call. Step3: Process the nodes in the right sub-tree with a recursive call.
//The following preorderPrint method prints the data from each node //at or below this node of the binary tree. //Assume that this method is defined in the Node class in the previous page. public void preorderPrint() { System.out.print(data + ); if (leftNode != will Here the outputnull) be G D B A C F E K I H J M L leftNode.preorderPrint();
229
In-order Traversal: The root is processed in between the processing of its two sub-trees. For a non-empty tree: Step1: Process the nodes in the left sub-tree with a recursive call. Step2: Process the root. Step3: Process the nodes in the right sub-tree with a recursive call.
//The following inorderPrint method prints the data from each node //using in-order. //Assume that this method is defined in the Node class in the previous page. public void inorderPrint() { if (leftNode != null) leftNode.inorderPrint(); System.out.print(data + ); if (rightNode != null) rightNode.inorderPrint(); } Here the output will be A B C D E F G H I J K L M
230
Post-order Traversal: The root is processed after processing its two sub-trees. For a non-empty tree: Step1: Process the nodes in the left sub-tree with a recursive call. Step2: Process the nodes in the right sub-tree with a recursive call. Step3: Process the root.
//The following postorderPrint method prints the data from each node //using post-order. //Assume that this method is defined in the Node class in the previous page. public void postorderPrint() { if (leftNode != null) leftNode.postorderPrint(); if (rightNode != null) rightNode.postorderPrint(); System.out.print(data + ); Here the output will be A C B E F D H J I L M K G }
231
The binary search property is that any element in the right sub tree is larger than the va and any element in the left sub tree is smaller than (or equals to ) the value of the node Thus those elements need to be compared such as numbers or strings.
Searching operation can be more efficient in a tree data structure than a linear list.
232
Inorder-Print/Traversal: prints out all the key in a binary search tree in sorted order.
15
6 3 2 4 9 7 13 17 18 20
2,3,4,6,7,9,13,15,17,18,20
233
The successor of a node x is the node with the smallest key greater than x. The predecessor of a node x is the node with the greater key smaller than x.
234
15 6 3 2 4 9 7 13 17 18 20
235
Insert key = 13
15 6 3 2 4 9 7 13 17 13 18 20
236
Heaps
A heap or min-heap (max-heap) is a binary tree with two special properties: 1. A heap is almost complete: all nodes are filled in, except the last level may have some nodes missing toward the right. 2. The tree fulfills the heap property: all nodes store values that are at most as small (large) as the values stored in their descendants. It is easy to see that the heap property ensures that the smallest element is stored in the root.
An example of a heap
A heap content can be physically stored in an array (or arrayList) because of the firs 0 1 2 3 4 5 6 7 8 9
20 75 43 84 90 57 71 93 91 96
20 75 43 84 90 57 71 93 91 96
For an element at the index i of the array, The index of its left child is: 2*i + 1 The index of its right child is: 2*i + 2 The index of its parent is: the integer part of (i-1)/2
Using these formula, we can find the children or the parent of a node in the array.
i=0
i=2
For example, for the node at the index = 3, the left child is 2*3+1=7 the right child is 2*3+2=8 the parent is: (3-1)/2 = 1
i=6
i=7
i=8
A priority queue collects elements, each of which has a priority. Elements are retrieved according to their priority. New items can be inserted in any order, but the item with the highest priority is removed first. example: A collection of work requests, some of which many be more urgent than others. A heap can be used to represent a priority queue because of its 2nd property. The element at the root position has the smallest value, so it can be viewed as having the highest priority. It is easy to find the element with the highest priority in a heap.
We will be looking at three operations: -Inserting a new element into a heap -Extracting (Deleting) the root of a heap -Sort an array using a heap (Heap Sort)
1. Inserting an element into a heap Example: Inserting a new element with 60.
Insertion steps: Step1: Insert a new element as the last element in the heap (array). (This makes the 1st property of the heap hold.) Step2: Repeat the following until we are done or reach the top of the heap (no parent) Compare the added element to its parent. If the parent is larger than the new element, then swap them Else DONE! (This makes the 2nd property of the heap hold.)
Efficiency of Insertion: -Step1 takes a constant time: O(1) -In each comparison and swapping in the step 2 using an array or an arraylist takes a constant time. Step 2 can be repeated at most the height of the heap. If we have n elements in a heap, the height of the heap is O( log n) -- same idea as binary search This total running time of Insertion is: O(1) + O(1) * O(log n) = O( log n). It is O(log n).
Extraction (Removing) steps: Step1: Extract the root element. Step2: Remove the last element in the heap (array) and set it as the root. (This makes the 1st property of the heap hold.) Step3: Repeat the following until we are done or reach the bottom of the heap (no child) Compare the new root element to its children. If at least one of the children is smaller than the new root, then swap it with the smaller value child element, Else DONE! (This makes the 2nd property of the heap hold.)
Efficiency of Extraction of the root: -Step1 and Step2 take a constant time: O(1) -In each comparison and swapping in the step 3 using an array or an arraylist takes a constant time. Step 3 can be repeated at most the height of the heap. If we have n elements in a heap, the height of the heap is O( log n) -- same idea as binary search This total running time of Deletion of the root is: O(1) + O(1) * O(log n) = O( log n). It is O(log n).
3. HeapSort
We can use a heap to sort an array. Here we use a max-heap instead of a min-heap.
The main idea: Build a heap from an array. With a max-heap, we can extract the root to get the largest value, and put it aside (put it as the last element of the array by swapping the root and the last element.) Then we continue to extract the next root (the second largest value, and put it as the second last element of the array. After doing this for n-1 times (where n is the number of elements in the initial heap), we will have a sorted (ascending order) array. To have a descending order array, we can use a min-heap.
Since sorting an array means to sort any array, first we need to build a heap before we start extracting the roots.
The fixHeap method: --------------------------------------------------------------Repeat the following until both children are smaller or we reach the bottom of the tree. 1. we compare the node and its children. 2. If at least one of the children is larger than the node, then swap it with the larger child. Else DONE! 3. If it is not done, go back to the step 1, with the nodes new location. ----------------------------------------------------------------
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.
12 27 10 7 33
swap
10 33 22 80 24
31 13
12 27
swap
12 10
swap
27 31 7
33 10
22 24
31 13
33
80
80
22
24
13
Next page
swap
12 33 7 10 22 31
80 33
80 27 22 24 31 13
27
24
12
13
7
swap
10
80 80 31 12
swap
33 7 10
33 27 13 7 10
27 22 24
31 13
22
24
12
DONE!
/** This class applies the heapsort algorithm to sort an array. */ public class HeapSorter { private int[] a;
// Constructs a heap sorter that sorts a given array. // @param anArray an array of integers public HeapSorter(int[] anArray) { a = anArray; }
// Sorts the array managed by this heap sorter. public void sort() { int n = a.length - 1; //for each node that has at least one child node for (int i = (n - 1) / 2; i >= 0; i--) fixHeap(i, n); while (n > 0) { swap(0, n); n--; fixHeap(0, n); } }
// Ensures the heap property for a subtree, provided its children already fulfill the heap property // @param rootIndex the index of the subtree to be fixed // @param lastIndex the last valid index of the tree that contains the subtree to be fixed private void fixHeap(int rootIndex, int lastIndex) { int rootValue = a[rootIndex]; //Remove root // Promote children while they are larger than the root int index = rootIndex; boolean more = true; while (more) { int childIndex = getLeftChildIndex(index); if (childIndex <= lastIndex) { // Use right child instead if it is larger int rightChildIndex = getRightChildIndex(index); if (rightChildIndex <= lastIndex && a[rightChildIndex] > a[childIndex]) { childIndex = rightChildIndex; }
if (a[childIndex] > rootValue) { // Promote child a[index] = a[childIndex]; index = childIndex; } else { // Root value is larger than both children more = false; }
} else { // No children more = false; } } // Store root value in vacant slot a[index] = rootValue; }
// Swaps two entries of the array. // @param i the first position to swap // @param j the second position to swap private void swap(int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } // Returns the index of the left child. // @param index the index of a node in this heap // @return the index of the left child of the given node private static int getLeftChildIndex(int index) { return 2 * index + 1; } // Returns the index of the right child. // @param index the index of a node in this heap // @return the index of the right child of the given node private static int getRightChildIndex(int index) { return 2 * index + 2; } }
3. HeapSort
We can use a heap to sort an array. Here we use a max-heap instead of a min-heap.
The main idea: Build a heap from an array. With a max-heap, we can extract the root to get the largest value, and put it aside (put it as the last element of the array by swapping the root and the last element.) Then we continue to extract the next root (the second largest value, and put it as the second last element of the array. After doing this for n-1 times (where n is the number of elements in the initial heap), we will have a sorted (ascending order) array. To have a descending order array, we can use a min-heap.
Since sorting an array means to sort any array, first we need to build a heap before we start extracting the roots.
The fixHeap method: --------------------------------------------------------------Repeat the following until both children are smaller or we reach the bottom of the tree. 1. we compare the node and its children. 2. If at least one of the children is larger than the node, then swap it with the larger child. Else DONE! 3. If it is not done, go back to the step 1, with the nodes new location. ----------------------------------------------------------------
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.
27
10
27
10
swap
22
13
7
swap
33
80
31
33
80
24
31
22
24
13
12 27
swap
12
27
10
33
swap
22
31
33
80
31
10
80
24
13
22
24
13
Next page
80 12
swap
31 80 33
33
27
27 31 7 10
12
7
swap
10
22 22 24 13
24
13
80 80 31 12
swap
33
33 27 13 7 10
27
31
10 22 24 12
22
24
13
DONE!
/** This class applies the heapsort algorithm to sort an array. */ public class HeapSorter { private int[] a;
// Constructs a heap sorter that sorts a given array. // @param anArray an array of integers public HeapSorter(int[] anArray) { a = anArray; }
// Sorts the array managed by this heap sorter. public void sort() { int n = a.length - 1; //for each node that has at least one child node for (int i = (n - 1) / 2; i >= 0; i--) fixHeap(i, n); while (n > 0) { swap(0, n); n--; fixHeap(0, n); } }
// Ensures the heap property for a subtree, provided its children already fulfill the heap property // @param rootIndex the index of the subtree to be fixed // @param lastIndex the last valid index of the tree that contains the subtree to be fixed private void fixHeap(int rootIndex, int lastIndex) { int rootValue = a[rootIndex]; //Remove root // Promote children while they are larger than the root int index = rootIndex; boolean more = true; while (more) { int childIndex = getLeftChildIndex(index); if (childIndex <= lastIndex) { // Use right child instead if it is larger int rightChildIndex = getRightChildIndex(index); if (rightChildIndex <= lastIndex && a[rightChildIndex] > a[childIndex]) { childIndex = rightChildIndex; }
if (a[childIndex] > rootValue) { // Promote child a[index] = a[childIndex]; index = childIndex; } else { // Root value is larger than both children more = false; }
} else { // No children more = false; } } // Store root value in vacant slot a[index] = rootValue; }
// Swaps two entries of the array. // @param i the first position to swap // @param j the second position to swap private void swap(int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } // Returns the index of the left child. // @param index the index of a node in this heap // @return the index of the left child of the given node private static int getLeftChildIndex(int index) { return 2 * index + 1; } // Returns the index of the right child. // @param index the index of a node in this heap // @return the index of the right child of the given node private static int getRightChildIndex(int index) { return 2 * index + 2; } }