Free Essay

Lol Girl

In:

Submitted By dessy21
Words 31284
Pages 126
Blue Pelican Java by Charles E. Cook

Version 3.0.5h
Copyright © 2004 - 2008 by Charles E. Cook; Refugio, Tx
(All rights reserved)

1-1

“Blue Pelican Java,” by Charles E. Cook. ISBN 1-58939-758-4.
Published 2005 by Virtualbookworm.com Publishing Inc., P.O. Box 9949, College Station,
Tx 77842, US. ©2005, Charles E. Cook. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, recording or otherwise, without the prior written permission of Charles E. Cook.
Manufactured in the United States of America.

Preface
You will find this book to be somewhat unusual. Most computer science texts will begin with a section on the history of computers and then with a flurry of definitions that are just “so many words” to the average student. My approach with Blue Pelican Java is to first give the student some experience upon which to hang the definitions that come later, and consequently, make them more meaningful.
This book does have a history section in Appendix S and plenty of definitions later when the student is ready for them. If you will look at Lesson 1, you will see that we go right to work and write a program the very first day. The student will not understand several things about that first program, yet he can immediately make the computer do something useful. This work ethic is typical of the remainder of the book. Rest assured that full understanding comes in time. Abraham Lincoln himself subscribed to this philosophy when he said, “Stop petting the mule, and load the wagon.”
The usual practice in most Java textbooks of introducing classes and objects alongside the fundamental concepts of primitive variable types, loops, decision structures, etc. is deferred until the student has a firm grasp of the fundamentals. Thus, the student is not overwhelmed by simultaneous introduction of OOPs (Object Oriented Programming) and the fundamentals. Once introduced, (Lesson 15), OOPs is heavily emphasized for the remainder of the book.
I fully realize that there are those who disagree with this idea of deferring the introduction of OOPs, and from their own point of view, they are right. In most cases they teach only the very highest achieving, mature students. In those cases, I agree that it is acceptable to begin with OOPs; however, for the average student and especially for younger high school students, I feel that they need to understand the fundamentals first.
Upon first examination of this book it may not appear to be very “robust” in that there is not great depth for some of the topics. Actually the depth is there,… in the Appendix.
The Appendix for this book is unusually large. Here is why the book is organized this way: •


The lessons are kept purposely short so as to hold down the intimidation factor.
As a result, the lessons should look “doable” to the students.
The in-depth material is placed in the Appendices, and references to the
Appendices are made in the lessons. As an example, in Lesson 18 the split method is introduced. The split method uses regular expressions that are briefly discussed there; however, the in-depth presentation of regular expressions is placed in
Appendix AC.

Unfortunately, this book does not introduce any graphics or windows programming. The
57 lessons in this book can be covered in one school year, but just barely. To prepare students for the AP test (and contests) there is only time to cover the essentials presented in this book. Check http://www.bluepelicanjava.com for the availability of study materials for the current AP case study, updates on this book, videos for each lesson, and an inexpensive way to purchase hard-cover books.

I am often asked how to use this book. “Which lessons are really important and which can be skipped?” The answer is simple:







Start on Lesson 1.
Proceed at a reasonable rate. (See Appendix P for a time-line.)
Don’t skip anything (except for, perhaps Lesson 23, Lesson 48 and Lesson 54)
Give a simple, confidence-building quiz on each lesson. Quizzes and keys are provided in the Answer Book (available at www.bluepelicanjava.com).
Make sure the students do the provided exercises and projects.
Give tests at regular intervals. Tests and keys are provided in the Answer Book.

In this book you will also notice another part of my philosophy of teaching and educational material in general…Keep it simple… I try to keep things as simple and uncluttered as possible. For example, you will find specific examples in greater numbers than long-winded explanations in this book. You won’t find many pictures and sidebars and lots of little colored side notes scattered about. Some of that type format does contain some useful information; however, I feel that it is largely distracting. Apparently more and more people are coming around to my way of thinking on this, and here is why I think so. Recall that just a few years ago that nearly all web pages looked like cobbled together ransom notes with just a profusion of colors, links, and tidbits scattered all over the page. Take a look at professional web pages today. They typically have a very neat, clean appearance…often with just a plain white background and with plenty of space between the various elements. This is good. Simple is better.
Since this textbook has a strong emphasis on preparation for the AP test and competition
(computer science contests), special “contest type” problems are provided at the end of most lessons. I realize that most students will not compete and some may not even take the AP exam; however, the material is not wasted on them. Those “contest type” problems are good for the average student too, as long as they are not overwhelmed with too many problems at one sitting. Hopefully, I have just the optimum number of these type problems on each lesson and students won’t be burned-out by too much of a good thing. Finally, we come to the reason for the choice of Blue Pelican Java as a name for this book. One of the early (and free) java IDE’s available for students was BlueJ and it was the first my students used. I always thought BlueJ was an elegant name and had expressed a desire to a colleague to continue the tradition by naming the book after some other blue-colored bird. He jokingly suggested Blue Pelican, not really being serious about naming a book after this rather ungainly, clunky bird. For the lack of an existing name for the book during development, it continued to be called Blue Pelican. If you call something by a particular name long enough, that’s its name, and so the name stuck.
I truly hope Blue Pelican Java is useful to you and that you find the experience of learning to program a rewarding one. Just remember, few things worthwhile are acquired without some sacrifice. The “sacrifice” here will be the time you invest in creating programs and trying the code suggested in these pages.
Charles E. Cook

Table of Contents - 1

Table of Contents
Lesson

Title

Description

Page

1

Hello World

Simple use of println, rems, remarks, comments, block rems. Project… From Me to You

1-1

2

Variable Types

String, int, double, legal names, illegal names, declaring, initializing

2-1

3

Simple String Operations

Concatenation, length, substring, toLowerCase, toUpperCase, escape sequences, backslash
Project… Name That Celebrity

3-1

4

Using Numeric variables

Assignment, ++, --, modulus, +=, -=, /=, *=,
PEMDAS, increment, decrement, multiple declarations, remainder, compound operator, roundoff. Project…Cheating on Your Arithmetic
Assignment

4-1

5

Mixed Data Types, Casting, and
Constants

final, mixed arithmetic, casting. Project… Mixed
Results

5-1

6

Math Class Methods

abs, pow, sqrt, ceil, floor, log, min, max, round, PI, sin, cos, tan, asin, acos, atan, toDegrees, toRadians.
Project… Compute This

6-1

7

Input from the Keyboard

Scanner class, nextInt, nextDouble, next, nextLine,
Project… Going in Circles, Project… What’s My
Name?

7-1

8

boolean Type and Operators

AND, OR, NOT, precedence

8-1

9

“if” statement

equals, equalsIgnoreCase. Project…Even or Odd?

9-1

10

The “switch” Statement and char

switch, default, break, char. Project… Weight on
Other Planets

10-1

11

The “for” Loop

Initializing, control, and step expressions. break, infinite loops, scope, for-loop project, Project…
Name Reversal

11-1

12

while and do-while loops

Testing at top and bottom of loop, break, continue

12-1

13

ASCII and more on char

ASCII codes for numbers and letters, conversion from String to char, conversion from char to String, isDigit, is Letter, isLetterOrDigit, isLowerCase, isUpperCase 13-1

14

Binary, Hex, and Octal

Conversion between number systems, binary addition. Project… Basically Speaking

14-1

15

Classes and Objects

Instantiate, methods, state variables, constructor, signature, public, void, Project… What’s That
Diameter? Project… Overdrawn at the Bank

15-1

16

More on Classes & Objects

Private methods and state variables, different lines to declare and instantiate, setting objects equal, equality of objects, reassignment of objects, Project… Gas
Mileage

16-1

17

Advanced String Methods

compareTo, indexOf( ), lastIndexOf( ), charAt( ), replace( ), trim, Scanner, reg expr. Project… Add
‘em Up, Project… Encryption / Decryption

17-1

18

Arrays

Declaring and initializing, length, parallel arrays,
Out-of-bounds exception, passing an array to a method, automatic initialization, split, reg expr.
Project… Array of Hope

18-1

Table of Contents - 2
19

Advanced Array Concepts

Arrays of objects, comparison of array values, null pointer exception, different reference to same array, arraycopy, toCharArray, logical vs physical size,
Arrays class, sort, binarySearch, equals, fill, importing, command line arguments, enhanced forloop. Project… Sorting a String Array. Project…
Two Orders for the Price of One

19-1

20

Static Methods and State
Variables

Class methods and variables, static constants static imports. Project… How Far To The Line?

20-1

21

Wrapper Classes

Converting primitives to objects and vice versa

21-1

22

More on Wrapper Classes

parseInt, parseDouble, toHexString, toOctalString, toBinaryString, toString, valueOf

22-1

23

StringTokenizer Class

countTokens, nextToken, hasMoreTokens, delimiter, token, Project… Military Censor

23-1

24

Input from a Disk File

Scanner, File, throws IOException, readLine, Project for Reading Files, close, Project… Reading Files

24-1

25

Processing File Input with
Scanner

Processing text coded numbers, using parseInt and parseDouble, tokenizing and manipulating text,
Project… Get Rid of That Plus Sign!, Project…
Student Averages

25-1

26

Writing to a Text File

FileWriter, PrintWriter, print, println, appending to the end of a file, close, Project… Write Student
Averages

26-1

27

Formatting (rounding off)

NumberFormat, formatting numbers, currency, and percent, Formatter class, printf. Project…
BaseClass. Project… Gymnastics

27-1

28

Bitwise operators

Bitwise-AND, OR, exclusive-OR, and NOT.
Negative numbers, sign bit, msb, most significant bit

28-1

29

Advanced Bitwise Operations

Shift left and right, , >>>, preservation of sign, short-circuit, precedence. Negative numbers, sign bit, msb, most significant bit. Project…
Tweaking for Speed

29-1

30

Random Numbers

nextDouble, nextInt, Monte Carlo, simulations,
Project… Monte Carlo Technique

30-1

31

StringBuffer Class

append, toString, substring, length, setCharAt, delete, deleteCharAt, insert, charAt. Project…
Concatenations Gone Wild

31-1

32

Boolean Algebra and
DeMorgan’s Theorem

OR, AND, truth table

32-1

33

Selection Operator

?: syntax

33-1

34

Passing by Value and by
Reference

Arrays, primitives, objects, references. Project…
Pass the Gravy, Please

34-1

35

Two-Dimensional Arrays

Subscripted variables, matrix, initializing, Arrays class. Project… Matrix Multiplication, Project…
Matrix Multiplication with File Input

35-1

36

Inheritance

Superclass, subclass, base class, derived class, abstract, final, overriding, shadowing, cosmic superclass, instanceof, Object, this, super

36-1

37

Exceptions

Checked, unchecked, try, catch, finally, throw, throws, Project… Keep Trying

37-1

Table of Contents - 3
38

Interfaces

Implementation perspective,objective perspective, instanceof, polymorphism, realizes, implements.,Project… Linear Function

38-1

39

Complexity Analysis (Big O)

sequential search, binary search

39-1

40

Recursion

Factorial, Fibonacci series, Project… Fibonacci

40-1

41

Sorting Routines

selection, insertion, quick, & merge sorts, partition, big O chart, Project… Multiple Key Sorting

41-1

42

List Interface

ArrayList, LinkedList, Vector

42-1

43

ArrayList

advantages, disadvantages, Project… Big Bucks in the Bank

43-1

44

Iterator/ListIterator

stepping through a list, Project… Big Bucks
Revisited

44-1

45

Comparable/Comparator

compare objects, compare, compareTo, Project…
Sorting BankAccount Objects, Project…Sorting
BankAccount Objects Alphabetically, Project…
Sorting BankAccount Objects using a Comprator

45-1

46

HashSet/TreeSet

Set interface, Iterators, Project… HashSet/
Intersection, Project… HashSet/Union

46-1

47

HashMap/TreeMap

Keys, values, Map interface, iterator, Project…
Mapping Bank Accounts, Project…Code Talker,
Project…Histogram, Project…Student
Classification

47-1

48

Flow Charts & Optimizing for
Speed

Writing code for a flow chart. Project… Divisors of a Number, Project… Optimized Code for
Divisors, Project… Super Optimized Code for
Divisors, Speed tricks

48-1

49

Singly Linked List

Example list of pipeline nodes. Project… insert
Method for Singly Linked List

49-1

50

The LinkedList Class (doubly linked) and Stacks

Methods of the LinkedList class used to implement a
Stack class (push, pop, etc). Queues. Project…
StackLL Class. Project… Stack Calculator

50-1

51

Binary Search

Binary search of primitive arrays & object arrays, recursive search . Arrays.sort, Arrays.binarySearch.
Project…Binary Search, Reverse Order;
Project… Binary Search with Objects

51-1

52

Binary Search Trees

Binary search trees. Preorder, inorder, postorder, and in level traversals. Expression trees. Project… BST find Method

52-1

53

Queues

LinkedListQueue, ArrayListQueue. Project…
Who’s Next?, Project.… Shifting Marquee

53-1

54

Inner Classes

Project… Inner Class inside Outer Class,
Project… Inner Class Inside Method

54-1

55

Heaps

Complete and full trees, adding and deleting nodes.
Project… Printing a Heap, …A Heap of Trouble

55-1

56

Priority Queues

Heap based priority queue, array implementation.
Project… Who Has Highest Priority?, Project…
Smile for the Camera

56-1

57

Lookup Tables and Hashing

Lookup tables, hashing techniques, collisions, chaining, probing load factor, and Object class methods. Project… A Taste of Hash; Project…
Hashing Abraham Lincoln

57-1

Table of Contents - 4
Case Study… A major project… Distance to a Meandering Trail

CS1-1

Golden Nuggets of Wisdom are short learning/review activities. In the six weeks preceding an AP exam, contest, or other major evaluation, study one of these each day. Follow up with a quiz
(provided in the Teacher’s Test/Answer Book) on that topic the next day.
#1

Golden Nugget of Wisdom #1

loop variable after exiting loop

Ng1

#2

Golden Nugget of Wisdom #2

overriding, overloading, polymorphism

Ng2

#3

Golden Nugget of Wisdom #3

implements, realizes, log, exclusive or

Ng3

#4

Golden Nugget of Wisdom #4

charAt, special feature of substring

Ng4

#5

Golden Nugget of Wisdom #5

masking

Ng5

#6

Golden Nugget of Wisdom #6

implementing an interface, converting decimal number to binary, hex, an octal

Ng6

#7

Golden Nugget of Wisdom #7

StringBuffer insert,alph order, simultaneously adding and concatenating

Ng7

#8

Golden Nugget of Wisdom #8

escape characters, null, continue, break, selection

Ng8

#9

Golden Nugget of Wisdom #9

operator (?:), bitwise not, modulus with fractions

Ng9

#10

Golden Nugget of Wisdom #10

final, arraycopy, calling a different constructor

Ng10

#11

Golden Nugget of Wisdom #11

LIFO, FIFO, bitwise ANDing and ORing of booleans, modulus with negative numbers

Ng11

#12

Golden Nugget of Wisdom #12

casting, incompatible object comparison, access control modifier

Ng12

#13

Golden Nugget of Wisdom #13

mixed arithmetic, declaring an array of objects

Ng13

#14

Golden Nugget of Wisdom #14

equality between Wrapper class objects, hex, binary, octal, exclusive or

Ng14

#15

Golden Nugget of Wisdom #15

short circuiting, valueOf, converting numerics to
Strings

Ng15

#16

Golden Nugget of Wisdom #16

Order within method signature, String replace, nextToken delimiter

Ng16

#17

Golden Nugget of Wisdom #17

indexOf, different references to same array, setting arrays and other objects equal to null

Ng17

#18

Golden Nugget of Wisdom #18

subclass method overriding superclass method, equivalence of methods and function, equivalence of signatures and headers

Ng18

#19

Golden Nugget of Wisdom #19

multiple constructors

Ng19

#20

Golden Nugget of Wisdom #20

initialization blocks

Ng20

#21

Golden Nugget of Wisdom #21

initializing numeric state and method variables

Ng21

#22

Golden Nugget of Wisdom #22

prototype, short-circuiting, isLetter (etc)

Ng22

#23

Golden Nugget of Wisdom #23

char & int, ASCII, casting, XOR

Ng23

#24

Golden Nugget of Wisdom #24

boolean simplification, law of absorption, printing 2D arrays.

Ng24

#25

Golden Nugget of Wisdom #25

random numbers, maps, sets, keySet

Ng25

#26

Golden Nugget of Wisdom #26

recursion

Ng26

#27

Golden Nugget of Wisdom #27

Big O, floor, ceil, round

Ng27

#28

Golden Nugget of Wisdom #28

split method

Ng28

Table of Contents - 5
#29

Golden Nugget of Wisdom #29

Iterator, ListIterator, exceptions, abstract, final

Ng29

#30

Golden Nugget of Wisdom #30

Static methods and variables, NumberFormat,
ListIterator interface

Ng30

Appendix
A

Key Words

Reserved words that are part of Java

A-1

Appendix
B

Escape Sequences

\b \t \n \” \’ \\

A-1

Appendix
C

Primitive Data Types

byte, short, int, long, float, double, char, boolean

C-1

Appendix
D

ASCII Codes

Decimal, hex, octal, and html equivalents

D-1

Appendix
E

Saving Text Files

Windows settings, Notepad, WordPad

E-1

Appendix
F

Text and Binary Files Explained

Storage methods

F-1

Appendix
G

Two’s Complement Notation

Negative numbers, invert, ones’ compliment, ten’s complement, odometer, msb, sign bit

G-1

Appendix
H

Operator Precedence

Order of operations

H-1

Appendix
I

Creating Packages and
Importing Classes

Importing, package, wildcard, 6steps to create a package, classpath variable

I-1

Appendix
J

Typical Contest Classes and
Interfaces

Scope of UIL contest

J-1

Appendix
K

Exception Classes

A list of some checked and unchecked exceptions

K-1

Appendix
L

An Essay on Interfaces

Down to earth explanation of Interfaces

L-1

Appendix
M

Input from the Keyboard

BufferedReader, InputStreamReader.

M-1

Appendix
N

Using the BlueJ Programming
Environment

Creation of projects and classes

N-1

Appendix
O

Using the JCreator Programming
Environment

Creation of projects and classes

O-1

Appendix
P

Time Allocation for Lessons

Time allocation for each lesson

P-1

Appendix
Q

AP(A & AB) Correlation

Page number correlation

Q-1

Appendix
R

Texas TEKS/TAKS Correlation

Page number correlation to TEKS

R-1

Appendix
S

History of Computers

Pascal, Babbage, ENIAC, operating systems, MITS
Altair, TRS 80, Apple, IBM pc, disk storage, key punch cards

S-1

Appendix
T

Viruses

What a virus is, how they are spread, types, protection, ethics, and etiquette

T-1

Appendix
U

Enrichment Activities

Use of LANs and WANs, Using a scanner and OCR software, Software specifications, Publish
Information, Electronic communities

U-1

Table of Contents - 6
Appendix
V

Computer Languages

Java, Visual Basic, Java Script, Assembly language,
Machine code, Compiled vs Interpreted languages

V-1

Appendix
W

Binary Tree Terms

Definitions of terms related to binary trees.

W-1

Appendix
X

Compiling and Executing without and IDE

Using javac.exe, java.exe, and javaw.exe.
Compiling and executing, DOS prompt, Path
Variable

X-1

Appendix
Y

Kilobytes, Megabytes,
Gigabytes

Tables with exact values “power of two” equivalents

Y-1

Appendix
Z

The DecimalFormat Class

Formatting numbers, currency, and percents with patterns Z-1

Appendix
AA

Matrix Multiplication

Matrix multiplication explained in detail

AA-1

Appendix
AB

Monospaced Fonts

Vertical alignment of printout

AB-1

Appendix
AC

Regular Expressions

A discussion on how to build and interpret regular expressions. Additional methods of the String class; split, replaceAll, replaceFirst

AC-1

Appendix
AD

Formatter class specifiers and flags Format specifiers, format flags

AD-1

Appendix
AE

javaDoc

The javDoc technique for generating web based documentation. AE-1

Appendix
AF

Generic Classes

Creation of generic classes

AF-1

Index

Indx1

1-1

Lesson 1…..Hello World
Program Skeleton:
Enter the following program skeleton, compile (prepare it to run), and then run (execute).
Your instructor may have you give it a specific project name; otherwise, call the project
Lesson1.
If you do not know how to enter and execute a program, ask your instructor, or use the appendices in this book for two of the more popular programming environments. See Appendix N for the BlueJ environment and Appendix O for the JCreator environment. public class Tester
{
public static void main(String args[])
{
}
}
At this point don’t worry about what any of this means. It’s just something we must do every time. Soon we will learn the meaning of all of this. For now it’s just the skeleton that we need for a program.
Adding some meaningful code:
Now, let’s add some meaningful code inside the main method. (Notice this word, method. We will constantly refer to methods throughout this course.) We will also add a remark. public class Tester //We could put any name here besides Tester
{
public static void main(String args[])
{
System.out.println(“Hello world”);
}
}
Remarks:
Notice the rem (remark) above that starts with //. You can put remarks anywhere in the program without it affecting program operation. Remarks are also called comments or notes. Printing:
System.out.println(“Hello world” ); is how we get the computer to printout something.
Notice the trailing semicolon. Most lines of code are required to end in a semicolon.
Now try putting in some other things in the println parenthesis above. Each time recompile and run the program:
1. “Peter Piper picked a peck of pickled peppers.”
2. “I like computer science.”

1-2
3. 25/5
4. 4 / 7.0445902
5. 13 * 159.56
Two printlns for the price of one:
Next, modify your program so that the main method looks as follows: public static void main(String args[])
{
System.out.println(“Hello world”);
System.out.println(“Hello again”);
}
Run this and note that it prints :
Hello world
Hello again
Printing “Sideways”:
Now remove the ln from the first println as follows: public static void main(String args[])
{
System.out.print(“Hello world”);
System.out.println(“Hello again”);
}
Run this and note that it prints:
Hello worldHello again
Here are the rules concerning println and print:
• System.out.println( ) completes printing on the current line and pulls the print position down to the next line where any subsequent printing continues.
• System.out.print( ) prints on the current line and stops there. Any subsequent printing continues from that point.
An in-depth look at rems:
Let’s take a further look at rems. Consider the following program (class) in which we wish to document ourselves as the programmer, the date of creation, and our school: public class Tester
{
//Programmer: Kosmo Kramer
//Date created: Sept 34, 1492
//School: Charles Manson High School; Berkley, Ca public static void main(String args[])
{
System.out.println(“Hello again”);
}
}

1-3
Block rems:
It can get a little tedious putting the double slash rem-indicator in front of each line, especially if we have quite a few remark lines. In this case we can “block rem” all the comment lines as follows: public class Tester
{
/*Programmer: Kosmo Kramer
Date created: Sept 34, 1492
School: Charles Manson Junior High; Berkley, Ca*/ public static void main(String args[])
{
System.out.println(“Hello again”);
}
}
Notice we use /* to indicate the start of the block and */ for the end.
Everything between these two symbols is considered to be a remark and will be ignored by the computer when compiling and running.

Project… From Me To You

Create a new project called FromMeToYou having a Tester class with the following content.
Also include remarks above public class Tester that identifies you as the author along with the date of creation of this program:
//Author: Charles Cook
//Date created: Mar 22, 2005 public class Tester
{
public static void main(String args[])
{

}
}
Supply code in the place of … that will produce the following printout:
From: Bill Smith
Address: Dell Computer, Bldg 13
Date: April 12, 2005
To: Jack Jones
Message: Help! I'm trapped inside a computer!

2-1

Lesson 2…..Variable Types (String, int, double)
Three variable types:
(A good way to learn the following points is to modify the code of the “Hello World” program according to the suggestions below.)
1. String….used to store things in quotes….like “Hello world”
Sample code: public static void main(String args[])
{
String s = “Hello cruel world”;
System.out.println(s);
}
2. int ….used to store integers (positive or negative)
Sample code: public static void main(String args[])
{
int age = 59;
System.out.println(age);
}
3. double ….used to store “floating point” numbers (decimal fractions). double means
“double precision”.
Sample code: public static void main(String args[])
{
double d = -137.8036;
System.out.println(d);
d = 1.45667E23; //Scientific notation…means 1.45667 X 1023
}
Declaring and initializing:
When we say something like double x = 1.6; we are really doing two things at once. We are declaring x to be of type double and we are initializing x to the value of 1.6. All this can also be done in two lines of code (as shown below) instead of one if desired: double x; //this declares x to be of type double x = 1.6; //this initializes x to a value of 1.6
What’s legal and what’s not: int arws = 47.4; //illegal, won’t compile since a decimal number cannot “fit” into an
//integer variable. double d = 103; //legal…same as saying the decimal number 103.0

2-2
Rules for variable names:
Variable names must begin with a letter (or an underscore character) and cannot contain spaces. The only “punctuation” character permissible inside the name is the underscore
(“_”). Variable names cannot be one of the reserved words (key words…see Appendix
A) that are part of the Java language.
Legal names
Agro
D d31 hoppergee hopper_gee largeArea goldNugget Illegal names
139
139Abc fast One class slow.Sally double gold;Nugget hopper-gee Variable naming conventions:
It is traditional (although not a hard and fast rule) for variable names to start with a lower case letter. If a variable name consists of multiple words, combine them in one of two ways: bigValue… jam everything together. First word begins with a small letter and subsequent words begin with a capital. big_value… separate words with an underscore.

2-3

Exercise on Lesson 2
1. What are the three main types of variables used in Java and what are they used to store?
2. What type of variable would you use to store your name?
3. What type of variable would you use to store the square root of 2?
4. What type of variable would you use to store your age?
5. Write a single line of code that will create a double precision variable called p and store
1.921 X 10-16 in it.
6. Write a single line of code that will create an integer variable called i and store 407 in it. 7. Write a single line of code that will create a String variable called my_name and store your name in it.
8. Write a line of code that will declare the variable count to be of type int. Don’t initialize. 9. Write a line of code that initializes the double precision variable bankBalance to
136.05. Assume this variable has already been declared.
10. Which of the following are legal variable names? scooter13 139_scooter homer-5 ;mary public

doubled

double

ab c

11. Which of the following is the most acceptable way of naming a variable. Multiple answers are possible.
a. GroovyDude
b. GROOVYDUDE
c. groovyDude
d. Groovydude
e. groovy_dude
f. groovydude
12. Comment on the legality of the following two lines of code. double dist = 1003; int alt = 1493.86;

Lesson 3…..Simple String Operations

3-1

In this lesson we will learn just a few of the things we can do with Strings.
Concatenation:
First and foremost is concatenation. We use the plus sign, +, to do this. For example:
String mm = “Hello”;
String nx = “good buddy”;
String c = mm + nx;
System.out.println(c); //prints Hellogood buddy…notice no space between o & g
The above code could also have been done in the following way:
String mm = “Hello”;
String nx = “good buddy”;
System.out.println(mm + “ ” + nx); //prints Hello good buddy…notice the space
We could also do it this way:
System.out.println(“Hello” + “ good buddy”); // prints Hello good buddy
The length method:
Use the length( ) method to find the number of characters in a String:
String theName = “Donald Duck”; int len = theName.length( );
System.out.println(len); //prints 11…notice the space gets counted
Right now we don’t see much value in this length thing…just wait!
A piece of a String (substring):
We can pick out a piece of a String…substring
String myPet = “Sparky the dog”;
String smallPart = myPet.substring(4);
System.out.println(smallPart); //prints ky the dog
Why do we get this result? The various characters in a String are numbered starting on the left with 0. These numbers are called indices. (Notice the spaces are numbered too.)
Spa rky th e d o g … so now we see that the ‘k’ has index 4 and we go from
0 1 2 3 4 5 6 7 8 9 10 11 12 13 k all the way to the end of the string to get “ky the dog”.
A more useful form of substring:
But wait! There’s another way to use substring
String myPet = “Sparky the dog”;
String smallPart = myPet.substring(4, 12);
System.out.println(smallPart); //prints ky the d
How do we get ky the d? Start at k, the 4th index, as before. Go out to the 12th index, ‘o’ in this case and pull back one notch. That means the last letter is d.

3-2
Conversion between lower and upper case: toLowerCase converts all characters to lower case (small letters)
String bismark = “Dude, where’s MY car?”;
System.out.println( bismark.toLowerCase( ) ); // prints dude, where’s my car? toUpperCase converts all characters to upper case (capital letters)
System.out.println( “Dude, where’s My car?”.toUpperCase( ) );
//prints DUDE, WHERE’S MY CAR?
Note: length, substring, toLowerCase, and toUpperCase are all methods of the String class. There are other methods we will learn later.
Concatenating a String and a numeric:
It is possible to concatenate a String with a numeric variable as follows: int x = 27;
String s = “Was haben wir gemacht?”; //German for “What have we done?”
String combo = s + “ ” + x;
System.out.println(combo); //prints Was haben wir gemacht? 27
Escape sequences:
How do we force a quote character (“) to printout…. or, to be part of a String. Use the escape sequence, \”, to print the following (note escape sequences always start with the \ character…see Appendix B for more on escape sequences):
What "is" the right way?
String s = “What \"is\" the right way?”;
System.out.println(s); //prints What "is" the right way?
Another escape sequence, \n, will create a new line (also called line break) as shown below: String s = “Here is one line\nand here is another.”;
System.out.println(s);
Prints the following:
Here is one line and here is another.
The escape sequence, \\, will allow us to print a backslash within our String. Otherwise, if we try to insert just a single \ it will be interpreted as the beginning of an escape sequence.
System.out.println(“Path = c:\\nerd_file.doc”);
Prints the following:

3-3
Path = c:\nerd_file.doc
The escape sequence, \t, will allow us to “tab” over. The following code tabs twice.
System.out.println(“Name:\t\tAddress:”);
Prints the following:
Name:

Address:

Exercise on Lesson 3
1. Write code in which a String variable s contains “The number of rabbits is”. An integer variable argh has a value of 129. Concatenate these variables into a String called report.
Then print report. The printout should yield:
The number of rabbits is 129.
Note that we want a period to print after the 9.
2. What is the output of

System.out.println( p.toUpperCase( ) ); if p = “Groovy Dude”?

3. Write code that will assign the value of “Computer Science is for nerds” to the String variable g. Then have it print this String with nothing but “small” letters.
4. What will be the value of c?
String c;
String m = “The Gettysburg Address”; c = m.substring(4);
5. What will be the value c?
String b = “Four score and seven years ago,”; c = b.substring(7, 12);
6. What is the value of count? int count;
String s = “Surface tension”; count = s.length( );
7. Write code that will look at the number of characters in String m = “Look here!”; and then print “Look here!” has 10 characters.
Use the length( ) method to print the 10 ….you must also force the two quotes to print.
8. How would you print the following?
All “good” men should come to the aid of their country.

3-4
9. Write code that will produce the following printout using only a single println( ).
Hello
Hello again
10. Write code that will produce the following printout.
A backslash looks like this \, …right?
11. What is output by the following?
String pq = “Eddie Haskel”; int hm = pq.length( );
String ed = pq.substring(hm - 4);
System.out.println(ed);
12. Which character is at the 5th index in the String “Herman Munster”?

Project… Name that Celebrity
Create a new project called NameThatCelebrity in which only partially recognizable names of celebrities are to be produced. In a real implementation of this game, the idea is for a contestant to be able to guess the real name of the celebrity after the first two and last three letters are dropped from the name. We have been given the task of testing the feasibility of this idea by producing the following printout:
Allan Alda>>>lan A
John Wayne>>>hn Wa
Gregory Peck>>>egory P
Begin your code within the main method as follows:
String s1 = “Allan Alda”;
String s2 = “John Wayne”;
String s3 = “Gregory Peck”;
Apply the length and substring methods to these Strings to produce the above printout.

4-1

Lesson 4…..Using Numeric Variables
The assignment operator:
The assignment operator is the standard equal sign (=) and is used to “assign” a value to a variable. int i = 3; // Ok,…assign the value 3 to i. Notice the direction of data flow.
3 = i; // Illegal! Data never flows this way! double p; double j = 47.2; p = j; // assign the value of j to p. Both p and j are now equal to 47.2
Multiple declarations:
It is possible to declare several variables on one line: double d, mud, puma; //the variables are only declared double x = 31.2, m = 37.09, zu, p = 43.917; //x, m, & p declared and initialized
// zu is just declared
Fundamental arithmetic operations:
The basic arithmetic operation are +, -, * (multiplication), / (division), and % (modulus).
Modulus is the strange one. For example, System.out.println(5%3); will print 2.
This is because when 5 is divided by 3, the remainder is 2. Modulus gives the remainder. Modulus also handles negatives. The answer to a%b always has the same sign as a. The sign of b is ignored.
PEMDAS:
The algebra rule, PEMDAS, applies to computer computations as well. (PEMDAS stands for the order in which numeric operations are done. P = parenthesis, E = exponents,
M = multiply, D = divide, A = add, S = subtract. Actually, M and D have equal precedence, as do A and S. For equal precedence operation, proceed from left to right. A mnemonic for PEMDAS is, “Please excuse my dear Aunt Sally”… See Appendix H for the precedence of all operators.)
System.out.println(5 + 3 * 4 –7); //10
System.out.println(8 – 5*6 / 3 + (5 –6) * 3); //-5
Not the same as in Algebra:
An unusual assignment….consider the following: count = count +3; //this is illegal in algebra; however, in computer science it
//means the new count equals the old count + 3. int count =15; count = count + 3;

4-2
System.out.println(count); //18
Increment and Decrement:
The increment operator is ++, and it means to add one. The decrement operator is --, and it means to subtract one: x++; x--; x++ x--

means the same as means the same as is the same as ++x is the same as --x

x = x +1; x = x – 1;
(the ++ can be on either side of x)
(the -- can be on either side of x)

int y = 3; y++; System.out.println(y); //4
Compound operators:
Syntax Example
a. += x += 3;

Simplified meaning x = x + 3;

b. -= x -= y - 2;

x = x – (y - 2);

c. *= z*= 46;

z = z * 46;

d. /= p/= x-z;

p = p / (x-z);

e. %= j%= 2

j = j%2;

Code Examples int g = 409; g += 5;
System.out.println(g); //414 double d = 20.3; double m =10.0; m*=d –1;
System.out.println(m); //193.0

The whole truth:
Actually, the full truth was not told above concerning x++. It does not always have the same effect as does ++x. Likewise, x-- does not always have the same effect as does --x. x++ increments x after it is used in the statement.
++x increments x before it is used in the statement.

4-3
Similarly,
x-- decrements x after it is used in the statement.
--x decrements x before it is used in the statement.
Code Examples int q = 78; int p = 2 + q++;
System.out.println(“p = ” + p + “, q = ” + q); //p = 80, q = 79 int q = 78; int p = ++q + 2;
System.out.println(“p = ” + p + “, q = ” + q); //p = 81, q = 79
Integer division truncation:
When dividing two integers, the fractional part is truncated (thrown away) as illustrated by the following: int x = 5; int y = 2;
System.out.println(x / y); //Both x and y are integers so the “real” answer of 2.5
//has the fractional part thrown away to give 2

Exercise on Lesson 4
Unless otherwise directed in the following problems, state what is printed. Some of these problems may have incorrect syntax and in those cases you should answer that the code would not compile.
1. int h = 103; int p =5;
System.out.println(++h + p);
System.out.println(h);
2. Give three code examples of how to increment the integer j by 1.
3. double def; double f = 1992.37; def = f;
System.out.println(def);

4-4
4. Write a single line of code that will print the integer variable zulu and then decrement its value by 1.
5. int a = 100; int b = 200; b/=a; System.out.println(b + 1);
6. Write a single line of code that uses the compound operator, -=, to subtract p-30 from the integer value v and store the result back in v.
7. Write a single line of code that does the same thing as #6 but without using - =.
8. int p = 40; int q = 4;
System.out.println(2 + 8 * q / 2 - p);
9. int sd = 12; int x = 4;
System.out.println( sd%(++x) );
System.out.println(x);
10. int g;
3 = g;
System.out.println(++g*79);
What is the result?
11. On a single line of code declare m, b, and f to be double and on that same line initialize them all to be 3.14.
12. On a single line of code declare x, y, and z all to be of integer type.
13. int m = 36; int j = 5; m = m / j; // new m is old m divided by j
System.out.println(m);
What’s printed?
14. System.out.println(3/4 + 5*2/33 –3 +8*3);
What’s printed?

4-5
15. What is the assignment operator?
16. Write a statement that stores the remainder of dividing the variable i by j in a variable named k.
17. int j = 2;
System.out.println(7%3 + j++ + (j – 2) );
18. Show three different ways to decrement the variable j.

Project… Cheating on Your Arithmetic Assignment
Create a new project called ArithmeticAssignment with a class called Tester that will calculate and print the results of the following arithmetic problems:
79 + 3 * (4 + 82 –68) – 7 +19
(179 +21 +10) / 7 + 181
10389 * 56 * 11 + 2246
The printout should look like the following:
79 + 3 * (4 + 82 - 68) -7 + 19
(179 + 21 + 10) / 7 + 181 =
10389 * 56 * 11 + 2246

=

=

211

6401870

145

5-1

Lesson 5…..Mixed Data Types, Casting, and Constants
So far we have looked mostly at simple cases in which all the numbers involved in a calculation were either all integers or all doubles. Here, we will see what happens when we mix these types in calculations.
Java doesn’t like to lose data:
Here is an important principle to remember: Java will not normally store information in a variable if in doing so it would lose information. Consider the following two examples:
1. An example of when we would lose information: double d = 29.78; int i = d; //won’t compile since i is an integer and it would have to chop-off
// the .78 and store just 29 in i….thus, it would lose information.
There is a way to make the above code work. We can force compilation and therefore result in 29.78 being “stored” in i as follows (actually, just 29 is stored since i can only hold integers): int i = (int)d; //(int) “casts” d as an integer… It converts d to integer form.
2. An example of when we would not lose information: int j = 105; double d = j; //legal, because no information is lost in storing 105 in the
// double variable d.
The most precise:
In a math operation involving two different data types, the result is given in terms of the more precise of those two types…as in the following example: int i = 4; double d = 3; double ans = i/d; //ans will be 1.33333333333333…the result is double precision
20 + 5 * 6.0 returns a double. The 6.0 might look like an integer to us, but because it’s written with a decimal point, it is considered to be a floating point number…a double.
Some challenging examples:
What does 3 + 5.0/2 + 5 * 2 – 3 return? 12.5
What does 3.0 + 5/2 + 5 * 2 – 3 return? 12.0
What does (int)(3.0 + 4)/(1 + 4.0) * 2 – 3 return? -.2
Don’t be fooled:
Consider the following two examples that are very similar…but have different answers: 5-2 double d = (double)5/4; //same as 5.0 / 4…(double) only applies to the 5
System.out.println(d); //1.25 int j = 5; int k = 4; double d = (double)(j / k); //(j / k) is in its own little “world” and performs
//integer division yielding 1 which is then cast as
//a double, 1.0
System.out.println(d); //1.0
Constants:
Constants follow all the rules of variables; however, once initialized, they cannot be changed. Use the keyword final to indicate a constant. Conventionally, constant names have all capital letters. The rules for legal constant names are the same as for variable names. Following is an example of a constant: final double PI = 3.14159;
The following illustrates that constants can’t be changed: final double PI = 3.14159;
PI = 3.7789; //illegal
When in a method, constants may be initialized after they are declared. final double PI; //legal
PI = 3.14159;
Constants can also be of type String, int and other types. final String NAME= “Peewee Herman”; final int LUNCH_COUNT = 122;

Project… Mixed Results

Create a new project called MixedResults with a class called Tester. Within the main method of Tester you will eventually printout the result of the following problems. However, you should first calculate by hand what you expect the answers to be. For example, in the parenthesis of the first problem, you should realize that strictly integer arithmetic is taking place that results in a value of 0 for the parenthesis. double d1 = 37.9; //Initialize these variables at the top of your program double d2 = 1004.128; int i1 = 12; int i2 = 18;
Problem 1:
Problem 2:
Problem 3:
Problem 4:
Problem 5:

57.2 * (i1 / i2) +1
57.2 * ( (double)i1 / i2 ) + 1
15 – i1 * ( d1 * 3) + 4
15 – i1 * (int)( d1 * 3) + 4
15 – i1 * ( (int)d1 * 3) + 4

5-3
Your printout should look like the following:
Problem
Problem
Problem
Problem
Problem

1:
2:
3:
4:
5:

1.0
39.13333333333333
-1345.39999999999
-1337
-1313

Exercise on Lesson 5
Unless otherwise instructed in the following problems, state what gets printed.
1. Write code that will create a constant E that’s equal to 2.718.
2. Write the simplest type constant that sets the number of students, NUM_STUDENTS, to 236.
3. What’s wrong, if anything, with the following code in the main method? final double Area;
Area = 203.49;
4. int cnt = 27.2;
System.out.println(cnt);
What’s printed?
5. double d = 78.1; int fg = (int)d;
System.out.println(fg);
What’s printed?
6. Is

double f4 = 22;

legal?

7. The following code stores a 20 in the variable j: double j = 61/3;
What small change can you make to this single line of code to make it print the “real” answer to the division?
8. System.out.println( (double)(90/9) );
9. System.out.println(4 + 6.0/4 + 5 * 3 – 3);

5-4
10. int p = 3; double d = 10.3; int j = (int)5.9;
System.out.println(p + p * d – 3 * j);
11. int p = 3; double d = 10.3; int j = (int)5.9;
System.out.println(p + p * (int)d – 3 * j);
The following code applies to 12 – 15: int dividend = 12, divisor = 4, quotient = 0, remainder = 0; int dividend2 = 13, divisor2 = 3, quotient2 = 0, remainder2 = 0; quotient = dividend/divisor; remainder = dividend % divisor; quotient2 = dividend2 / divisor2; remainder2 = dividend2 % divisor2;
12. System.out.println(quotient);
13. System.out.println(remainder);
14. System.out.println(quotient2);
15. System.out.println(remainder2);
16. Write a line of code in which you divide the double precision number d by an integer variable called i. Type cast the double so that strictly integer division is done. Store the result in j, an integer.
17. Suppose we have a line of code that says final String M = “ugg”;
Later in the same program, would it be permissible to say the following?
M = “wow”;

Lesson 6…..Methods of the Math Class

6-1

One of the most useful methods of the Math class is sqrt( ) …which means square root. For example, if we want to take the square root of 17 and store the result in p, do the following: double p = Math.sqrt(17);
Notice that we must store the result in a double…. p in this case. We must store in a double since square roots usually don’t come out even.
Signature of a method:
Below we will give the description of some methods of the Math class… along with the signatures of the method. First, however, let’s explain the meaning of signature (also called a method declaration). Consider the signature of the sqrt( ) method: double sqrt( double x )
|
|
|
type returned method name type of parameter we send to the method

Method
Signature
Description abs int abs(int x)
Returns the absolute value of x abs double abs(double x)
Returns the absolute value of x pow double pow(double b, double e)
Returns b raised to the e power sqrt double sqrt(double x)
Returns the square root of x ceil double ceil(double x)
Returns next highest whole number from x floor double floor(double x)
Returns next lowest whole number from x min double min(double a, double b)
Returns the smaller of a and b
Returns the larger of a and b max double max(double a, double b) min int min(int a, int b)
Returns the smaller of a and b max int max(int a, int b)
Returns the larger of a and b
(For both min and max there are also versions that both accept and return types float, short, and long. See Appendix C for more on these three data types.) random double random( )
Returns a random double (range 0≤ r < 1) round long round(double x)
Returns x rounded to nearest whole number
PI
double PI
Returns 3.14159625…..
Now, we offer examples of each (most of these you can do on a calculator for verification):
1. double d = -379.22;
System.out.println( Math.abs(d) ); //379.22
2. double b = 42.01; double e = 3.728;
System.out.println ( Math.pow(b, e) ); //1126831.027
3. double d = 2034.56;
System.out.println( Math.sqrt(d) ); //45.10609715
4. double d = 1.4;
System.out.println( Math.ceil(d) ); //2.0

6-2
5. double d = -1.6;
System.out.println( Math.ceil(d) ); //-1.0
6. double d = 1.4;
System.out.println( Math.floor(d) ); //1.0
7. double d = -1.6;
System.out.println( Math.floor(d) ); //-2.0
The last four examples illustrating floor and ceiling are best understood with the following drawing: ceiling 2
1

1.4

floor

0 ceiling -1
-2

-1.6

floor

Just think of the ceiling as it is in a house… on top. Likewise, think of the floor as being on the bottom.
Therefore, Math.ceil(-1.6) being -1 makes perfect sense since -1 is above. Similarly, -2 is below -1.6 so it makes sense to say that -2 is Math.floor(-1.6).

Figure 6-1 Relationship of ceiling and floor

8. double d = 7.89;
System.out.println(Math.log(d)); //2.065596135 …log is base e.
9. double x = 2038.5; double y = -8999.0;
System.out.println( Math.min(x,y) ); //-8999.0
10. double x = 2038.5; double y = -8999.0;
System.out.println( Math.max(x,y) ); //2038.5
11. double x = 148.2;
System.out.println( Math.round(x) ); //148 double x = 148.7;
System.out.println( Math.round(x) ); //149 double x = -148.2;
System.out.println( Math.round(x) ); //-148 double x = -148.7;
System.out.println( Math.round(x) ); //-149
12. System.out.println(Math.PI); //3.14159265…

6-3
Advanced Math methods:
Below are some additional Math methods that advanced math students will find useful:
Method
log sin cos tan asin acos atan toDegrees toRadians

Signature double log(double x) double sin(double a) double cos(double a) double tan(double a) double asin(double x) double acos(double x) double atan(double x) double toDegrees(double angRad) double toRadians(double angDeg)

Description
Returns log base e of x
Returns the sine of angle a… a is in rad
Returns the cosine of angle a… a is in rad
Returns the tangent of angle a… a is in rad
Returns arcsine of x…in range -PI/2 to PI/2
Returns arccosine of x…in range 0 to PI
Returns arctan of x. in range -PI/2 to PI/2
Converts radians into degrees
Converts degrees into radians

Exercise on Lesson 6
1. Write code that will take the square root of x and store the result in y.
2. Write code that will multiply the value of the integer j times the absolute value of the integer m and then store the result in the integer k.
3. Is the following legal? If not, what would you do to make it legal? int k = Math.abs(-127.5);
4. Write a statement that will print the result of 21.5.
5. System.out.println( Math.ceil(-157.2) );
6. System.out.println( Math.floor(-157.2) );
7. System.out.println( Math.ceil(157.2) );
8. System.out.println( Math.floor(157.2) );
9. System.out.println( Math.round(-157.2) );
10. System.out.println( Math.ceil(-157.7) );

6-4
11. System.out.println( Math.ceil(157) );
12. System.out.println( Math.ceil(157.7) );
13. Write a statement that will print the natural log of 18…. same as ln(18) on a calculator.
14. Write a line of code that multiplies double p times π and stores the result in b.

Project… Compute This
Create a new project called ComputeThis having a class called Tester. The main method of
Tester should calculate the value of the following formulas and present the answers as shown. d1 = 3πsin(187°) + |cos(122°)|

…Remember that the arguments of sin and cos must be in radians.

d2 = (14.72)3.801 + ln 72

…ln means log base e

The output of your code should appear as follows: d1 =

-0.618672237585067

d2

=

27496.988867001543

Verify these answers with a calculator.

7-1

Lesson 7…. Input from the Keyboard
We will consider how to input from the keyboard the three data types…. int, double, and String.
Inputting an integer:
Use the nextInt method to input an integer from the keyboard: import java.io.*; //see “Imports necessary” on next page import java.util.*; public class Tester
{
public static void main( String args[] )
{
Scanner kbReader = new Scanner(System.in); //see “Mysterious
//objects” on next page
System.out.print(“Enter your integer here. ”); //enter 3001 int i = kbReader.nextInt( );
System.out.println(3 * i); //prints 9003
}
}
Inputting a double:
Use the nextDouble method to input a double from the keyboard: import java.io.*; import java.util.*; public class Tester
{
public static void main( String args[] )
{
Scanner kbReader = new Scanner(System.in);
System.out.print(“Enter your decimal number here. ”); //1000.5 double d = kbReader.nextDouble( );
System.out.println( 3 * d ); //prints 3001.5
}
}
Inputting a String:
Use the next method to input a String from the keyboard: import java.io.*; import java.util.*; public class Tester{ public static void main( String args[] )
{
Scanner kbReader = new Scanner(System.in);
System.out.print(“Enter your String here. ”); //Enter One Two
String s = kbReader.next( ); //inputs up to first white space
System.out.println( “This is the first part of the String,… ” + s); s = kbReader.next( );
System.out.println( “This is the next part of the String,… ” + s);
}
}

7-2
Output would be as shown below:
Enter your String here. One Two
This is first part of the String,... One
This is next part of the String,... Two
Multiple inputs:
In a similar way nextInt( ) and nextDouble( ) can be used multiple times to parse data input from the keyboard. For example, if 34 88 192 18 is input from the keyboard, then nextInt( ) can be applied four times to access these four integers separated by white space.
Inputting an entire line of text:
Inputting a String (it could contain spaces) from the keyboard using nextLine( ): import java.io.*; import java.util.*; public class Tester
{
public static void main( String args[] )
{
Scanner kbReader = new Scanner(System.in);
System.out.print(“Enter your String here. ”); //Enter One Two
String s= kbReader.nextLine( );
System.out.println( “This is my string,… ” + s);
}
}
Output would be as shown below:
Enter your String here. One Two
This is my string,... One Two
Imports necessary:
We must import two classes,….java.io.* and java.util.* that provide methods for inputting integers, doubles, and Strings. See Appendix I for more on the meaning of
“importing”.
Mysterious objects:
In the above three examples we used the following code:
Scanner kbReader = new Scanner(System.in);
It simply creates the keyboard reader object (we arbitrarily named it kbReader) that provides access to the nextInt( ), nextDouble( ), next( ), and nextLine( ) methods. For now just accept the necessity of all this…it will all be explained later. The Scanner class used here to create our keyboard reader object only applies to1.5.0_xx or higher versions of Java. For older versions, see Appendix M for an alternate way to obtain keyboard input.

7-3
An anomaly:
Using a single Scanner object, the methods nextInt( ), nextDouble( ), next( ), and nextLine( ) may be used in any sequence with the following exception:
It is not permissible to follow nextInt( ) or nextDouble( ) with nextLine( ). If it is necessary to do this, then a new Scanner object must be constructed for use with nextLine( ) and any subsequent inputs.

Project… Going in Circles
The area of a circle is given by: area = π (r2)
Now, suppose we know the area and wish to find r. Solving for r from this equation yields: ________ r = √ (area / π)
Write a program (project and class both named RadiusOfCircle) that uses sqrt( ) and PI from the Math class to solve for the radius of a circle. Use keyboard input to specify the area (provide for the possibility of area being a decimal fraction).
Write out your solution by hand and then enter it into the computer and run. Before inputting the area, put a prompt on the screen like this.
What is the area? _

…(the underscore indicates the cursor waiting for input)

Present your answer like this:
Radius of your circle is 139.4.

Project… What’s My Name?
From the keyboard enter your first and then your last name, each with its own prompt.
Store each in a separate String and then concatenate them together to show your full name. Call both the project and the class FullName. When your program is finished running, the output should appear similar to that below:
What is your first name? Cosmo
What is your last name? Kramer
Your full name is Cosmo Kramer.

8-1

Lesson 8…The boolean Type and boolean Operators
Back in Lesson 2 we looked at three fundamental variable types… int, double, and String. Here, we look at another very important type…..boolean. This type has only two possible values… true or false.
Only two values:
Let’s look at some statements that could come out either true or false. Suppose we know that x = 3 and also that y = 97. What could we say about the truth (or falseness) of the following statements?
( (x =90)
{
System.out.println(“You made an A.”);
}
else if (theGrade>=80)
{
System.out.println(“You made a B.”);
}
else if (theGrade>=70)
{
System.out.println(“You made a C.”);
}
else if (theGrade>=60)
{
System.out.println(“You made a D.”);
}
else
{
System.out.println(“Sorry, you failed.”);
}

9-3

Exercise on Lesson 9
Use the following code for problems 1 – 10 and give the value of true_false for each: int i = 10, j = 3; boolean true_false;
1. true_false = (j > i);
2. true_false = (i > j);
3. true_false = (i= = j);
4. true_false = ( (j = i ) );
5. true_false = ( (i > j) && (j = = 0) );
6. true_false = ( (j < 50) | | (j != 33) );
7. true_false = ( !(j >= 0) | | (i 3) | | (5= =5) && (7>1) && (43) && !(q 3) || (q < b) )
d. !( !(p = b) )
e. More than one of these
14. Write a Boolean expression that produces the following truth table:
A

B
C
( input )
0
0
0
0
0
1
0
1
0
0
1
1
1
0
0
1
0
1
1
1
0
1
1
1

D
(output)
1
0
1
0
1
0
0
0

32-5

Boolean Algebra and DeMorgan’s Theorem… Contest Type
Problems
1. If we call bolTest(x, y) in the code to the right, which of the following is equivalent to what it returns? (assume that x and y are boolean types)
A.
B.
C.
D.
E.

!(x && y)
!(x && !y)
!x && y x || !!y
None of these

2. What is output in the code to the right?
A.
B.
C.
D.
E.

public static boolean bolTest(boolean a, boolean b) { boolean temp = !a || b; return temp;
}

Throws an exception false true
!bv
None of these

boolean bv = true; for(int j=0; j30) { return !!!(sv || !b); //
}
else { return false;
}
} private boolean sv;
}

33-1

Lesson 33…..Selection Operator (?:) ...ternary conditional
A strange syntax:
Consider the code fragment: double d = m > 0? x + 1.1 : x * x;
It is easy to understand this syntax if we see the equivalent code implemented with an ordinary if statement. double d; if (m > 0)
{
d = x + 1.1;
}
else
{
d = x * x;
}
General form of the selection operator:
(a boolean test) ? value1 : value2

…where value1 is returned if boolean is true; otherwise, value2 is returned

Below, are three examples of usage of the selection operator.
1. Example: int m = 15; double pos1 = b ? m + 1:m * 2;
System.out.println(pos1); //If b is true, prints 16. If b is false, prints 30.
2. Example: int jack = 19; double jill = 19.2; double merv = 22.02; int jDark = (jack = = jill) ? (int)(merv + 20) : (int)merv++;
System.out.println(jDark); //22
3. Example: int j = 4, k =5; int p = (j q)
{
i = 3;
}
else
{
i = 5;
}
}

It is recommended to not use the selection operator in code that you create. Use an if statement instead; however, it is sometimes valuable to know selection operator syntax when reviewing the code of others.

33-3

Exercise for Lesson 33
1. Write the equivalent of the following code using an if statement. j = kimTrq < jDorch ? Math.pow(3,p) : p * p;
2. What is output if a = true, b = false, m = 200?
System.out.println(a && b? m*m:--m);
3. What is the value of v if m = true and n = true? boolean v = m||n ? (m && !n) : (m || !n);
4. double g = 5.0, h = -2.0, s = 9.0; int ii = (g>=h) ? (int)(h+2) : (int)(s++);
What is the value of ii?
5. What is output by the following code? int soy = 12, tabasco = 10, noodles = 4, sauce = 0; int ugh = (Math.pow(soy, noodles)20.13)? “maybe”: “yes”: “no way”;
System.out.println(s);
8. What would have been the answer to problem 7 if toy had been equal to “Barbie”?

33-4

Selection Operator… Contest Type Problems
1. What would be an appropriate way to call vogue from some other class besides
Tire? (assume a and b are booleans)
A. String s; s = vogue(false, a&&b?a:!b);
B. int i; i = vogue(false, a&&b?a:!b);
C. vogue(false, a&&b?a:!b);
D. boolean bb;
Tire obj = new Tire( ); bb = obj.vogue(false, a&&b?a:!b);
E. boolean bol;
Tire obj = new Tire( ); bol = obj.vogue(3, a&&b?a:!b);

public class Tire
{
… public boolean vogue(boolean p, boolean q)
{
boolean perk; perk = !p || q ? p&&q : p||q; return perk;
}

}

2. What is returned by the method call, vogue(true, false)?
A.
B.
C.
D.
E.

0 false true
Nothing
None of these

3. Which of the following selection operator statements does the equivalent of the code to the right? m = (j= =g)?++j:37; m = if(j = =g)?j++:37; m = (j= =g)?37:j++; m = (j= =g)?j:37;
++j;
E. None of these

A.
B.
C.
D.

4. What will be the value of ht after the method call, ht = nerdMethod(false, false);? A.
B.
C.
D.

15.70796327
18.3
3.141592654 nerdMethod is static and can’t be called without creating an object
E. false

if(j = = g)
{
m = j++;
}
else
{
m = 37;
}

public static double nerdMethod(boolean x, boolean y)
{
double coneHeight; coneHeight = !(x&&y) ? 18.3 : 5 * Math.PI; return coneHeight;
}

34-1

Lesson 34…..Passing by Value and by Reference
Consider the following class: public class Tester
{
public static void main(String[] args)
{
double b[]= new double[10]; b[3] = 19;
BankAccount myAccount = new BankAccount(79); //sets balance to
//79
int y =39; method1(y, b, myAccount);
System.out.println(y + " " + b[3] + "
" + myAccount.balance);
//prints …. 39 -54.0 702.0
}
public static void method1(int x, double a[ ], BankAccount theAccount)
{
x =332; a[3] = -54; theAccount.balance = 702;
}
}
Passing by value:
This demonstrates that primitive data types like int, double, etc. are passed by value; i.e. a new copy of the variable is temporarily created in the method and any changes to that variable in the method are not made to the original. Notice above that we pass an int type y to the method where the temporary copy is called x. The x is changed to 332; however, back in the calling code, y stays at its original value of 39.
Passing by reference:
Arrays (the b[ ] array) and objects (myAccount) are passed by reference. Notice both of these are modified in method1, and sure enough, back in the calling code these changes are reflected there.
Actually, arrays are objects, so our rule is simply stated, “Objects are passed by reference.” There is an exception to the above rule. A String is an object; however, it acts like a primitive data type and is passed by value.
Passing an array to a method:
Now we are going to look a little deeper into passing arrays to methods. We must remember that the array may be named something different in the method; however, that new name is just a reference back to the original array. Passing an array does not create a new array in the method.

34-2
Consider the following code: public class Tester
{
public static void main(String args[])
{
int s[] = {1,2,3,4,5,6}; for(int g = 0; g < s.length; g++) //prints first
System.out.print(s[g] + " ");
System.out.print("\n");
testMethod(s); for(int g = 0; g < s.length; g++) //prints last
System.out.print(s[g] + " ");
}
public static void testMethod(int pp[])
{
//pp references the s array in main int len = pp.length; int t2[] = new int[len]; for(int j=0; j 0)
{ //d should be inserted somewhere in the branch to the right if(rightNode != null)
//right node exists, go down that branch, look for place to put it rightNode.addNode(d); else rightNode = new BsTree(d); //Create new rightNode, store d in it
}
else
{ //d should be inserted somewhere in the branch to the left if(leftNode != null)
//left node exists, go down that branch, look for place to put it leftNode.addNode(d); else leftNode = new BsTree(d); //Create a new leftNode, store d in it
}
return this;
}
private Comparable theData; private BsTree leftNode, rightNode;
}

It is left to the reader to create a find method comparable to those of the BST class earlier in this lesson. We also need a traverseAndPrint method for this class. Three different versions of traverseAndPrint will be offered below as the various types of traversals are discussed. 52-8
Traversal types:
There are four traversal types. They are preorder, inorder, postorder, and level order traversals.
Each visits all of the nodes in the tree, but each in a different order.
Preorder traversal of a Binary Search Tree:
Order of visitation of nodes: 50, 25, 18, 7, 19, 35, 30, 37, 76,
61, 56, 68, 80, 78, 85
Fig. 52-8
Preorder traversal follows the sequence of arrows. Rule: A node is visited before its descendants.

50
25

76

18
19

7

61

35
30

37

80
68

56

85

78

The following code implements a preorder traversal of a tree as depicted in Fig. 52-8. An easy way to remember this code is to note the printing for this preorder traversal comes before the two recursive calls. public void traverseAndPrint( ) //Use with BsTree class on previous page.
{
System.out.println(theData); if( leftNode != null ) leftNode.traverseAndPrint( ); if( rightNode != null ) rightNode.traverseAndPrint( );
}

Inorder traversal of a Binary Search Tree:
Order of visitation of nodes: 7, 18, 19, 25, 30, 35, 37, 50, 56,
61, 68, 76, 78, 80, 85
50
25

76

18
7

61

35
19

30

37

56

80
68

78

85

Fig. 52-9
Inorder traversal follows the sequence of arrows. The order is the ascending order of a sorted list. Rule: A node is visited after its left subtree and before its right subtree. The following code implements an inorder traversal of a tree as depicted in Fig. 52-9. This technique is important since it visits the nodes in a “sorted order.” An easy way to remember this code is to note the printing for this inorder traversal comes in-between the two recursive calls. public void traverseAndPrint( )
{

52-9 if( leftNode != null ) leftNode.traverseAndPrint( );
System.out.println(theData);
if( rightNode != null ) rightNode.traverseAndPrint( );
}
//Exchanging the first and last lines of this method results in a reverse-order traversal.
Postorder traversal of a Binary Search Tree:
Order of visitation of nodes: 7, 19, 18, 30, 37, 35, 25, 56, 68,
61, 78, 85, 80, 76, 50
Fig. 52-10
Postorder traversal follows the sequence of arrows. Rule: A node is visited after its descendants.

50
25

76

18
19

7

61

35
30

37

80
68

56

85

78

The following code implements a postorder traversal of a tree as depicted in Fig. 52-10. An easy way to remember this code is to note the printing for this postorder traversal comes after the two recursive calls. public void traverseAndPrint( )
{
if( leftNode != null ) leftNode.traverseAndPrint( ); if( rightNode != null ) rightNode.traverseAndPrint( );
System.out.println(theData);
}

Level order traversal of a Binary Search Tree:
Order of visitation of nodes: 50, 25, 76, 18, 35, 61, 80, 7, 19,
30, 37, 56, 68, 78, 85
Fig. 52-11
Level order traversal follows the sequence of arrows.

50
25

76

18
7

19

30

80

61

35
37

56

68

78

85

The code that would implement this is a bit more involved than the others. One way to do it is to have counters that keep up with how deep we are in the tree.

52-10

An Application of Binary Trees… Binary Expression Trees
Consider the infix expressions (6 + 8) * 2 and 5 + (3 * 4).
The expression trees to the right are a result of parsing these expressions. As can be inferred from the drawings, the following rules apply for an expression tree:




Each leaf node contains a single operand.
Each interior node contains an operator.
The left and right subtrees of an operator node represent subexpressions that must be evaluated before applying the operator at the operator node. o The levels of the nodes in the tree indicate their relative precedence of evaluation. o Operations at the lower levels must be done before those above them. o The operation at the root of the tree will be the last to be done.

*
2

+
6

8

Fig. 52-12 (6 + 8) * 2

+
5

*
3

4

Fig 52-13 5 + (3 * 4)

We will now look at a larger expression tree and see how the inorder, preorder, and postorder traversals of the tree have special meanings with regard to the mathematics of an expression.
*
7

/
+

2
6

9

Fig. 52-14 A binary expression tree for the infix expression
(7 - 2) * ( (6+3) / 9)

3

An Inorder Traversal of the above expression tree yields the infix form: (7 - 2) * ( (6+3) / 9)
A Preorder Traversal of the above expression tree yields the prefix form: * - 7 2 / + 6 3 9
A Postorder Traversal of the above expression tree yields the postfix form: 7 2 - 6 3 + 9 / *
Notice that the postfix form is Reverse Polish Notation (RPN), the form that was used for the stack calculator of Lesson 50.

52-11

Binary Search Tree… Contest Type Problems
1. Which of the following replaces in the code to the right to make the traverseAndPrint method visit and print every node in a “Postorder” fashion?
A. if(leftNd != null) leftNd.traverseAndPrnt( );
System.out.print(info);
if(rightNd!=null) rightNd.traverseAndPrnt( );

//Binary Search Tree public class Bst
{
public Bst(Comparable addValue)
{
info = addValue;
}
public Bst addNd(Comparable addValue)
{
int cmp = info.compareTo(addValue);

B. if(leftNd != null) leftNd.traverseAndPrnt( ); if(rightNd!=null) rightNd.traverseAndPrnt( );
System.out.print(info);

if(cmp0)
{
if(leftNd!=null) leftNd.addNd(addValue); else leftNd=new Bst(addValue);
}
return this;

C. System.out.print(info); if(leftNd != null) leftNd.traverseAndPrnt( ); if(rightNd!=null)rightNd.traverseAndPrnt( );
D. leftNd.traverseAndPrnt( ); rightNd.traverseandPrnt( );
E. None of these
2. Assume has been filled in correctly. Which of the following creates a Bst object obj and adds 55 as a wrapper class Integer?
A. Integer J;
J = 55;
Bst obj = Bst(J);

} public void traverseAndPrnt( )
{

B. Bst obj = new Bst( new Integer(55) );

C. Bst obj; obj.addNd(55); }

D. Bst obj; obj.addNd( new Integer(55) );

private Comparable info; private Bst leftNd; private Bst rightNd;

E. None of these
3. Assume has been filled in correctly and that n objects are added to an object of type Bst in order from largest to smallest. What is the Big O value for searching this tree?
A.
B.
C.
D.
E.

O(n log n)
O(log n)
O(n)
O(n2)
None of these

}

4. When a Bst object is constructed, to what value will leftNd and rightNd be initialized?
A.
B.
C.
D.
E.

this
0
null
Bst object
None of these

52-12
//Binary Search Tree public class Bst
{
public Bst(Comparable addValue)
{
info = addValue;
}
public Bst addNd(Comparable addValue)
{
int cmp = info.compareTo(addValue);

5. After executing the code below, what does the resulting tree look like?

if(cmp0)
{
if(leftNd!=null) leftNd.addNd(addValue); else leftNd=new Bst(addValue);
}
return this;

Bst obj = new Bst(new Integer(11)); obj.add(new Integer(6)) obj.add(new Integer(13));
A. ArithmeticException

11
B.

13

6
11

C.

6

13
13

D.

11

}

6

public void transverseAndPrnt( )
{

E. None of these

}

6. What replaces in the code to the right so that a “Preorder” traversal is done?
A. if(leftNd != null) leftNd.traverseAndPrnt( );
System.out.print(info);
if(rightNd!=null)rightNd.traverseAndPrnt();
B. if(leftNd != null) leftNd.traverseAndPrnt( ); if(rightNd!=null)rightNd.traverseAndPrnt(); System.out.print(info);
C. System.out.print(info); if(leftNd != null) leftNd.traverseAndPrnt( ); if(rightNd!=null)rightNd.traverseAndPrnt(); D. leftNd.traverseAndPrnt( ); rightNd.traverseandPrnt( );
E. None of these

private Comparable info; private Bst leftNd; private Bst rightNd;
}

52-13
7. What is a disadvantage of an unbalanced Binary Search Tree?
A. No disadvantage
D. Reduced search efficiency

B. Uses excessive memory
E. None of these

C. Limited accuracy

8. Average case search time for a Binary Search Tree that is reasonably balanced is of what order?
B. O(n2)

A. O(n log n)

C. O(n)

D. O(1)

E. None of these

9. What positive thing(s) can be said about a completely unbalanced tree that results from adding the following integers to a tree in the sequence shown?
{ 5, 6, 7, … 999, 1000}
A. The items are automatically in numerical order along the long sequential strand.
B. The smallest number is automatically the root node.
C. The largest number is the root node.
D. Both A and B
E. Both A and C

10. In what order are the nodes visited in the tree to the left if a preorder traversal is done?

M
R

G
A

H

X

P
N

Q

A.
B.
C.
D.
E.

A, G, H, M, N, P, Q, R, X
M, G, A, H, R, P, N, Q, X
A, H, G, N, Q, P, X, R, M
M, G, R, A, D, P, X, N, Q
None of these

11. In what order are the nodes visited in the tree to the left if a postorder traversal is done?
A.
B.
C.
D.
E.

A, G, H, M, N, P, Q, R, X
M, G, A, H, R, P, N, Q, X
A, H, G, N, Q, P, X, R, M
M, G, R, A, H, P, X, N, Q
None of these

12. In what order are the nodes visited in the tree to the left if an inorder traversal is done?
A.
B.
C.
D.
E.

A, G, H, M, N, P, Q, R, X
M, G, A, H, R, P, N, Q, X
A, H, G, N, Q, P, X, R, M
M, G, R, A, H, P, X, N, Q
None of these

13. For the tree above, which of the following is a possible order in which the nodes were originally added to the binary search tree?
A. M, G, R, A, H, X, P, N, Q
C. M, R, A, G, H, X, P, N, Q
E. None of these

B. M, G, R, A, H, Q, N, P, X
D. A, G, H, M, N, P, Q, R, X

52-14
14. What mathematical infix expression is represented by the binary expression tree to the right?
A.
B.
C.
D.
E.

(4 + 3) / 7
4 / (3 + 7)
7/4/3+7
(4 / 3) + 7
None of these

+

4

15. What mathematical infix expression is represented by the binary expression tree to the right?
A.
B.
C.
D.
E.

7

/

5*2+4
5 * (2 + 4)
(2 * 4) + 5
5 * 2 * (+4)
None of these

3

*
+

5
2

4

16. Which of the following is a postfix version of the following mathematical expression?
(37 - 59) * ( (4 + 1) / 6 )
A.
B.
C.
D.
E.

* - 37 59 / + 4 1 6
(37 - 59) * ( (4 + 1) / 6 )
37 59 - 4 1 + 6 / *
37 - 59 * 4 + 1 / 6
None of these

17. What is the minimum number of levels for a binary tree with 20 nodes?
A. 20

B. 7

C. 6

D. 5

E. None of these

18. What is the maximum number of levels for a binary tree with 20 nodes?
A. 20

B. 7

C. 6

D. 5

E. None of these

53-1

Lesson 53… Queues
Standing in line:
When you stand in a line to buy tickets at a movie box office, you are standing in a queue. This is a classic example of a First-In-First-Out (FIFO) data structure. The first person in the movie line is the first one to leave the line (after buying tickets), and a new person entering the line always enters at the end of the line.
Our own interface:
Is there an existing interface that’s a standard part of Java that could help us design a
FIFO queue? No, unfortunately there isn’t one that is strictly for a FIFO queue, so we must design our own. Java does have an interface Queue that is rather generic and that can serve as the basis for FIFO queues, LIFO queues (stacks), priority queues, etc. An interface with all the essentials for a strictly FIFO queue is given below (For the remainder of this book, when a queue is mentioned, it is assumed to be a FIFO queue.) public interface Queue
{
boolean isEmpty( ); //returns true if nothing in the queue void enqueue(Object obj ); //places object obj at the back of the queue
Object dequeue( ); //removes and returns object at front of the list
Object peekFront( ); //returns object at the front of the list
}
An underlying data structure:
As we think of implementing this in software, we first need to consider what underlying data structure to use. A natural choice is the LinkedList class. Below, we review just a few of the methods of the LinkedList class and how we might use them to implement the
Queue interface in a class that we will call LinkedListQueue. void addLast(Object obj) … use for enqueue
Object removeFirst( ) … use for dequeue boolean isEmpty( ) … use for isEmpty
Object getFirst( ) … use for peekFront
The implementation:
Here is the full implementation of the Queue interface in our new LinkedListQueue class. import java.util.*; //necessary for LinkedList class public class LinkedListQueue implements Queue
{
public LinkedListQueue( ) //constructor
{
lst = new LinkedList( ); } public void enqueue(Object obj)
{
lst.addLast(obj);

}

public Object dequeue( )
{
return lst.removeFirst( );

}

53-2 public Object peekFront( )
{
return lst.getFirst( );

}

public boolean isEmpty( )
{
return lst.isEmpty( );

}

private LinkedList lst; // state variable
}
Some miscellaneous facts concerning queues:
The front of a queue, as it is most commonly called, is sometimes called first, start, or beginning. The back of a queue, as it is commonly called, is sometimes called rear or end. The enqueue and dequeue methods for the LinkedList and ArrayList implementations of the Queue interface both have a Big O value of O(1).
If a queue class is implemented using ordinary arrays, the dequeue method will typically have a Big O value of O(n), where n is the size of the queue. This is due to the necessity of “compacting” the array after removal of the item at index 0. Typically, the other methods will have a value of O(1).

Exercise on Lesson 53
1. What is the meaning of the acronym FIFO?
2. What is the meaning of the acronym LIFO?
3. Of which type is a queue, a LIFO or a FIFO?
4. Identify each of the following as a FIFO or LIFO:
a. Cars lined up at a toll booth.
b. Students turn in tests to a teacher and place them on top of a stack. The teacher grades the papers by selecting the next paper to grade from the bottom of the stack. c. Students turn in tests to a teacher and place them on top of a stack. The teacher grades the papers by selecting the next paper to grade from the top of the stack.
d. A dishwasher in a cafeteria places newly washed trays on top of a stack and patrons take their tray from the top of that stack.
e. Characters entered from a keyboard into a character buffer in a computer.
5. What is the difference between the peekFront and dequeue methods?

53-3
6. In the LinkedList implementation of the Queue interface, which LinkedList method is responsible for implementing the enqueue method?
7. In the LinkedList implementation of the Queue interface, which LinkedList method is responsible for implementing the dequeue method?
8. In the LinkedList implementation of the Queue interface, which LinkedList method is responsible for implementing the peekFront method?
9. Is the FIFO Queue interface a standard part of Java and if so, in what package is it found?
10. What is output by the following, assuming an empty queue object q already exists?
q.enqueue(“Hello”);
q.enqueue(“Hello again”);
q.enqueue(“Good bye”);
System.out.print(q.dequeue( ));
System.out.print(q.peekFront( ));
System.out.println(q.dequeue( ));
11. What is output by the following code?
LinkedListQueue q = new LinkedListQueue( ); for(int j = 0; j < 5; j++)
{
q.enqueue(j); //pre Java 5.0, q.enqueue(new Integer(j));
}
for(int j = 4; j >= 0; j--)
{
System.out.print( (Integer)q.dequeue( ));
//pre Java 5.0, System.out.print( ((Integer)q.dequeue( )).intValue( ) );
}
12. What is output by the following code?
LinkedListQueue q = new LinkedListQueue( ); int x = 1;
Integer iw = 37; //pre Java 5.0, Integer iw = new Integer(37); do { x++; q.enqueue(x); //pre Java 5.0, q.enqueue(new Integer(x)); iw = q.dequeue( );
}while(x < 4);
System.out.println(iw); //pre Java 5.0, System.out.println(iw.intValue( ));

53-4
Use the following class for problems 13 and 14: public class TheIntQueue { public TheIntQueue(int maxSize) { intArray = new int[maxSize]; size = 0;
}
public void enqueue( int x) { intArray[size] = x; size++; }
…other methods not shown… private int[] intArray; private int size;
}
13. What is the greatest number of integers that could be stored if this class is instantiated with TheIntQueue iq= new TheIntQueue(59); ?
14. After just one call of the enqueue method, what is the value of size?

Project …Who’s Next?
Ye Olde Computer Co. has two service reps that take phone calls and help customers with software problems. These customers are placed in a phone queue to await their turn for help.
Naturally, customers have to wait in the queue until all those waiting before them have begun their help session and when one of the service reps is finally available.
Our task here is to determine how much time each customer must wait and add all the wait-times together for a grand total of wait-time. The wait-time for a customer is defined as the time elapsed from when he arrives in the phone queue until he is “dequeued” and his help begins.
Assume that as a service rep finishes helping a customer, he is immediately available to help the next customer at the head of the phone queue.
The following data will make up a text file call Customers.dat:
5 20
7 10
10 40
15 30
20 10
25 32
35 50
43 26
In this file each line represents a customer. The first integer represents his arrival time (in minutes from some arbitrary starting time) in the phone queue and the second is the time (in

53-5 minutes) required to solve his problem. It is assumed that no two customers arrive at the same time. For this data the answer is 160 minutes of accumulated waiting time, and the output is just:
160
Create a project called WhosNext and enter the interface Queue and the class LinkedListQueue
(both on p 53-1). The class with the main method will also be called WhosNext and will consist of the BaseClass code from Lesson 27 and the following additional code.
LinkedListQueue q = new LinkedListQueue( );
…place customer data in q…
//Initialize some variables int TotalWaitTime = 0;
Scanner sc = new Scanner((String)q.peekFront( )); int firstCustArrivalTime = sc.nextInt( ); int nextAvailTimeA= firstCustArrivalTime; int nextAvailTimeB= firstCustArrivalTime;
//dequeue each customer and calculate his wait-time. while(…determine if queue is not empty…)
{
//Get customer data
…dequeue next item in q and use a Scanner object to produce the following two variables… custArrivalTime and custHelpTime…
//Get time this customer's help begins (the time he is dequeued) int dequeueTime = 0; if(nextAvailTimeA >>46
18120518>>>68
18120725>>>50
18610422>>>72
18620124>>>24
18631023>>>48

Project… Hashing Abraham Lincoln

Create a project called HashingAbe with a main method inside a Tester class. The project should also have a static method called hashCode to which you can pass a key (a String) as a parameter.
As usual, the method should return an index of type int. Use the following “rule” for hashing the
String.
Create int keyInt consisting of the following calculations:
• First, convert String key to all uppercase.
• The ASCII code of the first character of key times 1000, plus
• the ASCII code of the second character of key times 100, plus
• the ASCII code of the next to last character of key times 10, plus
• the ASCII code of the last character of key.
The hashCode method should assume a table size of 180. The returned int type that is to be used for the index of a hash table will be keyInt % TABLE_SIZE.

57-7
In the main method test the four names from Table 57-5. The resulting printout from main should be as follows:
Bush, George>>>39
Clinton, Bill>>>16
Lincoln, Abraham>>>147
Washington, George>>>139
****************************************************************
The Object class hashCode method:
If the key for your hash table is an object, recall that it inherits the Object class (the cosmic superclass) and thus inherits four important methods:
Signature
String toString( ) boolean equals(Object o)
Object clone( ) int hashCode( )
Table 57-7

Description
Returns a String hex representation of the object.
For example, for a BankAccount object we get something like BankAccount@1a28362.
Tests for the equality of objects.This tests to see if two variables are references to the same object.
It does not test the contents of the two objects.
Produces a copy of an object. This method is not simple to use and there are several pitfalls.
Returns a decimal int from the entire int range.

This last method is of particular interest to us here. Since the int i it produces can lie anywhere in the range Integer.MIN_VALUE
>>>
>>>
>>>

1.2206555604934692
3.5777087211608887
5.68858528137207
0.9761870503425598

**********************************************************************
This is a fairly long, sophisticated project and the secret to success is not to bite off too much at once. Do a small, fundamental part of the code, test it, and revise as necessary. Then do a little more, test, and get that part working too. This will be our approach here.
The first thing we must do is create a project. Let’s call our project DistToTrail and have it include a class called Tester. To make things go a little faster, we will paste in the contents of the
BaseClass class developed in Lesson 27 and use that code to input the TrailData.in file. After creating two arrays, double trailX[ ] and trailY[ ] (both dimensioned to a length of 12), strip off the parenthesis and commas and store the x coordinates in trailX[ ]. Similarly, store the y coordinates in trailY[ ]. Use the following temporary code for testing: for(int j = 0; j < 12; j++)
{
System.out.println(trailX[j] + “, ” + trailY[j] + “
}
System.out.println(“”);
The output of this test should look like this:
-6.5, -7.0
-7.0, -5.0
-7.0, -3.0
-6.0, 3.0
-3.0, 3.5
-2.2, 4.0
-1.0, 3.0
1.0, -1.0
3.0, -6.5
5.0, -7.0
7.0, -5.0
6.0, -0.5

”);

CS1-3
The code for the project up to this point (and including the above test) can be found in the Blue
Pelican Java Answer Book in the Case Study section titled “Part 1”.
***************************************************************************
So far, so good. Next, we will bring in the TestData.in file and store its parts in three different arrays. Remove the previous test code and add new code to main that will create the following arrays with each dimensioned to a length of 4: char testLetter[ ], double testX[ ], double testY[ ].
Now write code that will bring in this file and separate the parts of each line of text and store each in one of the new arrays just created. Use the following test code to verify that this section of the code is working: for(int j = 0; j < 4; j++)
{
System.out.println(testLetter[j] + “ ” + testX[j] + “, ” + testY[j]);
}
System.out.println(“”);
The output of this test should appear as follows:
A
B
C
D

-1.5, 5.0
-3.0, -1.0
7.0, 5.1
7.0, -0.5

The code for the project up to this point (including the test just above) can be found in the Blue
Pelican Java Answer Book in the section titled “Part 2”.
**************************************************************************
Now we come to the major part of the code for this project. This code will go in another class called LineStuff. Briefly, the LineStuff class can be described by the following list. At this point, do not try to implement any of this. Just scan the list and become somewhat familiar with the methods and state variables. Implementation will come later, step-by-step.
1. A constructor receives four double parameters that represent the coordinates of the two end points of a line segment.
a. These four parameters are assigned to the double state variables segX1, segY1, segX2, and segY2.
b. Use the coordinates of the end points of the line segment to determine the equation of the line in Ax + By + C = 0 form.
i. Be sure to handle the special case in which the line is vertical. ii. Store A, B, and C in state variables of the same name.
2. Method public double distToLine(double tpX, double tpY)

CS1-4
a. The parameters tpX and tpY represent the coordinates of a test-point not necessarily on our line.
b. Return the distance from the point (tpX, tpY) to the line described by Ax + By + C
= 0. This involves the use of a formula from Analytic Geometry that will be presented a little later.
3. Method public boolean onSegment(double tpX, double tpY )
a. This method tests to see if the perpendicular projection of (tpX, tpY) onto line Ax
+ By + C = 0 falls on the segment defined by (segX1, segY1), (segX2, segY2).
b. Returns true if on the segment.
c. Returns false if not on the segment.
This analysis is somewhat complicated and will be explored later.
4. Create the following public double state variables: segX1, segY1, segX2, segY2, A, B, C

Constructor and State Variables
Ok, time to get busy and start building the LineStuff class. In your project, create the skeleton of the LineStuff class.
Create the double state variables segX1, segY1, segX2, segY2, A, B, and C.
Next, create part of the constructor and assign the parameters to the state variables segX1, segY1, segX2, and segY2.
In the Answer Book this code is labeled as “Part 3”.
***************************************************************************
Your next task is to finish the constructor by using the parameters to generate the equation of the line, thus producing A, B, and C. Be very careful here. You should not immediately calculate the slope of the line because it may be infinite. Instead, find out first if it is infinite by testing the denominator of the slope formula ( m = (y2 - y1)/(x2 - x1) ). This test is: if( (x2 – x1) = = 0 )
In fact, we can get in trouble if the difference between x1 and x2 is very, very small, but still nonzero. It is suggested that you use the following test instead: if( Math.abs(x2-x1) < .000000001 )
Some IDE’s like BlueJ will let your directly test your class without having to create test code in main of the Tester class. The table below shows the final values of A, B, and C after passing the test parameters x1, y1, x2, and y2 to the constructor. If your IDE does not permit such testing, you will need to hard code these tests into main of the Tester class.

CS1-5

x1

Test Values y1 x2

y2

A

B

C

8
-2.44
-42

-7.2
4.902
-19.1

19.5
1
-187.511 10.267502…
-19.1
0.0

0.0
1.0
1.0

-8.0
20.1507091…
19.1000003…

8
16.3
17.03

Results

Table CS1-1
The full code for the constructor and state variables for LineStuff is labeled as “Part 4” in the
Answer Book. distToLine method
Implement the distToLine method as previously described. Use the following formula to determine the distance from the test-point (tpX, tpY) to the line Ax + By + C = 0:

.(tpX, tpY)
_______
Dist = | A(tpX) + B(tpY) + C | ÷ √ A2 + B2

Dist

Ax + By + C = 0
Fig. CS1-2 Distance from a point to a line

Test the distToLine method by creating a LineStuff object. Send the arguments below to the constructor and verify that you get the expected results back from the distToLine method.

Arguments Sent to Constructor
Point #1

distToLine

Test-Point

Point #2

x

y

x

y

x

y

-1
7
-7

3
-5
-5

1
6
-7

-1
-.5
-1

-3
7
-3

-1
5.1
-1

double
3.57708721…
2.19099736…
4.0

Table CS1-2
In the Answer Book the full implementation of this method is labeled “Part 5”.

CS1-6

onSegment method
When projecting a test-point over to a line, there are two distinct cases. First, consider the scenario to the right in which a test-point projects over to a line and falls in the interior of the segment originally defining the line. In this case, the point of projection is on the segment and the onSegment method should return a true.

.

.

.(segX2, segY2)

(segX1, segY1)
Point of projection
(projX, projY)

Fig. CS1-3 Projection on the segment

Second, the test-point projects over to the line so as to fall outside the line segment originally defining the line. An example of this scenario is found in the drawing to the left. The onSegment method should return a false.

.

(segX1, segY1)

.
(segX2, segY2)

(tpX, tpY)

. (tpX, tpY)

How can we distinguish between these two situations? This is accomplished by comparing the three distances between the three points on the line.

Point of projection
(projX, projY)

Fig. CS1-4 Projection not on the line

Let’s examine these distances for the case when the point of projection falls on the line segment.
Fig CS1-5 shows three distances. The relative sizes of these distances will be used to verify that the point of projection does, indeed, fall on the line segment.

(tpX, tpY)

.

d1p

.
(segX1, segY1)

d12 d2p .

(projX, projY)

.(segX2, segY2)

Fig. CS1-5 Point of projection falls in the interior of the line segment.
From Fig. CS1-5 we see that the condition for the point of projection to fall in the interior of a line segment is for d1p and d2p to both be less than or equal to d12. This would result in the onSegment method returning a true.
You will need to calculate the distances d1p, d2p, and d12. Use the following distance formula to calculate, for example, the distance between (x1, y1) and (x2, y2).
_________________
dist = √(x2 – x1)2 + (y2 – y1)2

CS1-7
Now lets examine the case when the point of projection falls outside the line segment originally defining the line.

d2p

d12 d1p .

.(tpX, tpY)

.(segX2, segY2) .(projX, projY)

(segX1, segY1)

Fig CS1-6 Point of projection falls on the exterior of the line segment.
From Fig. CS1-6 we see that the condition for the point of projection to fall on the exterior of the line segment is for either d1p or d2p to be greater than d12. This would result in the onSegment method returning a false.
This is all well and good; however, there is still one major obstacle. How do we find the point of projection (projX, projY)? Very succinctly, here is how it’s done. In Fig CS1-7 we note that the two lines labeled line1 and line2 are perpendicular (their slopes are negative reciprocals of each other). That will help us obtain the equation of line1. The equation for line2 is already known; using the state variables A, B, and C, it is Ax + By + C = 0.

. (tpX, tpY) line1 line2

.(segX1, segY1)

.(projX, projY)

.(segX2, segY2)

Fig CS1-7 line1 and line2 are solved simultaneously to find the point of projection
After finding the equation of line1, solve the two lines simultaneously as follows to find the desired intersection point (projX, projY):
Assuming that the equation of line1 is of the form (A1)x + (B1)y + C1 = 0, the solutions are: ∆ = A1(B) – A(B1) x = [ -C1(B) + B1(C) ] / ∆ y = [ -C(A1) + A(C1) ] / ∆
The solution here, (x, y), is the desired intersection point (projX, projY).
Following is a flow chart that should prove useful in putting all these ideas together.

CS1-8
Use A and B to determine the slope, m, of line1.

Use m and (tpX, tpY) to determine the equation of line1. A1x + B1y + C1 = 0

Solve A1x + B1y + C1 = 0 and Ax + By + C = 0 to get (projX, projY).

Compare d12, d1p, and d2p to determine if (projX, projY) is on the segment.

Using (projX, projY),
(segX1,segY1), & (segX2, segY2) find d12, d1p, & d2p

Fig. CS1-8 onSegment flowchart
Test the onSegment method by creating a LineStuff object. Send the arguments below to the constructor and verify that you get the expected result back from the onSegment method.

Arguments Sent to Constructor
Point #1

Test-Point

onSegment

Point #2

x

y

x

y

x

y

boolean

-1
7
-7

3
-5
-5

1
6
-7

-1
-.5
-1

-3
7
-3

-1
5.1
-1

true false true

Table CS1-3
In the Answer Book the full implementation of the onSegment method is labeled “Part6”.
**********************************************************************
After having accomplished all of the above, the LineStuff class is complete. Next, we turn our attention to the Tester class. The additional code to be placed there looks at each test-point and determines the nearest point on the trail. The nearest point may either be the distance of a perpendicular projection onto the trail or the distance to a trail-point. In Fig CS1-1 test-point A is nearest a trail-point while test-point B is nearest a perpendicular projection onto the trail. For each test-point, both types of distances must be considered. Use the following to assist you in writing the code that determines the nearest place on the trail for each test-point.
1. A loop will cycle through the four test-points. The remaining items listed below will all be placed inside this loop.
2. Cycle through all eleven line segments (determined by the twelve trail-points) and determine the point of projection of the test-point onto each line defined by these segments. 3. Determine if the point of projection is on the segment (use onSegment). If it is, then get the distance to the line using distToLine and store the returned distance in the double dist[ ] array. Increment an integer counter, distArrayCounter, as each new distance is stored there. In the end it will finally become the length of this array.

CS1-9
4. Cycle through all twelve trail-points and determine the distance from the test-point to each. Store each of these distances in the dist[ ] array and increment distArrayCounter each time.
5. Sort the dist[ ] array.
6. The first item in the array is the desired shortest distance.
7. Produce output for each iteration of the loop described by item 1 above. The final output should appear as follows:

Test
Test
Test
Test

point point point point A
B
C
D

distance distance distance distance to to to to trail trail trail trail >>>
>>>
>>>
>>>

1.2206555604934692
3.5777087211608887
5.68858528137207
0.9761870503425598

The implementation of the code for the above seven steps is labeled in the Answer Book as
“Part 7”. Following that is the complete code for the Tester class.
On the next page is a flow chart that is the equivalent of the above seven steps:
*************************************************************************
Following is a practical application of a project such as this:
In GIS (Geographical Information System) software there might be a trail of points representing a road or perhaps a pipeline. As a mouse pointer is moved across a map containing such a trail, we could repeatedly call a method implementing the ideas of this project to continuously show the distance from the mouse pointer to the trail.

CS1-10
Get next test-point

Fill dist[ ] with large numbers

Get next segment

Get projection of test-point on seg.

Proj on
Segment
? no Set distCounter = 0 no yes

Get dist of test-point to line

Store distance in dist[ ]

Finished with all segs.? Increment distCounter

yes
Get next trail-pt

Get dist of trailpoint to test-point

Store in dist[ ] and increment distCounter

no

Finished with trail-points? yes

Sort dist[ ] array

Get distance in index 0 of array no

Finished with test-points? Use it to produce printout

yes end Fig. CS1-9 Flow chart for determining nearest point.

This page intentionally left blank.

Golden Nuggets of Wisdom
(Short Learning Activities)

Study one of these each day (followed by a quiz on the following day) during the six weeks preceding a contest to help sharpen your Java skills.

Nug01-1

Golden Nugget of Wisdom # 1

In each problem below, state what’s printed.
1.

for(int j = 0; j < 5; j++)
{

}
System.out.println(j); //???
Won’t compile. The scope of j is confined to the loop. It’s not recognized outside the loop.

2. int j = 19; for(j = 0; j < 5; j++)
{

}
System.out.println(j); //???
Prints 5. On the last iteration of the loop j is incremented to 5 but this doesn’t satisfy the loop condition, j < 5, so the loop is exited…however, j is still 5 and that’s what’s printed.

3. for(int j = 0; j < 5; j++)
{
int k = 10;
}
System.out.println(k); //???
Won’t compile. The scope of k is limited to the loop; therefore, k is not recognized outside the loop.
4. What are two other names for instance fields?
State Variables and Data Members

Nug02-1

Golden Nugget of Wisdom # 2 public class Bystander
{
public void method1(int x){
}
public void macho(int x, String s){ public void macho(int x, int y){
}

}
}

public class Parent
{
public void method2( ){…….}
}
public class Child extends Parent
{
public void method1(int x){ public void method2( ){…….}
}

}

***********************************************************
1. Name two methods that represent overriding. method2…in both the Parent and Child classes. Objects made with the
Child class will use its method2 in preference to method2 in the Parent class. 2. Name two methods that represent overloading.
The two macho methods in the Bystander class

3. Name two methods that represent polymorphism. method1…in both the Bystander and Child classes. They have nothing to do with each other…totally unrelated.

Nug03-1

Golden Nuggets of Wisdom # 3

1. What does it mean when it is said that some class realizes an interface?
Answer: It simply means that this particular class implements the interface.

2. Consider the following usage of the split method:
String lickety = "abcd123efgh456";
String sp[] = lickety.split("\\d+");
System.out.println(sp.length + sp[1]); //2efgh
Note that while “\\d+” is a regular expression indicating one or more digits there is a different meaning to “\\D+”. It is left to the reader to explore this and other similar regular expression in Appendix AC.
In the example above there are only two elements of sp. They are: sp[0] = “abcd”

and

sp[1] = “efgh”

3. System.out.println(18 ^ 10); // Prints 24…exclusive oring
18 = 1 0 0 1 0
10 = 1 0 1 0
1 1 0 0 0 = 24

Nug04-1

Golden Nugget of Wisdom # 4
1. String s = “Hello”;
System.out.println( s.substring(4,5) );
H e l l o
0 1 2 3 4
Notice the highest index is 4, yet we have an index of 5 in the code above!
Actually, this is legal because the meaning of the second parameter (5 in this case) is to “pull back” one notch for the last character of the substring. So, the println above would legally print an “o”.
It would be easier to pick-off the last character of s using the one parameter form of substring, s.substring(4);.
There is a more straight forward way to pick up the last character of a String using charAt( ). If you know the last character’s index, use, for example, s.charAt(4). If you don’t know how long the String is, use s.charAt(s.length( ) - 1);.
2. String s = “Hello”;
String ss = s.substring(3,3)
System.out.println(ss); //prints nothing
System.out.println(ss.length( )); //0 ss = s.substring(3,2); // StringIndexOutOfBoundsException
3. Returning an array from a method:
The following method will return an int array. public int [] myMethod( )
{
int ss[] = {1,2,3,4}; return ss;
}
Call this method as follows: int bb[] = myMethod( );

Nug05-1

Golden Nugget of Wisdom # 5
Masking:
Consider the integer 93. In binary it is written as:
93dec = 1 0 1 1 1 0 1 bit “positions” 6 5 4 3 2 1 0
Now, suppose we are interested in bit position number 3. What is it? From above we see that it’s 1. Similarly, bit position 5 is a 0. How can we programmatically determine the value of various bit positions? We do this by masking.
93dec = 1 0 1 1 1 0 1 mask = 0 0 0 1 0 0 0 = 8dec = 23 …all except bit position 3 are masked.
0 0 0 1 0 0 0 result of bitwise AND
Notice with the bitwise AND with this particular mask that we are guaranteed all 0’s in the answer except in bit position 3. In that position the bit will be the same as that of the number with which the mask is bitwise AND-ed.
The following code will identify the bit values in any desired position: import java.io.*; import java.util.*; public class Masking
{
public static void main(String [] args)
{
Scanner reader = new Scanner(System.in);
System.out.print("Enter an integer value. "); int x = reader.nextInt( );
System.out.print("What bit position in the integer entered above do you wish to read? "); int p = reader.nextInt( ); int m = (int)Math.round(Math.pow(2, p)); //create the mask int a = x & m; if(a= =0)
{
System.out.println("Bit position " + p + " is a 0.");
}
else
{
System.out.println("Bit position " + p + " is a 1.");
}
}
}
In the line of code above, where we create the mask we can’t trust Math.pow( ) alone because of round-off errors. This is why we use the round( ) method. Since it returns a double, we must cast the entire thing to an int type.

Nug06-1

Golden Nugget of Wisdom # 6
1. Illegal method calls: public interface Country
{
int method1(double d);
}
public class State implements Country
{
public int method1(double d)
{
… some code …
}
public void method2(int x )
{
… some code …
}
}
Country obj1 = new State( ); // Notice Country is the interface and State is the
// implementing class obj1.method1(38.2); //Legal because obj1 is a Country object and method1 is a
//method specified in Country obj1.method2(3); //Illegal because obj1 is a Country object and method2 is not
//a method specified in Country

2. Converting a decimal number to a binary, hex or octal string: int j = 17;
System.out.println(Integer.toBinaryString( j )); // 10001
System.out.println(Integer.toHexString( j )); // 11
System.out.println(Integer.toOctalString( j )); // 21
The last three lines of code could, instead, be done this way:
System.out.println(Integer.toString(j, 2));
System.out.println(Integer.toString(j, 16));
System.out.println(Integer.toString(j, 8));

Nug07-1

Golden Nuggets of Wisdom # 7
1. StringBuffer s = new StringBuffer("Yikes");
s.insert(3, "YES");
System.out.println(s); //prints YikYESes
// Notice it inserts just before index 3

2. String s1 = "A";
String s2 = "a";
System.out.println(s1.compareTo(s2));. //prints a negative number
Notice that “A” alphabetically precedes “a.” Alphabetical sequence is determined by the ASCII codes. ASCII code for “A” is 65 and it's 97 for “a.”
Since 65 < 97, that is why “A” < “a” in an “alphabetical” sense.

3. String s1 = "B";
String s2 = "a";
System.out.println(s1.compareTo(s2));.
//prints a negative number since “B” alphabetically precedes “a”. (ASCII
//code for “B” is 66 and for “a” is 97; hence “B” < “a”.)

4. int x = 8; double y = 2.3
String s = “hello”;
System.out.println(x + y + s + x + y); // prints 10.3hello82.3
Moving from left to right, we encounter regular addition so we get 10.3. Next, we encounter a String, so we go into the concatenation mode and get
“10.3hello”. We are now in a String mode, so the remaining “+”’s are concatenations… and we get “10.3hello82.3”.

Nug08-1

Golden Nuggets of Wisdom # 8
1. Escape characters: \”
\\
\n
\’
\t
System.out.println("Path:\tC:\\NerdStuff\nFile:\t\"nerd.doc\"\nH\'e\'llo");
Prints the following:
Path: C:\NerdStuff
File: "nerd.doc"
H'e'llo

2. Use of null:
Suppose acc is some object that has not yet been initialized. Is the following parenthesis true or false? if(acc = = null) true {
}

3. Use of continue: while( …some condition … )
{
…some code… continue; … some more code … jumps to here and we continue to loop
}

4. An unusual use of break:
YourDogsName: //this is a label that designates the outer loop…notice the colon while ( …outer loop condition… )
{
while ( …inner loop condition… )
{
if ( …something really bad happens… )
{
break YourDogsName; // Just as a plain “break” would
//break out of the inner loop. This
//breaks out of the outer loop.
}
}
}

Nug09-1

Golden Nuggets of Wisdom # 9
1. m = (…some Boolean expression…) ? ( …set m to this if true…) : (…set m to this if false…); if(…some Boolean expression…) // The above can be rewritten like this
{
m = something;
}
else
{
m = something else;
}

2. Bitwise not…. ~13 gives a weird negative number
13decimal = 0 0 …….0 0 1 1 0 1 binary
|
sign bit, 0 means its positive
~13decimal = 1 1 …….1 1 0 0 1 1 binary
|
sign bit, 1 means its negative

3. Shifting
12 3 ….gives 2…..16 / 23
-16 >> 3 ….gives -2…..16 / 23
-16 >>> 3 ….gives 536870910

…..sign is preserved
…..sign is preserved
…..sign is preserved
…..sign is preserved
…..sign is not preserved

4. Modulus with fractions
5.1%3 returns a 2.1…3 divides into 5.1, one time. Then subtract 5.1 – 3 and get 2.1.

Nug10-1

Golden Nuggets of Wisdom # 10
1. Constants….. (final) public class BankAccount
{
public BankAccount( )
{
balance = 5; //Ok to initialize it here in the constructor
}
public void aMethod( )
{
balance = 5; //Not legal
}
public final int balance; //Notice the constant is not initialized here as we
//would normally do.
}
2. System.arraycopy(a, aStartIndex, b, bStartIndex, howManyToCopy); a is an array……..b is an array
“From me to you” ….copies from a to b.

3. Calling one constructor from another: public class BankAccount
{
public BankAccount(double bal)
{
balance = bal;
}
public BankAccount( )
{
this(4.18); //calls the top constructor
}
}

Nug11-1

Golden Nuggets of Wisdom # 11
1. Bitwise OR-ing and AND-ing symbols can be used with boolean values. They give exactly the same answers that regular AND-ing and Or-ing do. This is somewhat strange and the only reason for using them is to effectively Boolean
AND or OR while circumventing short-circuiting…see Nugget 15, items 1 and 2. boolean a = true, b = false, c = true, d = false;
(a && c) returns true…….(a & c) returns true
(a && b) returns false…….(a & b) returns false
(a || c) returns true…….(a | c) returns true
(a || b) returns true…….(a | b) returns true etc…. 2. x * =y + z;
…means x = x * (y+z); //y+z must be in parenthesis.
3. int x = -5; int y = 9;
System.out.println(x % y);
-5
-5 %9 5 % (-9)
What about when the signs are mixed? -5 % (-9)
For the problem a%b, the sign of the answer will always be the sign of a. The sign of b is totally ignored.
4. FIFO…..first-in-first-out….classic example is a queue of people waiting to buy tickets in front of a box-office. The first person in line (First In) will be the first one to buy tickets and get out (First Out).
LIFO…….last-in-first-out……classic example is a stack. The last thing we push on the stack (Last In) will be the first thing we pop (sometimes called pull) off the stack (First Out).

Nug12-1

Golden Nuggets of Wisdom # 12
1. int x = 5; int y = 2; double d = (double)(x/y);
System.out.println(d); // prints 2.0
The parenthesis around x/y creates a little “world of its own” and since x and y are both integers, integer arithmetic is done giving 2.0
(not 2.5). This answer is then cast into a double.
2. int x = 5; int y = 2; double d = (double)x/y;
System.out.println(d); // prints 2.5
Only the x is cast as a double. x/y is now done with double arithmetic since x has been cast as a double.
3. Integer X = 5; //pre Java 5.0, Integer X = new Integer(5);
BankAccount myAccount = new BankAccount(5); if (X = = myAccount)
{
}
Is the parenthesis true or false, or will this not even compile?
It won’t compile because these two objects are incompatible for comparison. 4. Access Control….also called Access Control Modifier. These specify the accessibility of state variables, methods, and classes:
a. public …accessible from anywhere.
b. private …accessible from just within its own class. Note that a private item (state variable or method) in an instance of a class is accessible from within another instance of that same class.
c. Package …all methods of classes in the same package can access the feature. This is the default access control if none is specified. It is illegal to actually write Package; however, in the absence of an Access Control
Modifier, Package is assumed.
d. protected …access is permitted by methods of the same class, subclasses, and classes in the same package.

Nug13-1

Golden Nuggets of Wisdom # 13
1. Consider the running time (Big O) for the following code: for (int j = 0; j < p; j+=20) //O(p / 20)…drop the constant factor to get O(p)
{
for(int k = 0; k < q; k*=4) //O(log4q)… drop the base 4 to get O(log q)
{
...
}
}
Since one loop is nested in the other, we multiply…O(p log(q)). Notice that we drop the base 4 on the log and just call it log. This is because the log of any base is directly proportional to the log of any other base.

2. Is there any difference in the following expressions? and 5 * 4.1 / 3
5 / 3 * 4.1
With pencil & paper there is no difference.
On the computer however, if 5 / 3 is done first (as in the left example above), both are integers, so the answer to that part is obtained with integer arithmetic and will be 1….this corrupts everything else after that. On the other hand, if 5 * 4.1 is done first (as in the right-hand example above), then the compiler sees the 4.1 and does double arithmetic. Of course, the rest of the calculation will be as it would be with pencil and paper.

3. How do we declare an array of objects? Let’s consider the BankAccount class.
BankAccount theAccounts[] = new BankAccount[500]; //Creates 500 objects;
//however, they are each null theAccounts[17] = new BankAccount(205); //Initializes 17th account to have $205
Likewise, each of the remaining 499 accounts must be initialized separately.

Nug14-1

Golden Nuggets of Wisdom # 14
1. All objects inherit the cosmic superclass equals method. With this method, variables are compared to see if they reference the same object. Some standard classes (like String and the wrapper classes) override equals and implement their own so as to compare object contents.
(If you create objects from your own class, and if you want the equals method, you will have to specifically put it in your class.)
Integer i = 23; //pre Java 5.0, Integer i = new Integer(23);
Integer j = 23; //pre Java 5.0, Integer j = new Integer(23);
Integer k = j;
System.out.println(i.equals(j)); //true
System.out.println(i = = j); //false,… they are different objects.
System.out.println(k = = j); //true,…. they are references to the same object.
Integer i = 23; //pre Java 5.0, Integer i = new Integer(23);
Double j = 23; //pre Java 5.0, Double j = new Double(23);
System.out.println(i.equals(j)); //false
Please note that for i.equals(j) to be true, both i and j must be of the same object type….and furthermore must have the same values.
System.out.println(i.equals(j)); //will compile as long as i and j are both objects
//If they are different object types it will still
//compile but will be false.
2. Consider the relationships between decimal, hex, and binary
Dec

0 1 2

3

4

5

6

7

8

9

10

11

12

13

14

15

Hex

0 1 2

3

4

5

6

7

8

9

A

B

C

D

E

F

Bin

0

11

100

101

110

111

1000

1001

1010

1011

1100

1101

1110

1111

1

10

Now let’s think of the exclusive or problem 0x4BA ^ 0x132
Let’s break up each into its binary form.
0x4BA = 0100 1011 1010

0x132 = 0001 0011 0010

4

1

B

A

3

2

Stack them and do an exclusive or remembering that two 1’s yields a 0.
0x4BA = 0100 1011 1010
0x132 = 0001 0011 0010
0101 1000 1000 = 0x588, the answer
5

8

8

Nug15-1

Golden Nuggets of Wisdom # 15
1. int j = 3; int k = 5; int count = 0; if ( (j = = k) && (count++ < 59))
{
...
}
System.out.println(count);
Prints 0…Since (j = = k) evaluates false, the entire “if( )” is doomed to come out false, regardless of whether (count++ < 59) is true or false. “Short circuiting” just skips the second parenthesis to save time; therefore, the increment on count is never done.
2. Here’s a case in which short-circuiting does not take place. Back in Nugget 11, item 1 we explored using bitwise AND-ing and OR-ing symbols with boolean quantities.
Suppose as in #1 above we similarly have: int j = 3; int k = 5; int count = 0; if ( (j = = k) & (count++ < 59))
{
...
}
System.out.println(count); //Prints 1 since there is no short circuiting using &.
3. How do we convert a double or an int type variable into a String?
String m = String.valueOf(15.302); //Works on doubles.
String n = String.valueOf(18); //Works on integers.
String p = “” + 15.302; //Concatenation is probably the simplest way.
4. Use extends when we wish one class to inherit another. Use implements when we wish one class to have all the methods listed in an interface. The following example illustrates the School class inheriting the District superclass. School also implements both the TextBook and LunchRoom interfaces. Notice the order. The keyword extends comes first, followed by implements. public class School extends District implements TextBook, LunchRoom
{
...
}
Only one class can be extended; however, several interfaces can be implemented.

Nug16-1

Golden Nuggets of Wisdom # 16
1. What’s wrong with the following method signature? public boolean static hoover(int x)
The order should be…… public static boolean hoover(int x). Notice, the type specifier (boolean in this case) should immediately precede the method name. 2. String s = “Zorro”; s = s.replace(‘r’, ‘x’);
System.out.println(s); // Zoxxo … notice it replaces ALL occurrences of r

3. What is the meaning of String [ ] args in public static void main(String [ ] args) ?
If we write it as, String args[], we know that args is a String array.
Furthermore, the array is of length args.length…which means this is the number of command line arguments.
See page 19-4 to review DOS prompt usage of command line arguments.
4. Using an enhanced for-loop, write code that will find the product of all the integers in array x (assume x is of type int). int product = 1; for(int val:x) product *= val;
5. What is printed by the following? double []d = {20.0, 20.1, 20.2, 20.3} for( double valD: d) valD = valD + 1.0;
//The line just above compiles and runs but doesn’t affect the d array.
//This is because enhanced for-loops are “read-only”. for(double w : d)
System.out.print(w + “, ”)
20.0, 20.1, 20.2, 20.3,

Nug17-1

Golden Nugget of Wisdom # 17
1. Consider the overloaded String method indexOf. Following are the signatures of the several versions:
a. int indexOf( String s)
b. int indexOf(String s, int startingIndex)
c. int indexOf(int ch) //ch is the ASCII code of a desired character
d. int indexOf(int ch, startingIndex)
e. int indexOf(char ch)
f. int indexOf(char ch, startingIndex)
There is a “last” version of each of the above that searches from right to left, for example: int j = myString.lastIndexOf(“Hello”);
2. Different references to the same array:
Because arrays are objects, two or more variables can refer to the same array as in the following example: int []frst, sec; // same as int frst[], sec[]; frst = {1, 2, 3, 4, 5}; sec = frst; sec[2] = 99;
System.out.println(frst[2]); //notice that even though we changed only
//sec[2] to 99, frst[2] also changes to 99.
3. Suppose that we have a chain of inheritance Tree(superclass), Oak, and Bark with these respective objects: tr, ok, and brk. In a fourth class called DoStuff there is method with the signature, public static int method1(Oak oakster). The following are legal ways to call method1 from within a fifth class: DoStuff.method1(ok); and DoStuff.method1(brk); . An illegal call would be DoStuff.method1(tr); .
Recall form Lesson 36 that if a method is expecting to receive an object of a particular type, that it is legal to only send an object of equal or lower (on the inheritance and/or interface chain) type.
4. Boolean operators have the following order of precedence that should be memorized: &

^

|

&&

||

Example:
(false && true || false) yields false.
Example:
(true && true ^ true) yields false.

Nug18-1

Golden Nugget of Wisdom # 18
1. Suppose we have two classes, Big and Little. Little is a subclass of Big. Both have a void method called xray; however, the xray method in Little is different and overrides the version of xray in Big.
Big x = new Little( );
x.xray( ); //Which version of xray does it use?
The version in Little
2. What we call methods in this book, some other texts call functions or subroutines. 3. What we call signatures in this book, some other texts call headers.
4. Determining object type, legal methods, and where the methods are implemented.
(See Lesson 38.) objectName = new ;

This specifies the object type and what methods the object can use.

This tells us where the methods are implemented that we are to use ( including the constructor(s) ).

5. The boolean quantity anObject instanceof ClassOrInterface returns true if the anObject object was derived from either the class or interface represented by
ClassOrInterface. (See Lesson 38.)
6. The code in the left-hand panel below will produce the stack shown in the righthand panel at the completion of stck.push(“C”);. The toString method of the
Stack class is invoked to produce the resulting printouts:
Stack stck = new Stack( ); stck.push(“A”); stck.push(“B”); stck.push(“C”); System.out.println(stck);
String s = (String)stck.pop( );
String ss = (String)stck.peek( );
System.out.println(s + ss + stck);

C
B
A

top of stack

[A, B, C]
CB[A, B]

printout (notice top of stack is to the far right)

Nug19-1

Golden Nugget of Wisdom # 19
It is possible to have multiple constructors in the same class as is illustrated below: public class DemoClass
{
public DemoClass( ) //This one with no parameters is called the default
{
//constructor.

} public DemoClass(int i)
{

}
public DemoClass(int i, String s)
{

}
… remainder of class not shown…
}
1. All of the following instantiations are legal, and each will seek out the appropriate constructor. a. DemoClass obj1 = new DemoClass( );
b. DemoClass obj2 = new DemoClass(36);
c. DemoClass obj3 = new DemoClass(12, “Yes”);
2. It is possible to make one constructor call another using the this keyword. For example, suppose we instantiate an object obj using the default constructor as follows: DemoClass obj = new DemoClass( );
Futhermore, suppose we want the default constructor to call the two-parameter constructor and always pass an int value of 22 and a String value of “Sierra”. To accomplish this, modify the default constructor as follows: public DemoClass( )
{
this(22, “Sierra”);

}

Nug20-1

Golden Nugget of Wisdom # 20
1. Initialization blocks are blocks of code embedded within a class, and as the name implies, they are mostly used to initialize variables. Multiple initialization blocks are possible as is shown in the sample class below: public class DemoClass
{
//Non-static initialization block
{ stateVar1 = 50; }
//Static initialization block static //To manipulate static variables, use a static initialization block
{ stateVar2 = 20; } public DemoClass( ) //constructor
{
stateVar1++; stateVar2--; }
… Methods and other state variables… public int stateVar1; //If initialization blocks exist above don’t do any public static int stateVar2;
//initializing here.
}
2. Rules for initialization blocks:
• Non-static blocks run every time an object is created.
• Static blocks run just once (when the class is first loaded).
• Blocks are executed in the order in which they occur.
• Regardless of placement, code in the blocks executes before constructor code.
3. Sample usage:
DemoClass demo1 = new DemoClass( );
System.out.println( demo1.stateVar1 + “
DemoClass demo2 = new DemoClass( );
System.out.println( demo2.stateVar1 + “

” + demo1.stateVar2); //51 19
” + demo2.stateVar2); //51 18

Initialization blocks are rarely used and there really is no point in using them as in the two sample blocks above. It would be more straightforward to just initialize these two state variables on the bottom two lines where they are declared. So, what is the real purpose of initialization blocks? Suppose we have a program that absolutely must run as fast as possible; however, it has loops that require the laborious, time-consuming calculation of something like Math.tan(Math.log(Math.sqrt(1- x* x))) for values of x ranging from 1 to 360 in increments of 1. In this case it would be wise to iterate 360 times through a loop in an initialization block and precalculate all these values and store in a state variable array such as double val[ ]. Then in the actual program, when needed, quickly access the desired value with val[x].

Nug21-1

Golden Nugget of Wisdom # 21
Consider the following two classes: public class Tester
{
public static void main(String args[])
{
int j;
//System.out.println(j); //This line will not compile because j has
//not been initialized.
MyClass mc = new MyClass( );
System.out.println(mc.q); //prints 0
}
} public class MyClass
{
public MyClass( )
{
System.out.println(q); // prints 0
}
…other methods and state variables public int q; //q is automatically initialized to 0
}
Notice that numeric state variables are automatically initialized to zero unless initialized otherwise; however, ordinary (local) numeric variables (e.g. j above) must be initialized before being used.
**********************************************************************
In the absence of specific initialization, we can say the following about declarations:
1. When only declared, local variables are not automatically initialized to anything. 2. When only declared, objects are initialized to null (for an exception, see 4 below). 3. When declared, numeric arrays are initialized to zero.
4. When declared, a state variable is initialized to 0 (if it’s a numeric) or to “”
(empty String) if it’s a String.

Nug22-1

Golden Nugget of Wisdom # 22
1. Prototype:
The term prototype is extensively used in the c++ language. In Java, a method prototype is basically the signature of an abstract method (has a trailing semicolon and no following code). Following are examples: void delStat(int pdq, String s);
String conCatBunch( ); double[][] burnTime(double d, int i);
Suppose an object, obj, has Object type objects stored in it. The following would be the prototype of the getStuff( ) method such that obj.getStuff( ) would return a two dimensional array of Object type objects:
Object [][] getStuff( );

2. Short-Circuiting:
Consider the following two questions that involve short-circuiting.
A. When Boolean And-ing two boolean expressions, when is only one expression evaluated? a.
b.
c.
d.

When the left expression is false a
When the right expression is false
When the left expression is true
When the right expression is true

B. When Boolean OR-ing two boolean expressions, when is only one expression evaluated? a.
b.
c.
d.

When the left expression is false
When the right expression is false
When the left expression is true c
When the right expression is true

3. isLetter, isDigit, isLetterOrDigit, isWhitespace, isLowerCase, isUpperCase
In order to determine if the character at index j of String ss is a letter, for example, which of the following would be an appropriate way to evaluate the boolean that is returned?
a. ss.isLetter(j)
b. ss.charAt(j).isLetter
c. Character.isLetter(ss.charAt(j))
d. ss.charAt(is.Letter( ))
e. Character.ss.isLetter(j)
Answer is c. The method isLetter( ) method is a static method in the
Character class and we must begin with Character (unless it’s imported).

Nug23-1

Golden Nugget of Wisdom # 23
1. char and int:
One of these can be directly stored into the other; however, the opposite can only be done with a cast. See items 2 and 3 on page 13-1 for details. char ch = ‘x’; int j = 3; ch = j; //illegal ch = (char)j; //legal j = ch; //legal

2. ASCII codes:
Character
0
1
2
...
8
9

ASCII
48
49
50
...
56
57

Character
A
B
C
...
Y
Z

ASCII
65
66
67
...
89
90

Character a b c ... y z

ASCII
97
98
99
...
121
122

3. Casting Objects back to their original form:
Suppose we have a Queue class that stores Object type objects. Futhermore, suppose that we are storing String objects there (they are automatically converted to the Object type).
How do we get the Object type object returned by the dequeue method converted back to a String type object. Assume that we have a Queue object called q.
1. (String)(q.dequeue( ))
This is the best way since it clearly shows we are casting what is returned by dequeue. 2. (String)q.dequeue( )
On the surface this looks like we are incorrectly casting just the q instead of what
q.dequeue( ) returns; however, it actually means the same as number 1 above.

4. XOR
XOR means bitwise exclusive-or. Its operator symbol is ^.

Nug24-1

Golden Nugget of Wisdom # 24
The following facts about Boolean Algebra were presented in Lesson 32. Examples are presented here in different forms, yet are still applicable to the theorems. Study the examples and convince yourself that they are really representations of the original theorems. (Remember that addition here represents Or-ing and multiplication represents
AND-ing.)
1. Subtle Theorem:
This is subtle and not very obvious. It can be easily confirmed with a truth table. a + b = a + (!a)*(b)

…same as a || b = a || (!a) && (b)

Example1: !c + d = !c + c * d
Example 2: a + !b = a + (!a) * (!b)
2. Law of Absorption:
In these theorems, the value of boolean b does not matter (it could just take a hike). a = a * (a + b) a = a + (a * b)
Example 3:
Example 4:
Example 5:
Example 6:

…same as a = a && (a || b)
…same as a = a || (a && b)

!k = !k * (!k + !h)
!k = !k * (!k + h)
!k = !k + (!k * !h)
!k = !k + (!k * h)

******************************************************************
3. A two-dimensional int array is created and printed as follows: int ary[][] = {

{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 0, 1, 2} };

for(int row = 0; row < ary.length; row++)
{
for(int col = 0; col < ary[row].length; col++)
{
System.out.print(ary[row][col] + “ ”);
}
System.out.println(“”);
}
printout
1 2 3 4
5 6 7 8
9 0 1 2

Nug25-1

Golden Nugget of Wisdom # 25
Random Numbers: The following facts/examples are extracted from Lesson 30.
Random r = new Random( ); //create a random object. int i = r.nextInt( ); // This yields a randomly selected integer in the range
// Integer.MIN_VALUE to Integer.MAX_VALUE.
//(-2,147,843,648 to 2,147,843,647 as specified in Appendix C) int j = r.nextInt(7); // Yields an integer in the range 0
6
double d = r.nextDouble( ); // Yields a double in the range 0 (inclusive)
1
//(exclusive)
1. Print 20 integers in the range from 7
19.
for(int j = 0; j < 20; j++)
System.out.println( 7 + r.nextInt(13) ); // 13 = 19 – 7 + 1
2. Print 3005 floating point numbers in the range from 127.19
156.225.
for (int j = 0; j < 3005; j++)
System.out.println( 127.19 + 29.035 * r.nextDouble( ) );
// 29.035 = 156.225 – 127.19
Maps, Sets, keySet: (See Lesson 46 and Lesson 47)
1. Items in a set can’t be repeated.
2. The key values in a map can’t be repeated, the values can.
3. Write code that will create an Iterator object from Map m. Use it to print the keyvalue pairs in m. Assume that only String objects are stored as the objects in the map. Set keySet = m.keySet( ); //produces a Set object of the keys in m
Iterator itr = keySet.iterator( ); //produces a Iterator for Set keySet while( itr.hasNext( ) ) //loop through the objects in the set
{
String key = (String)itr.next( );
String value = (String)m.get(key);
System.out.println(“key = ” + key + “-----> value = ” + value );
}

Nug26-1

Golden Nugget of Wisdom # 26
Recursion: See Lesson 40 for more examples.
1. What is printed by the following? // 54 …(0 + 6 + 24 + 24)
System.out.println(recur1(0));
public static int recur1(int n)
{
if (n > 10) return n - 2; else { n = n * 3; return n + recur1(n + 2);
}
}
2. What is displayed by mayo(20); ? 0>
Bitwise shift right, do not preserve sign
Comparison Operators
<
Less than

Greater than
>=
Greater than or equal to instanceOf Class membership
==
Equal to
!=
Not equal to
Boolean Operators
&
boolean AND without short-circuit if boolean arguments
&
Bitwise And
^
boolean exclusive OR without short-circuit if boolean arguments

Appendix H-2
Operator
^
|
|
&&
||

Function
Bitwise exclusive OR boolean OR without short-circuit if boolean arguments
Bitwise OR boolean AND with short-circuit boolean OR with short-circuit

Assignment Operators
?:
Ternary conditional (selection operator)
=
Assignment
+=
Addion and assignignment
-=
Subtraction and assignment
*=
Multiplication and assignment
/=
Division and assignment
%=
Modulo and assignment
=
Shift right(preserve sign) and assign
>>>=
Shift right(do not preserve sign) and assign
&=
boolean or bitwise AND and assignment
|=
boolean or bitwise OR and assignment
^=
boolean or bitwise exclusive OR and assignment

Appendix I-1

Appendix I ….Creating Packages and Importing Classes
Java has several classes supplied with the language that you must “import” before you can make objects from them and/or access their methods. Let’s suppose your class is called MyClass and you wish to import the Random class (for the purpose of creating random numbers inside the methods of your class).
First, you must know the “package” name. For the Random class the package name is java.util .
There are several classes in this package. To bring in the Random class only, place the following command at the top of your class as follows: import java.util.Random;
//Use multiple lines here if there is a need to import other classes public class MyClass
{
…methods and state variables…
}
It is very common to import all of the classes in a package using the wildcard character “*”. import java.util.*;
Below we list just a few packages and some useful classes in them. java.util java.text java.io Random, Arrays, StringTokenizer, Interface, ListIterator, Set
NumberFormat
File, FileWriter, PrintWriter, IOException

***********************************************************************
(Before proceeding, the reader might want to first read Appendix X concerning the compiling and execution of classes from a command line prompt. That knowledge is assumed in much of the following discussion.)
Why we have packages:
Now we come to the task of understanding what “packages” really are and how to create them.
Packages serve two basic needs:
1. Packages are a convenient way to organize classes. Simply put, this means we can put related classes in the same package. When it is realized that there are thousands of classes, this is not only a convenience, it’s a necessity.
2. Packages help us avoid naming conflicts. As new classes are created, it is inevitable that there will be conflicts with some of the thousands of existing classes. Such conflicts are avoided by using the package name as a prefix to the class name (for example, java.util.Arrays.sort( );, where java.util is the package name and Arrays is a class inside it.) Appendix I-2
Creating a package:
Let’s now look at the six steps needed to create a package. For each step, two examples will be given. 1. Choose a base folder path under which the package will be stored.
Example 1: C:\MyBaseFolder
Example 2: C:\MyStuff\Libraries
2. Create a package name. You want your package name to be unique so that your package/class names will not conflict with others. Simple names may not conflict on your development computer; however, if you distribute your class to the outside world where you have no control, there might be a conflict.
Example 1: mypackage
Example 2: cleveland.maplest.smith.bill (Notice multiple parts are separated by dots.) 3. Create a sub folder(s) under the base folder path that matches the package name.
Example 1: C:\MyBaseFolder\mypackage
Example 2: C:\MyStuff\Libraries\cleveland\maplest\smith\bill
4. Create your source files and include as the very first noncomment line, a package statement. Be sure these files are saved with the .java extension.
Example 1: package mypackage; public class Tester
{ … some code … }
Example 2: package cleveland.maplest.smith.bill; public class Test
{ … some code … }
Source files in which there is no package designator are said to be stored in the default package.
5. Copy your source file (the text file with extension .java) into the package subfolder.
Example 1: C:\MyBaseFolder\mypackage\Tester.java
Example 2: C:\MyStuff\Libraries\cleveland\maplest\smith\bill\Test.java
6. Change to the base folder and from that position compile the class so as to produce a corresponding .class file. The following assumes you are in the “command line prompt” screen via the sequence Start | Run | cmd and that the Path variable points to the bin folder of your Java SDK as described in Appendix X.

Appendix I-3
Example 1: cd C:\MyBaseFolder
(make the base folder the current folder) javac mypackage\Tester.java (compile)
Example 2: cd C:\MyStuff\Libraries javac cleveland\maplest\smith\bill\Test.java
How Java finds Classes:
We should now have a package; however, it’s useless unless we know how to use it. First, we need to understand how Java finds the classes its needs. The compiler uses a special object called the class loader to sequentially locate the classes it needs.
1. The class loader first searches for standard Java classes that are a fundamental part of the language.
Optional packages are sought in the following ways.
2. Next, an extension mechanism is used to look for .jar files (bundling several classes) in the …jre\lib\ext subfolder of the Java SDK installation. This is where you should put extra or nonstandard jar files so that your IDE can recognize them.
3. Finally, if the desired class is not found inside a .jar file in the ext folder, then the class loader searches the classpath. The discussion that follows shows how to create a classpath so the compiler and JVM (Java Virtual Machine needed at runtime) can locate and use classes within packages we create or otherwise bring in from the outside world.
Creating and using classpath:
The classpath variable simply does what its name suggests. It provides a path for Java indicating where we are storing our extra classes. There are three ways to use classpath:
For each “Example 1” below we will assume that we are trying to compile a class file
Called MyClass1.java and that it has references to the Tester class in the mypackage package. Likewise, for each “Example 2” below we will assume that we are trying to compile a class file called MyClass2.java and that it has references to the Test class in the cleveland.maplest.smith.bill package. Also assume that MyClass1.java and
MyClass2.java are in the same folder and that that folder is the current folder.


Use -classpath as a command line option when compiling.
Example 1: javac –classpath .;C:\MyBaseFolder MyClass1.java
Example 2: javac –classpath .;C:\MyStuff\Libraries MyClass2.java
In using the –classpath option notice that it is immediately followed by the paths at which the base folder of our package is located. Separate the various paths with semicolons. Notice for each example that we are specifying two paths. One is simply a “dot”. This indicates the current directory and if not used, the compiler will not see MyClass1.java or MyClass2.java in the current directory. Always use the dot.

Appendix I-4


The above technique of using the –classpath option can become tedious if used very often during a session in the DOS prompt window. There is a way to enter the class path just once and have it persist during the current “command line” session. At the command line prompt, enter the following:
Example 1: set classpath = .;C:\MyBaseFolder
Example 2: set classpath = .;C:\MyStuff\Libraries
When compiling, all you now have to enter is javac MyClass1.java etc.



Setting classpath as just described has the drawback of being only a temporary
Environment Variable. It evaporates and is lost as soon as we close the command line window. In Windows 2K and XP there is a way to make it persist even after the computer is turned off and/or restarted. To do this, use the following sequence:
Start | Settings(skip this step for XP) | Control Panel | System | Advanced Tab |
Environment Variables
Create a new User Variable for called classpath with contents equivalent to the base folder path:
Example 1: .;C:\MyBaseFolder
Example 2: .;C:\MyStuff\Libraries
Typically, this takes effect without the necessity of a reboot, but if things don’t work immediately, try restarting the computer. If you want this new classpath to affect all users and if your logon name has Administrative permission, instead, create a new classpath variable in the System Variable section with the same contents as above.
If you created a System Variable, restart the computer. The classpath variable should now be in effect and permanent.

Accessing your own packages from within an IDE:
Unfortunately, none of the above techniques allows you to access your own class packages from within an IDE. It will be necessary to make setting from within the IDE to access these outside classes. Look for a Settings, Preference, etc. menu and then usually for a Libraries submenu.
Many times the IDE will not call it a classpath. All you will need to do is specify the base folder path of where your package resides. It is a common mistake to give the full path right down to the class itself. Part of that path is, of course, the package name itself. Just remember to give only the base folder path. For our two examples it would be:
Example1: C:\MyBaseFolder
Example 2: C:\MyStuff\Libraries
Notice that this IDE setting typically does not require the “dot” as does the classpath variable.

Appendix I-5
After all this talk about packages you way have wondered where important classes like, for example, those given by java.util.* are located. Search your hard disk for a folder or sub folder matching this package name, and you won’t find it. The class must be there somewhere because we use it all the time, but where? It’s tucked away along with the bulk of the standard runtime classes in a jar file. Its location is typically:
C:\Program Files\Java\jdk1.5.0_04\jre\lib\rt.jar
If you have Winzip on your computer you can examine the classes inside this or any other jar file. In summary, a student of Java should be able to look at an import statement such as the following and be able to tell which is the name of the class and which is the name of the package. import java.util.StringTokenizer;
For this example, java.util is the name of the package and StringTokenizer is the name of the class. Appendix J-1

Appendix J …..Typical Contest Classes and Interfaces class java.lang.object
• boolean equals(Object other)
• String toString( )
• int hashCode( ) interface java.lang.Comparable
• int compareTo(Object other)
//return value < 0 if this is less than other
//return value = 0 if this is equal to other
//return value > 0 if this is greater than other class java.lang.Integer implements java.lang.Comparable
• Integer(int value) //constructor
• intValue( )
• boolean equals(Object other)
• static String toString(int i)
• static String toString(int i, int base)
• int compareTo(Object other) //specified by java.lang.Comparable
• static int parseInt(String s) //Parses the string argument as a signed decimal integer
• static int parseInt(String s, int base) //returns a decimal int (s is expressed in base b) class java.lang.Double implements java.lang.Comparable
• Double(double value) //constructor
• double doubleValue( )
• boolean equals(Object other)
• String toString( )
• int compareTo(Object other) //specified by java.lang.Comparable
• static double parseDouble(String s) class java.lang.String implements java.lang.Comparable
• int compareTo(Object other) //specidied by java.lang.Comparable
• boolean equals(Object other)
• int length( )
• String substring(int from, int to) //returns the substring at from and ending at to-1
• String substring(int from) //returns substring(from, length( ))
• int indexOf(String s) //returns the index of the first occurrence of s; -1 if not found
• int indexOf(String str, int fromindex) //returns the index of the first occurrence of of str
// starting at index fromindex
• char charAt(int index) //returns the character at the specified index
• int indexOf(int ch) //returns the index of the first occurrence of of thecharacter ch
• int indexOf(int ch, int fromindex) // returns the index of the first occurrence of the
//character ch starting at index fromindex
• char [] toCharArray( ) //converts String into a character array
• static String copyValueOf(char [] ch) //converts a char array into a String
• static String valueOf(char [] ch) //converts a char array into a String

Appendix J-2


String toLowerCase( ) //converts all characters to lower case




String toUpperCase( ) //converts all characters to upper case
String [] split(String regex) //splits String into elements of a String array around matches
//to the “regular expression” regex
• String replace(char old, char new) //replace all occurrences of char old with char new
• String replace(String a, String b) //replace all occurrences of String a with String b
• String replaceAll(String regex, String replacement) //replace all matches to the regular
// expression regex with replacement
• String replaceFirst(String regex, String replacement) //replace first match to the regular
// expression regex with replacement class java.lang.Character
• static boolean isDigit(char ch)
• static boolean isLetter(char ch)
• static boolean isLetterOrDigit(ch)
• static boolean isLowerCase( )
• static boolean isUpperCase( )
• static boolean isWhitespace( )
• static char toUpperCase(char ch)
• static char toLowerCase(char ch) class java.lang.Math
• static int abs(int x)
• static double abs(double x)
• static double pow(double base, double exponent)
• static double sqrt(double x)
• static double ceil(double a)
• static double floor(double a)
• static double min(double a, double b)
• static double max(double a, double b)
• static double random( )
• static long round(double a) class java.util.Random
• int nextInt( ) //returns Integer.MIN_Value ≤ int value ≤ Integer.MAX_Value
• int nextInt(int i) //returns 0 ≤ int value ≤ i-1
• double nextDouble( ) interface java.util.List
• boolean add(E x)
• int size( )
• Iterator iterator( )
• ListIterator listIterator( ) class java.util.ArrayList implements java.util.List
(methods in addition to the List methods)
• E get(int index)
• E set(int index, E x) //replace the element at index with x and returns old one

Appendix J-3



void add(int index, E x) //inserts x at position index sliding elements right of index
//forward one position. Adjusts size.
E remove(int index) //removes element from position index, sliding elements at
//position index + 1 and higher to the left. Adjusts size.

class java.util.LinkedList implements java.util.List
(methods in addition to the List methods)
• void addFirst(E x)
• void addLast(E x)
• E getFirst( )
• E getLast( )
• E removeFirst( )
• E removeLast( ) interface java.util.Set
• boolean add(E x)
• boolean contains(Object x)
• boolean remove(Object x)
• int size( )
• Iterator iterator( ) class java.util.HashSet implements java.util.Set class java.util.TreeSet implements java.util.Set interface java.util.Map
• boolean containsKey(Object key)
• Set entrySet( ) //Returns a set of Map.Entry objects (only
//referenced with an iterator)
• V get(Object key)
• Set keySet( )
• Object put(K key, V value)
• int size( ) class java.util.HashMap implements java.util.Map class java.util.TreeMap implements java.util.Map interface java.util.Map.Entry
• K getKey( )
• V getValue( )
• V setValue(V value) interface java.util.Iterator
• boolean hasNext( )
• E next( )
• void remove( ) interface java.util.ListIterator extends java.util.Iterator
(methods in addition to the Iterator methods)

Appendix J-4



void add(E x) void set(E x)

class java.lang.StringBuffer
• StringBuffer append(char c)
• StringBuffer append(String str)
• StringBuffer append(StringBuffer sb)
• int capacity( )
• char charAt(int index)
• StringBuffer delete(int start, int end) //character at index end is not deleted
• StringBuffer deleteCharAt(int index)
• StringBuffer insert(int offset, char c) //insert just before index offset
• StringBuffer insert(int offset, String s) //insert just before index offset
• StringBuffer replace(int start, int end, String replacementString) // the substring starting
//at index start and ending with index end –1 is replaced with replacementString
• StringBuffer reverse( ) //for example, changes “Hello” into “olleH”
• int length( )
• void setCharAt(int index, char ch)
• String substring(int start)
• String substring(int start, int end)
• String toString( ) class java.util.Scanner
• Scanner(InputStream source) //source is normally System.in
• Scanner(File inputFilePathAndName)
• Scanner(String s) //Total of three constructors
• String next( ) //Returns the next String from the current position up to the next delimiter
• String nextLine( ) //Returns the String from the current position to the end of the line.
• double nextDouble
• int nextInt( )
• Scanner useDelimiter(String regex)
• String findInLine(String regex) //Advances position and returns the String found or null.
• boolean hasNext(String regex)
• boolean hasNext( )
• boolean hasNextDouble( )
• boolean hasNextInt( )
• Scanner skip(String regex)
• String findWithinHorizon(String regex, int x) //search limited to next x characters

Appendix K-1

Appendix K …..Exception Classes
Following is a list of some of the exception classes found in java.lang. The indentations are an indication of inheritance with the leftmost of an adjacent pair being the superclass. Beside some of the exception classes are uses and some (but not all) conditions that would cause that exception. Exception
RuntimeException

(all below this point are unchecked exceptions)

ArithmeticException …division by 0, etc.
IllegalArgumentException …can be used to enforce method preconditions
NumberFormatException…illegal conversion of String to numeric
IllegalStateException…can be used to enforce method preconditions
IndexOutOfBoundsException
StringIndexOutOfBoundsException … index=String length
ArrayIndexOutOfBoundsException … index=array length
NullPointerException …trying to use a variable not referencing an object
UnsupportedOperationException
If you are not sure of which of these exception to use, you can always use RuntimeException as in the following code: if( …something bad happens… )
{
RuntimeException e = new RuntimeException(“Your own error message goes here.”) throw e;
}
***********************************************************************
Some subclasses of IOException are EOFException … end of file,
FileNotFoundException,
MalformedURLException,
UnknownHostException
All of these are checked exceptions.

Appendix L-1

Appendix L …..An Essay on Interfaces
Students often question the usefulness of Interfaces. This essay presents an interesting point of view and, hopefully, shows their true utility.
What is the physical interface to the various systems of an aircraft that a pilot sees when he sits in the cockpit?
The interface consists of all the instruments, dials, gauges, and controls that a pilot sees in front of him. For example, he doesn’t deal directly with the elevator at the rear of the plane…rather the yoke (part of the interface) control circuitry that, in turn, moves the elevator and thus makes the plane go up or down.
Now suppose we are the aircraft manufacturer and we have a number of models that we produce.
When a pilot sits in the cockpit of any of our models, we want him to see essentially the same interface. In other words, we want the same color scheme, things to be essentially in the same position, and the controls to work basically the same…we want standardization. Thus a pilot who has flown one of our models could feel fairly comfortable when moving to another model he has never flown.
How do we make sure all our models have this common interface? We send the specification for what the layout of the cockpit is to our design engineers so they will work this basic design into new models they create.
…. And so it is with software interfaces. We tell the software engineers who create classes for us, the signatures of the methods we want. (We do this by giving them an interface.) All we have to do is look at the first line of their class and see if it says implements. We need not look further.
We are assured that they have implemented every method of the interface we specified… otherwise, their class won’t compile.
Thus we see that the interface does four things for us:
1. It lets us specify the exact method signatures we want in a class that someone else will design for us… without us having to implement the code.
2. It promotes uniformity if several classes implement this same interface… just as the airplane cockpit will be uniform between the various models.
3. We can look at the first line of a class and if it says implements, we know the author has implemented everything we specified… we have no need to look further in the code to be assured of this.
4. Someone who wants to know how to use a class need not look through what might be thousands of lines of code that make up the class. It would be much easier to look at the interface to see how to use the class. Let’s say that another way. It’s much easier to look at the interface document to see how we interface to the class.

Appendix M-1

Appendix M …..Input from the Keyboard
From Lesson 7 we learned that the Scanner class makes it easy to obtain input from the keyboard. For versions of Java preceding 1.5, use the following somewhat more complicated technique (requires importing java.io.*).
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine( ); //Reads in a line of text
This code is capable of throwing the checked exception IOException so, either handle with trycatch or append throws IOException to the method signature. The InputStreamReader class inputs one byte at a time from the keyboard. BufferedReader allows many bytes to be handled as a line of text.
**********************************************************************
For versions of Java preceding 1.5 there is an easier class to use for keyboard input, TerminalIO, however, it is not one of the standard Java classes. Below is a website from which TerminalIO can be downloaded: http://www.bluepelicanjava.com/Download_jar.htm (that’s an underscore between d and j)
Put this jar files in the appropriate folder similar to the following:
C:\Program Files\Java\jdk1.5.0_04\jre\lib\ext
Two popular programming environments, BlueJ and JCreator will both recognize classes within jar files placed in this folder. Do not place your jar file into C:\Program
Files\Java\jdk1.5.0_04\lib\ext. This is a different, although similarly named folder.
After importing TerminalIO, use as follows:
KeyboardReader reader = new KeyboardReader( ); int i = reader.readInt( ); //reads in an integer double d = reader.readDouble( ); //reads in a double
String s = reader.readLine( ); // reads in an entire line of text

Appendix N-1

Appendix N …..Using the BlueJ Programming Environment
The BlueJ IDE (integrated development environment) is a free download at http://www.bluej.org/download/download.html. The following sequence of steps details how to create a BlueJ project and then classes within that project.

Run BlueJ. From the Project menu item choose New Project.

Fig. N-1

Use the Look In control to navigate to the desired location of your project. For this example we chose the folder, Temp_Larry.
In the File Name control enter the name of your project. The name in this example is
MyFirstProject.
Click the Create button.

Fig. N-2

Your project now exists. You need to add at least one class to the project. To add a class click the New Class button.
Fig. N-3

Appendix N-2

Give your class a name in the Class
Name control. The name in this example is Tester.
Choose any one of the Class Type buttons (typically class). It really doesn’t matter which one since your instructor will probably have you wipe out any code it produces so that you can practice entering it yourself.
Click OK.
Fig. N-4

Enter your code here. (Most instructors will have you delete the preexisting code.) Click on the Compile button when you have finished entering the code. Any errors you might have made will be detailed at the bottom of this screen.
Fig N-5

If you exit the screen just above without a successful compile, the icon for this class will have stripes as shown to the right.
Fig. N-6

This class icon indicates that it has been compiled successfully (no stripes). To run your program, rightclick on this class icon (Tester for this example).
Fig. N-7

Appendix N-3

Click on void main(args).

Fig.N-7

Yet another dialog opens. Click on Ok and your program will run.

Fig. N-8
The Terminal Window pops up to display any output that your program produces. If desired you can close this window after viewing.
Fig. N-9
See Appendix M for how to make jar files available to BlueJ.

Appendix O-1

Appendix O …..Using the JCreator Programming Environment
The JCreator IDE (integrated development environment) is a free download at http://www.jcreator.com/download.htm. The following sequence of steps details how to create a
JCreator project and then classes within that project.
Run JCreator. From the
Project menu item choose New Project….
Fig. O-1

Choose Empty Project and click the Next button. Fig. O-2
In the Name control, enter the desired name of your project. Here, we have chosen the name MyBigProject.
The default values for
Location, Source Path, and Output Path are the normal ones you will choose. In this example we have changed these so that everything gets stored in
C:\Temp_Larry.
Click the Finish button.
Fig. O-3

Appendix O-2

Create a new class within your project with
Project | New Class. The dialog to the right will pop up.
In the Name control, enter the desired name of your class.
Most instructors will ask that you leave the six check boxes unchecked so that you can later enter the code yourself.
Click the Finish button.
Fig. O-4

In the large area to the far right you can enter your code for this class.

Fig O-5

Fig O-6

Use these tools to compile your project and then to execute the code.
There are 5 tools here and for reference we will number them from left to right (1 – 5).
1. Batch compile
2. Compile current file(class)
3. Execute the main method of the current class
4. Compile all classes in a project
5. Execute project…automatically seeks out the main method.

See Appendix M for how to make jar files available to JCreator.

Appendix P-1

Appendix P ….. Time Allocation for Lessons and Tests
Lesson

Time Comments

“First day” activities

1 day

Lesson 1
Lesson 2

1 day
1 day

Lesson 3

2 days

Test through Lesson 3

1 day

Lesson 4

2 days

Lesson 5
Lesson 6
Lesson 7

1 day
1 day
1 day

Test through Lesson 7

1 day

Lesson 8

2 days

Lesson 9
Lesson 10
Test through Lesson 10

2 days
3 days
1 day

Lesson 11

3 days

Lesson 12

3 days

Lesson 13

2 days

Lesson 14
Test through Lesson 14

2 days
2 days

Make-up test through
Lesson 14 (Alternate Test through Lesson 14)

2 days

Lesson 15

3 days

Lesson 16

3 days

Pass out books, demonstrate how to log-on, create project folder, learn how to launch and configure programming environment.
Enter the “Hello World” program into the computer and execute.
Illustrate each point of Lesson 2 by modifying the code of the “Hello
World” program of Lesson 1. Assign the exercise on Lesson 2 as homework. There should be some time to work on this towards the end of the period and time to check answers.
Illustrate each point of Lesson 3 by running code. Assign Exercise on
Lesson 3. Grade assignment at end of 2nd day.
Allow the students to work on the test, take it up at the end of the class, and let them know when them come back the next day they can make any corrections they look up that night. Keep beginning students from becoming discouraged from the start by making this an open-book test.
Have the students run many of the code examples in their IDE (integrated development environment) Some of the problems on the exercise must be finished as homework in order to fit this lesson into one day.
Run several of the code examples.
Run several of the code examples.
Do the first project together in class and assign the “Full Name” project as a written assignment. Typical grades range from 92 to 51. Problems 5, 9,
11, 12, 2, and 25 were those most often missed. On the day after the test go over these specific problems.
At this point still let the students use the book for the test… try to build up their confidence.
Many of the code example need to be run on the computer as they are discussed. Be sure to actually run the first two code examples.
Definitely run the code “menu” example.
This test may be difficult for some. On the day before the test let the students look over a copy of the test for about 10 minutes so there will be no surprises on the day of the test.
This is the most important lesson so far. Be sure to run several of the code examples. This is where we begin to acclimate the students to “contest type problems”.
Again, run many of the code examples… very important concepts here.
After the 14 regular exercise problems are completed, give the 5 “contest type” problems as a quiz.
Emphasize the techniques for storing a char into a String and vice versa.
Have students memorize the ranges of ASCII codes.
Use chalk board for demo of conversion techniques.
This will be a lengthy test and it is suggested that it not be an open-book test. Many students will need two days. Let the first day be an eye-opener for them so they will study overnight and continue the next day.
In order not to discourage students who do poorly on the original test, you might possibly want to give this 16-question re-take. Spend one day correcting the mistakes from the original and then one day taking this new test… The questions on this test are mostly what is likely to have been missed on the original test.
Spend time on this lesson! This is the most important lesson so far. Have students enter and test the code for the Circle class. There are 20 questions on the exercise for this lesson. If the students do poorly on the exercise there is a “redemptive” quiz that could be given.
This is a follow up to lesson 15…very important concepts here.

Appendix P-2
Test through Lesson 16
Lesson 17
Lesson 18
Lesson 19
Test through Lesson 19

1 day
3 days
3 days
4 days
2 days

Lesson 20
Lesson 21
Lesson 22
Test through Lesson 22

2 days
1 day
1 day
2 days

Lesson 23

4 days

Lesson 24

3 days

Test through Lesson 24
Lesson 25
Lesson 26
Lesson 27

1 day
3 days
1 day
2 days

Test through Lesson 27
Lesson 28
Lesson 29
Test through 29
Lesson 30
Lesson 31
Lesson 32
Lesson 33
Test through 33
Lesson 34
Lesson 35
Test through 35
Lesson 36

1 day
3 days
2 days
1 day
3 days
1 day
3 days
1 day
1 day
2 days
3 days
1 day
3 days

Test through 36
Lesson 37
Lesson 38
Test through 38
Lesson 39
Lesson 40
Test through 40
Lesson 41
Test on Lesson 41
Lesson 42
Lesson 43
Lesson 44
Test on Lesson 44
Lesson 45
Test on Lesson 45
Lesson 46
Lesson 47
Test on Lesson 47
Lesson 48
Lesson 49

1 day
2 days
2 days
1 day
2 days
3 days
1 day
6 days
1 day
1 day
3 days
4 days
1 day
3 days
1 day
2 days
3 days
1 day
2 days
3 days

This is primarily a test on objects and classes (lesson 15 and 16).
Students will find this much easier than the previous lessons on objects.
Let students know that arrays will be used in nearly all future lessons.
Be sure to do the programming projects.
It is suggested that this test be split across two days. Overnight they can study what they saw on the test and didn’t understand.

This is a difficult test. Let the students work on it for 30 minutes or so the first day, take it up, let them study overnight, and then finish the second day. Plan to spend 1 day going over the material in the textbook. The second day can be devoted to doing and explaining the exercises. The programming project will also take a complete period if the students are forced to do most of it themselves. The contest type problems will require a day. Some of those problems are tricky and will require some explanation. Many lesson from this point on depend on inputting data from a file. Make sure the students get a good foundation.
This test is considerably shorter than the others and probably easier.
Honing skills with file input.
Actually this lesson can be done in half a period.
Be sure students keep the BaseClass class. They will paste code from it into many of their future projects.
The project in this lesson will take an entire day for most students.
Be sure to do the Monte Carlo project.
Stress the append and toString methods.
DeMorgan’s theorem is very important.
Some important concepts are here.
This can be done in three days; however, this is such an important lesson that it might be more desirable to allocate 4 days.
This test focuses strictly on Lesson 36, the inheritance lesson.

This lesson on recursion is especially important.
Spend one day for each sorting type.
ArrayList. Spend at least one day on the project.
Iterators
These concepts are very important. Be sure to do all three projects.

Appendix P-3
Lesson 50
Test on Lesson 50
Lesson 51
Lesson 52
Test on Lesson 52
Lesson 53
Lesson 54
Test on Lesson 54
Lesson 55
Lesson 56
Lesson 57
Test on Lesson 57

2 days
1 day
3 days
3 days
1 day
2 days
2 days
1 day
3 days
3 days
3 days
1 day

See http://www.bluepelicanjava.com/LessonPlans.htm for eventual posting of detailed lesson plans. Appendix Q-1

Appendix Q ….. AP (A & AB) Correlation
Items on the A and AB Exam int, double
+, -,*, /, ++, --, %
= =, !=, >, =, cd C:\Temp_Larry\HelloWorld

You enter the bold part. The non bold part is the on-screen prompt.

If all went well, you will see a new command prompt as follows:
C:\Temp_Larry\HelloWorld >_
This indicates that you are, indeed, “parked” in the HelloWorld folder where your Hello.java source file is located. Thus, when we issue a command that references Hello.java the computer will find it.
Compile:
Let’s compile our file using the javac.exe file in the bin folder mentioned above. Here is the command: C:\Temp_Larry\HelloWorld > javac Hello.java
Unfortunately, this won’t work because the computer is unable to recognize or find javac. It has no idea where to find this file. The following will work where we explicitly give the full path to the javac.exe file:
C:\Temp_Larry\HelloWorld > C:\Program Files\Java\jdk1.5.0_04\bin\javac Hello.java
You can look in the HelloWorld folder and see that a new file has just been created, Hello.class.
This is the result of the compilation. You could, of course, use Windows Explorer to look in the folder, or from the command prompt, you could issue the command dir and get a listing of the files. (dir means “directory” which is the old-fashioned term for “folder”).
Setting a Path:
Entering long path names can become quite inconvenient. If we have much more activity with this session of the command prompt screen, we need a shortcut so as to avoid the necessity of entering these lengthy paths. At the command prompt, enter the Path that gives the location of the javac.exe and java.exe files:
C:\Temp_Larry\HelloWorld > Path = C:\Program Files\Java\jdk1.5.0_04\bin
We can now shorten the command necessary to compile our file:

Appendix X-3
C:\Temp_Larry\HelloWorld > javac Hello.java
The file javac is now easily found because the Path we set tells the computer to look in that folder for any exe, com, or bat files we might subsequently run from this session of the command prompt screen. Now, execute the main method in our compiled file by issuing the following:
C:\Temp_Larry\HelloWorld > java Hello
Notice in this last command line that we don’t specify the name of the class file (which is
Hello.class); rather, we give the name of the class, which is just plain Hello. The code will execute and any output will appear on the black DOS prompt screen, just as it would in the console window of our favorite IDE.
You should be aware that the setting of the Path command only persists while we are in the current session of the DOS prompt screen. If this window is closed and is then subsequently reopened, the setting will be lost.
Setting a permanent Path:
There is, however, a way to make the Path setting permanent via the following sequence:
Start | (Settings) | Control Panel | System | Advanced Tab | Environment Variables
Create a new User Variable for called Path with value C:\Program
Files\Java\jdk1.5.0_04\bin. Typically, this takes effect without the necessity of a reboot, but if things don’t work immediately, try restarting the computer. This Path setting augments the Path
System Variable. If you want this new Path to affect all users and if your logon name has
Administrative permission, instead, edit the Path variable in the System Variable section by appending the following to what it already has:
; C:\Program Files\Java\jdk1.5.0_04\bin
If you set the System Variable, reboot the computer. In either case you will find this new Path is now in effect and is permanent.
Related topics:
Two closely related subjects are the creation of packages and the setting of the classpath variable. See Appendix I for details on these topics.
A note concerning Windows 98:
All of the above is true with the following three exceptions:
1. Instead of using cmd to access the DOS prompt screen, use command.
2. Long path or file names (exceeding 8 characters in length) will need to be enclosed in quotes.
3. For permanent Path settings you will need to add the desired Path to the
Autoexec.bat file since this cannot be done within the Win 98 System dialog.

Appendix Y-1

Appendix Y… Bytes, Kilobytes, Megabytes, & Gigabytes
Recall from Lesson 14 that computer memory is organized into bytes and that a byte is 8 bits (for example, 10011011). The number of bytes of RAM (random access memory, a computer’s main memory) is always given by powers of two. Certain powers of two have been given special names recognized throughout the industry:

Name Abrev
Kilobyte
kb
Megabyte
mb
Gigabyte
gb

Actual Number Power of 2
1,024
210
1,048,576
220
1,073,741,824
230

Approximation
1,000 (one thousand)
1,000,000 (one million)
1,000,000,000 (one billion)

Table Y-1
In the chart above, it is the approximate value that people normally think of and use most often.
It is easier to remember than either the “Actual Number” or “Power of 2”.
The following table shows some other common, often used megabyte values.
Name
16 meagbytes
32 megabytes
64 megabytes
128 megabytes
256 megabytes
512 megabytes
Table Y-2

2x
224
225
226
227
228
229

Exact Value
16,777,216
33,554,432
67, 108,864
134,217,728
268,435,456
536,870,912

Appendix Z-1

Appendix Z… Formatting with the DecimalFormat Class
Use the following test class to demonstrate the abilities of the DecimalFormat class. Note the required import. import java.text.*; public class Formatting
{
public static void main( String args[] )
{
double testNum = 5847.2268;
String pattern = “##,###.##”;
DecimalFormat df= new DecimalFormat(pattern);
System.out.println(df.format(testNum)); //5,847.23
}
}
The following table shows the output for various combinations of String pattern and double testNum: pattern

“###,###.##”
“###,###.##”
“###,###.00”
“#,##0.##”
“$###,##0.00”
“$###,##0.##”
“$###,##0.##”
“#####00.00###”
“##0.##%”
“+”
“+##”
“##”
“##.##”
“+##.##”
“00000.00”

testNum

5368.8742
5368.876
38
.9881
8232.6
.9827
.997
3.8749879
.345667
.2245
36.889
36.889
-480.0934
-480.0934
45.97665

Output
5,368.87
5,368.88
38.00
0.99
$8,232.60
$0.98
$1
03.87499
34.57% (see note below)
+0
+37
37
-480.09
-+480.09 (blindly prints +)
00045.97

When using the percent sign, the number is first multiplied by 100, and then the pattern is applied.
Use the applyPattern method in the following way to apply a new formatting pattern after a
DecimalFormat object has already been created.
DecimalFormat df = new DecimalFormat(“000.##”);
System.out.println(df.format(12.7391)); //012.74 df.applyPattern(“0,000.00”); //applies a new pattern to the df object
System.out.println(df.format(12.7391)); //0,012.74

Appendix AA-1

Appendix AA… Multiplication of Matrices
The use and manipulation of matrices is of great interest in computer science. It is especially useful when working with images where a very common operation is the multiplication of two matrices. In this appendix we will learn how to multiply two matrices (because it’s the basis of a project in Lesson 35), but first, let’s define what a matrix is:
A matrix is simply a two dimensional array of numbers. Consider the following sample matrix, A.
A=

1
-3
6

2 -2
4 7
0 3

0
2
1

The matrix sample above has dimensions 3 X 4. This means that it has 3 rows and 4 columns. It is conventional to always give the dimension of a matrix in row column (RC) order. Next, let’s look at the multiplication of two matrices.
1
-3
6

2 -2
4 7
0 3

0
2
1

X

-1
3
0
9
1 -11
4 -5

=

-3
18
1

43
-60
-20

How does it produce the answer matrix on the right? Below, we show how to produce the –3 in the answer:
R=0

1
-3
6

2 -2
4 7
0 3

C=0

0
2
1

X

-1
3
0
9
1 -11
4 -5

R=0, C=0

=

-3
18
1

43
-60
-20

Calculate 1(-1) + 2(0) – 2(1) + 0(4) = -3.
Next, we produce the 18:
R=1

1
-3
6

2 -2
4 7
0 3

C=0

0
2
1

X

-1
3
0
9
1 -11
4
-5

R=1, C=0
=

-3
18
1

43
-60
-20

Calculate -3(-1) + 4(0) + 7(1) + 2(4) = 18.

Appendix AA-2
The 1 in the answer is produced as follows:
R=2

1
-3
6

2
4
0

C=0

-2 0
7 2
3 1

X

-1
3
0
9
1 -11
4 -5

R=2, C=0
=

-3
18
1

43
-60
-20

Calculate 6(-1) + 0(0) + 3(1) + 1(4) = 1.
The 43 in the second column of the answer is produced as follows:
R=0

1
-3
6

2 -2
4 7
0 3

C=1

0
2
1

X

-1
3
0
9
1 -11
4
-5

R=0, C=1
=

-3
18
1

43
-60
-20

Calculate 1(3) + 2(9) –2(-11) + 0(-5) = 43.
The -60 is produced as follows:
R=1

1
-3
6

2 -2
4 7
0 3

C=1

0
2
1

X

-1
3
0
9
1 -11
4
-5

R=1, C=1
=

-3
18
1

43
-60
-20

Calculate -3(3) + 4(9) + 7(-11) + 2(-5) = -60.
Finally, we produce –20:
R=2

1
-3
6

2 -2
4 7
0 3

C=1

0
2
1

X

-1
3
0
9
1 -11
4
-5

R=1, C=1
=

-3
18
1

43
-60
-20

Calculate 6(3) + 0(9) + 3(-11) + 1(-5) = -20.
**********************************************************************
Not all matrices are compatible for multiplication. The following shows the requirements for compatibility as well as a prediction for the dimensions of the product matrix.

Appendix AA-3

ARC X BRC = CRC
C=R

Notice that the number of columns in the A matrix must equal the number of rows in the B matrix. The answer matrix (C) will have the same number of rows as the A matrix and the same number of columns as B.
Finally, the reader is reminded that matrices can be represented in Java as two-dimensional int arrays as illustrated by the following:

A=

1
-3
6

2 -2
4 7
0 3

0
2
1

In code, enter this matrix as follows: int a[][] = {

{1, 2, -2, 0},
{-3, 4, 7, 2},
{6, 0, 3, 1 } };

Appendix AB-1

Appendix AB … Monospaced Fonts
The following information about monospaced fonts is useful for the “Heap of Trouble” project in
Lesson 55.
The Times New Roman font is used to print the following two lines:
….
klmnop
Next, print the same two lines using the Courier New font:
....
klmnop
Do you see the difference? Notice the space the periods occupy in the top line of each example.
Each character in the Courier New font (a monospaced font) occupies the same amount of horizontal space. This is characteristic of a monospaced font. Most fonts are not monospaced because for normal word-processing they do not look very professional or pleasing to the eye.
Consider the following paragraph in Times New Roman. The paragraph after it is done with
Courier New.
Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal.
Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal.
So if monospaced fonts are not as pleasing to the eye, why do we use them? The answer is that they are used for formatting. Suppose we wish to print the following two currency values using
Times New Roman.
$147,892.88
$101,111.11
They seem to line up just fine, so what’s the big deal? In this case the word processor that produced this document (Microsoft Word) is clever enough to go into a monospaced mode when writing numbers like this. However, when aligning codes as follows, we see the problem.
AIIXIULK-XXBQ
IIIXIUIB-K$%A
Each of the above two lines has the same number of characters before and after the dash. They don’t line up with each other. Now, look at the same pair of codes using a monospaced font and we can observe that vertical alignment is maintained.
AIIXIULK-XXBQ
IIIXIUIB-K$%A
For a table of such codes, the monospaced version is much more pleasing to the eye. Some other monospaced fonts are:
Arial Monospace
Courier
Letter Gothic
Lucida Console
OCR-A
OCR-B
MICR
Typewriter Gothic
Typewriter Elite
Typewriter

Appendix AC-1

Appendix AC… Regular Expressions
This appendix will only present a cursory explanation of regular expressions. There is much, much more to the grammar of regular expression than will be presented here. The reason for the presentation of regular expressions in this book is for the purpose of understanding the split method from the String class. Additionally, the replaceAll and replaceFirst methods (they also use regular expressions) will be discussed here. See Lesson 18 for more on the split method.
Certain methods of the Scanner class also use regular expressions.
Regular expressions describe character patterns that aid in the location of matching text. A popular program that uses regular expressions is grep (which stands for “generalized regular expression pattern”). Grep is part of UNIX, but versions do exist for Windows and MacOS.
So, how do we use regular expressions? First, we will show some examples of general usages of regular expressions:

Regular Expression

What it Finds

[0-9]+

Find sequences of digits like “183”, “2”, “19239”, etc. It would not, for example, find 23,826 in its entirety because the comma breaks the sequence. It would find 23 and 826 separately.
Notice that “[0-9]” denotes any digit between 0 and 9 while “[09]+” means “one or more” occurrence of 0 through 9.
Find occurrences of “xyz” in the text.
Find occurrences of a single “D” followed by a single occurrence of a letter that falls in the range between “J” and “Z”
(either upper or lower case).
Find occurrences of a single digit in the range from 4 through 8 followed by another single digit in the range from 0 through 5 followed by a single letter that is not in the range from “B” through “M”. Notice that the “^” means not.
Find occurrence of a single letter “J”, followed by any single character (the period means any character) followed by an “a” or an “m” followed by the digit 4.
This means the same thing as the previous expression except \. means we are looking for a literal period now instead of “any character”. Find occurrences of either the letter “A” or the letter “b” followed by any letter in the range “p” through “z”. Notice that | means OR.
Find occurrences of the letter “F” followed by zero or more occurrences of the letter “p” followed by the letter “a” or any letter between “m” and “z”. Notice that “*” means zero or more occurrences. Find occurrences of “C” followed by one or more white space characters. xyz
D[J-Zj-z]
[4-8][0-5][^B-M]

J.[am]4
J\.[am]4
A|b[p-z]
Fp*[am-z]

C\s+

Table AC-1 Sample regular expression usage
The following tables expose just some of the grammar used in regular expressions.

Appendix AC-2
Sample Character Classes

Results, Meaning

[xyz]
[^xyz]
[m-yA-K]
[m-y&&[^xy]]
[C-Z&&[^M-R]]

A single character consisting of “x”, “y”,or “z” (simple class)
Any character except “x”, “y”, or “z” (negation)
“m” through “y” or “A” through “K”, inclusive (range)
“m” through “y” except for “x” and “y” (subtraction)
“C” through “Z”, but not “M” through “R” (subtraction)

Table AC-2 Character classes
Predefined
Characters

Meaning

.
\d
\D
\p{Name}

Any character
A digit: [0-9]
A non-digit: [^0-9]
Matches any character in the named character class specified by Name. Supported names are Unicode groups and block ranges. Name could be something like Digit.
Matches text not included in groups and block ranges specified in Name.
A whitespace character: [\t\n\f\r\x0B]
A non-whitespace character: [^\s]
A word character: [a-zA-Z0-9]
A non-word character: [^\w]

\P{Name}
\s
\S
\w
\W

Table AC-3 Predefined character classes
Greedy quantifiers

Meaning

M?
M*
M+
M{n}
M{n, }
M{n,m}

“M”, once or not at all
“M”, zero or more times
“M”, one or more times
“M”, exactly n times
“M”, at least n times
“M”, at least n but not more than m times

Table AC-4 Greedy quantifiers
POSIX Character Classes

Results, Meaning

\p{Lower}
\p{Upper}
\p{ASCII}
\p{Alpha}
\p{Digit}
\p{Alnum}
\p{Punct}
\p{Graph}
\p{Print}
\p{Blank}
\p{Cntrl}
\p{XDigit}
\p{Space}

A lower-case alphabetic character: [a-z]
An upper-case alphabetic character: [A-Z]
All ASCII: [x00-\x7F]
An alphabetic character: [\p{Lower}\p{Upper}]
A decimal digit: [0-9]
An alphanumeric character: [\p{Alpha}\p{Digit}]
Punctuation: One of !”#$%&’( )*+,-./:;?@[\]^_`{ | }
A visible character: [\p{Alnum\p{Punct}]
A printable character: [\p{Graph}]
A space or a tab: [ \t]
A control character: [\x00-\x1F\x7F]
A hexadecimal digit: [0-9a-fA-F]
A whitespace character: [ \t\n\x0B\f\r]

Table AC-5 POSIX (Portable Operating System Interface for UniX) character classes

Appendix AC-3
Escape Sequence

Meaning

\\
\on
\onn
\omnn
\xhh
\uhhhh
\t
\n
\r
\f
\a
\e
\cx
\.
\*
\+
\[
\]

The backslash character
The character with octal value on (02341.450000<
(">%g%h%o%s%x

Similar Documents

Premium Essay

Story

...homeboy if i could post this. SOOOO my friend is that mutha fucka thats on the freeway that likes to try and talk to girls you know. Never really met anyone or knew anyone that actually did this like this but umm yea its like stupid crazy to me. He's telling me how he does this. How he scopes the car out, how he checks for kids in the back seat, checks for the carseats, looking for who else is in the car and looking to see if there is a ring on the finger. Yea he got this shit down to science, no ifs ands or buts about it. He told me he got the idea from sitting in traffic and trying to cut in front of people to get to this one female. Like who does that, like im not in my damn car in traffic thinking damn maybe i can get some booty on the freeway we stopped anyway. Pull up to the window like Burger king asking your vehicle or mine.What the fuck hell nah. But at this point i'm like you whatever you cant be serious with this. He's like "im as serious as beating some one elses bad ass kids in the movies" . So yea um i was like well then i have to see this for my self. He goes on to tell me he get some girls numbers others flip him off all times of things. He get flashed and all this other shit that is like beyond belief on a damn freeway. Ok so now i got to see this for my self i want to get flash too, (dont judge me *sniffle sniffle* i want to see something tooooo lol). Now its the day of and im thinking to my damn self what do i wear do i just put on a shirt and hat cause that all...

Words: 822 - Pages: 4

Free Essay

Doc Lock Dock Shock the Flock

...Stevens Institute of Technology) and Molski, in their essay entitled The Lost Art of Writing,[12][13] are critical of the terms, predicting reduced chances of employment for students who use such slang, stating that, "Unfortunately for these students, their bosses will not be 'lol' when they read a report that lacks proper punctuation and grammar, has numerous misspellings, various made-up words, and silly acronyms." Fondiller and Nerone[14] in their style manual assert that "professional or business communication should never be careless or poorly constructed" whether one is writing an electronic mail message or an article for publication, and warn against the use of smileys and these abbreviations, stating that they are "no more than e-mail slang and have no place in business communication". Yunker and Barry[15] in a study of online courses and how they can be improved through podcasting have found that these slang terms, and emoticons as well, are "often misunderstood" by students and are "difficult to decipher" unless their meanings are explained in advance. They single out the example of "ROFL" as not obviously being the abbreviation of "rolling on the floor laughing" (emphasis added). Haig[1] singles out LOL as one of the three most popular initialisms in Internet slang, alongside BFN ("bye for now") and IMHO ("in my honest/humble opinion"). He describes the various initialisms of Internet slang as convenient, but warns that "as ever more obscure acronyms emerge they can also...

Words: 607 - Pages: 3

Free Essay

Beeitch

...And it's great, I really like it Zoo says: thats good sry i signed in quietly Bəəə ` says: Lmao, you can do that? Zoo says: naw ur jus blind Bəəə ` says: I think you signed on when I went to myroom lol Zoo says: oh hows first day? Bəəə ` says: First day was long But interesting My first teacher was blind And indian, but he didn't have an accent My second teacher was also indian And she has a double chin and an indian accent My third teacher had no hair in the back Zoo says: lool Bəəə ` says: She's bald but has long hair in the front And the top of her head is blonde and the bottom is blue Zoo says: its like u pay attention to the wrong aspects of being in a class Bəəə ` says: And she was wearing a studded coller on her neck Yeah, I do Zoo says: lol Bəəə ` says: And I had weight training as my last class Zoo says: what'd u guys do ? Bəəə ` says: A lot We started with the bikes Then she made us too like everything Lift weights, squats, push ups, sit ups, everything She pretty much made us work out every muscle in our body Zoo says: lol first time ey? howd u like it ? Bəəə ` says: Yeah I WASN'T EVEN TIRED AT THE END Zoo says: u jus told me u were mad tired Bəəə ` says: That was yday lol Today, I'm exhausted Had a pretty long day too And I think the workout from yday is affecting me now Zoo says: what did u wear today? Bəəə ` says: Sorry, I'm talking so much Um Zoo says: naw its cool...

Words: 619 - Pages: 3

Free Essay

How Technology Has Changed Our Language

...Twitter.  Social media’s been responsible for a lot of new words, for example tweeps, twitterverse and retweet. The word “friend” has become a verb, as in “she friended me on Facebook”. The term “check-in” no longer applies just to hotels and airports; these days it’s just as commonly used when someone reports where they are via a social network. Technology has also changed the way we write. Mobile phones have been responsible for a lot of the change, as users have moved towards texting as an everyday form of communication. For a start, WRITING IN UPPER CASE MEANS YOU’RE SHOUTING, while lower case writing is now the accepted form. Meanwhile, text language is full of abbreviations, missing vowels and acronyms. For example, the abbreviations LOL, OMG and gr8 are all widely used today but hadn’t been invented a few years ago. One of the drivers in this is that screen sizes and character limits are low, meaning that users need to abbreviate to fit their messages in. My Knowledge: ‘Emojis’ which are small digital images and ‘emoticons’ which are representation of a facial expression such as a smile or frown, formed by various combinations of keyboard characters are also now used because of technology. Their main purpose is to show how someone is feeling and their emotions rather than a person typing out how they are actually feeling. Technology has also enabled new words to be created such as ‘selfie’ ‘twerk’ ect. Without technology, there would be no way in which everyone would...

Words: 324 - Pages: 2

Free Essay

Lolol

...cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool, bcauseit is lol lol lol History iz cool...

Words: 360 - Pages: 2

Free Essay

Lol Lol Lol Lol Much

...Reaction Paper Extraordinary Measures A Portland couple have two younger children that are afflicted with Pompe’s disease, a rare neuromuscular ailment that is usually fatal within the first eight years of life. Megan is the partner’s 8-year-old middle child and Patrick is the 6-year-old youngest, so time is running out of them. The husband, an advertising executive, leaves his job and contacts Dr. Robert Stonehill, a cranky, renegade scientist in Nebraska who has done an unprecedented research for enzyme treatment and is one of the leading researcher in the field of Pompe’s who’s idiosyncratic for thinking to the beat of rock music blasting from a boom box. The two men meet and clash after driving to the University of Nebraska where Stonehill is employed. He has little money to fund his laboratory, and a thorny personality that drives away colleagues and funders. John and his wife Aileen raise money to help Stonehill's research and the required clinical trials. John takes on the task full time, working with venture capitalists and then rival teams of researchers. They lock horns with each other, venture capitalists, and finally a large genomic research corporation, Zymagen. Stonehill's angry outburst hinder the company's faith in him, and the profit motive may upend John's hopes. The researchers race against time for the children who have the disease. The film is maudlin to say the least but earnestly true. The very first thing I’ve learned in the movie is that you...

Words: 630 - Pages: 3

Premium Essay

Jennifers Day

...was a beautiful Saturday morning when Jennifer decided to go to the salon and get her hair, nails, toes, and eye brows done for when she goes to club Skky tonight with her girls Lisa, Maggie, Mary, and Kelly. All the ladies will be going out tonight to the club to celebrate Jennifer’s promotion after all the hard work she put it she finally got the promotion she deserved. Kelly decided it would only be right to celebrate her hard work accomplished. Once Jennifer finish getting herself ready, the ladies met up at the mall to go shopping for the outfit they were going to wear that night. Each of them found their outfit for the night, but of course Jennifer was taking forever finding the right one. Jennifer and the girl decided to check one last store in the mall before moving on. As they were ready to give up Mary comes walking up with a beautiful red dress. The top of the dress is made with a lacey material with silver trimming and a few small flower design. Jennifer fell in love with it as she admired the details more and more. She quickly went to try it on. As she walked out to show the girls, she lite up the room. Jennifer is a very beautiful woman but that dress enhanced her beauty by ten if that was even humanly possible. “That’s it that one is definitely the one..girl if you don’t get it then I will..lol said...

Words: 255 - Pages: 2

Premium Essay

A True Life Story

...And trust me,that is sa question I dont want to answer....Around 10:00pm on that same day,i was in my room preparing to go to bed when some girls knocked on my door.I stood up to open the door and to my suprise,i saw seven beautiful and classy ladies who were dazzling from head to toe.I couldnt help but stare at them for over 40secs before I asked them to come in. Their names were :fatty,beebah,motun,rashy, stella,moyo and kenny.Even when they were introducing themselves,i just kept staring at their shoe,dress and hair. Then there was this short girl among them,she said her name was kenny.she was so short that I almost thought she was a younger sister to one of them not until they mentioned that she is the leader of the clique....mehn! I was dazed. They came in different sizes and shapes but they were beautiful.Motun and beebah were big and fierce,i almost thought they sent them to beat me up....lol....fatty and rashy on the other hand looked friendly but they were the talkatives,stella was the one who carried their bags for them.Everything was just weird to me,and with the way the short babe was commanding all of them. After sometime,they stated the reason why they came,they said they saw that I had potentials and they want me to join their Clique.Without thinking twice,i just jumped on the offer. Did I mention that these girls brought a new dress for me so that I could follow them to club? Damn! I was...

Words: 350 - Pages: 2

Free Essay

Socio 101

...in first to do this project, to see the people’s faces turning my direction in an unpleasant way. The store that I walked into was called “Dress Town” at the Eagle Rock Mall on Sunday, March 10, 2013 in the afternoon. As walking into the mall and into the store, we three girls had to put ourselves into a mind of a sociologist; and how they would “judge the book by its cover.” But realistically the shocking part is that they don’t, instead they use their sociological imagination to broaden their thinking mentality, to find other ways to live. Who ever said that there only is one certain way to live and that is the correct way? I realized that as Meghedi, Ani and I were walking the normal or decent looking shoppers were keeping a good amount of distance, more than usual. Also, the shoppers that had children with them, they were pulling their children towards them in a noticeable way while staring at us. As I walked into the store, being extremely nervous because I was the first one to do this project; completely nervous, not knowing what was to come before me, there were four sales associates. One of the associates stood by the door and greeted each customer as they walked in. When I walked in that girl greeted me but not the same way that she greeted the other customers. Her greeting them was a lot sincerer compared to the way she greeted me. Everyone seemed to be staring at me but when I glanced back at them they would look away to not catch my attention, so they would...

Words: 2138 - Pages: 9

Free Essay

Midsumme

...rLiterary Analysis on Midsummer by Manuel Arguilla By gaaabilagan | March 2013 * Zoom In * Zoom Out Page 1 of 3 Set in a very hot summer day, Manuel Arguilla’s Midsummer is a story with a very short and simple plot. It is basically a story of a man meeting a very beautiful Filipina woman by the well in a sizzling summer day. It starts off with the man and his cart tied to his bull on a long dry road when he suddenly sees a woman who stood unmoving watching the man come towards her. The woman was described from head to toe with such detail as the man looked from a distance. The man followed the woman to the where she went and led him to the well under a big mango tree. He watched her as she filled the jar and placed it on top of her head. The woman leaves and the man goes to the well and gathers water for his bull and himself while still thinking of the woman. The man then eats his dinner under the shade of the tree when the woman comes back to refill her jar. As she fills her jar the man invites the woman referring to her as Ading, to eat with her. The woman then addresses the man as Manong and thankfully refuses his invitation to eat as she herself just ate. They converse and suddenly the woman spills water all over the food and apologizes by getting him water but the Manong insists that he fetch it from the well. Ading notices Manong’s well built muscles and body as he fetches water, showing her how strong he is. He drinks his water as Ading lifts the bucket for him...

Words: 2275 - Pages: 10

Free Essay

Pink for Girls, Blue for Boys?

...Pink for girls; Blue for boys? Nowadays if we walk into a department store we can be sure that we will find pink and some blue clothes, toys and little other objects for children such as books, bikes, lunchboxes, board games, toy cookers, cash registers, even games consoles. If we look at these objects there is no wonder everybody knows that pink is specified for girls and blue for boys. But how did this become a common thought? Since when do we use colors to make a difference between genders? And why exactly did we choose pink and blue to fulfill this role? In the 1800s most infants were dressed in white and both boys and girls wore dresses or short skirts until the age of five or six. Although, there was a few small difference between boy and girl clothing. For example girls wore dresses which were buttoned up in the back while boys’ dresses were buttoned up in the front. So gender difference wasn’t highlighted just in a little scale. Why wasn’t this important in that age of time? One theory is that distinguishing boys from girls was less important than distinguishing kids from adults. Childhood was a time of innocence while adulthood typically meant working hard. By the 1850s other colors than white had started to appear in baby clothing, but gender-based distinctions were slow to emerge. For example a Times fashion report from 1880 says that boys and girls were dressed alike in shades of blue, pink, white or violet; another report from 1892 says young girls were wearing...

Words: 1419 - Pages: 6

Free Essay

Facing Poverty with Rich Girl's Habits

...The essay I chose to summarize is Facing Poverty with a Rich Girl’s Habits by Suki Kim. Suki Kim describes how life was different when she moved from Korea to America. She also pointed out how the differently American culture was from her own. Such as when she was in school in Korea they bowed at the teacher every chance they got, but not in America. Based on her Korean culture she felt that it was disrespectful the way America ran their schools with no respect for the teacher. Suki describes how when she was in ESOL, and sadly none of the fellow Korean students had anything in common with her. It did not take long for Suki to discover that most of the Koreans that lived in New York with a decent amount of wealth lived in West Chester or Manhattan. Obviously she didn’t get along with the lower class Koreans because that was not how she grew up in her country. I believe the purpose of this paper was to make other cultures aware of how things are different in every country. Also I believe this was healing and closure for the pain she felt from being rich, then unexpectedly poor and moving to a new country. The audience behind this story was the general public I felt because she wanted to make others aware of how quick life can change. We live in a country where we are used to things being a certain way, but this story can teach so many life lessons. Businesses can be successful and producing great revenue, but tomorrow can go bankrupt we have seen this in with our economy...

Words: 439 - Pages: 2

Free Essay

Skewed Sex Ratio

...Mortality differentials 8 Social Implications 8 Brought women 9 Polyandry/abduction 9 Social fabric 10 Crime rates 10 Economic Implications 10 Labor force 11 Unorganized sector 12 Consumer Power 13 Economic status 13 Policy Constraints 14 Recommendations 15 Immediate strategy 16 Short term strategy 19 Long term strategy 20 Role of NGO’s 22 What needs to be done 24 The future 25 References 25 Abstract The rise of boy child population in India for the past twenty years parallels the experience of other Asian Countries such as China and South Korea. There were 945 girls per 1000 boys in 1991, 927 in 2001 and only 914 in 2011. India’s increasing number of rich class seems to have increased the practice of sex selection in the new technology promoted by private health sector. The new technology has aggravated the social problem of bias against girl child and continues to have caused the drastic reduction in the proportion of female children. This article focuses on appeal to government and civil society for immediate action to eliminate sex selection. The article accounts a lesson sharing experience for effective public policy responses to crisis similarly faced in the country. Introduction When a boy is born in India, friends and relatives exclaim congratulations. A son means insurance. He will inherit his father's...

Words: 8947 - Pages: 36

Free Essay

Article Analysis

...Fixon Ball Clicker Erasable: Appealing to Younger Women There is a young American girl in the middle of the page. She is wearing a collared shirt and a sweater vest, she has her hand on her forehead as to show “oh no, not anther mistake.” She appears to be sitting at a desk in a classroom working on drawing pictures of animals. Above the girl’s head are the words “Erase every ‘Oops.’” in red, italicized font. At the bottom of the page there is a long red pen that takes up three-fourths of the width of the page. On the pen it says Frixon Ball Clicker Erasable. On the left side of the pen there is a picture of a hand using the pen to begin to erase the words Incredible, Erasable ink, in red little font. Under that illustration there is the logo for the Frixon Ball Clicker in blue font. Next to that, in the middle of the page, there is a brief description of the product. On the right side of the description, there is the logo for Pilot in blue and in the bottom right corner under that it says “Power to the Pen!” in black. The ad, placed in the Women’s Day magazine, is very effective in targeting the audience if mothers of young children. However, this audience is not the only ones that read this particular magazine. Young women, starting their own careers, and some still in college also read this magazine. This magazine provides many great ideas for women; ranging from healthy recipes, to relationship advice, to DIY home décor ideas. In this advertisement analysis and proposal...

Words: 893 - Pages: 4

Premium Essay

Pressure on Young Women

...For Girls. It’s Be Yourself, and Be Perfect, Too: Pressure on Young Women For young women today there seems to be enormous pressure to be beyond perfect. Why as a society do we place these kinds of pressures on our children? A good example is the story “For Girls, It’s Be Yourself, and Be Perfect, Too” by Sara Rimer. It focuses on two amazing teen girls Esther and Colby who have to face many issues that many young women today have to confront now as well as the stress it entails. Esther and Colby learn right from the start that they have to be perfect during every waking hour and not waste anytime. The girl’s lives are influenced by their parent’s desires and the opinions of their peers. They don’t even think of themselves. Today’s amazing girls are facing pressure from their parents, as well as images they see on T.V., in magazines, as well as everywhere they look. Society pressures young women to be smart, sexy, and athletic. Sara Rimer writes; “If you are free to be everything, you are also expected to be everything” (page 2). At one time young women were viewed as the lesser sex; and were expected to become obedient wives and good mothers. They weren’t expected to go to or even complete their schooling. It was viewed as a waste of time. As time passed women started to become able to receive an education, vote, and have a job outside of the home. Society then started expecting more out of young women. The young women today have to become the amazing girl’s...

Words: 1117 - Pages: 5