Development Lifecycle Models

Download Report

Transcript Development Lifecycle Models

CSC 176: Introduction to
Programming
Fall 2005
Dr. Chuck Lillie
Course Outline

Goals:
–
–
–

Learn to access Java environment
Learn to design and implement Java programs
Learn to evaluate and correct Java programs
Objectives:
–
By the end of this course the student should be able to:






Evaluation


Chart 2
Access Java environment
Design Java programs
Implement Java programs
Evaluate Java programs
Correct errors in Java programs

Homework/Programming 35%
Two Exams 30% (15% each)
Final Exam 35%
Course Outline

Lab 1
–

Lab 2
–
–
–
–
–

Operator order of precedence
Declarations
Standard input stream
Expressing mathematical equations
Class methods
Lab 3
–
–
–
–
Chart 3
How to access the Java environment & standard output stream
String class
Object variable references
Null references and unassigned variables
Using member methods
Course Outline

Lab 4
–
–
–
–
–
–
–
–
–

Lab 5
–
–
–
–
–
Chart 4
Class design
Data abstraction
Information hiding
Instance variables
Accessor methods
Mutator methods
Constructors
Facilitator methods
Graphics.drawArc() and Graphics.fillArc() methods
The if statement
Boolean logic
Truth tables
The switch statement
Comparing objects using equal()
Course Outline

Lab 6
–
–
–
–
–

Lab 7
–
–
–
–
–
Chart 5
Looping
while statement
do while statement
for statement
File stream extraction
–
Parameter passing
Methods inherited from Object
Overriding methods
static methods
java.util.Random class
Scope and name reuse
Course Outline

Lab 8
–
–
–
–
–
–
–

Lab 9
–
–
–
–
–
–
–
–
–
Chart 6
One-dimensional arrays
Subscripting
Array manipulation
Searching techniques
Java collection framework
Iterators
ArrayList
Inheritance
Inheritance hierarchies
Polymorphism
abstract classes
protected access
Overriding inherited methods
Extending swing class
Overriding paintComponent()
Proper use of repaint()
Course Outline

Lab 10
–
–
–
–
–
–

Lab 11
–
–
–

–
–
–
–
Chart 7
Using activation records to trace recursion
Mutual recursion
Recursive binary search
Lab 12
–

Throwable class hierarchy
Throwing exceptions
Exception propagation
try-catch blocks
Subclass exceptions
Finally
Timer class
TimerTask class
Fixed-rate vs. fixed-delay scheduling
Swing-based animation
Creating tasks at runtime
Final project
Problem Solving
Determine
problem features
Describe objects
and methods
Produce the
classes and code
Examine for
correctness
Chart 8
Analysis
Rethink as
appropriate
Design
Implementation
Testing
Problem Solving -Problem Definition



A clear statement of the problem
Defines problem without any reference to solution
Should be in user’s language
–
Not in technical terms
Failure to define problem may cause
you to solve the wrong problem
Chart 9
Problem Solving -- Analysis

Do I really understand the problem?
–
–
–
–
–
–
–
–
–
Chart 10
What exactly does the input consist of?
What exactly are the desired results or output?
Can I construct an example input small enough to solve by hand?
What happens when I try to solve it?
How important is it to my application that I always find an exact, optimal
answer? Can I settle for something that is usually pretty good?
How large will a typical instance of my problem be? Will I be working on
10 items? 1,000 items? 1,000,000 items?
How important is speed in my application? Must the problem be solved
within one second? One minute? One hour? One day?
How much time and effort can I invest in implementing my algorithm?
Will I be limited to simple algorithms that can be coded up in a day, or do
I have the freedom to experiment with a couple of approaches and see
which is best?
Am I trying to solve a numerical problem? A graph algorithm problem? A
geometric problem? A string problem? A set problem? Might my problem
be formulated in more than one way? Which formulation seems easiest?
Problem Solving -- Reuse

Is my problem in a catalog of algorithmic problems?
–
–
–
Chart 11
If it is, what is known about the problem? Is there an implementation
available that I can use?
If I don't see my problem, did I look in the right place? Did I browse
through all the pictures? Did I look in the index under all possible
keywords?
Are there relevant resources available on the World-Wide Web? Did I do
a Google, Lycos, Alta Vista, or Yahoo search?
Problem Solving -- Design

Can I find a simple algorithm or heuristic for the problem?
–
Can I find an algorithm to solve my problem correctly by searching
through all subsets or arrangements and picking the best one?




–
Can I solve my problem by repeatedly trying some simple rule, like
picking the biggest item first? The smallest item first? A random item
first?



Chart 12
If so, why am I sure that this algorithm always gives the correct answer?
How do I measure the quality of a solution once I construct it?
Does this simple, slow solution run in polynomial or exponential time? Is my
problem small enough that this brute-force solution will suffice?
If I can't find a slow, guaranteed correct algorithm, why am I certain that my
problem is sufficiently well-defined to have a correct solution?
If so, on what types of inputs does this heuristic work well? Do these
correspond to the data that might arise in my application?
On what types of inputs does this heuristic work badly? If no such examples
can be found, can I show that it always works well?
How fast does my heuristic come up with an answer? Does it have a simple
implementation?
Problem Solving -- Design

Are there special cases of the problem that I know how to solve
exactly?
–
–
–
–
–
Chart 13
Can I solve the problem efficiently when I ignore some of the input
parameters?
What happens when I set some of the input parameters to trivial values,
such as 0 or 1? Does the problem become easier to solve?
Can I simplify the problem to the point where I can solve it efficiently? Is
the problem now trivial or still interesting?
Once I know how to solve a certain special case, why can't this be
generalized to a wider class of inputs?
Is my problem a special case of a more general problem in the catalog?
Problem Solving -- Design

Which of the standard algorithm design paradigms are most relevant to
my problem?
–
–
–
–
–
–
–
Is there a set of items that can be sorted by size or some key? Does this
sorted order make it easier to find the answer?
Is there a way to split the problem in two smaller problems, perhaps by doing a
binary search? How about partitioning the elements into big and small, or left
and right? Does this suggest a divide-and-conquer algorithm?
Do the input objects or desired solution have a natural left-to-right order, such
as characters in a string, elements of a permutation, or the leaves of a tree? If
so, can I use dynamic programming to exploit this order?
Are there certain operations being repeatedly done on the same data, such as
searching it for some element, or finding the largest/smallest remaining
element? If so, can I use a data structure to speed up these queries? What
about a dictionary/hash table or a heap/priority queue?
Can I use random sampling to select which object to pick next? What about
constructing many random configurations and picking the best one? Can I use
some kind of directed randomness like simulated annealing in order to zoom in
on the best solution?
Can I formulate my problem as a linear program? How about an integer
program?
Does my problem seem something like satisfiability, the traveling salesman
problem, or some other NP-complete problem? If so, might the problem be
NP-complete and thus not have an efficient algorithm?
Chart 14
Problem Solving -- Design

Am I still stumped?
–
–
Chart 15
Am I willing to spend money to hire an expert to tell me what to do? If so,
check out the professional consulting services mentioned in Section .
Why don't I go back to the beginning and work through these questions
again? Did any of my answers change during my latest trip through the
list?
Problem Solving – General Rules










Chart 16
Identify the inputs
Identify the outputs
Break problem into smaller sub-problems
Identify the functions required
Outline the solution or draw a diagram
Identify how individual pieces will interact (identify
interfaces between components)
Start with implementation for specific input
Refine to more general solution
Don’t be afraid to rebuild
Don’t be afraid to try something new
Lab 1

How to access the Java environment & standard output
stream

Compile .java program

Double click on .java program




Select Build from menu bar
Select Compile from drop-down menu
Execute compiled program








Chart 17
JCreator program will open with .java program in main window

Select Build from menu bar
Select Execute File from drop-down menu
Click on … to select the path and file to execute
Click on down arrow on Files of type
Select All Files (*.*)
Change Look in to the directory where your .java program is
stored
Select the .class file that you want to execute
Select Open
Select OK
Lab 2





Chart 18
Operator order of precedence
Declarations
Standard input stream
Expressing mathematical equations
Class methods
Operator Precedence

Chart 19
The precedence for the arithmetic, relational, Boolean operators, and assignment from highest to lowest is:
Operation
Symbol
Precedence
Association
---------------------------------------------------------------------------------------------------------------------------(from highest, 1, to lowest, 11)
grouping
()
1
left to right
unary
+2
right to left
multiplication
*
3
left to right
division
/
3
left to right
remainder
%
3
left to right
addition
+
4
eft to right
subtraction
4
left to right
less than
<
5
left to right
less than or equal
<=
5
left to right
greater than
>
5
left to right
greater than or equal >=
5
left to right
equal
==
6
left to right
not equal
!=
6
left to right
bit and
&
7
left to right
xor
^
8
left to right
bit or
|
9
left to right
conditional and
&&
10
left to right
conditional or
||
11
left to right
assignment
=, +=, *= ...
12
N.A.
Object

Chart 20
An object is a structure that represents a state
and knows methods to manipulate it. The
structure components are called instance
variables.
Class



Chart 21
A class consists of all objects with like state which know
exactly the same methods, i.e., a class knows the
structure of its objects and contains the methods to
manipulate the structure. An object is called an instance
of a class.
Given a class, one normally creates objects. Objects are
created dynamically with the prefix operator new which in
turn calls a constructor method to initialize the instance
variables. Uninitialized instance variables are zeroed.
Methods mostly access the instance variables of the
receiver. If methods return their receiving objects, method
calls (messages) can be cascaded.
Object Declarations


Each object must be declared.
Example of a declaration:
–



mainWindow is an identifier. The value of the identifier
can be a reference to a MainWindow object.
At this point of the program, the value of the identifier is
null. This means, you can't send a message to the object.
Example of creating an object and assign it to a identifier:
–
Chart 22
MainWindow mainWindow;
mainWindow = new MainWindow();
Identifier

1.
2.
3.
4.
5.
6.
Chart 23
An identifier is an unlimited-length sequence of
Java letters and Java digits, the first of which
must be a Java letter. An identifier cannot have
the same spelling as a keyword, Boolean literal,
or the null literal.
Can be any length
First character must be a letter \ { 0, .. 9 }
Following characters can be letters or digits
Are case sensitive: TOM is NOT the same as
Tom
A Java reserved word CANNOT be used as an
identifier, ex. true
Must be declared to be of some type.
Identifier (cont.)


Identifier should/must be self explained.
The words i, k, lth, ... have no real meaning for a human
being.
–
–
–
–

The basic syntax for declaring variables is:
–
–

typename identifier;
typename identifier = expression;
A variable has the following properies:
–
–
–
Chart 24
lessThanTen versus ltt
thisIsSorted versus t
mph versus speed
maximum versus m
memory location to store the value.
type of data stored in the memory location.
name used to refer to the memory location.
Character








Java uses the unicode standard. The type char has 16 bits and is not
considered to be an integer type.
The use of 16bits allows us to use most written languages.
Arabic
Gurmukhi
Miscellaneous Symbols
However, char values can be converted into arithmetic values and vice versa.
Other than that, char values can only be compared and assigned.
The class Character provides, among others, class methods to classify
characters that are used in char/Wc .
Character constants consist of a character in single quotes. There are (only!)
the following escape conventions as in C:
–
–
–
-- \b \f \n \r \t
-- \\ \' \"
-- \o \oo \ooo


Chart 25
with 1 to 3 octal digits for an 8 bit value.
Every character in the program source can be represented with hexadecimal
digits in unicode as \uxxxx; however, replacement happens very early and is
no alternative to \n etc.
Character Example
/*
*
* This program is using the Character class
* @version $Id$
* @author Hpb
* Revisions:
* $Log$
*/
import javabook.*;
class Char_1 {
public static void main( String args[] ) {
Character c_1 = new Character('a');
Character c_2 = new Character('a');
System.out.println(c_1 + " " + c_2);
System.out.println("Character.isDigit('a') " +
Character.isDigit('a'));
System.out.println("Character.isDigit('0') " +
Character.isDigit('0'));
System.out.println("Character.isDigit('0') " +
Character.isDigit('0'));
if ( c_1 == c_2 )
System.out.println("c_1 == c_2");
else System.out.println("c_1 != c_2");
if ( c_1.equals(c_2) )
System.out.println("c_1.equal(c_2) ");
else System.out.println("!c_1.equal(c_2) ");
}
}
Chart 26

Output:
aa
Character.isDigit('a') false
Character.isDigit('0') true
Character.isDigit('0') true
c_1 != c_2
c_1.equal(c_2)
Java Primitive Types


A primitive type is predefined by the Java language and named by its reserved keyword.
A variable has the following properies:
–
–
–
memory location to store the value.
type of data stored in the memory location.
name used to refer to the memory location.
Java knows the following types:
type
#bits
def.
v. minimum value maximum value
-----------------------------------------------------------------------------------------------byte
8 bits
0
-128
127
char
16 bits
0
0
65,535
short
16 bits
0
-32,768
32,767
int
32 bits
0
-2,147,483,648
2,147,483,647
long
64 bits
0
-9,223,372,036,854,775,808 9,223,372,036,854,775,807
float
32 bits
0.0
-3.40282347E38
3.40282347E38
double
64 bits
0.0
-1.79E+308
1.79E308

Chart 27
Types – Example
int index;
int milesPerHour, maximumSpeed;
float pressure, sizeOfme;
double starTrekSpeed;
int picturesTakenSofar = 20;
double probability = 0.789;
 Conditions can only be expressed with Boolean values.
–
Boolean has the predefined constants


–
Chart 28
true and
false.
The names are not reserved; however, they are only recognized
as Boolean constants.
Arithmetic Operators



The table below shows some of the arithmetic operators that Java provides in the order
of their precedence.
Parentheses can be used to change the order of evaluation
An arithmetic expression returns (calculates) a value when executed.
binary Operator
Description
------------------------------------------------------------------+
addition
subtraction
*
multiplication
/
integer division, if both operands are integer;
real division otherwise
%
remainder
unary Operator
Description
-----------------------------------------------------------------------++
increment by 1
-decrement by 1
!
not
Chart 29
Arithmetic Operators -- Examples
int left;
int right;
int result;
left = 4;
right = 3;
result = 4 * 3;
result = 4 + 3;
result = 4 / 3;
result = 4 % 3;
left ++;
result = left++;
result = ++left;
right ++;
result = right++;
result = ++right;
Chart 30
Mixed Mode Arithmetic and Casting




Chart 31
When an expression contains more than one arithmetic
type all are converted to the heaviest.
byte  short  int  long  float  double
For example, 2 + 3.3 is interpreted as 2.0 + 3.3.
Java is strongly typed. However, the type of the results of
evaluating an expression may be changed using casting.
To cast, place the target type in parentheses before the
operand or expression to be converted.
For example, if we really wanted the results of 2 + 3.3 to
be integer, we could use
int index;
index = 2 + (int) 3.3;
index = (int) (2 + 3.3);
Casting Example
/*
*
* The program deals with operators.
* Comment not included.
* @version $Id$
*
* @author hp bischof
*
* Revisions:
* $Log$
*/
class OpEx {
public static void main(String args[]) {
int intVar_1 = 1;
int intVar_2 = 2;
int intRes = 3;
double doubleVar_1 = 3.8;
double doubleVar_2 = 4.8;
double doubleRes = doubleVar_1 - doubleVar_2;
intRes = 5 / 3; System.out.println(intRes);
intRes = 5 % 3; System.out.println(intRes);
// intRes = 5 / doubleVar_2); // Doesn't work, why?
intRes = (int)(5 / doubleVar_2); System.out.println(intRes);
doubleRes = 5 / doubleVar_2; System.out.println(doubleRes);
doubleRes = 5.0 / doubleVar_2; System.out.println(doubleRes);
}
}
Chart 32

Results
% javac OpEx.java
% java OpEx
1
2
1
1.0416666666666667
1.0416666666666667
Assignment Operators

There are 12 assignment operators; all are syntactically rightassociative (they group right-to-left).
= *=
<<=


/=
>>=
%=
>>>=
+=
&=
-=
^=
|=
Note: We will ignore the second line for the moment.
The syntax for an assignemnt is:
Assignmnet: LeftHandSide AssignmentOperator AssignmentExpression


LeftHandSide must be a variable
AssignmentOperator must be one of
= *= /= %= += -= <<= >>= >>>= &= ^= |=


Chart 33
AssignmentExpression must be ConditionalExpression or Assignment
Note: A variable that is declared final cannot be assigned to.
Assignment Example
/**
* The program deals with assignment and ++, -- operators.
* Comment not included.
*
* @version $Id$
*
* @author hp bischof
*
* Revisions:
* $Log$
*/
class Assignment {
public static void main(String args[]) {
int intVar_1 = 1;
int intVar_2 = 1;
int intRes;
intRes = intVar_1++; System.out.println(intRes);
intRes = ++intVar_1; System.out.println(intRes);
intRes += intVar_1; System.out.println(intRes);
intRes -= intVar_1; System.out.println(intRes);
intRes = 4;
intRes /= 2; System.out.println(intRes);
intRes = ++intRes + ++intRes;
System.out.println(intRes);
}
}
Chart 34

Result
% javac Assignment.java
% java Assignment
1
3
6
3
2
7
Math Class
Chart 35
/**
* The program handles is using the Math class.
*
* @version $Id$
*
* @author hp bischof
*
* Revisions:
* $Log$
*/
/**
* The program handles is using the Math class.
*
* @version $Id$
*
* @author hp bischof
*
* Revisions:
* $Log$
*/
import java.lang.Math.*;
import java.lang.Math.*;
class MathTest
{
public static void main(String args[])
{
int intId;
class MathTest
{
public static void main(String args[])
{
int intId;
System.out.println("pi = " + Math.PI );
System.out.println("sqrt(2.0) = " + Math.sqrt(2.0) );
System.out.println("abs(-3) = " + Math.abs(-3.0) );
System.out.println("pi = " + Math.PI );
System.out.println("sqrt(2.0) = " + Math.sqrt(2.0) );
System.out.println("abs(-3) = " + Math.abs(-3.0) );
intId = Math.min( 12, 2 );
intId = Math.min( 12, 2 );
System.out.println("intId = " + intId );
}
}
System.out.println("intId = " + intId );
}
}
Class Declarations










Chart 36
Class declarations define new reference types and describe how they are implemented.
Constructors are similar to methods, but cannot be invoked directly by a method call; they are used to initialize new
class instances. Like methods, they may be overloaded.
Static initializers are blocks of executable code that may be used to help initialize a class when it is first loaded.
The body of a class declares members, static initializers, and constructors. The scope of the name of a member is
the entire declaration of the class to which the member belongs. Field, method, and constructor declarations may
include the access modifiers public, protected, or private. The members of a class include both declared and
inherited members. Newly declared fields can hide fields declared in a superclass or superinterface. Newly declared
methods can hide, implement, or override methods declared in a superclass.
Definition of a method:
<visibility modifier> <return type> <method name> ( <parameters> ) {
<statements>
}
Example:
public int getX() {
...
return x; // x is a int variable
}
public void getX( int y) {
...
x = y;
}
visibility modifier: public/private
Return type: void/primitive type/reference to a object
Class methods/Class variables are declared with static.
Static declaration inside a method change the lifetime of a variable.
Lab 3




Chart 37
String class
Object variable references
Null references and unassigned variables
Using member methods
String Class


Chart 38
The String class represents character strings. All
string literals in Java programs, such as "abc",
are implemented as instances of this class.
Strings are constant; their values cannot be
changed after they are created. String buffers
support mutable strings. Because String objects
are immutable they can be shared.
String Example
/**
* Play with the String class
* @version $Id$
* @author Hpb
* $Log$
*/
import javabook.*;
class String_1 { public static void main( String args[] ) {
String w_1 = "oslo";
String w_2 = new String("ich glaub's nicht");
String w_3 = new String();
System.out.println(w_1.length());
System.out.println(w_2.length());
System.out.println(w_3.length());
System.out.println(w_2.concat(w_2).length());
System.out.println(w_1.charAt(0));
System.out.println(w_1.charAt(2));
System.out.println(w_1.substring(2,3));
System.out.println("Drum".substring(2,3));
}
}
Chart 39

Output:
4
17
0
34
o
l
l
u
Palindrom checker
/*

Output:
*
* Find's out if a word is a palindorm.
-otto- = true
* @version $Id$
-ich glaub's nicht* @author Hpb
* Revisions:
-a- = true
* $Log$
-- = true
*/
import javabook.*;
class Palindrom {
private static boolean palindrom(String w) {
boolean res = true;
for ( int index = 0; index < w.length(); index ++ ) {
res = res && ( w.charAt(index) == w.charAt(w.length() 1- index) );
}
return res;
}
public static void main( String args[] ) {
String w_1 = "otto";
String w_2 = new String("ich glaub's nicht");
String w_3 = new String("a");
String w_4 = new String();
System.out.println("-" + w_1 + "- = " + palindrom(w_1) );
System.out.println("-" + w_2 + "- = " + palindrom(w_2) );
System.out.println("-" + w_3 + "- = " + palindrom(w_3) );
System.out.println("-" + w_4 + "- = " + palindrom(w_3) );
}
Chart 40 }
= false
Lab 4









Chart 41
Class design
Data abstraction
Information hiding
Instance variables
Accessor methods
Mutator methods
Constructors
Facilitator methods
Graphics.drawArc() and
Graphics.fillArc() methods
Lab 5





Chart 42
The if statement
Boolean logic
Truth tables
The switch statement
Comparing objects using equal()
Boolean Expressions


Chart 43
In order to write programs that solve any but the
most elementary problems we need a way to
make decisions.
In order to make decisions, we need to
understand how to construct Boolean
expressions. These are expressions that evaluate
to one of two values, true or false.
Relational Operators





Chart 44
Simple Boolean expressions consist of comparing things
using relational operators. There are two types of
relational operators: equality and comparison.
Equality operators are defined for all objects and primitive
types.
== equal
!= not equal
For basic types these are the values and things work as
expected. For reference types this just checks if they point
to the same object. It does not check if the objects
referenced have the same contents.
Logic Operators










Chart 45
These operators take Boolean arguments and return
Boolean results.
They are used to construct complex Boolean expressions
from simple ones consisting of Boolean values and
relational expressions.
& and
&& conditional and (short circuits)
| or
|| conditional or (short circuits)
^ xor
! not (unary operator)/boolean complement
x && y y will be evaluated only if x is true
x || y y will be evaluated only if x if false
Truth Tables for Boolean Operators
not
|
------+-------False | True
True | False
|
|
and
| False
True
or | False True
------+---------------- ----------+-------------False | False
False
False | False True
True | False
True
True | True True
|
|
|
|
xor
| False
True
implies | False True
------+---------------- ----------+-------------False | False
True
False | True True
True | True
False
True | False True
The left operand (``receiver'') is specified in the left column;
the right operand (``argument'') is specified in the top row.
Chart 46
IfThen Statement


The if statement allows conditional execution of a
statement or a conditional choice of two
statements, executing one or the other but not
both.
IfThen Statement:
–

Chart 47
if ( Expression ) Statement
Example:
x = 3;
y = 4;
if ( x > y )
z = x;
IfThenElse Statement


Chart 48
IfThenElse Statement:
if ( Expression )
Statement
else
Statement
Example:
x = 3;
y = 4;
if ( x > y )
z = x;
else z = y;
Find the Maximum of two Numbers I
/**
* Find the maximum of two numbers.
* @version $Id$
*
* @author Hpb
*
* Revisions:
$Log$
*/
import javabook.*;
class Maximum {
public static void main( String args[] ) {
MainWindow win = new MainWindow("Maximum program");
InputBox input = new InputBox(win);
OutputBox output = new OutputBox(win);
double firstN = input.getFloat("Enter the first number:");
double secondN = input.getFloat("Enter the second number:");
double max;
// the if then else part
if ( firstN > secondN )
max = firstN;
else max = secondN;
output.show();
output.printLine("Maximum(" + firstN + ", " + secondN + ") = " + max);
}
}
Chart 49
Find the Maximum of two Numbers II
/*
*
Find the maximum of two numbers. This program is using a class method.
*
* @version $Id$
*
* @author Hpb
*
* Revisions:
* $Log$
*/
import javabook.*;
class Maximum_2 {
public static double maximum(double _first, double _second ) {
double max;
// find maximum
if ( _first > _second )
max = _first;
else max = _second;
return max;
}
public static double minimum(double _first, double _second ) {
double minimum;
// find minimum
if ( _first < _second )
minimum = _first;
else minimum = _second;
return minimum;
}
public static void main( String args[] ) {
MainWindow win = new MainWindow("Maximum 2");
InputBox input = new InputBox(win);
OutputBox output = new OutputBox(win);
double firstN = input.getFloat("Enter the first number:");
double secondN = input.getFloat("Enter the second number:");
// win.show();
output.show();
output.printLine("Maximum(" + firstN + ", " + secondN + ") = " + maximum( firstN, secondN) );
output.printLine("Minimum(" + firstN + ", " + secondN + ") = " + minimum( firstN, secondN) );
}
}
Chart 50
Find the Maximum of two Numbers III
/*
*
* Find the maximum of two numbers.
*This program is using a class method.
*
* @version $Id$
*
* @author Hpb
*
*Revisions:
*$Log$
*/ import javabook.*;
class Maximum_3 {
public static double maximum(double _first, double _second ) {
if ( _first > _second )
return _first;
else
return _second;
}
public static double minimum(double _first, double _second ) {
if ( _first < _second )
return _first;
else
return _second;
}
public static void main( String args[] ) {
MainWindow win = new MainWindow("Maximum 3");
InputBox input = new InputBox(win);
OutputBox output = new OutputBox(win);
double firstN = input.getFloat("Enter the first number:");
double secondN = input.getFloat("Enter the second number:");
// win.show();
output.show();
output.printLine("Maximum(" + firstN + ", " + secondN + ") = " + maximum( firstN, secondN) );
output.printLine("Minimum(" + firstN + ", " + secondN + ") = " + minimum( firstN, secondN) );
}
}
Chart 51
Switch Statement

The switch statement transfers control to one of several statements
depending on the value of an expression. The type of the switch
expression can be
-char
-byte
-short
-int

Chart 52
Switch Statement:
switch ( Expression ) {
case ConstantExpression_1 : action_1;
case ConstantExpression_2 : action_2;
...
default: action_d
}
Switch Statement Example
class Many {
static void howManyWithBreak(int k) {
System.out.println(k + ":------------------");
switch (k) {
case 1: System.out.println("with break: one ");
break;
case 2: System.out.println("with break: too ");
break;
default: System.out.println("with break: many");
}
}
static void howManyWithoutBreak(int k) {
System.out.println(" " + k + ":------------------");
switch (k) {
case 1: System.out.println(" without break: one ");
case 2: System.out.println(" without break: too ");
default: System.out.println(" without break: many");
}
}
public static void main(String[] args) {
howManyWithBreak(3);
howManyWithBreak(2);
howManyWithBreak(1);
howManyWithoutBreak(3);
howManyWithoutBreak(2);
howManyWithoutBreak(1);
}
}
Chart 53
Execution:
% javac Many.java && java Many
3:------------------ with break: many
2:------------------ with break: too
1:------------------ with break: one
3:------------------ without break: many
2:------------------ without break: too
without break: many
1:------------------ without break:
one without break: too
without break: many

Partial Lowercase  Uppercase
/*
*
Test of the switch statement.
*
•
* @version $Id$
•
*
•
* @author hpb
•
*
•
* Revisions:
•
* $Log$
•
*/
import javabook.*;
class Switch_1 {
public static String itWasA(char c) {
switch( c ) {
case 'a': return("A");
// break??
case 'b': return("B");
// break??
case 'c': return("C");
// break??
case 100: return("D");
// break??
case 101: return("E");
// break??
default: return("no clue, but not an [a-e]");
// What happens if // we delete this line?
}
}
public static void main( String args[] ) {
MainWindow win = new MainWindow("Maximum 2");
InputBox input = new InputBox(win);
OutputBox output = new OutputBox(win);
char theChar;
do {
theChar = input.getString("Enter a character:").charAt(0);
output.show();
output.printLine("You typed in an '" + itWasA(theChar) + "'");
}
while ( theChar != 'q' );
System.exit(0);
// beware of ...
}
}
•
•
Chart 54
Lab 6





Chart 55
Looping
while statement
do while statement
for statement
File stream extraction
While Statement




Chart 56
The while statement executes an Expression and
a Statement repeatedly until the value of the
Expression is false.
While Statement:
while ( Expression ) Statement
Example:
x = 1;
while ( x < 10 ) {
print x x += 2;
}
Abrupt Completion

1.
2.
Chart 57
Abrupt completion of the contained Statement is
handled in the following manner:
If execution of the Statement completes abruptly
because of a break with no label, no further
action is taken and the while statement
completes normally.
If execution of the Statement completes abruptly
because of a continue with no label, then the
entire while statement is executed again.
Calculate Sqrt(2)
without the MathClass
/*
*
* Calculate Sqrt(2) without the MathClass
*
* @version $Id$
* @author Hpb
* Revisions:
* $Log$
*/
import javabook.*;
class Sqrt {
public static double calculateSqrt_2() {
double n1 = 1.0;
double n2 = 2.0;
while ( (n2 * n2 - n1 * n1) > 0.0001) {
double x = ( n2 + n1 ) * 0.5;
if ( x * x > 2.0 )
n2 = x;
else n1 = x;
}
return n1;
}
public static void main( String args[] ) {
MainWindow win = new MainWindow("Sqrt(2)");
InputBox input = new InputBox(win);
OutputBox output = new OutputBox(win);
output.show();
output.printLine("sqrt(2) = " + calculateSqrt_2() + " +- 0.0001 " );
}
}
Chart 58
Do Statement

Chart 59
The do statement executes a Statement and an
Expression repeatedly until the value of the
Expression is false.
do Statement while ( Expression ) ;
For Statement






Chart 60
The for statement executes some initialization code, then executes an
Expression, a Statement, and some update code repeatedly until the
value of the Expression is false.
For Statement:
for ( ForInit; Expression; ForUpdate)
Statement
Example:
for ( index = 0; index < 10; index ++ )
System.out.println(index);
If the value of the Expression is false the first time it is evaluated, then
the Statement is not executed.
If the Expression is not present, then the only way a for statement can
complete normally is by use of a break statement.
Find all Prime Numbers in [ 2 ... 100 ]
/*
*
* Find all prime numbers in the range
* between 1 and 100
* This program is using a class method.
*
* @version $Id$
*
* @author Hpb
*
* Revisions:
* $Log$
*/
import javabook.*;
class Prime_1 {
public static boolean isPrime(int n) {
for ( int index = 2; index < n; index ++ ) {
if ( n % index == 0 )
return false;
}
return true;
}
public static void main( String args[] ) {
MainWindow win = new MainWindow("Prime_1");
OutputBox output = new OutputBox(win);
output.show();
for ( int index = 2; index <= 100; index ++ )
if ( isPrime(index) )
output.printLine(index + " " );
}
}
Chart 61
/*
* Find all prime numbers in the range
* between 1 and 100. Improved version.
* This program is using a class method.
* @version $Id$
* @author Hpb
* Revisions:
* $Log$
*/
import javabook.*;
class Prime_2 {
public static boolean isPrime(int n) {
if ( n == 1 )
return false;
if ( n == 2 )
return true;
for ( int index = 2; index < n; index += 2 ) {
if ( n % index == 0 )
return false;
}
return true;
}
public static void main( String args[] ) {
MainWindow win = new MainWindow("Prime_1");
OutputBox output = new OutputBox(win);
output.show();
for ( int index = 2; index <= 100; index ++ )
if ( isPrime(index) ) output.printLine(index + " " );
}
}
Lab 7






Chart 62
Parameter passing
Methods inherited from Object
Overriding methods
static methods
java.util.Random class
Scope and name reuse
Parameter Passing






Chart 63
The formal parameters of a method, if any, are specified by a list of
comma-separated parameter specifiers.
Each parameter specifier consists of a type and an identifier
(optionally followed by brackets) that specifies the name of the
parameter.
If a method has no parameters, only an empty pair of parentheses
appears in the method's declaration.
If two formal parameters are declared to have the same name (that is,
their declarations mention the same Identifier), then a compile-time
error occurs.
When the method is invoked, the values of the actual argument
expressions initialize newly created parameter variables,. each of the
declared Type, before execution of the body of the method.
The scope of formal parameter names is the entire body of the
method. These parameter names may not be redeclared as local
variables or exception parameters within the method; that is, hiding
the name of a parameter is not permitted.
Example
Use of a Point Class
public class TestPoint_1 {
private static Point_1 aPoint;
public static void main(String args[]) {
aPoint = new Point_1(2, 3);
System.out.println("x = " + aPoint.getX() );
System.out.println("y = " + aPoint.getY() );
aPoint = new Point_1();
aPoint.initPoint(4, 5);
System.out.println("x = " + aPoint.getX() );
System.out.println("y = " + aPoint.getY() );
aPoint.move(6, 7);
System.out.println("x = " + aPoint.getX() );
System.out.println("y = " + aPoint.getY() );
}
}
Chart 64

Execution of the test program:
% javac TestPoint_1.java Point.java && java
TestPoint_1
in Point() constructor
in Point(int, int) constructor
in getX()
x=2
in getY()
y=3
in Point() constructor
in initPoint(int, int)
in getX()
x=4
in getY()
y=5
in move(int, int)
in getX()
x = 10
in getY()
y = 12
Parameter Passing
/*
*
* This program deals with parameter passing
* @version $Id$
* @author Hpb
* Revisions:
* $Log$
*/
class Param {
public static void intMethod(int intArg) {
System.out.println("\t 2. intMethod!intArg = " + intArg );
intArg = 33;
System.out.println("\t 3. intMethod!intArg = " + intArg );
}
public static void intArrayMethod(int[] intArg) {
System.out.println("\t 6. intMethod!intArg[0] = " + intArg[0] );
intArg[0] = 33;
System.out.println("\t 7. intMethod!intArg[0] = " + intArg[0] );
}
public static void main(String[] args) {
int intVariable = 3;
int intArray[] = { 3, 3, 3 };
System.out.println("1. main!intVariable = " + intVariable );
intMethod(intVariable);
System.out.println("4. main!intVariable = " + intVariable );
System.out.println("5. main!intArray[0] = " + intArray[0] );
intArrayMethod(intArray);
System.out.println("8. main!intArray[0] = " + intArray[0] );
}
}
Chart 65

Result:
javac Param.java && java Param
1. main!intVariable = 3
2. intMethod!intArg = 3
3. intMethod!intArg = 33
4. main!intVariable = 3
5. main!intArray[0] = 3
6. intMethod!intArg[0] = 3
7. intMethod!intArg[0] = 33
8. main!intArray[0] = 33
Lab 8







Chart 66
One-dimensional arrays
Subscripting
Array manipulation
Searching techniques
Java collection framework
Iterators
ArrayList
Arrays



Chart 67
Java arrays are objects, are dynamically created, and may be
assigned to variables of type Object. All methods of class Object may
be invoked on an array.
An array object contains a number of variables. The number of
variables may be zero, in which case the array is said to be empty.
The variables contained in an array have no names; instead they are
referenced by array access expressions that use nonnegative integer
index values. These variables are called the components of the array.
If an array has n components, we say n is the length of the array; the
components of the array are referenced using integer indices from 0
to n-1, inclusive.
There is one situation in which an element of an array can be an
array: if the element type is Object, then some or all of the elements
may be arrays, because any array object can be assigned to any
variable of type Object.
Array Example
/*
*
* This program is using an array.
* It calculates the sum of the first n integers
* @version $Id$
* @author Hpb
* Revisions:
* $Log$
*/
class Array_1 {
public static void main(String[] args) {
int[] ia = new int[6];
int sum = 0;
for (int i = 0; i < ia.length; i++)
ia[i] = i;
for (int i = 0; i < ia.length; i++)
sum += ia[i];
System.out.println(sum);
}
}
Chart 68

Result:
% javac A*1*java && java Array_1
15
Array Example
• Result:
% javac A*2*java && java Array_2
monthName.length = 12
0: = January
1: = February
2: = March
3: = April
4: = May
5: = June
6: = July
7: = August
8: = September
9: = October
10: = November
11: = December
/*
*
* This program is using an array.
* It prints the name of each month.
* @version $Id$
* @author Hpb
* Revisions:
* $Log$
*/
class Array_2 {
public static void main(String[] args) {
// String[]monthName = new String[12]; or
String[]monthName = { "January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December" };
System.out.println("monthName.length = " + monthName.length );
for (int i = 0; i < monthName.length; i++)
System.out.println(i + ": = " + monthName[i] );
}
}
Chart 69
2 dimensional arrays
/*
*
* This program is using n dimensional arrays.
* @version $Id$
* @author Hpb
* Revisions:
* $Log$
*/
class Array_3 {
public static void main(String[] args) {
int ia[][] = { {1, 2}, { 3, 4 } };
int iNew[][] = new int[20][20];
int threeDim[][][] = new int[20][20][20];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
System.out.println(ia[i][j]);
for (int i = 0; i < 20; i++)
for (int j = 0; j < 20; j++)
iNew[i][j] = i * j;
for (int i = 0; i < 20; i++)
for (int j = 0; j < 20; j++)
for (int k = 0; k < 20; k++)
threeDim[i][j][k] = i * j * k;
}
}
Chart 70
Vector


Chart 71
The Vector class implements a growable array of objects.
Like an array, it contains components that can be
accessed using an integer index. However, the size of a
Vector can grow or shrink as needed to accommodate
adding and removing items after the Vector has been
created.
Each vector tries to optimize storage management by
maintaining a capacity and a capacityIncrement. The
capacity is always at least as large as the vector size; it is
usually larger because as components are added to the
vector, the vector's storage increases in chunks the size
of capacityIncrement. An application can increase the
capacity of a vector before inserting a large number of
components; this reduces the amount of incremental
reallocation.
Vector Example
/*
*
* This program is using an array.
* It calculates the sum of the first n integers
* @version $Id$
* @author Hpb
* Revisions:
* $Log$
*/
import java.util.Vector;
class Vector_1 {
public static void fillVector(Vector vector) {
vector.addElement("January");
vector.addElement("February");
vector.addElement("March");
vector.addElement("April");
vector.addElement("May");
vector.addElement("June");
vector.addElement("July");
vector.addElement("August");
vector.addElement("September");
vector.addElement("October");
vector.addElement("November");
vector.addElement("December");
}
public static void main(String[] args) {
Vector vector = new Vector();
if ( vector.isEmpty() )
System.out.println("Vector is empty");
fillVector(vector);
System.out.println(vector.size() );
System.out.println(vector.lastElement() );
vector.setSize(3);
System.out.println(vector.lastElement() );
}
}
Chart 72

Results
javac Vector_1.java && java Vector_1
Vector is empty
12
December
March
Selection Sort

Chart 73
Idea: The selection sort works by finding the
smallest number in the array and places it in the
first position in the array. It then repeats the
process of finding the smallest element, except
this time it starts looking at the second position in
the array, and places the smallest element in the
second position. This process continues until the
array is sorted.
Lab 9









Chart 74
Inheritance
Inheritance hierarchies
Polymorphism
abstract classes
protected access
Overriding inherited methods
Extending swing class
Overriding paintComponent()
Proper use of repaint()
Private, Protected, Public and Final

Private
A private class member or constructor is accessible only within the class body in which the member is declared and is not inherited
by subclasses. In the example:
class Point {
Point() {
setMasterID();
}
int x, y;
private int ID;
private static int masterID = 0;
private void setMasterID() {
ID = masterID++;
}
}
–
the private members ID, masterID, and setMasterID may be used only within the body of class Point.
–

Protected
–

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that
is responsible for the implementation of that object
Public
A public class member or constructor is accessible throughout the package where it is declared and from any other package that has
access to the package in which it is declared. For example, in the compilation unit:
public class Point {
int x, y;
public void move(int dx, int dy) {
x += dx;
y += dy;
moves++;
} public static int moves = 0;
}
–
the public class Point has as public members the move method and the moves field. These public members are accessible to any
other package that has access to package points. The fields x and y are not public and therefore are accessible only from within the
package points.
–

Chart 75
Final
Lab 10






Chart 76
Throwable class hierarchy
Throwing exceptions
Exception propagation
try-catch blocks
Subclass exceptions
Finally
Lab 11



Chart 77
Using activation records to trace recursion
Mutual recursion
Recursive binary search
Lab 12





Chart 78
Timer class
TimerTask class
Fixed-rate vs. fixed-delay scheduling
Swing-based animation
Creating tasks at runtime