java notes

84
9/7/2009 AP Lesson Notes “A” Curriculum Lesson A1: Intro to OOP o Some important words to understand: object-oriented programming (OOP), object, attributes, behaviors, constructors, class, methods o An example of a Java class o Creating your first AP Java Project o Notes on compiling and running Java programs and more vocabulary Lesson A2: Object-Oriented Programming o Our First Java Application o Program Components: comments, import statements, method o Object Declaration, Creation, and Message Sending o Class Diagrams o The Difference Between Objects and Classes Lesson A3: Primitive Data Types o Identifiers in Java o Primitive Data Types in Java: byte, short, int, long, float, double, char, and Boolean o Declaring and Initializing Variables in Java o Printing Variables Using the System.out Object o Assignment Statements o Math Operators + - * / % casting o Precedence of Math Operators o Assignment Operators = += -= *= /= %= o Increment and Decrement Operators ++ -- Lesson A4: Object Behavior o Writing Methods in Java o Parameters and Arguments o Returning Values o The Signature of a Method o Lifetime, Initialization, and Scope of Variables o Getters/Setters Lesson A5: Designing and Using Classes o Designing a Class o Implementation of a Class o Determining Object Behavior o Instance Variables o Implementing Methods o Constructors o Using Classes Lesson A6: Libraries and APIs o Understanding APIs o Final and Static o DrawingTool o Point2D.Double o Random o Math o Javadoc Tool Lesson A7: Simple IO o Reading Input with Scanner Class o Multiple Line Stream Output Expressions o Formatting Output Lesson A8: Control Structures o Structured Programming o Control Structures o Algorithm Development and Pseudocode o Relational Operators o Logical Operators o Precedence and Associativity of Operators o if-else Statements o Compound Statements o Nested if-else Statements o Boolean Identifiers o Switch Statements (optional) Lesson A9: Recursion o Recursion o Pitfalls of Recursion Lesson A10: Strings o String Class o String Constructors o Object References o null Value o String Query Methods o String Translation Methods o Immutability of Strings o Comparing Strings o Strings and Characters o toString method o String I/O Lesson A11: Inheritance o Single Inheritance o Class Hierarchies o Using Inheritance o Method Overriding o Interfaces

Upload: trey-kai-daniels

Post on 26-Nov-2014

457 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Java Notes

9/7/2009

AP Lesson Notes – “A” Curriculum Lesson A1: Intro to OOP

o Some important words to understand:

object-oriented programming (OOP), object,

attributes, behaviors, constructors, class,

methods

o An example of a Java class

o Creating your first AP Java Project

o Notes on compiling and running Java

programs – and more vocabulary

Lesson A2: Object-Oriented Programming

o Our First Java Application

o Program Components: comments, import

statements, method

o Object Declaration, Creation, and Message

Sending

o Class Diagrams

o The Difference Between Objects and

Classes

Lesson A3: Primitive Data Types

o Identifiers in Java

o Primitive Data Types in Java: byte, short,

int, long, float, double, char, and Boolean

o Declaring and Initializing Variables in Java

o Printing Variables Using the System.out

Object

o Assignment Statements

o Math Operators + - * / % casting

o Precedence of Math Operators

o Assignment Operators = += -= *= /=

%=

o Increment and Decrement Operators ++ --

Lesson A4: Object Behavior

o Writing Methods in Java

o Parameters and Arguments

o Returning Values

o The Signature of a Method

o Lifetime, Initialization, and Scope of

Variables

o Getters/Setters

Lesson A5: Designing and Using Classes

o Designing a Class

o Implementation of a Class

o Determining Object Behavior

o Instance Variables

o Implementing Methods

o Constructors

o Using Classes

Lesson A6: Libraries and APIs

o Understanding APIs

o Final and Static

o DrawingTool

o Point2D.Double

o Random

o Math

o Javadoc Tool

Lesson A7: Simple IO

o Reading Input with Scanner Class

o Multiple Line Stream Output Expressions

o Formatting Output

Lesson A8: Control Structures

o Structured Programming

o Control Structures

o Algorithm Development and Pseudocode

o Relational Operators

o Logical Operators

o Precedence and Associativity of Operators

o if-else Statements

o Compound Statements

o Nested if-else Statements

o Boolean Identifiers

o Switch Statements (optional)

Lesson A9: Recursion

o Recursion

o Pitfalls of Recursion

Lesson A10: Strings

o String Class

o String Constructors

o Object References

o null Value

o String Query Methods

o String Translation Methods

o Immutability of Strings

o Comparing Strings

o Strings and Characters

o toString method

o String I/O

Lesson A11: Inheritance

o Single Inheritance

o Class Hierarchies

o Using Inheritance

o Method Overriding

o Interfaces

Page 2: Java Notes

9/7/2009

Lesson A12: Iterations

o while Loop

o Loop Boundaries

o Conditional Loop Strategies

o for Loop

o Nested Loops

o The do-while Loop (optional)

o Loop Invariants

Lesson A13: Exceptions and File IO

o Exceptions

o Handling Exceptions

o Exception Messages

o Throwing Exceptions

o Reading From a File

o Writing to a File

Lesson A14: Boolean Algebra and Loop

Boundaries

o Negations of Boolean Assertions

o Boolean Algebra and DeMorgan's Laws

o Application of DeMorgan's Laws

Lesson A15: ArrayList

o ArrayList Implementation of a List

o ArrayList Class

o Object Casts

o Wrapper Classes

o Iterator

Lesson A16: Single Dimension Arrays

o Example of an Array

o Array Declarations and Memory Allocation

o Application of Arrays

o Arrays as Parameters

o Arrays and Algorithms

Lesson A17: Quadratic Sorting Algorithms

o Sorting Template Program

o Bubble Sort

o Selection Sort

o Insertion Sort

o Counting Steps - Quadratic Algorithms

o Animated Sort Simulations

o Sorting Objects

Lesson A18: Merge and MergeSort

o Non-Recursive MergeSort

o A Merge Algorithm

o Recursive MergeSort

o Order of Recursive MergeSort

Lesson A19: Sequential and Binary Searches

o Sequential Search

o Binary Search

o Recursive vs. Non-recursive Algorithms

Lesson A20: Inheritance, Polymorphism, and

Abstract Classes

o Inheritance

o Abstract Classes

o Polymorphism

o Interfaces

Lesson A21: Number Systems

o Introduction to Number Systems

o Review Decimal

o Octal

o Hexadecimal

o Binary

o Short Cuts Between Binary, Octal, and

Hexadecimal

o How this Relates to Computers and

Overflow Errors

Lesson A22: General Computer Knowledge

o Hardware

o Software

o Networking

o Ethics

Page 3: Java Notes

9/7/2009

Lesson A1 notes: Intro to OOP

Some important words to understand

object-oriented programming (OOP)

o programs consist of a collection of interacting objects

o each object in a program has a job to do.

object (i.e., a pencil or a piece if paper)

o attributes: aspects of an object that describe it (i.e., a pencil‟s color, width, location,

etc.)

o behaviors: things the object can do (i.e., draw line, draw circle, move to new

location, etc.)

o constructors: create a new object and determine its initial attributes

class

o a definition for a type of object, like the blueprint for a type of house

o defines the object‟s attributes, behaviors, and constructors

o while a program is running, we create objects from class definitions to accomplish

tasks

methods

o to tell an object to perform a task, we send a message to it…in Java, these messages

are called methods

o an object can only receive a message that it understands, so each type of message

must be defined within the class definition

o examples of some methods for the DrawingTool class which is provided by this

curriculum

o create a new object named “myPencil”…we say the object myPencil is an instance of

the DrawingTool class…an object can only be an instance of one class

o to draw a line of a specified length, we call the method “forward” and pass (i.e.,

communicate) the distance to move the pencil…a value we pass to an object‟s

method is called an argument

o if we need to change the direction myPencil is facing, we can call the “turnLeft”

method, which will cause a ninety-degree turn to the left…we do not need to pass any

arguments with the turnLeft method

o we can use the “getColor” method to return the value…this method responds to user

o wherever possible, reuse an existing class to create objects instead of writing code for

a new class

An example of a Java class

o here is an example of a Java class which uses the pre-existing DrawingTool class for

the pencil object and SketchPad class for the paper object

o note, this code does not do anything by itself…later we will learn how to utilize this

code in an actual program

Page 4: Java Notes

9/7/2009

/*

DrawSquare: this class will create a piece of paper and a pencil,

place the pencil on the paper, and then draw a square.

*/

import gpdraw.*;

public class DrawSquare

{

private DrawingTool pencil;

private SketchPad paper;

public DrawSquare() // the constructor

{

paper = new SketchPad(300, 300);

pencil = new DrawingTool(paper);

}

public void draw()

{

// draw the square

pencil.forward(100);

pencil.turnLeft(90);

pencil.forward(100);

pencil.turnLeft(90);

pencil.forward(100);

pencil.turnLeft(90);

pencil.forward(100);

}

}

o some notes about the above Java class

o the DrawSquare object includes one DrawingTool object and one SketchPad object

o the constructor is a method with the same name as the class

first instruction constructs new SketchPad object named “paper” with

dimensions of 300 x 300

next instruction constructs new DrawingTool object named “pencil” using

SketchPad object named “paper”

o an object‟s behavior is determined by instructions within its methods…when the

method draw() is called:

the instructions within the draw method will execute in the order they appear

there are seven instructions in draw method

first instruction will cause the “pencil” to move forward 100 units drawing a

line as it goes

next instruction tells “pencil” to turn left

remaining five instruction repeat this process to draw remaining three sides of

square.

o the DrawSquare example illustrates the tools that a programmer uses to write a

program

o a program is built from objects and classes that a programmer writes or reuses

o classes are built from instructions

o these instructions manipulate objects to perform the desired tasks

Creating your first AP Java Project [we will do this together]

Page 5: Java Notes

9/7/2009

o start BlueJ

o create new project

o Project –> New Project…select a location on your X-drive and enter

“\myFirstProject” to create a folder for your new project

o create new class named “Main”

o New Class -> enter “Main” as the class name -> click “OK”

o double click on main

o enter the following code (to replace the code for “Main” which is already there):

public class Main

{

public Main()

{

}

public static void main(String[] args)

{

System.out.println("Starting my first AP Java program.");

DrawHouse house1 = new DrawHouse();

house1.draw();

System.out.println("Finishing my first AP Java program.");

}

}

o click “Close”

o add “DrawHouse” class to your project

o Edit -> Add class from file

o select java file “DrawHouse.java” from “C:/stuff for BHS programming students/

first AP Java project” on your C-drive

o click “Add”

o compile and run your program

o click “Compile”

o right-click “Main”

o click “void main(String[] args)”

o click “OK”

o a square should appear in a window called “Drawing Tool”

Notes on compiling and running Java programs – and more vocabulary

o a programmer writes the text of a program using a software program called an editor

o the text of a program in a particular programming language is referred to as source

code o the source code is stored in a file called the source file…for the first example, source

code would be saved in a file named “DrawSquare.java”

o the Java compiler converts source code written in Java into the bytecode language

the Java interpreter understands…for the first example, the Java compiler will create

a bytecode file named “DrawSquare.class”

o errors detected by the compiler are called compilation errors…usually violation of

various Java language syntax rules that programmers must follow

Page 6: Java Notes

9/7/2009

o when you run a Java program, the Java interpreter processes the bytecode file and

executes the instructions in it.

o if an error occurs while running the program, the interpreter will catch it and stop its

execution…such errors detected by the interpreter are called run-time errors

Lesson A2 notes: Object-Oriented Programming

Our First Java Application

o in lesson 1 we encountered a Java program called the DrawSquare class

o includes following two methods DrawSquare(): named exactly the same as the class…used to construct new

instances of this class…calls SketchPad‟s constructor to create a new

SketchPad object named myPaper with an initial size of 300 by 300 pixels…

calls DrawingTool constructor to create a new DrawingTool object named myPencil

draw(): where most of action for this class takes place for actual drawing of square o we create what is called a driver or throwaway class for the purpose of testing DrawSquare.

public class driverClass

{

public static void main(String[] args)

{

DrawSquare sq = new DrawSquare();

sq.draw();

}

}

Program Components

o comments

helps programmer and other readers understand what is going on…not part of

actual code

three types

/*

Multi-line comment

For longer documentation notes

*/

// Single-line comment which starts at the slashes

// and stops at the end of the line

/** Java-doc comment…a special type of comment we will

discuss later

*/

o import statement to allow program to use predefined classes written by others so

programmer does not have to "reinvent the wheel"… in Java, these predefined classes are

grouped into packages…some come with Java and some are written by other programmers…

the package we have been using so far is called gpdraw which includes the

DrawingTool and SketchPad classes…they are imported using the statement:

import gpdraw.*;

Page 7: Java Notes

9/7/2009

o the driver class includes a main method o most classes contain methods to define a class‟s behavior…a method has the following

general syntax:

modifiers return_type method_name ( parameters )

{

method_body

}

o modifiers define access to methods (e.g. public, private)

o method_name is name of the method (e.g. draw) o return_type refers to the type of data a method returns, either one of predefined

types (e.g., int, double, char, String, etc.) or a user-defined class or void if

method does not return a value o parameters list allows us to send values to a method (e.g. 100) o method_body contains statements to accomplish the work of the method

Object Declaration, Creation, and Message Sending

o every object in a program must be declared using following syntax

class_name object_name

o class_name is name of class to which objects belong

o object_name is sequence of object names separated by commas o examples

DrawingTool myPencil;

Customer bob, betty, bill;

o no objects are actually created (or instantiated) by the declaration…calling a constructor

using the following syntax creates an object:

object_name = new class_name ( arguments ) ;

o object_name is name of declared object

o class_name is name of class to which object belongs o arguments is a sequence of zero or more values passed to the constructor o example

myPaper = new SketchPad(300, 300);

o after object is created, we can start sending messages to it using the following syntax:

object_name.method_name( arguments ) ;

o object_name is name of declared object o method_name is name of method of object. o arguments is a sequence of zero or more values passed to method. o example

myPencil.forward(100);

Page 8: Java Notes

9/7/2009

Class Diagrams o pictures are often helpful when designing software, such as the class diagram

Class Name:

DrawSquare

Attributes: SketchPad

DrawinfTool

Methods: DrawSquare()

draw()

o an attribute, or instance variable, represents a property of an object

o a method is an operation that can be performed upon an object

o this diagram is part of the Unified Modeling Language (UML), the most widely used

set of notations in today‟s software engineering industry

o “...” notation can be shown in a class diagram to indicate list of methods is

incomplete

o class diagrams frequently include labels within “<< >>” symbols to categorize class

methods (e.g. << constructor>>, << modifier>>)

The Difference Between Objects and Classes

o a class: o a blueprint that defines attributes and methods.

o written by a programmer.

o cannot be altered during program execution.

o named by a class name.

o an object:

o must belong to some class. o is an instance of that class.

o exists during the time that a program executes

o must be explicitly declared and constructed by the executing program

o has attributes that can change in value and methods that can execute during program

execution. (The class to which the object belongs defines theses attributes and

methods.)

o is most often referenced using an identifier.

Lesson A3 notes: Primitive Data Types

Introduction o Java allows two different types of attributes: objects and primitive data types

Identifiers in Java

o an identifier is a name that will be used to describe classes, methods, constants,

variables; anything a programmer is required to define

Page 9: Java Notes

9/7/2009

o rules for naming identifiers in Java:

o must begin with a letter.

o only letters, digits, or an underscore may follow the letter.

o the blank space cannot be used Identifiers

o cannot be reserved words already defined in Java such as new, class, etc.

o Java is a case sensitive language, so grade and Grade are different identifiers

o a good identifier should help describe the nature or purpose of whatever it is naming

o the following conventions are used throughout ICT curriculum guide

o single word identifier will be written in lower case only: grade

o class names will begin with upper case: DrawingTool

o if an identifier is made up of several words, all words beyond the first will begin with

upper case: passingScore, DrawHouse

o identifiers used as constants will be fully capitalized: PI

Primitive Data Types in Java o Java provides eight primitive data types: byte, short, int, long, float, double,

char, and Boolean

o byte, short, int, and long are for integers

o float and double are for real numbers (numbers with decimal places)

o AP Exam only requires you to know int, double, and boolean

o this curriculum will, from time to time, also use the char type when appropriate.

o int: integer…any positive or negative number without a decimal point…7…-23

o double: signed or unsigned number with a decimal point, but no commas… -

7.5…66.72…5…scientific notation such as 1.625e3 or 1.25e-4

o see lesson for bytes allocated as well as minimum and maximum values for each data type

o char: characters

o letters, digits 0 through 9, and punctuation symbols

o enclosed within single quotes such as 'A', 'a', '8', '*'

o stored as integers using ASCII (American Standard Code for Information

Interchange) codes…for example, ‟A‟ is stored as the number 65 and „K‟ as 75, so:

char letter = 'A';

int number = 75;

System.out.println(letter); // prints “A”

System.out.println((int)letter); // prints “65”

System.out.println((char)number); // prints “K”

note, the use of “(int)” is called casting…data type of variable is

converted to type in parentheses temporarily

o Java provides escape sequences for using unusual keystrokes on the keyboard such as

Newline („\n‟), Horizontal tab („\t‟), Backslash („\\‟), Single quote („\‟‟), Double

quote („\”‟) and Null character („\0‟) in a String literal, such as in a

System.out.println statement

o boolean: used to represent a single true/false value…ccan have only one of two values:

true or false

Declaring and Initializing Variables in Java o a variable must be declared before it can be initialized with a value, using following syntax

data_type variableName;

Page 10: Java Notes

9/7/2009

o examples:

int number = 4; // declared and initialized in one line

char ch; // just declared

int first = 5, second; // multiple variables declared on one line

double x;

boolean done;

int sum = first + second;

o variables can be declared in a class outside of any methods or inside of a method

Printing Variables Using the System.out Object

o the System.out object is automatically created in every Java program

o it has methods for displaying text strings and numbers in plain text format on the system

display, which is sometimes referred to as the “console.”

o examples:

int number = 5;

System.out.println("number = " + number); // displays number = 5

char letter = 'E';

System.out.println("letter = " + letter);

double average = 3.95;

System.out.println("average = " + average);

boolean done = false;

System.out.println("done = " + done); // displays done = false

System.out.print("The "); // does not skip to next line

System.out.println( 2 + 2); // Output: 4

System.out.println(“2 + 2”); //Output: 2 + 2

System.out.println(“2” + “2”); //Output: 22

o first System.out.println uses + operator to “add” a string (the literal "number = ") and

number (the int variable containing the number 5)…Java defines a version of the + operator

for String concatenation that enables a string and a value of another data type to be

concatenated (added)…result is new (and normally longer) String

Assignment Statements o an assignment statement has the following basic syntax:

variable = expression;

o assignment operator (=) assigns the value of the expression on the right to the variable and

returns the value of the expression o examples

a = 5;

b = 6 * a; a = b = 5;

primitiveValue = 18234;

myPencil = new DrawingTool();

o primitiveValue is a primitive type, so assignment statement puts data directly into

it, replacing previous value

Page 11: Java Notes

9/7/2009

o myPencil is an object reference variable (the only other possibility) so a reference to

object is put into that variable, replacing previous reference…object reference tells

program where to find an object…a variable will never actually contain an object,

only a reference to an object

Math Operators o Java provides 5 math operators as listed below:

+ Addition, as well as unary +

- Subtraction, as well as unary -

* Multiplication

/ Floating point and integer division

% Modulus, remainder of integer or floating point division

o numerical result and data type of answer depends on type of operands used

o if both operands are integers, result is an integer: 2 + 3 -> 5...11/2 -> 5

o If either of operands is a double type, result is a double: 25 / 6.75 -> 3.7037…the

integer is promoted to a double value, and then the math is executed

o modulus operator (%) returns the remainder of dividing the first operand by the second:

10 % 3 -> 1…27.475 % 7.22 -> 5.815

o changing the sign of a value can be accomplished with negation operator (-), often called

unary (-) operator. A unary operator works with only one value

o to obtain answer of 5.5 to a question like 11/2, must cast one of operands using following

syntax: (type) operand...such as (double)11/2

Precedence of Math Operators o precedence rules govern the order in which an expression is solved

Level of Precedence Operator Associativity

Highest unary - right to left

* / % left to right

Lowest + - left to right

o for example 2 + 3 * 6 -> 20 since * operator has priority over +

o associativity refers to order in which operators are applied if they have same precedence

level. The two possibilities are from left-to-right or right-to-left

o parentheses take priority over all the math operators so (5+6)/(9-7) -> 11/2 -> 5

Assignment Operators o the statement “number = number + 5;” is an example of an accumulation statement. The

old value of number is incremented by 5 and the new value is stored in number.

o above statement can be replaced as follows: number += 5;

o Java provides the following assignment operators: += -= *= /= %=

o precedence of the assignment operators is the lowest of all operators

Increment and Decrement Operators o incrementing or decrementing by one is a common task in programs

o can be accomplished by the statements: “n = n + 1;” or “n += 1;” or “n++” or “++n”

o Java also provides for a decrement operator, --, which decrements a value by one

Page 12: Java Notes

9/7/2009

o statement “b = ++a” uses pre-increment operator to increment value of a and return new

value of a

o statement “b = a++” uses post-increment operator to return value of a and then increment a

by 1

Summary o at first it is necessary to memorize the above syntax of data types and their operations, but,

with time and practice, fluency will come

Lesson A4 notes: Object Behavior

Introduction o programs of any significant size should be broken down into smaller pieces

o classes can be used to create objects that will solve those smaller pieces

o we determine what behaviors these objects will perform; these behaviors are called methods

Writing Methods in Java o methods are what an object can actually do, such as “myPencil.forward(100);” in our

DrawingTool example

o we wrote our own methods (DrawSquare, draw) and we used methods from the DrawingTool

class (forward, turnLeft)

o remember the general syntax of a method from lesson 2

Parameters and Arguments o parameters and arguments are used to pass information to a method

o arguments are used when calling the method

o for example, in “myPencil.forward(100);” we tell the forward method how

far to move by passing an argument to it: int value 100

o turnLeft method will default to 90 degrees if we don‟t pass it a value…if we want it

to turn a different amount, we can send how far left we want it to turn in degrees such

as by saying “myPencil.turnLeft(60);”

o arguments can be either literal values (2, 3.5) or variables (a, x)

//These are equivalent calls

double db4 = doMath(5, 10); // example using literal values int a = 5;

int x = 10;

double db5 = doMath(a, x); // example using variables

o parameters are used when defining a method

o when defining a method, the list of parameters can contain multiple parameters:

o for example

public double doMath(int a, double x)

{

... code ...

return doubleVal;

}

Page 13: Java Notes

9/7/2009

when this method is called, arguments fed to doMath method must be correct

type and in same order. First argument must be int. Second argument can be

double or int (since int will automatically be converted by Java)

double dbl = doMath(2, 3.5); // this is okay

double db2 = doMath(2, 3); // this is okay

double db3 = doMath(1.05, 6.37); // this will not compile

o when method is called with an argument, parameter receives value of argument

if data type is primitive, we can change value of parameter within method as

much as we want and not change value of argument passed in method call

object variables, however, are references to object‟s physical location.

Therefore, when we use reference to access object within method, we have

ability to directly change the object. This can get very messy if the

programmer doesn‟t realize what is going on

Returning Values o sometimes we want a method to return a value

o in order for a method to return a value, there must be a return statement somewhere in body

of method.

o you must also declare which type of data value will be returned in the method declaration.

This can be any primitive data type, a Java class, or any class that you have defined yourself.

public int getNumber()

{

int myNumber = 1234;

return myNumber;

}

o if a method returns no value, the keyword void should be used. For example:

public void printHello()

{

System.out.println("Hello world");

}

The Signature of a Method o in order to call a method legally, you need to know its name, how many parameters it has, the

type of each parameter, and the order of those parameters. This information is called the

method's signature. The signature of the method doMath can be expressed as:

doMath(int, double)

o signature does not include names of parameters; if you want to use method, you

don't need to know what parameter names are

o Java allows two different methods in same class to have same name, provided their signatures

are different. We say that name of the method is overloaded because it has different

meanings. The Java compiler can tell which one you want to call by the number and types of

arguments that you provide in call statement. For example with DrawingTool class

turnLeft()

turnLeft(120)

Page 14: Java Notes

9/7/2009

o it is illegal to have two methods in same class that have same signature but different return

types. For example:

double doMath(int a, double x){} int doMath(int a, double x){}

Lifetime, Initialization, and Scope of Variables o three categories of Java variables have been explained thus far in these lessons. instance

variables, local variables, and parameters

o lifetime of a variable defines portion of runtime during which variable exists

o when an object is constructed, all its instance variables are created. As long as any

part of program can access object, it stays alive

o a local variable is created when program executes statement that defines it. It stays

alive until block that encloses variable definition is exited

o when a method is called, its parameters are created. They stay alive until method

returns to caller

o type of variable determines its initial state

o instance variables are automatically initialized with a default value (0 for numbers,

false for boolean, null for objects)

o parameters are initialized with copies of arguments

o local variables are not initialized by default so an initial value must be supplied by

the programmer. The compiler will generate an error if an attempt is made to use a

local variable that may not have been initialized.

o scope refers to area of program in which an identifier is valid and has meaning

o instance variables are usually declared private and have class scope. Class scope

begins at the opening left brace ({) of the class definition and terminates at the

closing brace (}). Class scope enables methods to directly access all of its instance

variables

o scope of a local variable extends from the point of its definition to the end of the

enclosing block

o scope of a parameter is the entire body of its method

Getters/Setters o when you are first starting to program, some of the most commonly used methods are called

Getters and Setters

o Getter methods

o purpose is to provide others with current information about an object‟s attributes

o example: a “double getLength()” method which returns value of object‟s “length”

attribute

o storing “length” in a private instance variable prevents others from accessing length

directly, because they might alter that data when we don‟t want them to

o also called Accessors

o Setter methods

o purpose is to allow others to change an object‟s attributes

o example: a “void setLength(double d)” method which changes value of object‟s

“length” attribute

o often Setter methods are given a return type of boolean which will return true if the

value was valid and false if the value was not. This lets clients know if their value

was accepted or not.

o also called Mutators or Modifiers

Page 15: Java Notes

9/7/2009

Lesson A5 notes: Designing and Using Classes

Designing a Class o one of advantages of object-oriented design is that it allows a programmer to create a new

data type that is reusable in other situations o when designing a new class, three components must be identified – attributes, behaviors, and

constructors. Let‟s consider a checking account at a bank o the account would need to record such things as the account number, the current

balance, the type of checking account it is, etc (these are nouns). These would be the

attributes of the checking account o it would also need to be able to do certain actions, such as withdrawing or depositing

money (these are verbs). These would be the behaviors of the checking account o finally, the checking account object needs to be created in order to be used, so the

class must define how the creation process works. This is accomplished in the

constructors.

Implementation of a Class

o a possible implementation of such a CheckingAccount class is given below

public class CheckingAccount

{

private double myBalance;

private int myAccountNumber;

public CheckingAccount()

{

myBalance = 0.0;

myAccountNumber = 0;

}

public CheckingAccount(double initialBalance, int acctNum)

{

myBalance = initialBalance;

myAccountNumber = acctNum;

}

public double getBalance()

{

return myBalance;

}

public void deposit(double amount)

{

myBalance += amount;

}

public void withdraw( double amount )

{

myBalance -= amount;

}

}

Determining Object Behavior

Page 16: Java Notes

9/7/2009

o before you start programming, you need to understand how the objects of your class

behave. Possible behaviors for a checking account could be

accepting a deposit

withdrawing from the account

getting the current balance

o in Java, these behaviors are expressed as method calls such as the following:

checking.deposit(1000);

checking.withdraw(250);

System.out.println("Balance: " + checking.getBalance());

o to the calling program, an object of type CheckingAccount can be viewed as a “black box”

that can carry out its methods. The programming concept of not needing to know how things

are done internally is called abstraction

o once we understand what objects of the CheckingAccount class need to do, it is possible to

design a Java class that implements these behaviors. To describe object behavior, you first

need to implement a class and then implement methods within that class

o we could start by writing the following

public class CheckingAccount

{

// CheckingAccount data

// CheckingAccount constructors

// CheckingAccount methods

}

o next we add the three methods

public class CheckingAccount{

// CheckingAccount data

// CheckingAccount constructors

public void deposit( double amount ){

// method implementation

}

public void withdraw( double amount ){

// method implementation

}

public double getBalance(){

// method implementation

}

}

o what we have been doing here is not real code and wouldn‟t actually do anything. However,

it is useful to lay out what your class will look like. When we use a mixture of English and

Java to show what we are doing, it is called pseudocode

o next we can write out what methods will do with pseudocode so that it becomes easier to see

how everything will fit together. This process of starting with a very broad concept or outline

and working down to smaller and smaller details is called top-down design

public class CheckingAccount

{

Page 17: Java Notes

9/7/2009

// CheckingAccount data

// CheckingAccount constructors

public void deposit( double amount )

{

// receive amount of deposit and add it to current balance

}

public void withdraw( double amount )

{

// remove amount of withdrawal from current balance

}

public double getBalance()

{

// return current balance in a double value

}

}

o a method header consists of the following parts

access_specifier return_type method_name ( parameters )

o access_specifier controls where this method can be accessed from

“public” if method needs to be accessed by other objects

“private” if it should only be accessed within this object

o return_type is data type that method sends back

examples: int, double or DrawingTool

can be any primitive type or any object that your class knows about

void if method does not return a value o method_name needs to follow rules of identifiers and should indicate method‟s

purpose.

o list of parameters of the method such as “double amount”

parameters are the input to the method

the deposit and withdraw methods each have one parameter, the amount

of money to deposit or withdraw

type of parameter, such as double, and name for each parameter, such as

amount, must be specified

if a method has no parameters, like getBalance, it is still necessary to

supply a pair of parentheses () behind the method name.

Instance Variables o before any code can be written for behaviors, object must know how to store its current state

o state is set of attributes that describes object and influences how object reacts to method calls.

For checking account objects, state includes current balance and an account identifier.

o each object stores its state in one or more instance variables.

public class CheckingAccount

{

private double myBalance; // instance variable

private int myAccountNumber; // instance variable

// CheckingAccount constructors

Page 18: Java Notes

9/7/2009

// CheckingAccount methods

}

o an instance variable declaration consists of following parts:

access_specifier type variable_name

o access_specifier tells who can access that data member…generally declared

with access specifier private so they can be accessed only by methods of same

class

o type of variable (such as double).

o variable_name

o if instance variables are declared private, then all external data access must occur through the

non-private methods. This means that instance variables are hidden. The process of hiding

data is called encapsulation. For example, because myBalance instance variable is

private, it cannot be accessed from outside of the class, so:

double balance = checking.myBalance; // would generate compiler ERROR!

o however, the public getBalance method can be called to inquire about the balance:

double balance = checking.getBalance(); // OK

Implementing Methods

o once method header has been specified, implementation of method must be supplied in a

block that is delimited by braces {...} public void deposit(double amount){

myBalance += amount;

}

o syntax of a return statement is:

return expression;

or

return; // Exits the method without sending back a value

Constructors o final requirement to implement a class is to define one or more constructors, whose purpose

is to initialize values of instance variables of an object, such as

public CheckingAccount()

{

myBalance = 0.0;

myAccountNumber = 0;

}

o constructors always have same name as their class

o similar to methods, constructors are generally declared as public to enable any code

in another program to construct new objects of the class

o unlike methods, constructors do not have return types

Page 19: Java Notes

9/7/2009

o many classes define more than one constructor through overloading, such as

public CheckingAccount(double initialBalance, int acctNum)

{

myBalance = initialBalance;

myAccountNumber = acctNum;

}

o using constructors

o to construct objects of class, first it is necessary to declare an object variable, such as

CheckingAccount checking; // object‟s reference, the address of

object

o new operator allocates memory for object, returning reference to newly constructed

object.

checking = new CheckingAccount(); // to create object

o in most cases, declare and store reference to object on one line as follows:

CheckingAccount checking = new CheckingAccount();

o occasionally, it would be repetitive and unnecessary to create an object identifier:

DrawingTool pen = new DrawingTool(new SketchPad(500,500));

o notice that we never create an object identifier for the SketchPad object

Using Classes o using the CheckingAccount class is best demonstrated by writing a program that solves a

specific problem. We want to study the following scenario: an interest-bearing checking

account is created with a balance of $1,000. For two years in a row, add 2.5% interest. How

much money is in the account after two years?

o two classes are required

o CheckingAccount class that was developed above

o second class called CheckingTester. Main method of CheckingTester class

constructs a CheckingAccount object, adds interest twice, then prints out balance

class CheckingTester

{

public static void main(String[] args)

{

CheckingAccount checking = new CheckingAccount(1000.0, 123);

double INTEREST_RATE = 2.5;

double interest;

interest = checking.getBalance() * INTEREST_RATE / 100;

checking.deposit(interest);

System.out.println("Balance after year 1 is $"

+ checking.getBalance());

interest = checking.getBalance() * INTEREST_RATE / 100;

checking.deposit(interest);

System.out.println("Balance after year 2 is $"

+ checking.getBalance());

}

Page 20: Java Notes

9/7/2009

}

Lesson A6 notes: Libraries and APIs

Introduction o huge number of pre-made classes provided with Java o as a Java programmer, you want to avoid redoing work already done o this lesson covers

o how to read the APIs that come with those classes, and o how to write our own APIs so that other people can use our classes

Understanding APIs o API stands for Application Programming Interface

o APIs show exactly how to use pre-made classes

o lists classes and constructors…tells us what methods we can access, how to interact with

those methods, and what those methods will return back to us.

o does not tell us how class eas designed and programmed

o can access Java APIs on Web at java.sun.com…click on API Specifications on main page,

then choose version of Java…can also download APIs to your computer for offline

access…organized both by package and by class (packages are groups of related classes that

are “packaged” together)

o when you use the code “import gpdraw.*;”, you are adding the entire gpdraw package

to your code…if you only need a few classes from a package, you can add classes

individually with the code “import gpdraw.DrawingTool;”

Final and Static o keywords final and static frequently come up in API documentation

o final

o when used with a primitive data type, final means that value of variable will never

change

o useful in many cases, such as tax rates and math constants such as PI

o identifiers with final are generally made with only capital letters so they are easily

distinguishable from rest of code

o example: final double TAXRATE = 0.0825;

o you can initialize the value when the variable is declared or determine it at run time,

but once a final variable is given a value within a program, that value may never

change in that run

o using final values makes program easier to modify and reduces errors

o static

o using keyword static means that data member or method is attached to class rather

than to an object of class

o with a static method, you only need to type name of class followed by the name of

method, such as “int jason = Math.pow(3,4);”

o similar for a static data member…if one object changes value of a static variable,

then value is changed for all other objects of that type

o you never need to create a new object when dealing with static methods or data

members

DrawingTool

Page 21: Java Notes

9/7/2009

o for DrawingTool, Handout A1.1 gives an introduction to purpose of class and how to use its

various methods: name of method, type of arguments it takes, and what will happen after

method is called

o it was not the official Java format for an API, but it accomplished same thing

Point2D.Double o Point2D class is useful for storing locations on a two dimensional space

o whenever possible we want to avoid writing code that has already been written, so do a little

research to see if someone else has written code you can use

Random o java.util package is full of utility classes that you will find very useful

o java.util.Random is one of them…here is some information from its Javadoc…the word

“pseudorandom” just indicates that the number is not completely random

Constructor Summary

Random()

Creates a new random number generator.

Method Summary

double nextDouble()

Returns the next pseudorandom, uniformly distributed double value

between 0.0 and 1.0 from this random number generator's sequence.

int nextInt(int n) Returns a pseudorandom, uniformly distributed int value between 0

(inclusive) and the specified value (exclusive), drawn from this random number

generator's sequence.

o here is an example of some code:

Random chooser = new Random();

int winner = chooser.nextInt(200) + 1;

Math o Math class in the java.lang package contains class methods for commonly used

mathematical functions o Java loads the java.lang package automatically, so no special actions are required to

access these o here is some information from its Javadoc

java.lang Class Math

java.lang.Object

java.lang.Math

public final class Math

extends Object

Page 22: Java Notes

9/7/2009

Field Summary

static double E

The double value that is closer than any other to e, the base of the

natural logarithms.

static double PI

The double value that is closer than any other to pi, the ratio of the

circumference of a circle to its diameter.

Method Summary

static double abs(double a)

Returns the absolute value of a double value.

static int abs(int a)

Returns the absolute value of an int value.

static double pow(double a, double b)

Returns the value of the first argument raised to the power of the

second argument.

static double sqrt(double a)

Returns the correctly rounded positive square root of a double

value.

o there are over 30 other methods such as Math.sin…you can access them by going to

java.sun.com, clicking on API‟s, selecting a version of Java such as J2SE 1.5.0, and selecting

the Math class within the Java.lang package o here is an example using the Math class:

Math.abs(-25)

Javadoc Tool o basics of creating your own APIs are pretty simple o use tag /**…*/ before each class, variable, constructor, and method to create block comments o these comments work within your code in essentially same way as regular block comment tag

/*…*/ o however, when we run the Javadoc tool, APIs will be created based on these comments o the first line of each comment should be a quick description o rest of comment should consist of a more detailed description

o when you run “javadoc.exe” program on your Java class file (as discussed in Handout A6.1,

Javadocs), it will create html files in local directory if you open up index.html with your Web browser, you will find yourself looking at an API created for your class

Lesson A7 notes: Simple IO

Introduction o input and output is usually referred to as I/O

Page 23: Java Notes

9/7/2009

o many different ways a Java program can perform I/O…this lesson covers some very simple

ways

o Advanced Placement subset does not require that you know how to use any specific input and

output classes, only that you know how to use I/O in some manner

Reading Input with Scanner Class o some programs from preceding lessons have been written without any flexibility…to change

data values in programs, it is necessary to change variable initializations, recompile program,

and run it again

o sometimes prompting user for a value is more efficient and convenient

o accepting user input in Java can be complex…we will use Scanner class to make processing

input easier

o just as System class provides System.out for output, there is an object for input,

System.in; it does not directly support convenient methods for reading numbers and

strings, so Scanner class sits between System.in object and our program

o Scanner is part of java.util package, so we need to start off by adding Scanner class to our

import section.

import java.util.Scanner;

o next, we create a Scanner object and pass System.in object to it

Scanner in = new Scanner(System.in);

o this tells Scanner to look at System.in object for all of its input (in Lesson A13,

Exceptions and File I/O, we will learn how to change object we pass to Scanner so we

can read data stored in text files)

o here are some examples:

int num1;

num1 = in.nextInt( ); // program pauses until an appropriate

value is entered on keyboard

double bigNum;

bigNum = in.nextDouble( );

boolean isTrue;

isTrue = in.nextBoolean( );

o whitespace (spaces, tabs, newline) separates input values…when reading values, whitespace

keystrokes are ignored

o when requesting data from user via keyboard, it is good programming practice to provide a

prompt such as:

System.out.print("Enter an integer --> ");

Multiple Line Stream Output Expressions o when length of an output statement exceeds one line of code, it can be broken up in several

different ways:

System.out.println("The sum of " + num1 + " and " + num2 +

" = " + (num1 + num2));

Page 24: Java Notes

9/7/2009

or

System.out.print("The sum of " + num1 + " and " + num2);

System.out.println( " = " + (num1 + num2));

but not

System.out.print("A long string constant must be broken

up into two separate quotes. This will NOT work.");

Formatting Output o to format, use printf()…it works similarly to print() and println() methods

o printf() method takes two arguments…first is formatting String, a special sequence of

characters that tells printf() how to display second argument…syntax is:

%[flags][width][.precision]conversion

o „%‟ tells printf method that formatting is coming…all formatted String constants

start with %...does not have to be first thing in String constant, just first part of any

formatted text.

o most important conversion tags are „s‟, „d‟, and „f‟.

Conversion

Tag

Usage Type Example

s String

literals

printf(“%s”, “Sam”)

d Ints printf(“%d”, 5182)

f Doubles printf(“%f”, 2.123456)

o precision…max # characters to print out when used with „s‟….# decimal places to

print out, rounded to the closest number, when used with „f‟, with default to six

places

System.out.printf(“%.2s”, “Hello”) -> He

System.out.printf(“%.10s”, “Hello”) -> Hello

System.out.printf(“%.4f”, Math.PI) -> 3.1416

System.out.printf(“%f”, Math.PI) -> 3.141593

o width: min # characters to print out…for creating right-aligned lists…“Prices:”

and “Prices:\n” are two different sizes…for left-aligned, add „-„ to left of width

value

System.out.printf(“%-10s”, “Name:”);

System.out.printf(“%11s”, “Price:\n”); // 11 to adjust for /n error

System.out.printf(“%-10s”, “Soda”);

System.out.printf(“%10.2f”, 10.25);

System.out.println(); // since numeric cannot use special characters

System.out.printf(“%-10s”, “Candy”);

System.out.printf(“%10.2f”, 1.50);

Run Output:

Name: Price:

Soda 10.25

Candy 1.50

Page 25: Java Notes

9/7/2009

o flags: „+‟ for positive or negative sign…„(‟ cause negative numbers to be enclosed

with parentheses…„,‟ add commas…to get a dollar sign before printed value, place

„$‟ before „%‟

System.out.printf(“%,d”, 12345678) ->

12,345,678

System.out.printf(“$%,d”, 12345678) ->

$12,345,678

System.out.printf(“%,(d”, -12345678) ->

(12,345,678)

o can put multiple arguments in one call to printf()…put multiple formatting Strings in

first argument, then add additional arguments separated by commas.

double mySum = 123.456

System.out.printf(“%10s %10.2f”, “Total:”,

mySum);

o this curriculum uses just a few of many things printf() is capable of…look at

API for Formatter class for more information on formatting Strings.

Lesson A8 notes: Control Structures

Introduction

o most basic control structures are if, if-else, and switch statements

Structured Programming

o in early days of programming (1960's), the approach to writing software was relatively

primitive and ineffective…much of code was written with goto statements that transferred

program control to another line in the code…the term "spaghetti code" comes from trying to

trace code linked together with goto statements

o the complexity this added to code led to the development of structured programming:

o no goto statements are to be used in writing code

o all programs written in terms of three control structures: sequence, selection, iteration

o each control structure has one entrance point and one exit point, except for multiple exit

points from a control structure using break statement

o control structures may be stacked (sequenced) one after the other.

o control structures may be nested inside other control structures.

o control structures of Java encourage structured programming…staying within guidelines of

structured programming has led to great productivity gains in field of software engineering

Control Structures

o only three necessary control structures needed to write programs: sequence, selection, and

iteration

o sequence refers to line-by-line execution as used in your programs so far…program enters

sequence, does each step, and exits sequence

o selection allows choice among different paths…Java provides different levels of selection

• one-way selection with an if structure

• two-way selection with an if-else structure

Page 26: Java Notes

9/7/2009

• multiple selection with a switch structure

o iteration refers to looping…Java provides three loop structures discussed Lesson A12: • while loops

• do-while loops

• for loops

Algorithm Development and Pseudocode

o an algorithm is a solution to a problem such as "finding the average of two numbers"

o major task is conversion of rough designs into refined algorithms that be coded in language of

choice

o Pseudocode refers to a rough-draft outline of an answer, written in English-like

terms…generally uses phrases and words that are close to programming

languages…translation into code occurs more easily than if skipped pseudocode stage

o Stepwise refinement is the process of gradually developing a more detailed description of an

algorithm

Relational Operators

o a relational operator compares two values…following symbols used in Java as relational

operators:

< less than

> greater than

<= less than or equal to

>= greater than or equal to

== equal to

!= not equal to

o example:

number > 16 grade == 'F' passing >= 60

o result of relational expression is boolean value of either true or false. o when character data is compared, ASCII code values are used to determine answer

'A' < 'B' evaluates as true, (65 < 66)

'd' < 'a' evaluates as false, (100 < 97)

't' < 'X' evaluates as false, (116 < 88) since upper case letters come first in

ASCII

Logical Operators

o three logical operators in AP subset are AND, OR, and NOT, represented by following

symbols

AND &&

OR || (two vertical bars)

NOT !

o && (and) operator requires both operands (values) to be true for result to be true.

(true && true) -> true

(true && false) -> false

(false && true) -> false

(false && false) -> false

Page 27: Java Notes

9/7/2009

((2 < 3) && (3.5 > 3.0)) -> true

((1 == 0) && (2 != 3)) -> false

o && operator performs short-circuit evaluation in Java: if first operand in && statement

is false, operator immediately returns false without evaluating second half.

o || (or) operator requires only one operand (value) to be true for result to be true.

(true || true) -> true

(true || false) -> true

(false || true) -> true

(false || false) -> false

((2+3 < 10) || (19 > 21)) -> true

o || operator also performs short-circuit evaluation in Java: if first half of ||

statement is true, operator immediately returns true without evaluating the second

half

o ! operator is a unary operator that changes a boolean value to its opposite

(! true == false) -> true

!(2 < 3) -> false

Precedence and Associativity of Operators

o abbreviated precedence chart:

Operator Associativity

! unary - ++ -- right to left

* / % left to right

+ - left to right

< <= > >= left to right

== != left to right

&& (and) left to right

|| (or) left to right

= += -= *= /= right to left

o parentheses not needed, but can be used to make complex expressions more readable

((2 + 3 < 10) && (75 % 12 != 12)) // easier to read (2 + 3 < 10 && 75 % 12 != 12) // harder to read

if-else Statements o general syntax of the if statement is as follows:

if (expression)

{

statement1;

}

o if expression evaluates to true, statement1 is executed…if expression is false, nothing is

executed and program execution picks up after ending curly brace (})

o following diagram shows flow of control:

Page 28: Java Notes

9/7/2009

o to provide for two-way selection, an if statement may add an else option.

if (expression)

{

statement1;

}

else

{

statement2;

}

o if expression evaluates to true, statement1 is executed…if false, statement2 would be

executed

o following diagram shows flow of control

o expression being tested must always be placed in parentheses

Compound Statements

o statement executed in a control structure can be a block of statements, grouped together into a

single compound statement

o created by enclosing any number of single statements by braces as shown in following

example:

if (expression){

statement1;

statement2;

statement3;

}else{

statement4;

statement5;

Page 29: Java Notes

9/7/2009

statement6;

}

Nested if-else Statements

o statement inside of if or else option can be another if-else statement

o known as nested if-else constructions

o example:

if (expression1)

{

if (expression2)

{

statement1;

}

else

{

statement2;

}

}

else

{

statement3;

}

o braces need to be correct to ensure ifs and elses get paired with their partners

o above example has three possible different outcomes as shown in the following chart:

expression 1 expression2 statement executed

true true statement1

true false statement2

false not tested statement3

o braces not needed for if and if-else structures with only one statement, but safer to always use

braces

o another alternative makes use of the && operator, which is slightly easier to read.

if (expression1 && expression2)

{

statement1;

}

o example determining type of triangle given three sides A, B, and C.

if ( (A == B) && (B == C) )

System.out.println("Equilateral triangle");

else if ( (A == B) || (B == C) || (A == C) )

System.out.println("Isosceles triangle");

else

System.out.println("Scalene triangle");

Boolean Identifiers

o can use boolean variables to write code that is easier to read such as

Instead of

if(done == true)

{

System.out.println("We are done!");

Page 30: Java Notes

9/7/2009

}

we can write

if(done)

{

System.out.println("We are done!");

}

o second version is less dangerous, because if you make a mistake and only put “=” instead of

“= =”, Java will not catch that and interprets statement as assignment

Switch Statements (optional)

o AP exam does not test on switch statement, but it is a very useful tool o general form of switch statement is:

switch (expression)

{

case value1:

statement1;

statement2;

...

break;

case value2:

statement3;

statement4;

...

break;

case valuen: //any number of case statement may be used

statement;

statement;

break;

default:

statement;

statement;

break;

} // end of switch statement

o flow of control of switch statement is illustrated below

Page 31: Java Notes

9/7/2009

o switch statement attempts to match value of expression with one of case values

o if match occurs, all statements past case value are executed until a break statement is

encountered

o break statement causes program control to jump to end of switch statement

o if break statement is omitted, all statements following matching case value are executed

o if it is possible that none of case statements will be true, can add default statement at end of

switch…this will only execute if none of case statements are ctrue

o example for printing work day of week, where “day” is an integer variable

switch (day)

{

case 1: System.out.println ("Monday"); break;

case 2: System.out.println ("Tuesday"); break;

case 3: System.out.println ("Wednesday"); break;

case 4: System.out.println ("Thursday"); break;

case 5: System.out.println ("Friday"); break;

default: System.out.println ("not a valid day"); break;

}

o example using character variable

if (('a' <= letter) && (letter <= 'z'))

{

switch (letter)

Page 32: Java Notes

9/7/2009

{

case 'a' : case 'e' : case 'i' : case 'o' : case 'u' :

vowel++;

break;

default :

consonant++;

break;

}

}

o note above that multiple case values can lead to one set of statements

o it is good programming practice to include a break statement at end of switch structure

o switch statement cannot compare double values

Lesson A9 notes: Recursion

Recursion

o a problem solving technique that can turn long and difficult solutions into compact

and elegant answers

o recursion occurs when a method calls itself to solve another version of same problem

o with each recursive call, problem becomes simpler and moves towards a base case

o base case is when solution can be calculated without another recursive call.

o recursion involves internal use of a stack…a stack is a data abstraction that works like

this…new data is "pushed," or added to top of stack…when information is removed

from stack it is "popped," or removed from top of stack

o problem of computing factorials is our first example of recursion…illustrated below.

1! = 1

2! = 2 * 1 or 2 * 1!

3! = 3 * 2 * 1 or 3 * 2!

4! = 4 * 3 * 2 *1 or 4 * 3!

o notice that each successive line can be solved in terms of previous line

o a recursive method to solve factorial problem is given below…notice recursive call in

last line of method…method calls another implementation of itself to solve a smaller

version of problem.

int fact(int n){

// returns the value of n!

// precondition: n >= 1

if (n == 1){

return 1;

}else{

return n * fact(n - 1);

}

}

o base case is a fundamental situation where no further problem solving is

necessary…in case of finding factorials, 1! is by definition 1…no further work is

needed

o each recursive method must have at least one base case.

Page 33: Java Notes

9/7/2009

o suppose we call method to solve fact(4). This will result in four calls of method

fact.

fact(4): not base case, so return result of 4 * fact(3)…multiplication

not carried out until answer is found for fact(3)…second call of fact

to solve fact(3)

fact(3): again, not base case so return 3 * fact (2)…leads to another

recursive call to solve fact(2)

fact(2): still not the base case, so solve 2 * fact(1)

fact(1): finally reach base case, which returns the value 1

o when recursive call is made, current computation is temporarily suspended and placed

on stack with all its current information available for later use.

o a completely new copy of method is used to evaluate recursive call…when that is

completed, value returned by recursive call is used to complete suspended

computation…suspended computation is removed from stack and its work now

proceeds

o when base case is encountered, recursion will now unwind and result in a final

answer

o diagram below shows what happens:

fa c t (4 )

4 * fa c t (3 )

fa c t (3 )

3 * fa c t (2 )

fa c t (2 )

2 * fa c t (1 )

fa c t (1 )

1

2

6

fa c t (4 ) 2 4

o each box represents a call of method fact

Pitfalls of Recursion

o if recursion never reaches base case, recursive calls will continue until computer runs

out of memory and program crashes

o message “stack overflow error” or “heap storage exhaustion” indicates a possible

runaway recursion.

Page 34: Java Notes

9/7/2009

o when programming recursively, make sure algorithm is moving toward base

case…each successive call of algorithm must be solving a version of problem that is

closer to base case

Lesson A10 notes: Strings

Introduction

o strings are needed in many programming tasks…much of information that identifies a

person must be stored as a string: name, address, city, social security number, etc.

o this lesson covers specifications of String class and how to use it

o use String class without knowing its inner details, an excellent example of data

type abstraction

String Class

o groups of characters in Java are not represented by primitive types as are int or char

o strings are objects of String class

o defined in java.lang.String and automatically imported for use in every program

you write

o so far, our experience with Strings has been with String literals, consisting of any

sequence of characters enclosed within double quotation marks:

"This is a string"

"\tHello World!\n"

o characters in a String object can include escape sequences such as tab (\t) and

linefeed (\n)

o also, String class supports "+" operator to concatenate two String expressions:

sentence = "I " + "want " + "to be a " + "Java programmer.";

o "+" operator can be used to combine a String expression with any other expression

of primitive type…when this occurs, primitive expression is converted to a String

representation and concatenated with string…to invoke concatenation, at least one of

the items must be a String

PI = 3.14159;

System.out.println("The value of PI is " + PI);

String Constructors

o because Strings are objects, can create a String object by using keyword new and a

String constructor method:

String name = new String();

String name2 = new String(“Nancy”);

o though they are not primitive types, strings are so important and frequently used that

Java provides additional syntax for declaration:

String aGreeting = "Hello world";

Page 35: Java Notes

9/7/2009

o a String created in this short-cut way is called a String literal…only Strings have

shortcut like this…all other objects are constructed using new operator…many new

Java programmers get confused because of this shortcut and believe that Strings

are primitive data types

Object References

o whenever new operator is used, a new object is created…each time an object is

created, there is a reference to where it is stored in memory…reference can be saved

in a variable…reference is used to find the object

o it is possible to store another object reference in a variable:

String str;

str = new String("first string");

System.out.println(str);

str = new String("second string");

System.out.println(str);

Run Output:

first string

second string

o in example above, variable str is used to store a reference to String “first string”…in

second part of example, a reference to String “second string” is stored in variable str…it

replaces previous reference

o if a reference to an object is no longer being used, then there is no way to find it…while a

program is running, a part of the Java system called the "garbage collector" reclaims each lost

object (the "garbage") so that the memory is available again. In the above example, the

String object “first string” becomes garbage

o multiple objects of the same class can be maintained by creating unique reference

variables for each object.

String strA; // reference to the first object

String strB; // reference to the second object

o different reference variables that refer to same object are called aliases… there are

two names for same object:

strB = strA; // copy the reference to strB

o assignment operator copies information that is in strA to strB…it does not make a copy of

object

null Value

o a reference variable sometimes does not refer to an object

o do this by assigning null to variable

o value null is a special value that means "no object"

String b = null; // variable b refers to no object

if (b != null) System.out.println(b); // println(b) is skipped

Page 36: Java Notes

9/7/2009

String Query Methods

int len = str1.length(); // returns # of characters in String object.

char ch = str1.charAt(0); // extract character from within String object

// parameter specifies position of desired character

// 0 for the leftmost character,

// 1 for the second from the left, etc.

// example: System.out.println(str1.charAt(2));

int n = str2.indexOf("World");// find first occurrence of “World” within str2

// return index of the first character

// if str does not occur, return -1.

int n = str2.indexOf('!'); // identical except looking for single character

String Translation Methods

String toLowerCase(); // returns String with same characters as String object,

// but with all characters converted to lowercase

String toUpperCase(); // returns String with same characters as String object,

// but with all characters converted to uppercase

String trim(); // returns String with same characters as String object,

// but with leading and trailing whitespace removed

String substring(int beginIndex) // returns substring of String object

// starting from beginIndex through

// to end of String object

String substring(int beginIndex, int endIndex)

// returns substring of String object starting from

// beginIndex through, but not including, position

// endIndex of String object

Immutability of Strings

o immutability of Strings means you cannot modify any String object

o method toLowerCase returns a new String

String greeting = "Hi World!";

greeting.toLowerCase();

System.out.println(greeting); // run output “Hi World!”

o object greeting did not change…to change value of greeting, assign return value to

object greeting.

greeting = greeting.toLowerCase();

System.out.println(greeting); // run output “hi world!”

Comparing Strings o boolean equals(String anotherString);

o evaluates contents of two String objects to determine if they are equivalent

o returns true if objects have identical contents

String aName = "Mat";

String anotherName = new String("Mat");

Page 37: Java Notes

9/7/2009

if (aName.equals(anotherName)) System.out.println("Name's the

same");

if (aName.equals("Mat")) System.out.println("Name's the same");

o the == operator can create some confusion when comparing objects

o == operator will check reference value, or address, where object is

being stored

o will not compare data members of the objects

o because Strings are objects and not primitive data types, Strings

cannot be compared with the == operator

o boolean equalsIgnoreCase(String anotherString);

o similar to the equals() method, but ignores case

String aName = "Mat";

if (aName.equalsIgnoreCase("MAT"))

System.out.println("the same");

o int compareTo(String anotherString)

o compares calling String object and String argument to see which comes

first

o lexicographic ordering is same as alphabetical ordering when both strings are

all uppercase or all lowercase

o if calling string is first lexicographically, it returns a negative value

o if two strings are equal, it returns zero

o if argument string comes first lexicographically, it returns a positive number.

String aName = "Mat"

n = aName.compareTo("Rob"); // n < 0

n = aName.compareTo("Mat"); //

n = aName.compareTo("Amy"); // n > 0

Strings and Characters

o natural to think of a char as a String of length 1

o in Java char and String types are incompatible since a String is an object and a

char is a primitive type

o extracting a char from within a String can be accomplished using charAt method

o concatenating any char with an empty string (String of length zero) results in a

string that consists of that char

char myChar = „X‟;

String myString = "" + myChar;

System.out.println(myString); // X

char anotherChar = „Y‟;

myString += anotherChar;

System.out.println(myString); // XY

toString method

o wouldn‟t it be nice to be able to output objects that you have made using simple line

System.out.print(Object name), without having to do a lot of System.out.print

statements

Page 38: Java Notes

9/7/2009

o can create a toString method in any of your classes…within toString() method, format

your class variables into one String object and return that String

public String toString()

{

String a = “Sides: ” + getSides();

a += “ Length: ” + getLength();

a += “ Area: ” + getArea();

return a;

}

RegularPolygon square = new RegularPolygon(4, 10);

System.out.println(square); // prints “Sides: 4 Length: 10 Area: 100”

o provides a quick way to look at state of your objects

String I/O

o Scanner class has two methods for reading textual input from keyboard

o next method

o returns reference to String object that has from zero to many characters typed

by user at keyboard

o String will end whenever it reaches white space: blank spaces, tabs,

newline characters

o nextLine method

o returns reference to String object that contains zero to many characters

entered by user

o String object may contain blank spaces and tabs but will end when it

reaches newline character

o nextLine reads in whole lines of input rather than only one word at a time

o an example:

Scanner keyboard = new Scanner(System.in);

String word1, word2, anotherLine;

System.out.print("Enter a line: ");

word1 = keyboard.next();

word2 = keyboard.next();

anotherLine = keyboard.nextLine(); //skip to the next line

anotherLine = keyboard.nextLine(); //grab all of the next line

System.out.println("word1 = " + word1);

System.out.println("word2 = " + word2);

System.out.println("anotherLine = " + anotherLine);

Run Output:

Enter a line: Hello World! This will be discarded.

Enter another line: This line includes whitespace.

word1 = Hello

word2 = World!

anotherLine = This line includes whitespace.

o formatting Strings is done with same style as using printf() method:

import java.util.Formatter; // need to import Formatter class

Formatter f = new Formatter();

f.format("%10s","Bob");

Page 39: Java Notes

9/7/2009

String bob = f.toString(); // creates altered string variable

System.out.println(bob.length()); // prints 10

System.out.println(bob); // prints ”Bob”

Lesson A11 notes: Inheritance Introduction o inheritance is a major component of OOP

o primary tool for reusing your own and standard library classes

o allows you to define a very general class and then later define more specialized classes based

upon it

o do this by adding new capabilities to existing class definitions or changing way existing

methods work

o inheritance saves work because the more specialized class inherits all the properties of the

general class and you, the programmer, only need to program the new features

o with the size and complexity of modern programs, reusing code is the only way to write

successful programs in a reasonable amount of time.

Single Inheritance

o inheritance enables you to define a new class based on a class that already exists

o new class inherits characteristics of existing class, but may also provide additional

capabilities

o this makes programming easier, because you can reuse and extend your previous

work and avoid duplication of code.

o class used as basis for defining new class is called superclass (or parent class or base class)

o new class based on superclass is called subclass (or child class or derived class)

o process by which subclass inherits characteristics from just one parent class is called single

inheritance

o some languages allow a derived class to inherit from more than one parent class in a

process called multiple inheritance…difficult to determine which class contributes

what characteristics to child class…Java avoids these issues by only providing

support for single inheritance

o example: person as superclass and student as subclass…"a Student is a Person", called

an “is a” relationship

Class Hierarchies

o in a class hierarchy, each class has at most one superclass, but might have several subclasses

o class at top of hierarchy has no superclass, sometimes called root of hierarchy

o example: Principal is a Person, Student is a Person, Teacher is a Person, both

HighSchoolStudent and CollegeStudent are types of Student. o in Java, syntax for deriving a child class from a parent class is:

class subclass extends superclass{

// new characteristics of subclass go here

}

o several classes are often subclasses of same class…a subclass may in turn become parent

class for a new subclass…this means that inheritance can extend over several "generations"

of classes…for example, HighSchoolStudent is subclass of Student, which is subclass

of Person class …HighSchoolStudent is considered to be a subclass of Person class

Page 40: Java Notes

9/7/2009

o in Java, every class that does not specifically extend another class is a subclass of class

Object…for example, Person class extends class Object

o class Object has a small number of methods that make sense for all objects, such as

toString method, but class Object‟s implementations of these methods are not very

useful and the implementations usually get redefined in classes lower in hierarchy.

Using Inheritance

o following program uses class Person to represent people you might find at a

school…Person class has basic information in it, such as name, age and gender…an

additional class, Student, is created that is similar to Person, but has Id number and grade

point average of student.

public class Person

{

private String myName ; // name of person

private int myAge; // person's age

private String myGender; // "M" for male, "F" for female

// constructor

public Person(String name, int age, String gender)

{

myName = name;

myAge = age;

myGender = gender;

}

public String getName()

{

return myName;

}

public int getAge()

{

return myAge;

}

public String getGender()

{

return myGender;

}

public void setName(String name)

{

myName = name;

}

public void setAge(int age)

{

myAge = age;

}

public void setGender(String gender)

{

myGender = gender;

}

public String toString()

{

return myName + “, age: “ + myAge + “, gender: “ + myGender;

}

Page 41: Java Notes

9/7/2009

}

//-----------------End of Person Class-----------------//

public class Student extends Person

{

private String myIdNum; // Student Id Number

private double myGPA; // grade point average

// constructor

public Student(String name, int age, String gender,

String idNum, double gpa)

{

// use the super class' constructor

super(name, age, gender);

// initialize what's new to Student

myIdNum = idNum;

myGPA = gpa;

}

public String getIdNum()

{

return myIdNum;

}

public double getGPA()

{

return myGPA;

}

public void setIdNum(String idNum)

{

myIdNum = idNum;

}

public void setGPA(double gpa)

{

myGPA = gpa;

}

}

//-----------------End of Student Class-----------------//

public class HighSchool

{

public static void main (String args[])

{

Person bob = new Person("Coach Bob", 27, "M");

Student lynne = new Student("Lynne Brooke", 16, "F",

"HS95129", 3.5);

System.out.println(bob); // or

system.out.println(bob.toString());

System.out.println(lynne);//

}

}

//-----------------End of HighSchool Class-----------------//

Page 42: Java Notes

9/7/2009

o Student class is a derived class (subclass) of Person

o an object of type Student contains myIdNum and myGPA, which are defined in Student

o it also has indirect access to the private variables myName, myAge, and myGender from

Person through the methods getName(), getAge(), getGender(), setName(),

setAge(), and setGender() that it inherits from Person

o constructor for Student class

o statement super(name, age, gender) invokes Person class‟s constructor to

initialize inherited data in superclass…when super is used in a constructor, it must

be first statement.

o next two statements initialize data members that only Student has

o protected access modifier

o so far, we have only seen public and private access modifiers

public - class members that can be accessed outside class

private - class members that are inaccessible from outside class

o there is a third access modifier that can be applied to an instance variable or method

o if it is declared to be protected, then it can be used in class in which it is defined

and in any subclass of that class

o this declaration is less restrictive than private and more restrictive than public

o A.P. Java subset allows use of protected with methods but discourages its use for

instance variables…it is preferred that all instance variables are private…indirect

access from subclasses should be done with public "getter" and "setter" methods

o while protected members are available to provide a foundation for subclasses to

build on, they are still invisible to public at large.

Method Overriding

o a derived class can override a method from its base class by defining a replacement method

with same signature

o for example, in Student subclass, toString() method contained in Person

superclass does not reference new variables added to objects of type Student, so

nothing new is printed out…we need a new toString() method in class Student:

// overrides toString method in parent class

public String toString()

{

return getName() + ", age: " + getAge() + ", gender: "

+ getGender() + ", student id: " + myIdNum

+ ", gpa: " + myGPA;

}

o a more efficient alternative is to use super to invoke

toString() method from parent class while adding information

unique to Student subclass:

public String toString()

{

return super.toString() + ", student id: " + myIdNum

+ ", gpa: " + myGPA;

}

o even though base class has a toString() method, new definition of toString() in

derived class will override base class‟s version…base class has its method, and derived class

has its own method with same name:

Page 43: Java Notes

9/7/2009

Person bob = new Person("Coach Bob", 27, "M");

Student lynne = new Student("Lynne Brooke", 16, "F",

"HS95129", 3.5);

System.out.println(bob.toString()); // “Coach Bob, age: 27, gender:

M”

System.out.println(lynne.toString());

// “Lynne Brooke, age: 16, gender: F, student id: HS95129, gpa:

3.5”

o line bob.toString() calls toString() method defined in Person, and line

lynne.toString() calls toString() method defined in Student

Interfaces

o Person class defines attributes and behaviors of a person

o an employment program might need only salary and employee ID

o so, an Employable interface would define, but not implement, methods that set and get

salary, assign ID number, and so on

o Teacher class must agree to this protocol by implementing interface…to implement an

interface, a class must implement all of methods and attributes defined in interface

o in Java, an interface consists of a set of attributes and methods, without any associated

implementations…here is an example of a Java interface that defines behaviors of

“employability”:

public interface Employable

{

public double getSalary();

public String getEmployeeID();

public void setSalary(double salary);

public void setEmployeeID(String id);

}

o a class implements an interface by defining all the attributes and methods defined in interface

o implements is a reserved word

o for example:

public class Teacher implements Employable

{

...

public double getSalary() { return mySalary; }

public int getEmployeeID() { return myEmployeeID; }

public void setSalary(double salary) { mySalary = salary; }

public void setEmployeeID(String id) { myEmployeeID = id; }

}

o a class can implement any number of interfaces…a class can both extend another class and

implement one or more interfaces…so, we can have things like (assuming we have an

interface named Californian):

public class Teacher extends Person implements Employable, Californian{

...

}

o interfaces are useful for the following:

o declaring a common set of methods that one or more classes are required to

implement

Person

Principal Student Teacher

Employable

Page 44: Java Notes

9/7/2009

o providing access to an object's programming interface without revealing details of its

class.

o providing a relationship between dissimilar classes without imposing an unnatural

class relationship

o you are not likely to need to write your own interfaces until you get to the point of writing

fairly complex programs…however, there are a few interfaces that are used in important

ways in Java's standard packages…you'll learn about some of these standard interfaces in

future lessons

Lesson A12 notes: Iterations

Introduction

o solving problems on a computer often requires repetition of a block of code: reading in data

from a file, outputting to a file, adding numbers, etc

o Java provides three ways for repeating code: for loop, while loop, do-while loop

while Loop

o general form of a while statement is:

while (expression)

{

statement;

}

o boolean expression must be enclosed in parentheses ()

o statement executed by while loop can be simple statement, or compound statement with

braces {}.

o if the expression is true, statement is executed

o after execution of statement, program control returns to top of while construct

o statement will continue to be executed until expression evaluates to false

o following loop will print out integers from 1-10.

int number = 1; // initialize

while (number <= 10) // loop boundary condition

{

System.out.println(number);

number++; // increment/decrement

}

Page 45: Java Notes

9/7/2009

o above example has three key lines that need emphasis.

o must initialize loop control variable

o loop boundary conditional test (number <= 10) often source of error…correct

comparison (<, >, ==, <=, >=, !=) and boundary value correct...performing loop one

too many or one too few times is called Off By One Bug

o some type of increment/decrement or other statement so execution of loop eventually

ends

o possible for body of while loop to execute zero times

Loop Boundaries

o loop boundary is boolean expression that evaluates as true or false

o must eventually become false…when task of loop is done, loop boundary must

become false o variety of loop boundaries of which two will be discussed in this section:

o idea of attaining a certain count or limit, such as code above

o use of a sentinel value…while loop continues until a specific value is entered as

input:

Scanner in = new Scanner(System.in);

int total = 0;

int number;

while (true)

{

System.out.print ("Enter a number (0 to quit) --> ");

number = in.nextInt();

if (number == 0)

{

break;

}

else

{

total += number;

}

}

System.out.println("Total = " + total);

o because we don‟t know how many times we want loop to run, we simply declare boundary

condition as always true…loop will run until we tell it to stop with break command

o a similar construct to break statement is continue statement…when loop encounters

continue statement, every statement left to execute in that specific iteration is

ignored…loop will then go back to check its boundary condition like normal…can be useful

for ignoring special cases

Conditional Loop Strategies

o strategies that assist novice programmer in developing correct while loops

o problem to be solved is described first.

Problem statement:

A program will read integer test scores from keyboard until a negative

value is typed in. The program will drop lowest score from total and

print average of remaining scores.

o one strategy in designing a while loop is to think about following four sections of the loop:

Page 46: Java Notes

9/7/2009

o Initialization - variables will usually need to be initialized before you get into loop

o Loop boundary - must construct a Boolean expression that becomes false when

problem is done…most common source of error…be careful of off-by-one errors

o Contents of loop - where problem is solved…must provide opportunity to reach loop

boundary

o State of variables after loop - determine status of key variables used in loop,

perhaps by tracing the code on paper.

o solve problem by first developing pseudocode.

Pseudocode:

initialize total and count to 0

initialize smallest to Integer.MAX_VALUE

get first score

while score is not a negative value

increment total

increment count

change smallest if necessary

get next score

subtract smallest from total

calculate average

o now easy to develop working loop from this concise and easy to read pseudocode

o tracing code is best done in a chart or table format:

score score >= 0 total count smallest

undefined undefined 0 0 INT_MAX

65 true 65 1 65

23 true 88 2 23

81 true 169 3 23

17 true 186 4 17

45 true 231 5 17

-1 false

o when loop is terminated, key variables (total, score, and smallest) contain correct

answers.

for Loop

o for loop has same effect as while loop, but uses different format…general form is:

for (statement1; expression2; statement3)

{

statement4;

}

o for loop is typically set up as follows.

statement1 initializes loop variable

expression2 is boolean expression

statement3 alters key value, usually via increment/decrement statement

statement4 is task to be done during each iteration

Page 47: Java Notes

9/7/2009

o example used to print integers 1-10

for (int loop = 1; loop <= 10; loop++)

{

System.out.print(loop);

}

o flow of control in a for loop:

o after statement is executed, control passes to increment/decrement statement, then back to

Boolean condition.

o equivalent while loop:

int loop = 1;

while (loop <= 10)

{

System.out.print( loop);

loop++;

}

o for loop is appropriate when initialization value and number of iterations is known in

advance

o constructing a for loop is easier than a while loop because key structural parts of a loop

(initialization, loop boundary, and increment/decrement statement) are contained in one line

o while loop is more appropriate when boundary condition is tied to some input or changing

value

o a simple, but time-consuming error to find and fix is accidental use of a null statement.

for (loop = 1; loop <= 10; loop++); // note ″;″

System.out.print(loop);

o two basic options for variable: declared beforehand or declare and initial within for loop

itself

int number = 1;

for (; number <= 10; number++)

{

System.out.println(number);

}

For (int a = 1; a <= 10; a++)

{

System.out.println(a);

}

Page 48: Java Notes

9/7/2009

o blank statements within for loop are allowed

o several key differences

o number may be changed to any number desired during run of program

o scope of the variables number and a…value of number may be used after for

loop. But a was declared within or loop and thus will not be usable past end bracket

of for loop.

Nested Loops

o to nest loops means to place one loop inside of another loop

o statement of the outer loop will be another inner loop

o example to print rectangular grid of stars with 4 rows and 8 columns

for (int row = 1; row <= 4; row++)

{

for (int col=1; col <= 8; col++)

{

System.out.print("*");

}

System.out.println( );

}

o for each occurrence of outer row loop, inner col loop will print 8 stars, terminated by

newline character

o suppose we wanted to write a method that prints out following 7-line pattern of stars:

*******

******

*****

****

***

**

*

o here is an analysis of problem, line-by-line.

Line # # spaces # stars

1 0 7

2 1 6

3 2 5

...

7 6 1

L L - 1 N - L + 1

o for a picture of N lines, each line L will have (L-1) spaces and (N-L+1) stars

o pseudocode version of method.

A method to print a pattern of stars:

Print N lines of stars, each Line L consists of

(L-1) spaces

(N-L+1) stars

a line feed

o code for method.

Page 49: Java Notes

9/7/2009

void picture (int n)

{

int line, spaces, stars, loop;

for (line = 1; line <= n; line++)

{

spaces = line - 1;

for (loop = 1; loop <= spaces; loop++){

System.out.print (" "); // print a blank space

}

stars = n - line + 1;

for (loop = 1; loop <= stars; loop++)

{

System.out.print ("*");

}

System.out.println();

}

}

The do-while Loop (optional)

o there are situations where it is desirable to have loop execute at least once, and then evaluate

exit expression at end of loop

o do-while loop allows you to do a statement first, and then evaluate an exit condition

o general form of do-while loop:

do

{

statement;

} while (expression);

o flow of control

o following code will keep a running total of integers, terminated by a sentinel zero value.

int number, total = 0;

do

{

System.out.print("Enter an integer (0 to quit) --> ");

number = in.readInt();

total += number;

} while (number != 0);

Page 50: Java Notes

9/7/2009

o same strategies used to develop while loops apply to do-while loops…make sure you

think about initialization, loop boundary, contents of loop, and state of variables after loop

o key difference between while and do-while loop is location of the boundary condition

o because do-while loop has boundary condition at bottom, loop body must occur at least

once

Loop Invariants

o a loop invariant is an assertion about loop that is relevant to purpose of loop

o a precise statement, in terms of loop variables, of what is true before and after each iteration

of loop

o used to reason about programs formally and to prove their correctness without tracing all the

iterations through a loop

o if you can establish that an assertion is true the first time loop is evaluated as well as after

each iteration of loop body, then your assertion is a loop invariant

o consider following code segment…note that count! means factorial of count

int factorial (int num)

{

int product = 1;

int count = 0;

while (count < num) // invariant: product == count!

{

count += 1;

product *= count;

}

return product;

}

o each time that loop test is evaluated, value of variable product is always equal to (count)!

Lesson A13 notes: Exceptions and File IO

Introduction o Java provides an approach for dealing with errors that occur while program is running

o referred to as “exception-handling”

o word “exception” is meant to be more general than “error”

o exception-handling is used to keep a program running even though an error is

encountered that would normally stop program

o this lesson will explore file input and output (I/O) as an example of how exceptions

are used

Exceptions

o when a Java program performs an illegal operation, a special event known as an

exception occurs

o an exception represents a problem that compiler was unable to detect before

execution of program

o called a run-time error

Page 51: Java Notes

9/7/2009

o example of this would be dividing by zero…compiler often cannot tell before

program runs that a denominator would be zero at some later point and therefore

cannot give an error before program is run.

o an exception is an object that holds information about a run-time error

o programmer can choose to ignore exception, fix problem and continue processing, or

abort execution

o an error is when a program does not do what it was intended to do

o compile time errors occur when code entered into computer is not valid

o logic errors are when code compiles correctly but logic behind code is flawed

o run-time errors happen when Java realizes during execution that it cannot

perform operation.

o Java provides way for program to detect exception has occurred and execute

statements designed to deal with problem…process is called exception handling…if

you do not deal with exception, program will stop execution completely and send an

exception message to console

o cmmon exceptions include: o ArithmeticException o NullPointerException o ArrayIndexOutOfBoundsException

o ClassCastException o IOException

o for example, if you try to divide by zero, this causes an ArithmeticException

o in the code below, second println() statement will not execute because once

program reaches divide by zero, execution will be halted completely and a message

will be sent to console:

int numerator = 23;

int denominator = 0;

// the following line produces an ArithmeticException

System.out.println(numerator/denominator);

System.out.println(″This text will not print″);

o a NullPointerException occurs if you use a null reference where you need an

object reference:

String name = null;

// the following line produces a NullPointerException

int i = name.length();

System.out.println(″This text will not print″);

o since name has been declared to be reference to a String and has value null,

indicating that it is not referring to any String at this time, an attempt to call a

method within name, such as name.length(), will cause a NullPointerException

Handling Exceptions

o three ways of handling a possible exception occurrence (we say that the exception is

thrown)

Page 52: Java Notes

9/7/2009

o not dealing with exception at all…e.g. situations where programmer has

already taken steps to ensure that a denominator never becomes zero

o attempt to fix problem

o skip over the problem

o for latter two, programmer needs to catch any exception that may be thrown:

o to catch an exception, one must anticipate where the exception might occur

and enclose that code in a try block

o try block is followed by catch block that catches exception (if it occurs) and

performs desired action

o general form of try–catch statement:

try

{

try-block

}

catch (exception-type identifier)

{

catch-block

}

o try-block refers to a statement or series of statements that might throw an

exception…if no exception is thrown, all statements within try-block will be

executed…once exception is thrown, all of statements following exception in try-block

will be skipped

o catch-block refers to a statement or series of statements to be executed if exception

is thrown…a try block can be followed by more than one catch block…when an

exception is thrown inside a try block, first matching catch block will handle

exception

o exception-type specifies kind of exception object catch block should

handle…can be specific or general…i.e. IOException or just Exception…latter

will catch any exception

o identifier is arbitrary variable name used to refer to exception-type

object…any operations done on exception object or any methods called will use this

identifier

o example of try and catch:

int quotient, numerator = 23, denominator = 0;

try

{

quotient = numerator/denominator;

System.out.println("The answer is: " + quotient);

}

catch (ArithmeticException e)

{

System.out.println("Error: Division by zero");

}

o either way, program continues executing at next statement after catch block.

Exception Messages

o if program does not handle exception, it will stop program and produce message that

describes exception and where it happened…this information can be used to help

track down cause of problem.

Page 53: Java Notes

9/7/2009

o code below throws an ArithmeticException when program tries to divide by

zero…program crashes and prints out information about exception:

int numerator = 23, denominator = 0;

// following line produces an ArithmeticException

System.out.println(numerator/denominator);

System.out.println("This text will not print");

Run Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero

at DivideByZero.main(DivideByZero.java:10)

o first line of output tells which exception was thrown and why

o “DivideByZero.main” indicates exception occurred in main method of DivideByZero

class

o in parentheses, file name and line number are given so programmer can find where code

went wrong (in example above, exception occurred on line 10 of Java file,

DivideByZero.java)

o this is line where Java found problem, but actual cause of problem may be a line or two

ahead

o rest of output tells where exception occurred and is referred to as call stack trace

o in this case, there is only one line in call stack trace, but there could be several, depending

on where exception originated.

o when exceptions are handled by a program, it is possible to obtain information about

an exception by referring to the “exception object” that Java creates in response to an

exception condition…every exception object contains a String that can be accessed

using getMessage method as follows:

try

{

quotient = numerator/denominator;

System.out.println("The answer is: " + quotient);

}

catch (ArithmeticException e)

{

System.out.println(e.getMessage());

}

o if divide by zero error occurs, an exception is thrown and following message is displayed:

/ by zero

o printing value returned by getMessage can be useful in situations where unsure of

type of error or its cause.

o if exception is unknown by Java class, may need to import appropriate exception (just

like you would import any other class you wanted your class to know about)…for

example, ArithmeticException is standard Java class and no import statement

is needed for it, but IOException is part of java.io package and must therefore

be imported before it is used

Throwing Exceptions

o there are times when it makes sense for program to deliberately throw an

exception…when program discovers some sort of exception or error condition, but

Page 54: Java Notes

9/7/2009

there is no reasonable way to handle error at point where problem is

discovered…program can throw an exception in hope that some other part of program

will catch and handle exception

o to throw an exception, use throw statement…syntax of throw statement is:

throw exception-object;

o example:

if (number == 0)

{

throw new ArithmeticException("Division by zero");

}

o exception object is created with new operator right in throw statement…exception

classes in Java have default constructor that takes no arguments and a constructor that

takes a single String argument…if provided, this String appears in exception

message when exception occurs

Reading From a File

o reading textual data from a file is similar to reading input from keyboard

o Scanner class and its methods remain same

o must also import classes java.io.File and java.io.IOException

o way you use Scanner class constructor changes

o java.io.File is a “holder” class that can take a String representing path to a

file on your computer…creating a Scanner object that reads from a file:

Scanner in = new Scanner(new File(“test.txt”));

File f = new File(“C:\MyDocuments\Java\tester.txt”);

Scanner in2 = new Scanner(f);

o first line assumes there is file named “test.txt” in directory or folder where you

run java files

o second line shows an example of creating File object in its own line of code

o it also shows File being created with full path to file…this would be used if text

file was not in same directory as your Java files

o what happens if file you are looking for doesn‟t exist or has some other status that

prevents it from being read?...this causes an exception to be thrown…Scanner will

take no responsibility in handling exception, so every time that you want to use

Scanner with a file, you will have to use a try-catch block…a full example is shown

below:

Scanner in;

try

{

in = new Scanner(new File(“test.txt”));

String test = in.nextLine();

System.out.println(test);

}

catch (IOException i)

{

System.out.println(“Error: “ + i.getMessage());

Page 55: Java Notes

9/7/2009

}

o when reading large amount of data from a file, often useful to know whether there is

any more data in file to read

o reading from a file which has no more data will give you a

NoSuchElementException and stop your program

o Scanner class has several methods for determining if there is any more data in file

to be read: hasNext(), hasNextDouble(), and hasNextInt() will be

the methods most useful for you

o if there is anything still to come, hasNext() will return true, while

hasNextDouble() will return true only if a valid double is next and

hasNextInt() will return true only if an int value is next

o using a simple while loop, you can easily read in data until end of file

while (in.hasNext())

{

System.out.println(in.next());

}

Writing to a File

o creating your own files is a little bit trickier than reading from them

o two basic ways to write data to files: raw bytes and character streams…raw byte

writing is useful for items such as pictures…character streams are used for writing

plain text…this curriculum will focus only on character streams

o this curriculum uses the java.io.FileWriter class…has two basic constructors:

FileWriter file = new FileWriter(“test.txt”);

FileWriter file2 = new FileWriter(“test2.txt”, true);

o first constructor opens a basic FileWriter object that points at file "test.txt" in

same directory where Java files are being run…when this file is first opened and

written to, all of data previously stored in file will be erased

o second constructor indicates that new data being sent to file will be appended to

end of the file

o in either case, if file does not exist, Java will attempt to create new file with

indicated name and at indicated location.

o writing data to file is done by using FileWriter.write(String, int, int)

method…the String is data that will be written to file…first int is where to start

writing data in String…second int indicates how many characters of String to

actually write…example:

String one = “#Hello!!!”;

FileWriter out = new FileWriter(“test.txt”);

out.write(one, 1, 5); // will write only “Hello” to file “test.txt.”

o merely opening a file and writing to it is not enough to store your data in most

cases…if you don‟t save your work in a word processor, your work will not be there

the next time you start up your computer…data must be saved with FileWriter by

Page 56: Java Notes

9/7/2009

calling close() method when you are done writing …this “closes” the output stream to

file and saves your data

out.write(one, 1, 5);

out.close();

o what if there is some error in opening file?...an exception is thrown and it must be

dealt with

String one = “Hello World!!!”;

FileWriter out;

try

{

out = new FileWriter(“test.txt”);

out.write(one, 0, one.length());

out.close();

}

catch(IOException i)

{

System.out.println(“Error: “ + i.getMessage());

}

o no equivalent to println() with FileWriter class, so newlines done with

„\n‟ character.

o FileWriter only writes Strings to text files, but can change other data types to Strings.

String temp;

int a = 5;

temp = “” + a + “\n”;

out.write(temp, 0, temp.length());

double p = 3.14;

temp = “” + p + “\n”;

out.write(temp, 0, temp.length());

boolean test = true;

temp = “” + test + “\n”;

out.write(temp, 0, temp.length());

o since FileWriter requires you to specify how many characters of String to print

out, must be careful…if int value that you send is bigger than the String itself,

you will get a StringIndexOutOfBoundsException when FileWriter

object tries to access characters in String which do not exist…an easy way to prevent

this from ever occurring is:

String one = “Hello World!!!\n”;

Out.write(one, 0, one.length());

Lesson A14 notes: Boolean Algebra and Loop Boundaries

Introduction

o conditional loops are often most difficult control structure to work with

Page 57: Java Notes

9/7/2009

o this lesson will give you strategies for defining beginning and ending conditions for

loops

Negations of Boolean Assertions

o a Boolean assertion is simply an expression that results in a true or false

answer…examples:

a > 5 0 == b a <= b

o to negate a Boolean assertion means to write its opposite…examples:

A !A

5 == x 5 != x

x < 5 x >= 5

x >= 5 x < 5

o negations of Boolean assertions can be used to re-write code…example: if (!(x <

5)) can be rewritten as if (x >= 5)

o useful because we understand positive statements more easily than statements that

contain “!”s

Boolean Algebra and DeMorgan's Laws

o Boolean Algebra is a branch of mathematics devoted to study of Boolean values and

operators

o consists of these fundamental operands and operators:

o operands (values): true, false

o operators: and (&&), or (||), not (!)

o note: Java has other Boolean operators, but this curriculum does not cover

them because they are not part of AP subset

o many identities have been developed for compound Boolean expressions…two of

more useful identities are DeMorgan's Laws o !(A || B) -> ! A && ! B

o !(A && B) -> ! A || ! B

o symbols A and B represent Boolean values, true or false.

o truth table that proves first DeMorgan's Law

A B !(A||B) !A !B !A&&!B

true true false false false false

true false false false true false

false true false true false false

false false true true true true

o truth table that proves second DeMorgan's Law

A B !(A&&B) !A !B !A||!B

true true false false false false

true false true false true true

Page 58: Java Notes

9/7/2009

false true true true false true

false false true true true true

Application of DeMorgan's Laws

o we understand positive statements much more easily than statements that contain one

or more !s

o therefore, when developing a loop, it is helpful to think about what will be true when

loop is done

o for example, for a craps program, when loop is done, one of two things will be true:

((sum == point) || (sum == 7))

o writing boundary condition involves a simple negation of loop assertion:

!((sum == point) || (sum == 7))

o applying DeMorgan's law and simplifying:

(!(sum == point)) && (!(sum == 7))

(sum != point) && (sum != 7)

Lesson A15 notes: ArrayList

Introduction

o it is common for a program to manipulate data that is kept in a list

o lists are a fundamental feature of Java and most programming languages

o Java Development Kit includes ArrayList class, which provides classic operations

for a list.

ArrayList Implementation of a List

o a data structure combines data organization with methods of accessing and

manipulating data

o ArrayList is data structure for storing list of elements; provides methods to find,

insert, and remove an element

o at an abstract level, we can describe a general “list” object

o contains elements arranged in sequence

o can find target value in list, add elements to list, remove elements from list

and process each element of list

o Abstract Data Type (ADT): abstract description of data structure, with emphasis on

its properties, functionality, and use, rather than on a particular implementation

o ADT defines methods for handling abstract data organization without details

of implementation

o “list” ADT, for example, may be described as follows:

Data organization:

– contains data elements arranged in linear sequence

Methods:

Page 59: Java Notes

9/7/2009

– create empty List

– append element to List

– remove i-th element from List

– obtain value of i-th element

– traverse List (process or print out all elements in sequence, visiting each element once)

o ArrayList object contains

o array of object references

o many methods for managing array

o can keep adding elements no matter what size it was originally…size of

ArrayList will automatically increase and no information will be lost

ArrayList Class

o to declare reference variable for an ArrayList:

// myArrayList is reference to future ArrayList object ArrayList <ClassName> myArrayList;

o array of references to objects of type ClassName, any class defined by you or Java.

o to declare reference variable and construct ArrayList with unspecified initial capacity:

// myArrayList is reference to ArrayList object

// Java picks initial capacity ArrayList <ClassName> myArrayList = new ArrayList <ClassName> ();

o this may not be very efficient…if you have an idea of what size ArrayList you need, start

your ArrayList with that capacity.

o to declare reference variable and construct ArrayList with initial capacity of 15:

// myArrayList is reference to ArrayList object

// initial capacity of 15 elements

ArrayList <ClassName> myArrayList = new ArrayList <ClassName> (15);

o partial list of ArrayList methods

int size(); // returns number of elements currently stored in

list

boolean isEmpty(); // returns true if list is empty, otherwise

returns false

boolean add(Object obj); // appends obj at end of list, returns

true

void add(int i, Object obj); // inserts obj before i-th element,

increments

// the indices of subsequent elements by 1

Object set(int i, Object obj); // replaces i-th element with obj,

// returns old value

Object get(int i); // returns value of i-th element

Object remove(int i); // removes i-th element from list and

returns

// its old value; decrements indices of

// subsequent elements by 1

o one way of accessing elements of ArrayList is by using integer index, which starts

at 0 and goes to size()-1

o to access object at particular index:

Page 60: Java Notes

9/7/2009

// returns value of element at index, an object

System.out.println(myArrayList.get(i));

o example

import java.util.ArrayList;

ArrayList <String> names = new ArrayList <String> (10);

names.add("Cary");

names.add("Chris");

names.add("Sandy");

names.add("Elaine");

// remove last element from list

String lastOne = names.remove(names.size()-1);

System.out.println("removed: " + lastOne);

// add reference to an Object at index 2 of ArrayList, increase size by one

names.add(2, "Alyce");

for (int j = 0; j < names.size(); j++)

System.out.println(j + ": " + names.get(j));

Run Output:

removed: Elaine

0: Cary

1: Chris

2: Alyce

3: Sandy

o a shorthand way to iterate through collection is provided by a “for each” loop…starts

at beginning of collection and proceeds through all of elements…will not allow you

to skip, add or remove elements:

for (String n : names){System.out.println(n);}

o add() method adds to end of ArrayList…to replace data at a particular index,

use:

Object set(int index, Object obj)

o index should be within 0 to size-1…data previously at index is replaced with

obj…object previously at specified position is returned.

o removing an element from a list: ArrayList class has method that will remove an

element from list without leaving a hole in place of deleted element:

// removes element at index from list and returns its old value

// decrements indices of subsequent elements by 1

Object remove(int index);

o element at location index will be eliminated…elements at locations index+1,

index+2, …, size()-1 will each be moved down one to fill in gap

o inserting element into an ArrayList at a particular position: when an element is

inserted at index, element previously at index is moved up to index+1, and so

on until element previously at size()-1 is moved up to size()…size of

ArrayList has now increased by one, and capacity can be increased again if

necessary.

Page 61: Java Notes

9/7/2009

// inserts obj before i-th element

// increments indices of subsequent elements by 1

void add(int index, Object obj);

o inserting is different from set…when set(index, obj) is used, object

reference previously at index is replaced by new obj…no other elements are affected

and size does not change

o whether you are adding at beginning, middle or end, remember you are adding an

object and must instantiate that object somewhere…strings hide this fact

names.add(2, "Alyce"); // actually creates String object with value

Alyce

o if we are using any object other than a string, we must instantiate object…if we have

an ArrayList drawList of DrawingTools, we could add a DrawingTool in

following way:

drawList.add(new DrawingTool());

Object Casts

o Java compilers before J2SE 1.5 (codename: Tiger) did not support typing of an

ArrayList as shown above…this new feature is called generics…it is now a valid

way to deal with ArrayLists…you declare what kind of objects you are going to

put in ArrayList…Java will only allow you to put that type of object in, and it

knows the type of object coming out…in previous versions of Java, you had to tell

compiler what kind of object you were putting in and taking out

o for example, consider following:

ArrayList aList = new ArrayList();

aList.add("Chris");

String nameString = aList.get(0); // SYNTAX ERROR!

System.out.println("Name is " + nameString);

o this code creates an ArrayList called aList and adds single String

object "Chris" to list

o intent of third instruction is to assign item "Chris" to nameString

o state of program execution following add is that aList stores the single item, "Chris"

o this code will never execute, because of a syntax error with third statement

o problem is a type conformance issue

o get method returns an Object, and an Object does not conform to a String

(even though this particular item happens to be a String)

o instruction can be modified to work as expected by incorporating (String)

cast:

String nameString = (String) aList.get(0);

Wrapper Classes

o because numbers are not objects in Java, you cannot insert them directly into pre 1.5 ArrayLists

Page 62: Java Notes

9/7/2009

o to store sequences of integers, floating-point numbers, or boolean values in a pre 1.5

ArrayList, you must use wrapper classes

o classes Integer, Double, and Boolean wrap primitive values inside

objects…these wrapper objects can be stored in ArrayLists.

o Double class is a typical number wrapper…there is a constructor that makes a Double

object out of a double value:

Double r = new Double(8.2057);

o conversely, doubleValue method retrieves double value that is stored inside

Double object:

double d = r.doubleValue();

o to add a primitive data type to a pre 1.5 ArrayList, you must first construct a

wrapper object and then add object…for example, following code adds a floating-

point number to an ArrayList

ArrayList grades = new ArrayList();

double testScore = 93.45;

Double wrapper = new Double(testScore);

grades.add(wrapper);

o or shorthand version:

grades.add(new Double(93.45));

o to retrieve number, cast return value of get method to Double, then call

doubleValue method:

wrapper = (Double) grades.get(0);

testScore = wrapper.doubleValue();

o with Java 1.5, declare your ArrayList to only hold

Doubles…with a new feature called auto-boxing in Java 1.5,

when you define an ArrayList to contain a particular wrapper

class, you can put corresponding primitive value directly into

ArrayList without having to wrap it…you can also pull

primitive directly out

ArrayList grades2 <Double> = new ArrayList <Double>();

grades2.add(93.45);

System.out.println(“Value is “ + grades2.get(0));

Iterator

o an Iterator is an object that is attached to ArrayList and allows you to traverse

array from first to last element…many data structures implement an Iterator…it

keeps track of where it is in list even if we are adding and removing from it…we will

cover topic of Iterators more thoroughly in AB level curriculum.

ArrayList <String> names = new ArrayList <String>();

names.add(“George”);

names.add(“Nancy”);

Page 63: Java Notes

9/7/2009

names.add(“John”);

Iterator iter = names.iterator();

while(iter.hasNext())

{

System.out.println(iter.next());

}

Lesson A16 notes: Single Dimension Arrays

Introduction

o a single dimension array is an alternative to ArrayList

o arrays are useful data structures

Example of an Array

o following program will introduce you to some of syntax and usage of array class in

Java:

int[] A = new int[6]; // an array of 6 integers

int loop;

for (loop = 0; loop < 6; loop++)

{

A[loop] = loop * loop;

}

System.out.println("The contents of array A are:");

System.out.println();

for (loop = 0; loop < 6; loop++)

{

System.out.print(" " + A[loop]);

}

System.out.println();

Run Output:

The contents of array A are:

0 1 4 9 16 25

o an array is similar to an ArrayList…it is a linear data structure composed of adjacent

memory locations, or “cells”, each holding values of same type

A

A[1] A[2] A[3] A[4] A[5]

1 4 9 16 25

A[0]

0

o variable A is an array, a group of 6 related scalar values…there are six locations in

this array referenced by indexes 0 to 5…note that indexes always start at zero, and

count up by one until last slot of array…if there are N slots in an array, indexes will

be 0 through N-1 (for example, if N=6, indexes are 0 through 5 or (N-1))

Page 64: Java Notes

9/7/2009

o variable loop is used in a for loop to reference indexes 0 through 5…in this

program, square of each index is stored in memory location occupied by each cell of

array…syntax for accessing a memory location of an array requires use of square

brackets []

o square brackets [] are an operator in Java, and are called index operator…similar to

parentheses as they have highest level of precedence compared to all other operators

o index operator performs automatic bounds checking…bounds checking makes sure

index is within range for array being referenced…whenever a reference to an array

element is made, index must be greater than or equal to zero and less than size of

array…if index is not valid, exception ArrayIndexOutOfBoundsException is thrown

Array Declarations and Memory Allocation

o array declarations look like this:

type[] arrayName;

o tells compiler that arrayName will be used as name of an array

containing type…however, actual array is not constructed by

this declaration…often an array is declared and constructed in

one statement like this:

type[] arrayName = new type[length];

o this tells compiler that arrayName will be used as name of an

array containing type, and constructs an array object

containing length number of slots

o an array is an object, and like any other object in Java, is constructed out of main

storage as program is running…array constructor uses different syntax than most

object constructors…type[length] names type of data in each slot and number of

slots…for example:

int[] list = new int[6];

double[] data = new double[1000];

Student[] school = new Student[1250];

o once an array has been constructed, number of slots it has does not change

o size of an array can be defined by using a final value

final int MAX = 200; int[] numb = new int[MAX];

o when an array is declared, enough memory is allocated to set up full size of array

Application of Arrays

o suppose we have a text file votes.txt of integer data containing all votes cast in an

election…this election happened to have three candidates and values in integer file

are 1, 2, or 3, each corresponding to one of three candidates

FileInput inFile = new FileInput("votes.txt");

int vote, total = 0, loop;

// sized to 4 boxes, initialized to 0's

int[] data = new int[4];

Page 65: Java Notes

9/7/2009

vote = inFile.readInt();

while (inFile.hasMoreTokens())

{

data[vote]++;

total++;

vote = inFile.readInt();

}

System.out.println("Total # of votes = " + total);

for (loop = 1; loop <= 3; loop++)

{

System.out.println("Votes for #" + loop +

" = " + data[loop]);

}

o array data consists of four cells, each holding an integer value…first cell, data[0],

is allocated but not used in this problem…after processing entire file, variable

data[n] contains number of votes for candidate n…we could have stored

information for candidate 1 in position 0, candidate 2 in position 1, and so forth, but

code is easier to follow if we can use a direct correspondence

data

data[0] data[1] data[2] data[3]

75 32 19 0

o value of vote is used to increment appropriate cell of the array by +1

o second example counts occurrence of each alphabet letter in a text file

FileInput inFile = new FileInput("sample.txt");

int[] letters = new int[26]; // use positions 0..25 to count letters

int total = 0;

char ch;

while (inFile.hasMoreLines())

{

String line = inFile.readLine().toLowerCase();

for (int index = 0; index < line.length(); index++)

{

ch = line.charAt(index);

// line.charAt is from chn.util. It extracts entry

if ('a' <= ch && ch <= 'z') // if letter

{

letters[ch – „a‟]++;

total++;

}

}

}

System.out.println("Count letters");

System.out.println();

ch = 'a';

for (int loop = 0; loop < 26; loop++){

System.out.println(ch + " : " + letters[loop]);

ch++;

}

System.out.println();

System.out.println("Total letters = " + total);

Page 66: Java Notes

9/7/2009

o each line in text file is read in, then each character in line is copied into ch…if ch is

uppercase, it is converted to its lowercase counterpart

o if character is a letter, ASCII value of letter is adjusted to fit range from 0-25…for

example, if ch == 'b', program calculates „b‟–„a‟= 1…appropriate cell of

array is incremented by one

Arrays as Parameters

o program ArrayOps.java from Handout 16.1 provides examples of passing arrays as

parameters

o main method declares an array named data…array is initialized with values 0...5

final int MAX = 6;

ArrayOps arrayOps = new ArrayOps();

int[] data = new int[MAX];

for (int loop = 0; loop < MAX; loop++) data[loop] = loop; // initialize

array

o parameter of printList method is a references to an array object…any local reference

to array list inside printList method is an alias for array data inside of main method

arrayOps.printList(data); // from main method

public void printList (int[] list)

// list is a reference parameter. list is the same array as

// array data in the main method

{

for (int index = 0; index < list.length; index++)

System.out.print( list[index] + " ");

System.out.println();

System.out.println();

}

o parameter of squareList method is also a reference to an array object…notice that

after call of squareList, values stored in array data in main method have been

permanently changed

Arrays and Algorithms

o five important algorithms that are common in programs that analyze data in arrays

o insertion is a standard problem that must be solved for all data

structures…suppose an array had 10 values and an 11th value was to be added

if place value at end, no problem

if at beginning, other 10 values must be moved one cell over in list

o deletion creates an empty cell….most likely solution is to move all values that

to right of empty spot one cell to left

o a traversal of an array consists of visiting every cell, probably in order…visit

could involve printing, initializing, finding largest or smallest value, etc.

o Sorting array means to organize values in either ascending or descending

order

Page 67: Java Notes

9/7/2009

o Searching array means to find a specific value in the array…there are several

standard searching algorithms.

o these algorithms will be covered in later lessons and labs.

Lesson A17 notes: Quadratic Sorting Algorithms

Introduction

o sorting data is one of the best applications of computers and software

o three sorting algorithms: bubble, selection, and insertion

o responsible for knowing how they work, but you do not necessarily need to memorize code

o these quadratic algorithms have problems sorting large amounts of data

Sorting Template Program

o a program shell has been provided in curriculum as SortStep.java (main test method), and

SortsTemplate.java (sort class template)

o program asks user to select a sorting algorithm, fills array with amount of data chosen by

user, calls sorting algorithm, and prints out data after it has been sorted

o at this point, each sorting algorithm has been left as a method stub…a stub is an incomplete

routine that can be called but does not do anything yet…stub will be filled in later as each

algorithm is developed and understood

o stub programming is a programming strategy…as each sorting algorithm is completed, it can

be added to program shell and tested without having to complete other sections

o stepwise development of programs

Bubble Sort

o Bubble Sort is simplest of three sorting algorithms…also slowest

o gets its name from way that largest items “bubble” to the top (end)

1. move largest remaining item in current pass to end of data as follows

a. starting with first two items, swap them if necessary so that larger item is

after smaller item

b. move over one position in list and compare to next item

c. swap items if necessary

2. remove largest item most recently found from data to be searched, then perform

another pass with this new data at step 1

3. repeat steps 1 and 2 above until number of items to be searched is one

o example:

Steps

Data for

pass

Sorted

data

Start pass 1: compare 4 & 1. 4 1 3 2

4 > 1 so swapped, now compare 4 & 3. 1 4 3 2

4 > 3 so swapped, now compare 4 & 2. 1 3 4 2

4 > 2 so swapped, end of pass. 1 3 2 4

Start pass 2: compare 1 & 3. 1 3 2 4

3 > 1 so no swap, now compare 3 & 2. 1 3 2 4

3 > 2 so swapped, end of pass. 1 2 3 4

Start pass 3: now compare 1 & 2. 1 2 3 4

2 > 1 so no swap. 1 2 3 4

Page 68: Java Notes

9/7/2009

Only one item in this pass so it is done. 1 2 3 4

Done. 1 2 3 4

o following program implements Bubble Sort algorithm.

void bubbleSort(ArrayList <Integer> list) {

for (int outer = 0; outer < list.size() - 1; outer++)

{

for (int inner = 0; inner < list.size()-outer-1; inner++)

{

if (list.get(inner) > list.get(inner + 1))

{

//swap list[inner] & list[inner+1]

int temp = list.get(inner);

list.set(inner, list.get(inner + 1));

list.set(inner + 1, temp);

}

}

}

}

o if (list.get(inner) > list.get(inner + 1)) is true, values are out of order and a

swap takes place

o after first pass (outer = 0), largest value will be in its final resting place

o when outer = 1, inner loop only goes from 0 to 3 because a comparison between

positions 4 and 5 is unnecessary

Selection Sort

o Selection Sort also makes several passes through list

o on each pass, it compares each remaining item to smallest (or largest) item that has been

found so far in pass

o at end of a pass, smallest item found is swapped with last remaining item for that pass

o thus, swapping only occurs once for each pass…reducing number of swaps makes algorithm

more efficient

o logic of Selection Sort is similar to Bubble Sort except that fewer swaps are executed:

void selectionSort(ArrayList <Integer> list)

{

int min, temp;

for (int outer = 0; outer < list.size() - 1; outer++)

{

min = outer;

for (int inner = outer + 1; inner < list.size(); inner++)

{

if (list.get(inner) < list.get(min))

{

min = inner; // a new smallest item is found

}

}

//swap list[outer] & list[min]

temp = list.get(outer);

list.set(outer, list.get(min);

list.set(min, temp);

}

}

Insertion Sort

Page 69: Java Notes

9/7/2009

o Insertion Sort takes advantage of following fact: if A < B and B < C, then A < C, so can skip

comparison of A and C.

o consider following partially sorted list of numbers: 2 5 8 3 9 7

o first three values of list are sorted…4th value in list, (3), needs to move between 2 and 5

o this involves two tasks: finding correct insert point and a right shift of any values between

start and insertion point

o code follows:

void insertionSort(ArrayList <Integer> list)

{

for (int outer = 1; outer < list.size(); outer++)

{

int position = outer;

int key = list.get(position);

// Shift larger values to right

while (position > 0 && list.get(position – 1) > key)

{

list.set(position, list.get(position – 1));

position--;

}

list.set(position, key);

}

}

o by default, a list of one number is already sorted…hence outer loop skips position 0 and

ranges from positions 1 to list.size()

o for each pass of outer, algorithm does two things:

o finds location where list[outer] needs to be inserted in list

o does right shift on sections of array to make room for inserted value

o two halves of boundary condition cover these situations:

o (position > 0) –> we are still within list, keep processing

o list[position - 1] > key –> value in list[pos-1] is larger than key,

keep moving left (position--) to find first value smaller than key

o Insertion Sort algorithm is appropriate when a list of data is kept in sorted order with

infrequent changes…if a new piece of data is added, probably at end of list, it will get quickly

inserted

Counting Steps - Quadratic Algorithms

o these three sorting algorithms are categorized as quadratic sorts because number of steps

increases as quadratic function of size of list

o it is helpful to study algorithms based on number of steps they require to solve problem

o we will add code to sorting template program to count number of steps for each algorithm

o will require use of an instance variable - we'll call it steps

o steps variable will be maintained within sorting class and be accessed through appropriate

accessor and modifier methods

o will only count comparisons of items in list, and gets or sets within the list…these operations

are typically most expensive (time-wise) operations in a sort

Page 70: Java Notes

9/7/2009

o revised version of the bubbleSort method

public void bubbleSort(ArrayList <Comparable> list)

{

steps = 0;

for (int outer = 0; outer < list.size() - 1; outer++)

{

for (int inner = 0; inner < list.size()-outer-1; inner++)

{

steps += 3;//count one compare and 2 gets

if (list.get(inner).compareTo(list.get(inner + 1)) > 0)

{

steps += 4;//count 2 gets and 2 sets

Comparable temp = list.get(inner);

list.set(inner,list.get(inner + 1));

list.set(inner + 1,temp);

}

}

}

}

o as size of data set doubles, number of steps executed increases by approximately four times

o Bubble Sort is an example of a quadratic algorithm in which number of steps required

increases at a quadratic rate as size of the data set increases.

o a quadratic equation in algebra is one with a squared term, like x2

o in sorting example, as size of array increases to N, number of steps required for any of

quadratic sorts increases as a function of N2

Animated Sort Simulations

o web site http://www.cs.hope.edu/~alganim/ccaa/sorting.html, provides animated sorting

simulations

Sorting Objects

o sorts above compare Integers…comparison is built into Integer class

o what if we wanted to write a sort that could work on Strings?...cannot use „<‟ on

Strings…have to use compareTo method

o to convert BubbleSort, make following changes that are underlined

void bubbleSort(ArrayList <String> list)

{

for (int outer = 0; outer < list.length - 1; outer++)

{

for (int inner = 0; inner < list.size()-outer-1; inner++)

{

if (list.get(inner).compareTo(list.get(inner + 1) > 0)

{

//swap list[inner] & list[inner+1]

String temp = list.get(inner);

list.set(inner, list.get(inner + 1));

list.set(inner + 1, temp);

}

}

}

}

o if able to sort data, must be an order defined for it…classes that have an order should have a

compareTo method…Java defines an Interface, Comparable, just for this purpose

Page 71: Java Notes

9/7/2009

o to make a BubbleSort that will work on any objects that implement Comparable, make

following changes, again underlined

void bubbleSort(ArrayList <Comparable> list)

{

for (int outer = 0; outer < list.length - 1; outer++)

{

for (int inner = 0; inner < list.size()-outer-1; inner++)

{

if (list.get(inner).compareTo(list.get(inner + 1) > 0)

{

//swap list[inner] & list[inner+1]

Comparable temp = list.get(inner);

list.set(inner, list.get(inner + 1));

list.set(inner + 1, temp);

}

}

}

o this method is reusable because we can use it to sort any

Comparable object

o compareTo interface follows

interface java.lang.Comparable

int compareTo(Object other)

// returns value < 0 if this is less than other

// returns value = 0 if this is equal to other

// returns value > 0 if this is greater than other

o remember to consider whether it makes sense to compare objects

that you build…if it does, implement Comparable Interface…also

provide an equals method for your class

Lesson A18 notes: Merge and MergeSort

Introduction

o in Lesson A17, Quadratic Sorting Algorithms, we saw how number of steps required

increased N2 when sorting N elements

o in this lesson, we will study a recursive sort, called mergeSort that works by dividing lists

in half

o recursive mergeSort produces a dramatic increase in efficiency in comparison with the N2

order of quadratic sorts

o concept of dividing problem in two is used in several other classic algorithms

o recursion makes it easier to define problem and code solution

Non-Recursive MergeSort

o overall logic of mergeSort is to "divide and conquer"

o divide list into two (or more) approximately equal-sized parts, sort each with selection sort,

then merge the two using an algorithm to be discussed below

o here is a non-recursive mergeSort method

Page 72: Java Notes

9/7/2009

// list A is unsorted, with A.size() values…first is index of first

value

// last is index of last value… first < last

void mergeSort (ArrayList <Integer> A, int first, int last)

{

int mid;

mid = (first + last) / 2;

selectionSort (A, first, mid);

selectionSort (A, mid+1, last);

merge (A, first, mid, last);

}

o a modified selection sort will have to be written to sort a range of values in list A…likewise,

merge method will have to be modified to internally merge two halves of the array into one

ordered array

o example to illustrate non-recursive mergeSort

3 4 2 3 4 8 3 7 3 1 71 1 ... re s t o f l is t ...

U nso rte d Lis t

3 5

3 42 3 4 8 3 73 1 71 1 ... re s t o f l is t ...

Lis t A fte r So rting Ea ch H a lf

3 5

o because two sublists are stored within one array, easiest approach is to merge two sublists

into another array, then copy temp array back to original

3 42 3 4 8 3 73 1 71 1 ... re s t o f l is t ...Lis t A 3 5

3 42 3 4 83 73 1 71 1 ... re s t o f l is t ...T e m p 3 5

o then copy Temp back into List A:

... re s t o f l is t ...Lis t A

3 42 3 4 83 73 1 71 1 ... re s t o f l is t ...T e m p 3 5

3 42 3 4 83 73 1 71 1 3 5

o this version of merge will need to work with sections of ArrayList A…here is a proposed

parameter list for merge:

/* merge two sorted sublists within A into one continuous sublist from

A[first] .. A[last]. The left list ranges from A[first]..A[mid].

The right list ranges from A[mid+1]..A[last].

*/

Page 73: Java Notes

9/7/2009

void merge (ArrayList <Integer> A, int first, int mid, int last)

A Merge Algorithm

o recursive version of mergeSort will require above version of merge, but first a simpler

merge algorithm

o method header and specifications of merge method are given below…assume ArrayList

definitions from sorting template program in Lesson 17 apply

/* Preconditions: Lists A and B are non-empty and in sorted nondecreasing

order

Action: Lists A and B are merged into one ArrayList, C

Postcondition: List C contains values from A and B, in nondecreasing

order */

void merge (ArrayList <Integer> A, ArrayList <Integer> B, ArrayList

<Integer> C)

o merge method breaks down into four cases:

a. ArrayList A is done, so pull value from ArrayList B

b. ArrayList B is done, so pull value from ArrayList A

c. Neither is done, and if A[i] < B[j] (where i & j are index markers in lists A and B)

then pull from ArrayList A

d. Neither is done, and if B[j] <= A[i] then pull from ArrayList B

o it is important to deal with four cases in order described above

Recursive MergeSort

o instead of dividing list once, recursive mergeSort keeps dividing list in half until sublists

are one or two values in length.

o when developing any recursive solution, key step is identifying base case of solution…what

situation will terminate recursion?...in this case, a sublist of one or two values will be our two

base cases

o example with recursive mergeSort of list of eight values

16 91 4577 5 88 65 21

o list is divided into two sublists

16 91 4577 5 88 65 21

o left sublist divided into lists of two

16 91 4577

o each list of two is very easy to sort, then merge two lists back into list of four.

Page 74: Java Notes

9/7/2009

16 91 45 7716 91 45 77

45 7716 9145

o now algorithm proceeds to solve right sublist recursively, then two lists are merged back

together

5 88652145 7716 9145

R ig h t Su b l ist

R e c u r siv e W o r k

5 16 21 45 65 77 88 91

N o w w e m e r g e

th e tw o su b l ists

o f f o u r

Order of Recursive MergeSort

o suppose list of 8 numbers…if we trace migration of one value, it will be a member of

following sizes of lists: eight, four, two…number of calls of mergeSort needed to sort one

value into its final resting spot is log2N

o must apply log2N steps to sort N elements in list…order of recursive Mergesort is O(N *

log2N) or O(N * log N)

o what about cost of merging fragments of list?...merge algorithm is linear, so when combined

with mergeSort routine, we have O (N * log N) + O(N), which remains in category of O(N

* log N) algorithm

Lesson A19 notes: Sequential and Binary Searches

Introduction o searching for an item is a very important algorithm to a computer scientist

o computers can do this very quickly

o for example, Internet search engines process billions of pages of information…a word

processor‟s spell-checking feature enables quick searching of large dictionaries

Page 75: Java Notes

9/7/2009

o in this lesson, you will learn about a simple sequential search and the very efficient binary

search

Sequential Search

o searching a linear data structure, such as an array, can be as simple and straightforward as

checking through every value until you find what you are looking for

o a sequential search, also known as a linear search, involves starting at the beginning of a list

or sequence, sorted or not, and searching one-by-one through each item, in the order they

exist in the list, until the value is found.

o this unsophisticated approach is appropriate for small lists or unordered lists.

o the order of a sequential search is linear, O(N).

Binary Search

o binary searching is faster than sequential, but list must be sorted

o the word binary (from the word two) refers to anything with two possible options or parts…a

binary search involves binary decisions – decisions with two choices

o in a binary search

o list must be sorted

o divide list in half

o examine value in middle of list: is target value equal to value there, or does it come

before or after middle value?...if target value comes before or after, then return to

step a to repeat process with halved list where target value is located

o stop when middle value equals target value

o example with a list of 1,024 sorted values, searching for target value that is stored in position

492

o list of 1,024 is split in half

o because target value is not found in position 512, we proceed to search first half, and

so on

o speed of a binary search comes from elimination of half of data set each time…if each arrow

below represents one binary search process, a maximum of ten steps are required to search a

list of 1,024 numbers

1024 512 256 128 64 32 16 8 4 2 1

o if list were doubled to 2,048, at most one more step would be required using a binary search

o efficiency of binary search is illustrated in comparison below of number of entries in a list

and maximum number of binary divisions required.

Number of Entries Number of Binary Divisions

1,024 10 = log21024

2,048 11 = log22048

4,096 12 = log24096

… …

1,048,576 20 = log21048576

N log2N

o the order of a binary search is O(log2N).

Recursive vs. Non-recursive Algorithms

o binary search algorithm can be coded recursively or non-recursively

Page 76: Java Notes

9/7/2009

o non-recursive version requires less memory and fewer steps by avoiding overhead of making

recursive calls.

o recursive version is easier to code and understand

Lesson A20 notes: Inheritance, Polymorphism, and Abstract Classes

Introduction

o a class represents a set of objects that share same structure and behaviors

o class determines structure by specifying variables that are contained in each instance of class

o it determines behavior by providing methods that express behavior of objects

o central new idea in object-oriented programming is to allow classes to express similarities

among objects that share some, but not all, of their structure and behavior

o main goals of OOP are team development, software reusability, and easier program

maintenance

o OOP concepts to serve these goals are abstraction, encapsulation, inheritance, and

polymorphism

Inheritance

o key element in OOP is ability to derive new classes from existing classes by adding new

methods and redefining existing methods…new class can inherit many of its attributes and

behaviors from the class…process of deriving new classes from existing classes is called

inheritance

o general class that forms basis for inheritance is called the superclass

o specialized class that inherits from superclass is called the subclass (or derived class).

o in Java, all classes belong to one big hierarchy derived from most basic class, called

Object…this class provides a few features common to all objects…it is useful for

implementing structures that can deal with any type of object

o if we start a class from “scratch,” the class automatically extends Object

public class SeaCreature

{

...

}

is equivalent to:

public class SeaCreature extends Object{

...

}

o when new classes are derived from SeaCreature, a class hierarchy is created. For example:

public class Fish extends SeaCreature

Page 77: Java Notes

9/7/2009

{

...

}

public class Mermaid extends SeaCreature

{

...

}

o this results in hierarchy shown below

Abstract Classes

o Java allows us to formally define an abstract class…in an abstract class, some or all methods

are declared abstract and left without code.

o an abstract method has only a heading: a declaration that gives method‟s name, return

type, and arguments…an abstract method has no code

o for example, all of methods in definition class shown below are abstract…SeaCreature

tells us what methods a sea creature must have, but not how they work.

// A type of creature in the sea

public abstract class SeaCreature

{

// Called to move the creature in its environment

public abstract void swim();

// Returns the name of the creature

public abstract String getName();

}

o in an abstract class, some methods and constructors may be fully defined and have code

supplied for them while other methods are abstract

o subclasses of an abstract class have more and more methods defined…eventually, down

inheritance line, code is supplied for all methods

o a class where all methods are fully defined is called a concrete class…a program can only

create objects of concrete classes (an object is called an instance of its class)…an abstract

class cannot be instantiated

o different concrete classes in same hierarchy may define same method in different ways:

public class Fish extends SeaCreature{

...

// returns the name of the creature

public String getName() {return "Wanda the Fish";}

}

public class Mermaid extends SeaCreature{

...

// returns the name of the creature

public String getName() {return "Ariel the Mermaid";}

Figure 20-1. SeaCreature and two derived classes

Page 78: Java Notes

9/7/2009

}

o a class may be declared abstract for other reasons as well…for example, some of instance

variables in an abstract class may belong to abstract classes

Polymorphism

o can refer to objects of specific types through more generic reference

o can mix objects of different subtypes in the same collection:

SeaCreature s = new Fish(...);

...

s.swim();

o instance of Fish class is a Fish, but also a SeaCreature

o there are situations that require reference to an object using its more generic supertype rather

than its most specific type

o for example, when different subtypes of objects in same collection (array, list, etc.) are

mixed:

ArrayList <SeaCreature> creature = new ArrayList <SeaCreature>;

Creature.add( new Fish(...));

Creature.add( new Mermaid(...));

...

creature.get(currentCreature).swim();

o Fish and Mermaid classes provide two different implementations of the swim method, so

correct method is located by the Java virtual machine

o overriding method

o when subclass redefines implementation of a method from its superclass

o actual method to call is determined at run time

o called dynamic binding or late binding

o polymorphism: principle that actual type of object determines method to be called (Greek for

“many shapes”)…same computation works for objects of many forms and adapts itself to

nature of object

o overloading a method

o often confused with overriding because names are so similar

o means to keep name of method, but change parameter list

o compiler can choose method that is actually called because the signatures are

different

Interfaces

o Java has a class-like form called an interface that can be used to encapsulate only abstract

methods and constants

o can be thought of as a blueprint or design specification

o a class that uses interface is a class that implements the interface

o similar to an abstract class: it lists methods, giving their names, return types, and argument

lists, but does not give any code

o difference is that abstract class may have some constructors and methods implemented, while

an interface does not give any code for its methods, leaving their implementation to a class

that implements interface

o interface and implements are Java reserved words…here is an example:

public interface Comparable

{

Page 79: Java Notes

9/7/2009

public int compareTo(Object other);

}

o looks like class definition, except implementation of compareTo() method is omitted

o a class that implements Comparable interface must provide an implementation for this

method…class can also include other methods and variables…for example,

class Location implements Comparable

{

public int compareTo(Object other)

{

. . . // do something -- presumably, compare objects

}

. . . // other methods and variables

}

o a class can implement any number of interfaces…a class can both extend another class and

implement one or more interfaces:

class Fish extends SeaCreature implements Locatable, Eatable

{

...

}

o can declare a variable whose type is given by interface…if Fish and Mermaid are classes

that implement Locatable, you could say:

Locatable nemo; nemo = new Fish(); // nemo now refers to an object of type Fish

nemo.location(); // Calls location () method from class Fish

nemo = new Mermaid(); // Now, nemo refers to an object of type Mermaid

nemo.location(); // Calls location() method from class Mermaid

o a variable of type Locatable can refer to any object of any class that implements

Locatable interface…statement nemo.location() is legal because nemo is of type

Locatable and any Locatable object has a location() method

Lesson A21 notes: Number Systems

Introduction

o there are some dangers and pitfalls in assuming that a computer will always give you correct

answer

o knowing how computer stores information will give you an understanding of some of

common computational errors such as over-flow, round-off and, under-flow errors

o this lesson is a very light introduction to number systems and their relationship to Computer

Science

Introduction to Number Systems

o our number system has 10 as its base

o this numbering system (decimal) may have arisen quite naturally from counting on our ten

fingers

Page 80: Java Notes

9/7/2009

o there are other common number bases that we use without thinking about them, such as when

we deal with time (base 60 or sexagesimal): there are, 60 minutes in an hour, and 60 seconds

in a minute

o in Computer Science, we use binary (base 2), octal (base 8), and hexadecimal (base 16) quite

a bit

Review Decimal

o we are taught very early on about place values…in decimal number system, starting at

rightmost digit we have ones place, then tens place, hundreds place, and finally thousands

place…we are only allowed the digits 0 through 9

o the number 1234 represents following components:

1*1000 + 2*100 + 3*10 + 4*1

or

1*103 + 2*102 + 3*101 + 4*100

o if we move to the right of the decimal place, we start using negative exponents.

103 10

2 10

1 10

0 10

-1 10

-2

Octal

o in base 8 (octal), available digits are 0 through 7, and each number occupies a place value

o place values are

83 8

2 8

1 8

0 8

-1 8

-2

o we can designate that a number is in a base other than base 10 (decimal) by using

subscripts…if there is no subscript, number is assumed to be decimal

o number 123.6 in base 8 – it must be written as 123.68.…it can be converted to a decimal as:

1*82 + 2*8

1 + 3*8

0 + 6*8

-1

1*64 + 2*8 + 3*1 + 6*(1/8)

83.75

o converting 567 from decimal system to octal system

o start by looking for largest power of 8 less than 567 ..512 or 83…put a 1 in 8

3 place

value

o leaves us with a remainder of 55

o next place value is 82, but 64 is greater than 55 so that place holds a zero

o next place value is 81…55 divided by 8 gives 6 for the 8

1 place value, with a

remainder of 7

o leftover gets placed in the ones column.

83 8

2 8

1 8

0 8

-1 8

-2

1 0 6 7 0 0

or 10678

Hexadecimal

Page 81: Java Notes

9/7/2009

o Hexadecimal is base 16

o will allow the digits 0 through 15

o gets confusing, however, because the digits 10 through 15 are double digits

o to avoid confusion we use other symbols, A through F, to represent the values of 10 through

15

o convert hexadecimal number 34CD to decimal

o 3*16

3 + 4*16

2 + 12*16

1 + 13*16

0

12288 + 1024 + 192 + 13

13517

o converting from decimal to hexadecimal is same process used for octal earlier:

convert 12547

12547/( 163) -> 3, remainder 259

259/( 162) -> 1, remainder 3

3/( 161) -> 0, remainder 3

o so 12547 in decimal number system is equivalent to 310316 in hexadecimal system

Binary

o binary works same way as octal and hexadecimal

o binary is base 2, so only digits used are 0 and 1 and place values are all powers of 2

23 2

2 2

1 2

0 2

-1 2

-2

8 4 2 1 1/2 1/4

o a binary digit is called a bit

o examples converting from decimal to binary

13 -> 1101 (1*2

3 + 1*2

2 + 0*2

1 +1*2

0)

convert 482 to binary

find largest power of two that divides into 482: 28 or 256

482/256 = 1, subtract to get the leftover, 226.

check to see if 27, 128 goes into 226…only have the choice of 1 or 0 so

this

will be simple to calculate: 226 – 128 -> 98 (another 1)

98-64 -> 34 (another 1)

34-32 ->2 (another 1)

can‟t subtract 16 (so a 0 goes here)

can‟t subtract 8 (another 0)

can‟t subtract 4 (another 0)

2 – 2 -> 0 (another 1)

can‟t subtract 1 (another 0)

Answer: 1111000102

Short Cuts Between Binary, Octal, and Hexadecimal

o there is a relationship between binary, octal, and hexadecimal numbers

o binary is base 2, octal is base 8(23) and hexadecimal is base 16(2

4)

o convert binary number 101101011010111 to hexadecimal

o starting at rightmost digit, split number into groups of 4: 101 1010 1101 0111

o each of these groups has 4 binary digits that can range from 0 –15…this is

exactly value of one hexadecimal digit, so match each group of four bits with

one hexadecimal digit:

Page 82: Java Notes

9/7/2009

Binary Number

Groups

Hexadecimal

Equivalent

101 5

1010 A

1101 D

0111 7

o so our binary number is equivalent to 5AD716

o going from hexadecimal reverses procedure so each hexadecimal digit

expands to 4 bits

o same process occurs between octal and binary using only 3 bits

How this Relates to Computers and Overflow Errors

o modern computers are binary computers…they are made up of switches…each switch is

either on or off at any one time…everything we put into the computer (numbers and letters)

must be converted to binary numbers

o overflow error

o if we had only 8 bits for our integers and there were no negative numbers

27 2

6 2

5 2

4 2

3 2

2 2

1 2

0

128 64 32 16 8 4 2 1

o then the numbers available to us would range from 0000 0000 to 1111 1111

(binary), which is 0 to 255 (decimal)

o attempting to put a larger number into an integer would result in an overflow

error

o see charts in Lesson A3 for minimum and maximum values for the different

types of primitive data types

o round-off error

o arises when using numbers that have decimal places

o assume allocate in our 8-bit storage 6 bits for the mantissa (the part to the left of the

decimal place) and 2 bits for the fractional portion…this storage will hold numbers

from 0 to 63.75.

25 2

4 2

3 2

2 2

1 2

0 2

-1 2

-2

32 16 8 4 2 1 1/2 1/4

o let‟s convert 7.25 to our binary representation

o now try 7.4…first 6 bits are same, 000111, but only four choices for decimal places:

00 -> 0

01 -> .25

10 -> .5

11 -> .75

25 2

4 2

3 2

2 2

1 2

0 2

-1 2

-2

0 0 0 1 1 1 0 1

Page 83: Java Notes

9/7/2009

o so we would have to choose between .25 and .5

o this is called round-off error

o converting from decimal numbers with fractional parts to a binary representation can

cause errors…we are using a very simplified version here, so errors would usually

occur much further out in the decimal places

o most of time we would not see these errors but as programmers, we should be aware

of them

o this is why it is never a good idea to compare two floating numbers using “==”…it is

much safer to compare the two and check for a certain level of accuracy

(Math.abs(x – y)< .000000001) is better than (x == y)

o this is also why a programmer should choose best data type for the job

o under-flow error

o let's use our 8-bit storage scheme again, and try to store decimal number 0.1

25 2

4 2

3 2

2 2

1 2

0 2

-1 2

-2

0 0 0 1 1 1 0 1

o first 6-bits are 000000. Remember the four choices of decimals:

00 -> 0

01 -> .25

10 -> .5

11 -> .75

o the number we are trying to store is too small for our storage scheme

o converting from decimal numbers to binary may not work for numbers very

close to 0

Lesson A22 notes: General Computer Knowledge

Introduction

o computers are very complex and interesting machines

o any computer programmer should know as much about them as possible

Hardware o a computer must have a location to store information that is being manipulated

o when computer is engaged in processing data, it is stored in computer‟s primary memory,

generally Random Access Memory (RAM)…primary memory only holds data for as long as

computer is powered up…it is lost when computer is shut down

o secondary memory is generally slower. higher capacity, and does not need a constant current,

so it is useful for long-term storage…hard disk drives, floppy disk drives, and flash drives, as

well as to optical discs such as CD-ROMs and DVDs

o Central Processing Unit (CPU) conducts all the calculations…housed in a silicon chip called

a microprocessor…understand basic computer instructions provided by computer's

software…even though CPUs are often physically small, they can contain millions of parts

Page 84: Java Notes

9/7/2009

o hardware means computer components that can actually be physically touched, including

storage devices (such as disk drives), display devices (such as computer monitors or screens),

output devices (printers, speakers), input devices (keyboards, mice, joysticks, scanners) and

other peripherals (modems and network cards)

Software

o software is a general term for all the computer instructions and data (programs or

applications) that exist on a computer…stored in memory…do not have a tangible aspect

o range from computer games to word processors (applications software) to the computer‟s

operating system (OS or system software), which manages and controls all the other software

on the system

o operating systems have been evolving for many years and have become more and more

advanced…major operating systems competing for the personal computer market today are:

o Microsoft Windows (i.e., 2000, NT, XP Home, XP Pro)

o Apple Macintosh (i.e., OS 8, 9, X, Tiger)

o Linux (there are dozens of operating systems based on Linux)

o main object of this curriculum is to teach students how to create their own computer software

o when creating computer software programs, a language translator and compiler are required

to convert the Java code into software 'language' that CPU is able to understand…without

these tools, it would be necessary to program computers entirely in binary, with 1‟s and 0‟s

Networking

o network of computers is defined as two or more computer systems connected to each other, in

order to communicate and share data

o simple linking of computers found close together or span a relatively large geographical area

o wide-area network (WAN) consists of two or more local-area networks (LANs)

o largest WAN is the Internet, an interconnected system of networks which has been expanding

rapidly around the world over the last couple of decades…millions of websites today

o another feature of networking is called thin client – exists computer (client) has little or no

hardware or software on it…depends on a host server for data and processing

Ethics

o power and expansion of computers and networking has brought many problems and ethical

issues

o anti-virus, anti-spyware, anti-spam, and privacy protection software programs

o computers getting infected with a malicious computer virus and behaving strangely

o spyware sends data to third parties

o new field of criminal justice that deals with computer crimes, such as theft of usernames and

passwords, identity theft, denial of service attacks, alteration of websites, illegal or offensive

material posted on websites or received in emails, predatory sexual behavior, copyright

infringement, unregulated gambling, and more

o sexual predators hide behind a screen name

o computer hackers attempt to get bank account and credit card information

o pornography and gambling can be hard to regulate over Internet

o copyright infringement much more likely to go unnoticed

o important to think about ramifications of one's own actions when using computer technology