SlideShare a Scribd company logo
1 of 99
Download to read offline
AP COMPUTER SCIENCE
USING JAVA
ICS3M
Copyright 2004 by Terence Prezens.
All rights reserved. No part of this book may be reproduced in any way or by any means
without the permission of Terence Prezens.
i
Preface
Java is an excellent language for learning about computer science. It’s also a very
powerful language, and its popularity is probably due to its strong ties to the Internet. In
fact, when you talk of the Internet and the growing popularity of e-commerce, it is hard to
avoid discussing Java.
The power and popularity of Java is one reason why it is a good choice as the language of
instruction for high school computer science. You’ll be learning something real,
something that is current, and yes, fashionable.
Another reason to use Java is its graphics capabilities. One big attraction to computer
science is computer games. Everyone likes to play them and many wish they could
create their own. Java has an extensive graphics library that is part of the language, and
within a lesson or two, you can create some fairly basic but interesting pictures and
animations.
Lastly, Java is the choice of many universities. If you wish to continue your interest in
computer science at the university level, then this book will prepare you well.
The contents of this book will attempt to cover all the topics suggested by the ministry of
education, pertaining to a grade eleven computer science course. Furthermore, it will
cover them in the manner suggested by the College Board so as to prepare you to write
the Advance Placement Computer Science A exam.
The AP Computer Science exam is typically administered in May, and usually consists of
two parts. Part one consists of 40 multiple choice questions and lasts one-and-a-half
hours. Part two consists of four free response questions and also lasts one-and-a-half
hours. The exam is marked by the College Board, and each paper is given a ranking of
one to five, relative to all the other papers. Generally, Canadian and American
universities will accept a three or higher, and consequently, allow you to skip the first
year computer science course or at least the first half course in computer science.
The AP computer science exam will be administered only in Java, commencing in the
2003/2004 school year.
Table of Contents
Chapter 1 What is a computer .................................................................................. 1-1
Number systems....................................................................................... 1-1
ASCII....................................................................................................... 1-2
The modern computer.............................................................................. 1-2
Controlling the computer......................................................................... 1-3
Programming life cycle............................................................................ 1-6
Chapter 2 Input and output....................................................................................... 2-1
Our first program ..................................................................................... 2-1
Testing and debugging............................................................................. 2-2
Analyzing the object oriented code.......................................................... 2-3
Variables .................................................................................................. 2-4
Objects, packages of them ....................................................................... 2-5
Chapter 3 Variable types .......................................................................................... 3-1
Primitive data types.................................................................................. 3-1
Primitive variables ................................................................................... 3-3
Input and output....................................................................................... 3-5
Fancy printing.......................................................................................... 3-7
Commenting your program...................................................................... 3-9
Chapter 4 Simple repetition...................................................................................... 4-1
Accumulators........................................................................................... 4-4
Short-cuts................................................................................................. 4-5
Random and math classes........................................................................ 4-7
Chapter 5 String accumulators ................................................................................. 5-1
Searching strings...................................................................................... 5-4
Substrings................................................................................................. 5-4
Advanced searches and substrings........................................................... 5-6
String tokens ............................................................................................ 5-8
Chapter 6 Selection................................................................................................... 6-1
Two choice selection................................................................................ 6-2
Compound conditions.............................................................................. 6-3
Multiple choice selection ......................................................................... 6-5
Counted loops .......................................................................................... 6-6
Chapter 7 Methods and modular programming........................................................ 7-1
Applets..................................................................................................... 7-1
Using methods ......................................................................................... 7-3
Graphic methods...................................................................................... 7-4
Mouse interaction..................................................................................... 7-6
Advanced applets..................................................................................... 7-9
Summary of Graphic Methods............................................................... 7-12
Chapter 8 Our own methods..................................................................................... 8-1
Call by value ............................................................................................ 8-4
Call by reference...................................................................................... 8-5
Procedures and functions......................................................................... 8-6
Chapter 9 File input and output................................................................................ 9-1
Errors and exceptions............................................................................... 9-1
File output................................................................................................ 9-2
File input.................................................................................................. 9-5
System input............................................................................................. 9-8
Chapter 10 Statistics................................................................................................. 10-1
Arrays..................................................................................................... 10-1
Arrays and methods ............................................................................... 10-3
Sorting and searching............................................................................. 10-5
Related lists............................................................................................ 10-8
Two dimensional arrays....................................................................... 10-10
Appendix A Installing Java ......................................................................................... A-1
Appendix B Installing jEdit..........................................................................................B-1
Appendix C Installing JCreator....................................................................................C-1
1-1
Chapter 1
What is a computer?
A computer is an electronic device that processes numerical information. Yes, it is true
that computers can process words and manipulate pictures and play songs, but all these
other types of information must first be converted into numbers.
Computers are composed of wires and electronic circuits that control them. A wire can
either be on or off. It either has electricity flowing through it or it doesn’t. We can
represent this on/off nature of a wire by assigning it a 1 for on and a 0 for off. Suddenly,
we have numbers where before we had just wires.
Number systems
This number system of on’s and off’s, 1’s and 0’s, is called the Binary number system.
Every single wire, or every single 1 or 0, is called a bit. And to make our lives more
manageable, we generally talk about groups of bits; four or eight bits are called a nibble
or a byte respectively.
If we have four wires — a nibble — they can generate many different patterns of 1’s and
0’s, binary numbers. In fact, they can generate 24
, or 16, different binary numbers:
00002, 00012, 00102, 00112, 01002, 01012, 01102, 01112, 10002, 10012, 10102, 10112,
11002, 11012, 11102, and 11112.
A subscript 2 after each number indicates that the patterns are binary numbers, not
decimal numbers. We can use these binary numbers to represent decimal numbers. We
can let 00002 represent zero, and 00012 represent one, and 00102 represent two and 00112
represent 3 and so on, all the way too 11112 which would represent fifteen. If we need
bigger numbers, we simply get more wires, bits. It turns out that the number of patterns
we can make with n number of bits is 2n
. If we have a byte of information, then we can
have 28
patterns, and because one of the patterns represents the zero, a byte of
information can represent numbers as big as 28
-1, or 255.
Besides the binary number system, another popular number system in the computer world
is the Hexadecimal number system. It deals with groups of four bits at a time, a nibble.
Since each nibble can represent 16, 24
, patterns, each hexadecimal digit can be a value
between 0 and 15. Because it is confusing to write a single hexadecimal digit like 15
using what seems to be two digits, the hexadecimal digits 10 to 15 are written as A, B, C,
D, E, and F. A hexadecimal number like 2B16 would represent 2 * 16 + 11, or 43 in
decimal.
1-2
ASCII
Characters like ‘A’, ‘B’, etc. are also stored in the computer as numbers. The computer
uses a standard called American Standard Code for Information Interchange (ASCII).
This standard has assigned each character on your keyboard a numerical value. The
upper case letters ‘A’ through ‘Z’ have been assigned the values 65 through 90, and the
lower case letters ‘a’ through ‘z’ have been assigned the values 97 through 122. Even the
digits ‘0’ through ‘9’ have ASCII values 48 through 57. It is the existence of the ASCII
standard that allows us to tell the computer to make comparisons between words, for
example, when we’re trying to alphabetize a list of names.
The modern computer
The computer you buy at the store generally comes in two boxes, one for the monitor and
one for the computer case and its attachments. Usually the case is upright, and called a
tower. The tower is where all the interesting computing in going on.
Inside the case there is a large rectangular piece of plastic with quite a bit of metal
etchings on it. This is the motherboard. On this piece of plastic, all the key components
are placed. The most import component is the Central Processing Unit (CPU). It is the
brain of the computer and controls all the other components. The CPU comes in various
speeds and some of the more popular lines of CPUs are the Pentium by Intel, the Athlon
by AMD, and the PowePC by Apple.
Also on the motherboard are smaller narrow strips of plastic with components —
memory chips — attached to them. These are the computer’s random access memory
(RAM), and they too come in various speeds and capacities.
Another section of memory chips called read only memory (ROM), is where important
instructions are kept that are executed when the computer is turned on. The metal
etchings on the motherboard connect the CPU, memory and all the other components on
the motherboard together. This set of metal lines that allows all the components to send
and receive data is called a bus.
Near the back of the motherboard are a few slots where you can plug in expansion cards.
These cards could be internal modems, sound cards, video cards, or the increasingly
popular network card. There are also a couple of little plugs attached to the motherboard
where you can plug in your keyboard and your mouse. Most of the remaining
components on the motherboard help the CPU and all the other components to
communicate.
Inside the case there is also the power supply, a hard drive and floppy drive for saving
files, and probably a CD-ROM or DVD drive as well. These components are connected
to the motherboard by cables, and the with the exception of the power supply, are called
peripherals. The final important peripheral that would make this computer complete is
not in the tower, and must usually be bought separately. It is a printer.
1-3
Skills Check:
1-1. How many bits are there in one byte and what is the biggest decimal value that
can be represented by one byte?
1-2. Name three different number systems used in computer science.
1-3. How are letters stored in a computer?
1-4. If a computer were to alphabetize the words "apple" and "Orange" which word
would come last and why?
1-5. What is the major difference between RAM and ROM?
1-6. What is the name given to the set of wires that connects the computers memory
with its CPU and where can these wires be found?
Controlling the computer
Remember that a computer is a machine. It consists of wires and tiny electronic
components. The modern CPU consists of a few million of a particular component called
a transistor. The CPU is the brain of the computer and these transistors basically act as
on/off switches allowing electricity to either flow through a particular wire or not.
Generally the more transistors a CPU has the more powerful it is. Unfortunately,
electricity moving through transistors gives off heat and therefore more transistors also
means more heat. Consequently, many CPUs must have fans and other devices to keep
them cool and prevent them from overheating.
We write programs to tell a computer what to do. A program is essentially a list of
instructions telling the computer what to do next. This list usually results in various
different wires turning on or off at different times. Luckily, we don’t have to write
specific instructions for turning on or off individual wires, but essentially, that is what’s
happening.
We can think of that level of programming as the micro level, and it is far beyond the
scope of this book. We’ll concern ourselves more with a higher level, even higher than
machine language.
The machine language is the language a program must be written in if the CPU is to
understand it. Each type of CPU uses a different machine language. A CPU made by
Intel understands a different machine language than one made by Apple. We can write
programs very close to machine language by using a language called Assembly
Language.
Assembly language uses mnemonic English, like abbreviations, to represent individual
machine language instructions. There is one assembly language instruction for each of
the machine language instructions. A program called an assembler takes the assembly
language program and converts it into machine language.
1-4
Below is a table of assembly language instructions, along with their machine language
equivalent, written as a decimal number and a description of the instruction. These
instructions are not for any particular CPU, and usually when we talk about computers
and certainly machine language, we use the hexadecimal number system or the binary
number system.
Machine
Language
Assembly
Language Description
18 SUB A, B -subtract the contents of memory location B from the contents
of A and store the result in A
50 ADD A, B -add the contents of memory location B to the contents of A
and store the result in A
64 JMP A -jump to the memory location A and execute the program
instructions starting there
67 JE A -same as JMP but only if the last comparison instruction
found both values to be equal
68 JG A -same as JMP but only if the last comparison instruction
found the left value to be greater
69 JL A -same as JMP but only if the last comparison instruction
found the left value to be less
70 JNE A -same as JMP but only if the last comparison instruction
found the two values to be unequal
182 MOV A, #n -move the value n into the memory location A
183 MOV A, B -move the contents of the memory location B into the
memory location A
195 CMP A, B -compare the contents of memory location A with the
contents of B
Many years ago, writing programs in assembly language was the only way to control a
computer. Consequently, programming was left to a select few, and took quite a bit of
time. A simple program to add two numbers, like 23 and 47, using the previously
described assembly language would look like this:
100 MOV 200, #23 ;store 23 into memory location 200
103 MOV 201, #47 ;store 47 into memory location 201
106 MOV 202, 200 ;copy the value 23 into memory location 202
109 ADD 202, 201 ;add 23 and 47 and store the result in 202
On the left, I have included the actual memory locations where each instruction of the
program would be stored. In memory location 100, the MOV command is stored; in 101,
the value 200; and in 102, the value 23. On the right, is some helpful documentation
explaining each line.
1-5
The same program would be even harder to read if we had to read it in machine language.
100 182 200 23
103 182 201 47
106 183 202 200
109 50 202 200
Assembly is what we call a low level language. Java is an example of a high level
language. Programming in assembler can produce very fast programs but it is very time
consuming, and assembler programs can be very hard to fix should an error occur.
High level languages, like Java, are easier to learn because they are similar to English.
There are many different high level programming languages: Fortran, Pascal, Turing,
C/C++, and BASIC. The problem is that the computer only understands machine
language, and doesn’t know anything about Java or any other high level language.
Therefore, we need some way of translating the high level language into machine
language.
Often, programmers refer to programs as code, and throughout the rest of the book, I’ll
use code, program, and even language, interchangeably. We will call the program
written in a high level language the source code, and the same program after it has been
converted into machine language the object code.
There are two ways to convert source code to object code. Both ways require a program,
and that program is either called an interpreter or a compiler, depending upon how it
translates the source code.
An interpreter takes the source code and translates it one line at a time into object code,
and then immediately executes that line of object code. It then translates the next line
and so on. If you wish to execute your program a second time, then the interpreter starts
again with the first line of the source code, translates it, and then executes it, and so on.
This translation and then execution that takes place every time you execute your program
can slow down the execution of your program. However, a compiler takes the file you
created with your source code in it, and translates all the source code into object code. It
creates a new file and stores all the object code in it. The next time you wish to execute
your program, you can just execute the file containing the object code, and no translation
is needed. The only problem is that not all CPUs understand the same machine language.
Remember that Intel CPUs and Apple CPUs have different machine languages so the file
containing the object code created on one computer may not work on another. Here is
where Java shines, at least in theory.
Java programs are compiled into a machine code for a virtual machine. By a virtual
machine, I mean a machine that really doesn’t exist, and the machine code is called
bytecode. This means that for any computer to run your Java program, it must still
convert your bytecode into machine code for its CPU. To do this, it runs a Java
1-6
interpreter. The interpreter takes the file containing the machine code for the virtual
machine, and translates and executes each line just like any other interpreter. But the
virtual machine code is much closer to real machine code, than high level code like Java,
and so the translation and execution of the virtual code is pretty fast. The interpreter can
also be added as a plug-in to a web browser, and this allows your browser to execute Java
programs regardless of which type of computer was used to create the Java program. A
Java program written to run in a web browser is called a Java Applet.
Programming life cycle
Programming is basically problem solving. It can however be broken down into five
stages: problem definition and analysis, design, implementation, testing, and
maintenance. Unfortunately, most of the problems covered in this book will not require
a great deal of time to be spent on defining or analyzing the problem. This is primarily to
get you quickly started on learning the Java language and some of the fundamentals of
computer science. However, it is important to note that sometimes the most important
and difficult stage of programming is defining and analyzing a problem. If you don’t
clearly understand the problem, it is very hard to find a solution.
Designing a solution for a problem can occur in various ways. We call the set of step-by-
step instructions to solve a particular problem an algorithm. An algorithm can be written
in plain English but is usually written in a sort of point form and is called pseudocode,
pseudo meaning false. For example, the pseudocode for an algorithm for making a pizza
may look something like this:
Preheat oven
Prepare crust
Put sauce and toppings on crust
Cook pizza
An alternative way of representing an algorithm is by representing it graphically by using
a flowchart. Four of the basic flowchart symbols are:
Start / Stop Process / Calculate Comparison Input / Output
1-7
For example, the flowchart of an algorithm to get two numbers from a user and display
the sum could look like this:
The implementation stage should occur only after we have formulated an algorithm. This
doesn’t always happen, especially when dealing with very small problems. Generally, in
an introductory course, this is where most student programmers begin their programming
life cycle. At this stage, we type in our algorithm using a specific programming language
like Java. This is sometimes called coding the algorithm.
Next, we try to execute our program and unless we’re very lucky, or working with a very
simple program, this leads us to the next stage, testing. The first time a program is run it
generally has some errors. Programmers call these errors bugs, and the process of
correcting them is called debugging. This stage can be the most frustrating stage and
often turns away many a student programmer.
There are two types of errors that can occur. One type of error is a compile-time error,
an error that occurs when the compiler tries to convert your Java source code into
bytecode. Your program may be trying to use a command that belongs to a package of
commands that you forgot to include in your program, or your program may have a
simple syntax error.
Syntax errors are a type of compile-time error and occur when your program violates a
rule of the programming language. For example, if you forget to put a semi-colon at the
end of a Java statement, you will probably get at least one syntax error when the compiler
tries to translate your program into bytecode.
The second type are run-time errors, errors that occur when your program is running.
For example, if a user enters two values, the second being a zero, and your program is
suppose to divide the first by the second, this will cause a run-time error because
computers can’t divide anything by zero. In Java run-time errors are also called
exceptions, and we’ll see how to deal with them much later.
Add numbers Display
sum
Stop
Start
Get two
values
1-8
Another error that is sometimes only noticed at run-time is a logic error. Logic errors
are much more difficult to find and correct because they are caused when you design the
actual algorithm incorrectly. Finally, once the program has been debugged and tested for
accuracy, it enters the final stage, maintenance.
We quickly became aware of the maintenance stage with the Year 2000 problem. We
found that many important large programs were still being used even though the original
programmers had changed companies or even retired. Once a large program has been
implemented and tested, it seems only natural that if any minor modifications are needed,
they should simply be added to the original program. Often these minor modifications
lead to new bugs and we must debug the code, perhaps make more modifications, debug
some more, and so on. Some programs just never end!
Skills Check:
1-7. What important component, found in a CPU, controls whether a wire is on or off?
1-8. What advantages do higher level programming languages offer over assembly
language and vice versa?
1-9. Write an assembly language program similar to the one found in this chapter but
that evaluates 20427 minus 8315. You may use any memory addresses you wish
for the program. You should also assume that each assembly language instruction
uses one memory location and each of its arguments requires one memory
location as in the example given in this chapter.
1-10. What is the difference between a compiler and an interpreter and which does Java
use?
1-11. Explain what bytecode is and how it differs from traditional object code.
1-12. Why was Java originally created?
1-13. Describe the five stages of a program's life cycle.
1-14. What is the difference between a syntax error and a logic error and when does
each occur?
1-15. Using the assembly language instructions listed in this chapter write a program
that calculates 17 * 12.
2-1
Chapter 2
Input and output (I/O)
Before we start programming, it is important to clarify a few terms. Firstly, when I talk
about input, I mean information moving from somewhere into the computer, or more
specifically, the CPU. If information is being typed into the keyboard and therefore
being sent into the computer, that information is called input. Likewise, if information is
coming from a file on a disk, and going into the computer, that is also called input.
The designation of whether information is input or output is relative to the computer, not
the peripheral or object sending or receiving the information. This notion will become
very important later when we discuss file input and output, more commonly referred to as
file I/O.
If a printer is receiving information and printing it out, it is called output because the
information is going out of the computer. Therefore, output is any information moving
from the computer to somewhere else, like a printer, disk drive, or even the monitor.
Output from a printer is called a hardcopy but output on a monitor is called a softcopy.
Our first program
Now it’s time to write our first program. Below you’ll find the program listing for a
program that asks the user to enter her name and then welcomes her with the word
"Hello" followed by her name. This is a variation of the typical program that most
people find in programming books. Most books use a program that doesn’t ask for any
user input and simply says "Hello World". I have included the notion of user input
because in Java, input from the keyboard is not the simplest thing to do. The reason
being that Java was designed more for the Web and therefore graphical input seems to
have been the priority. Consequently, we’ll skip over the messy standard keyboard input
commands, and use a more graphical keyboard and mouse method. We will revisit the
input problem later when we discuss input from files:
import javax.swing.*;
public class HelloUser {
public static void main(String [] args) {
String name;
name = JOptionPane.showInputDialog("Please enter your name: ");
System.out.println("Hello " + name);
System.exit(0);
}
}
The above program can be entered using any text editor, but must be saved in a file called
HelloUser.java. You can use your favorite editor to enter the Java code but be sure the
editor saves it as a text file. If you use your favorite word processor to enter the code,
then the previous point becomes very important because, by default, word processors
2-2
don’t save files as plain text. The Windows application Notepad can be used to enter the
program but remember it must be saved as HelloUser.java not HelloUser.txt.
You must also make sure you name the file exactly as shown with all the letters in their
proper case. The H of Hello must be uppercase and so must be the U of User; the rest
must all be lowercase. If you haven’t already done so, this might be a good time to check
the appendix and install a Java editor. Hopefully, you already have the Java SDK,
Software Development Kit, installed on your computer. If not, then definitely take a
break now and check the appendix, and install both the SDK and an editor. There are
many Java editors and even very elaborate programs that combine editors with other
program development tools. An Integrated Development Environment or IDE is a
program that usually combines an editor with a compiler and various tools to help you
create and debug your program. An IDE can make Java programming easier and faster
for knowledgeable programmers. However, this book is an introduction to programming
and will assume that you're using a very simple Java text editor to enter your programs.
Testing and debugging
We have our Java program saved in a file called HelloUser.java, and we have the Java
SDK installed on our computer. Now what? We need to translate the Java code, our
source code, into machine language, object code. To do this we need a compiler. The
Java SDK comes with a compiler called javac.
To compile our program, we must go to the command prompt and enter, javac
HelloUser.java, and the compiler will create a new file called HelloUser.class that will
contain the machine code. However, the machine code will be for the Java Virtual
Machine, the Java interpreter, and, therefore, still can’t be directly executed. To run our
program, we must enter at the command prompt, java HelloUser. This will run our
program. If either the javac or the java command fail, then refer to the appendix
regarding the installation of the Java SDK to confirm that the SDK was properly
installed.
Even if the SDK was properly installed, you could still encounter some problems when
you try to compile your Java program. You have now entered the debugging phase. If
you didn’t type in the Java code exactly as shown, then there may be one or two syntax
errors. Remember syntax errors are the easy ones to fix. You may have forgotten a
semi-colon or made a typo. Double-check your code against the listing in the book and
resave your program and try compiling it again. If all goes well, you should see
something similar to the figure below when you run your program.
2-3
You can enter your name and press enter, or click on the OK button, and the input box
will disappear, and the phrase “Hello” followed by whatever you typed-in should appear
on the screen. You’ve just written your first Java program and a pretty good-looking one
at that.
Skills Check:
2-1. Enter and run the program HelloUser.
2-2. Try introducing different errors into the program so that you can become familiar
with the error messages the java compiler generates. Try removing a semi-colon
or two. Try changing a capital letter to a small one. Try removing one or two
braces from the program, the brace is the '{' or '}' character.
Analyzing the object oriented code
Java is an Object Oriented language. It is a language based on describing things to the
computer and associating certain properties and commands with those things.
The keyword class is used to indicate that the programmer is about to describe a new
thing. A class is like a blue print or template of something that we will later create.
When a programmer needs to use something like what is described by a particular class,
she makes one or more of those things, and when they’re created, they’re referred to as
objects. You can think of a class as the recipe for a cake and the actual cake as the
object.
2-4
In the terminology of Object Oriented Programming, the properties of an object are called
attributes and the commands associated with it are called behaviours. This is a very
simple definition of Object Oriented Programming, or OOP, but it will be expanded upon
throughout the book.
In our program, we made a class called HelloUser with the line, public class
HelloUser {. Whenever you write a program in Java you must make a class. The
opening brace, {, indicates the start of our description of the class. There is a
corresponding closing brace, }, at the end of our program to indicate the end of our
description. Below the, public class HelloUser {, line we have the first behaviour
associated with our class. The behaviour is called main. Behaviours are called methods
in Java, and are indicated by their name followed by parenthesis, ie. main( ). If the
method requires certain information to execute properly, then that information appears
between the parenthesis, ie main( String [] args). The open and close braces are
then used to enclose the Java statements that belong to the method. We’ll leave the
public static void stuff for later, but for now, just know that you must include them
as shown. Between the braces of the method, main, are three Java statements. It is
important to note that each statement must end with a semi-colon. Forgetting a semi-
colon is one of the most common mistakes.
Variables
The first line in the method, String name;, declares a variable called name. Variables
are how we define the attributes of objects in Java. A variable is a block of memory in
the computer where we can store information. The computer has millions of these
blocks, and to help us use them, we can assign them names. The computer keeps track of
matching the name we give a block with its actual memory address, which is just some
large number.
Good programmers always try to give their variables mnemonic names. A mnemonic
variable name is one where the name indicates how the variable will be used. If you
were going to use a variable to store the sum of a set of numbers, then a good mnemonic
name would be sum. Besides using mnemonic names for variables, there are also some
Java rules we must abide by when naming variables or anything else in Java. The names
we use for our program class, variables, and later for our methods, are all referred to as
identifiers. Identifiers created in Java must begin with either a letter, a dollar sign or the
underscore, _, and then can be followed by any number of letters, dollar signs,
underscores, and even digits. However, we may not use any of the Java keywords,
reserved words, or special values as identifiers.
2-5
Below is a list of the words that may not be used as identifiers.
abstract default if private this
boolean do implements protected throw
break double import public throws
byte else instanceof return transient
case extends int short try
catch final interface static void
char finally long strictfp volatile
class float native super while
const for new switch
continue goto package synchronized
-const and goto are reserved words while true, false and null are special Java values.
When we ask for a memory block, we must also tell the computer what type of
information we plan on storing in the memory. This allows the computer to give us a
memory block big enough to hold our information. The first line of the main method
asked the computer for a memory block big enough to hold information of the type String
and to call it name. The String type is used for holding strings. A string is any set of
letters, numbers, and symbols, usually enclosed in quotes. For example: “apple”, “111
Somewhere”, and even “3245” are all examples of strings.
Objects, packages of them
The second line, name = JOptionPane.showInputDialog("Please enter your
name:");, is where we tell the computer to get input from the user. The name= part says
that whatever the user enters, store it in the memory location that we called name. On the
right side of the equal sign, we cause the graphical dialog window to appear with the
message "Please enter your name: ". The dialog window is an example of Object
Oriented Programming.
The creators of Java have made many useful classes for us to use in our programs. The
JOptionPane class has the associated method showInputDialog that will display a dialog
window for us, and all it needs to know is what we wish the dialog to say. To use a
variable or method that is a part of a class, we write the name of the class, followed by a
period, and then the name of the variable or method. The second last line of the main
method, System.out.println("Hello " + name);, caused the phrase "Hello"
followed by the users input to appear on the screen. This is not graphical, but if we
wanted to, we could have easily made it so by using the JOptionPane class and one of its
other associated methods.
This program uses the JOptionPane class to get input from the user and, therefore, the last
line, System.exit(0);, is needed to end the program. Whenever your Java program
uses JOptionPane you must use System.exit(0) to end your program or it won't
end until you press CTRL-C, the break key. That brings us to the very first line of our
program, import javax.swing.*;. This line makes the JOptionPane class available to
us.
2-6
There are so many classes in Java, and we will eventually make many new ones
ourselves, so we need some way of organizing them. This is done using a concept called
packages.
A package is a group of related classes that are placed together, and whenever you need
to use a particular class, you can either import just it, or all the classes in the package that
contains it. The package that contains JOptionPane is the swing package, and it is
located in the javax directory. The asterisk at the end of the line indicates that we wish to
import all the classes in the swing package, and then last but not least, we have the semi-
colon.
You may be wondering when we’re going to make these things called objects. We made
a class called HelloUser and it used a class called JoptionPane, but where were all the
objects? This is where the keyword, static, comes in. If a programmer makes a class,
and puts the keyword static before a variable or method in the class, then she can use the
variable or method of the class without having to first make an object of that class. This
little fact makes our life a little easier when programming, but perhaps a little harder
when we’re trying to learn about OOP.
However, there was at least one object created and it was of type String. It was created
when we used the showInputDialog method, and a reference to it was assigned to the
variable name. But references and objects being created by methods will have to wait for
a later chapter. Be patient and don’t worry about OOP; all its intricacies will be
explained in time. That was a lot of explanation for a six-line program, but future
examples will have more code and will now require less explanation.
Skills Check:
2-3. What is the difference between a hardcopy and a softcopy?
2-4. What is the name of the program that is the Java compiler and what is the name of
the interpreter?
2-5. What file extension do Java source files end with and what do Java bytecode files
end with?
2-6. What is the difference between a class and an object?
2-7. Whenever we write a program in Java what are we also defining?
2-8. When talking about object oriented programming we often talk about attributes
and behaviours. What are these referred to as in Java?
2-9. What are the rules governing the use of identifiers in Java?
2-10. Describe the concept of a package in Java.
3-1
Chapter 3
Variable types
There are two kinds of variables: variables for primitive data types, and reference
variables. The latter will be discussed in greater depth later on. However, we did already
use a reference variable in our first programming example:
import javax.swing.*;
public class HelloUser {
public static void main(String [] args) {
String name;
name = JOptionPane.showInputDialog("Please enter your name: ");
System.out.println("Hello " + name);
System.exit(0);
}
}
The variable name was a reference variable. A reference variable is a variable that will
refer to an object. Remember that an object is what we get when we make something of
a particular class. In this case, the something was an object of the String class, and we
used the reference variable name to refer to it.
Primitive data types
The simplest type of variable is one used with one of the primitive data types. A
primitive data type is one that is not a class data type, and essentially denotes a set
number of bytes in the computer’s memory that must be reserved for it. We saw in
chapter one, that the amount of bits used by a computer dictates the number of patterns
that can be represented, and therefore the largest value that can be stored. The formula
was 2n
- 1, where n was the number of bits. Primitive data types basically tell the
computer what is the largest value the programmer may need to store in a particular
location of the computers memory.
In Java, the primitive data types are: char, byte, short, int, long, float, double and
boolean. When you declare a variable of any of these types, the computer reserves just
enough memory for you to store exactly one value of that type. It is very important to
remember that only one value can be stored at a time in the memory location
reserved for the primitive variable. In the table below is a list of the primitive data
types, and the number of bytes the computer must reserve for each type, along with an
example of the type and possible range of values that can be stored in it.
3-2
Primitive Type Memory Requirement Type of value and range
char 16 bits, (2 bytes) -any single character
ex: char letter = ‘A’;
byte 8 bits, (1 byte) -any integer from –128 to 127
ex: byte num = -43;
short 16 bits, (2 bytes) -any integer from –32,768 to 32,767
ex: short num = -43;
int 32 bits, (4 bytes) -any integer from –231
to 231
-1
ex: int num = -43;
long 64 bits, (8 bytes) -any integer from –263
to 263
-1
ex: long num = -43;
float 32 bits, (4 bytes) -any real number from 3.4e-38 to 3.4e+38
ex: float num = (float)3.14;
double 64 bits, (8 bytes) -any real number from 1.7e-308 to 1.7e+308
ex: double num = 3.14;
boolean Not specified -either the value true or the value false
ex: boolean answer = true;
As you can see, the amount of memory reserved for a particular data type dictates the
range of values it can store. This goes back to Chapter 1 where we discussed the fact that
computers use the Binary numbers system, and the number of bits the computer uses
dictates the number of different binary patterns that can be formed, and thus the largest
number that can be represented.
The relationship was that for n bits we could make 2n
different patterns, and if we were
just looking at positive numbers, then we could represent a number as big as 2n
-1. We
needed the minus one to take into account that one of the patterns represented zero. In
order to deal with negative numbers as well, computers use one of the n bits to indicate if
the number is positive or negative, thus we only have n-1 bits for the size or magnitude of
the number. Therefore the range of numbers we can represent can only go from –2n-1
to
2n-1
-1. This method is called two’s complement but will not be discussed any further in
this book.
The computer uses a different method for representing real numbers, but this method also
depends upon the number of bits it uses. Therefore, variables of the double data type can
store much larger numbers than variables that are declared as float. The boolean data
type is not affected by the number of bits used to represent it because it can only have one
of two values, and this is possible with as little as one bit — we could use 0 for false
and 1 for true. The char data type, which can store a single character, will not be used
in the rest of the book, and instead, whenever we need a character or characters, we will
use the String data type. This will alleviate some of the confusion when dealing with
strings which require double quotes, and single characters which require single quotes, ie
‘x’ versus "x". This is also the recommended course of action by the AP Committee for
computer science.
3-3
Furthermore, to adhere to the AP Committee and to emphasize the concepts of computer
science as opposed to the Java language, the remainder of this book will use only three of
the primitive data types, int, double, and boolean.
Primitive variables
Remember that variables are just a way of naming memory locations in the computer.
This is especially true when dealing with primitive data types. Below is an illustration of
how the computer’s memory changes when we declare a variable, and again, when we
assign it a value. Declaring a variable is when we ask the computer to set aside memory
for us to later store some information in and give that memory a name. Initializing a
variable is when we actually place a value into the reserved memory location. Note:
only the middle column, the column labeled “Value” actually represents the computer’s
memory. The other columns were added so that you can follow along with what’s going
on in the computer. Also, the memory addresses in this example were chosen arbitrarily.
MEMORY BEFORE JAVA STATEMENTS MEMORY AFTER
Variable Value Address
int num1;
int num2;
Variable Value Address
1009 1009
1008 1008
1007 1007
1006 1006
1005 num2 1005
1004 1004
1003 1003
1002 1002
1001 num1 1001
1000 1000
On the left, we see that the computer’s memory is just like a bunch of empty boxes, each
large enough to hold one byte of information, ie. 8 bits, or 8 wires that can be on or off.
Initially, these boxes may have some value in them, but we don’t know what that value
is. When the interpreter sees the line, int num1;, it tells the computer that four bytes are
required to store a value, and that the start of that chunk of memory must be called num1,
as shown in the table on the right. This is what happens when we declare a variable, and
in this case, the computer has reserved the memory locations 1001, 1002, 1003 and 1004.
Furthermore, we can now refer to the four memory locations collectively as num1. A
similar thing happens when the interpreter executes the second Java statement, int
num2;. Now we have two chunks of memory each big enough to hold a single integer
value, four bytes.
3-4
The next table shows us how memory changes when we store a value in each of these
chunks. This is where we initialize the variables. Remember initializing a variable is
when we place an initial value in the memory reserved for the variable.
JAVA STATEMENTS MEMORY
num1 = 3;
num2 = 7;
Variable Value Address
1009
7
1008
1007
1006
num2 1005
3
1004
1003
1002
num1 1001
1000
When we assign a value to a variable, it is placed in the chunk of memory associated with
that variable and is actually stored as a group of bits. In the case of integers, four bytes,
the equivalent of 32 bits, are used, and the number three for example would be stored as,
000000000000000000000000000000112. That’s 30 zeros followed by 2 ones; you can
see why I chose to simply write it in decimal in the table. However, always remember
that all things are stored in the computer using bits. Also, always remember that only one
value can occupy a primitive variable at any given time. If we initialize a variable and
then later in our program try to assign it a different value the new value will replace
the previous one and the previous one will be lost.
Below is a small program that uses int variables and demonstrates how to store a value
in a variable, and how to use arithmetic operators to manipulate a value in a variable.
public class Numbers {
public static void main(String[] args) {
int num1;
num1 = 5;
int num2 = 2, sum;
sum = num1 + num2;
System.out.println(sum);
int answer;
answer = num1 / num2;
System.out.println(answer);
}
}
For the above program we don’t need to import any special packages. All the Java
functionality we need is automatically provided for us.
3-5
Certain Java classes are used so frequently that the Java compiler always makes them
available. The program starts by defining a new class. The class is called Numbers and it
contains one method called main. The main method starts by declaring a variable called
num1 that can store one integer. At this point, the computer reserves enough memory —
four bytes — and calls this chunk of memory num1. However, the computer does not set
the contents of num1 to zero, and so at this point the value stored in num1 is something,
but we don’t know what. Since num1 has some unknown value in it, we initialize it by
storing the number five in it on the next line.
Next, two more variables of type int are declared. The variable sum is similar to the
variable num1 but when num2 is declared, the value two is also placed into the memory
chunk labeled num2. Often programmers will combine the declaration and initialization
of a variable on the same line. Next, we assign the variable sum a value but this value is
the sum of the two other variables. Hence, the value seven will be stored in sum and
consequently be displayed on the screen when the next line executes. All the common
math operators are available in Java, +, -, /, and * for multiplication.
The next three lines declare another variable, answer, and assign it the quotient of the
first two variables, and then unexpectedly displays the value two. Usually, when we
divide five by two we get 2.5, not two, but 2.5 is not an integer answer. The variable
we’re trying to store the quotient into, is an int type variable. Consequently, Java
truncates the .5 and stores just the two into answer. Even more interesting is the fact that
if answer had been declared as a double instead of an int, the program would still
display two and not 2.5. The reason is that both num1 and num2 are ints and Java
always truncates quotients if the values on both sides of the division sign are
integers.
Skills Check:
3-1. What is it that primitive data types essentially ask the computer to do.
3-2. Write a program that evaluates 20427 minus 8315. Use the integer variables, n1
and n2, and assign to each variable one of the values. Store the result of the
calculation in the integer variable, answer, and display the result.
3-3. Write a program that evaluates 27832 divided by 3. Use three integer variables to
represent the arguments and the result, and display the result. Your program
should then also perform the same calculation but using three double variables
and display the result. Why are the two answers different?
Input and output (I/O)
Programs have limited usage if they cannot interact with a user — the person who has run
the program. Output is the term used when information travels from the CPU out to
somewhere else, like the monitor, perhaps to enable the user to see the result of a
calculation. Input refers to information entering the CPU, perhaps resulting from the user
typing something on the keyboard. In our first code example, we received input from the
user via the keyboard, namely their name, and sent output to the monitor to greet them.
3-6
The input received by the computer was treated as a String, a sequence of characters.
However, a String is not a primitive data type, and unfortunately, if we use the Java class
JOptionPane to get input from the user, we always get the input returned to us as a String.
Luckily, Java provides us with several classes, one for each primitive data type that will
convert a String into a primitive value, if possible. Below is a program that gets two
integers from the user and displays the average value. Remember that integer division
always truncates or rounds down the result, so we’ll need to tell the computer that we
definitely want the result to be calculated as a double.
import javax.swing.*;
public class Average {
public static void main(String[] args) {
int num1, num2;
String value;
value = JOptionPane.showInputDialog("Enter first value: ");
num1 = Integer.parseInt(value);
value = JOptionPane.showInputDialog("Enter second value: ");
num2 = Integer.parseInt(value);
double avg;
avg = (double) (num1 + num2) / 2;
System.out.println(“The average is ” + avg);
System.exit(0);
}
}
In the above example, we declared a total of three primitive variables and one reference
variable, value. We used value to get the first integer entered by the user, and then we
used the Java class Integer and its method parseInt to extract the int value from the
String type variable and assign it to num1. We then did the same thing for the second
integer, but assigned its int value to num2. The third primitive variable, avg, for average,
was assigned the resulting average of the two numbers. The average was calculated by
adding the int value stored in the memory location referred to as num1 to the value in
num2. The sum was then converted to a double and then divided by 2 resulting in a
double type value of 2.5. The line System.out.println, was then used to output the
value stored in the variable avg, to the screen, along with some user-friendly information.
The first important thing to note in the previous example was the way we could extract
primitive type data from a String type variable using Integer.parseInt or
Double.parseDouble. The second is how we can force a calculation involving integers
to be done, as a double, by placing the word double enclosed in parenthesis in the
calculation. However, the Java syntax: (double)(num1 + num2), may look as though
we’re multiplying double by the result of num1 and num2 but this is completely incorrect.
In fact, Java and most other languages require you to use the asterisk to indicate
multiplication in calculations and will generate a syntax error if you wrote something like
this, ans = 3 (num1 + num2 ), or, ans = (a + b) (c +d).
3-7
Skills Check:
3-4. Write a program that gets an integer from the user and displays double its value.
Then your program should reuse the variables you already declared and get
another integer from the user but display half its value.
3-5. Write a program that gets two integers, num1 and num2, from the user and
displays their product.
3-6. Write a program that gets 3 real numbers from the user, a, b, and c, all doubles,
and calculates and displays the result of the expression (a + b) / c.
Fancy printing
If you'd prefer the output of your program had a similar appearance to the input then you
can use the JOptionPane.showMessageDialog method. The output of the Average
program above could have been written as follows:
JOptionPane.showMessageDialog(null, “The average is ” + avg);
The showMessageDialog method works similarly to the showInputDialog method
except that it doesn't allow the user to type any information it just displays information.
It must also have the Java value null placed before the string to be displayed and only
strings can be displayed. If you want to display a number by itself then you have to place
two quotes with nothing between them followed by a plus sign before the number. For
example to display avg by itself you would type:
JOptionPane.showMessageDialog(null, “” + avg);
Whether you use the showMessageDialog method or the println method to display text
you may wish to display several lines of text at once. You can display several lines of
text at the same time by placing the escape sequence "n" between each string to be
displayed. Below is an example using the showMessageDialog method with its
corresponding output.
JOptionPane.showMessageDialog(null, “Thenaveragenisn” + 5/2);
3-8
You may also need to print answers to calculations using a specified number of digits
after the decimal point or perhaps print answers as monetary values. Java provides a
special class called NumberFormat that can help you format your numbers when you
output them. The program FancyOutput listed below shows how you can print an answer
to at most three decimal places with the method setMaximumFractionDigits and also
how to display an answer as a dollar value.
import javax.swing.*;
import java.text.*;
public class FancyOutput {
public static void main(String[] args) {
int num1, num2;
num1=5;
num2=3;
double answer;
answer = (double) num1/num2;
JOptionPane.showMessageDialog(null, "The answer is " + answer);
NumberFormat nf;
nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(3);
System.out.println(num1 + "/" + num2 +"=" + nf.format(answer));
nf=NumberFormat.getCurrencyInstance();
System.out.println("The monetary answer is " + nf.format(answer));
System.exit(0);
}
}
The output of the above program is:
5/3=1.667
The monetary answer is $1.67
3-9
The program must first get a NumberFormat object with the line:
NumberFormat nf;
nf = NumberFormat.getNumberInstance();
However, to use NumberFormat classes we must tell the computer to include the package
java.text.*. You can import as many packages of classes as you need for your
program. The program then uses the method setMaximumFractionDigits to ensure
that at most three digits will be displayed after the decimal. If you wanted at least three
digits you could use the method setMinimumFractionDigits to specify that as well.
Next, the method format is used to actually create a string that uses the numeric answer
but is formatted the way we want.
To display a dollar value we must get a NumberFormat object with the line:
nf = NumberFormat.getCurrencyInstance();
However, for dollar values all we need to use is the format method to create a string with
the number formatted the way we want. This is accomplished with the line:
System.out.println("The monetary answer is " + nf.format(answer));
Commenting your program
As our programs get longer, and especially if we work in a group on a particular problem,
then commenting or documenting a program becomes very helpful. To comment a
program means to write a line or lines of text that are ignored by the computer but are
meant to be helpful to other programmers who may read the code of your program. Java
provides two methods for commenting a program. The characters, //, are used to
indicate a single line comment is beginning, and the characters, /*, and, */, are used to
enclose a multi-line comment. The Average program may have been commented as
follows:
/*
A program that gets two integers from the user and
displays the average of the two with the precision
of arithmetic using the double data type.
*/
import javax.swing.*;
public class AverageDocs {
public static void main(String[] args) {
int num1, num2; //the first and second integers
String value; //temporary variable to hold users input
value = JOptionPane.showInputDialog("Enter first value: ");
num1 = Integer.parseInt(value); //convert String type to int
value = JOptionPane.showInputDialog("Enter second value: ");
num2 = Integer.parseInt(value);
3-10
double avg; //average of two integers entered by user
avg = (double) (num1 + num2) / 2;
System.out.println("The average is " + avg);
System.exit(0);
}
}
As you can see, commenting can make programs a lot easier to read and understand.
Skills Check:
3-7. Write a program that gets the subtotal of a restaurant bill from the user and then
calculates the final total of the bill including a 15% tax.
3-8. Write a program that asks the user to enter the radius of a circle and then displays
the circumference of the circle with at most one digit after the decimal.
Note: C = 2 * PI * RADIUS and PI = 3.14.
3-9. Write a program that asks the user to enter how much the food portion of the bill
comes to and calculates 15% tax on it. It then asks the user to enter how much the
beverage bill comes to and calculates 12% tax on it. Finally it prints the grand
total including the food, beverages and taxes.
4-1
Chapter 4
Simple repetition
One of the reasons computers were created was so we wouldn’t have to perform
repetitive tasks. It makes sense, therefore, that one of the first things we should learn to
do is create a program that can perform a repetitive task.
A loop is used to repeat a statement or block of statements, and by block of statements, I
mean Java statements enclosed in a pair of braces as shown below. There are basically
two types of loops: conditional loops and counted loops. In this chapter, we’ll discuss
conditional loops; loops that continue while a particular condition evaluates to true. A
Java keyword that indicates that a statement or block of statements must be repeated is
while. The format looks like this:
while ( condition ) {
Java statement;
Java statement;
}
The keyword while is followed by a condition, enclosed in parenthesis, and then an open
brace, {, and one or more Java statements followed by semi-colons and finally a close
brace, }. The loop will continue to repeat as long as the condition evaluates to the
boolean value of true. Consequently, if we wanted an infinite loop, a loop that repeats
forever, we could replace the condition with the special Java value true. Below is an
example of an infinite loop that repeatedly displays the word "apple" on the screen until
the user presses CTRL-C. The keyboard combination CTRL-C is the break key and asks
a Java program to stop executing.
while ( true ) {
System.out.println("apple");
}
Infinite loops are generally not very useful. Usually the condition is an expression that
consists of a variable, a comparison operator, and either a value or another variable. If
the comparison between the two things evaluates to true, then the loop repeats.
4-2
There are several comparison operators in Java as shown in the table below.
Operator Description
== -evaluates to true if both operands are equal
!= -evaluates to true if the operands are not equal
< -evaluates to true if the operand on the left is less than the one on the right
> -evaluates to true if the operand on the left is greater than the one on the
right
<= -evaluates to true if the operand on the left is less than or equal to the one on
the right
>= -evaluates to true if the operand on the left is greater than or equal to the one
on the right
Some examples of conditions are:
A) num < 5, would result in true if the value in the variable num was less than 5.
B) num == num2, would result in true if the value in both variables was the same.
Note: the == operator for checking to see if two primitive values are
the same is often confused with the = operator used for assigning a
value to a variable. In some languages this can lead to very odd
behaving programs, so always double check your comparison
operators when making a condition that checks for equality.
C) num != num2, would evaluate to true if the values in num and num2 were
different.
Also note that the previously mentioned comparison operators only work as
described when dealing with primitive data types. They behave a little differently
when comparing reference type variables. Below is a program that gets positive
integers from the user, and outputs the square of the number entered. It stops
when the user enters a negative number. Therefore, a negative number is used to
signal that the user is finished her input, and when we use a value to indicate the
end of a set of input, it is called a sentinel. In this case, the sentinel value is fixed
at anything less than zero, and will not change at any time while the program is
executing.
If a variable is going to keep the same value throughout a program, then we can
use what is called a constant to represent it. We indicate that a variable’s value
will remain constant by using the Java keyword final and placing it before the
variable’s declaration as shown below with the constant minValue. Note: the
constant’s value does not have to be immediately assigned to it, but once any
value has been assigned to a variable declared as final, then its value cannot
be changed.
4-3
import javax.swing.*;
public class WhileSquares {
public static void main(String[] args) {
int num, squareNum;
final int minValue = 0;
String value;
value = JOptionPane.showInputDialog("Enter an integer: ");
num = Integer.parseInt(value);
while (num >= minValue) {
squareNum = num * num;
System.out.println("The square is " + squareNum);
value = JOptionPane.showInputDialog("Enter an integer: ");
num = Integer.parseInt(value);
}
System.out.println("The End! ");
System.exit(0);
}
}
The above program uses what’s referred to as a seeded while loop. A seeded while loop
is a loop that repeats as long as a particular condition is true and the condition depends on
a particular variable, called the seed. The seed is given a value just before the loop
begins. In the above case, num, is the seed and it is given a value by the user. Generally,
the seed is also given a value again at the end of each repetition of the loop, that way the
seed has a new value each time the loop repeats. In our program, the user enters a value
for num and then we compare it to the value zero. If num is greater than or equal to zero,
then the loop executes. Namely, it calculates the square of the number and outputs it.
Next, it gets a new value for the seed, num, and then jumps back to the top of the loop and
tries to repeat the loop by first checking the condition of the loop. If the new number
entered is greater than or equal to zero, then the loop repeats again. If it is negative, then
the loop ends and the program outputs, "The End! ".
The use of the constant minValue in the above program also helps us to write code that
doesn’t use magic numbers. If the condition of the while loop had been written as, (num
>= 0), then the 0 would be an example of a magic number. Magic numbers are
numbers that can sometimes be found in loops, calculations, or other parts of a program.
The use of magic numbers, especially ones that repeat in several parts of a program,
make modifying programs very difficult, and it is recommended that you use constants
instead. If you use constants, then the magic number only has to be changed in one spot.
Skills Check:
4-1. Define a conditional loop.
4-2. What is a seeded while loop and what part does a sentinel value play?
4-3. What is the difference between a variable and a constant?
4-4
4-4. Write a program that gets negative integers from the user and displays their
absolute value, their positive value. Your program should end when a positive
number is entered.
4-5. Write a program that gets pairs of numbers from the user and displays their
product. The program should end if the first number the user enters is negative.
Accumulators
One of the most common tasks computers perform in a loop is to add up, or accumulate
values. We may wish to have the user enter several positive values and then output the
sum of those numbers. An accumulator is a variable that changes with each repetition of
a loop. An accumulator might change by a constant value each time the loop repeats, or
perhaps by a varying value entered by the user. For example, the code below uses an
accumulator, total, to calculate the sum of several positive values and displays the sum
when the user enters a negative number. Here again, a negative number is used as our
sentinel, or signal, to end the loop.
import javax.swing.*;
public class Accumulate {
public static void main(String[] args) {
double num, total;
total = 0;
String value;
value = JOptionPane.showInputDialog("Enter a number: ");
num = Double.parseDouble(value);
while (num >= 0) {
total = total + num;
value = JOptionPane.showInputDialog("Enter a number: ");
num = Double.parseDouble(value);
}
System.out.println("The sum is " + total);
System.exit(0);
}
}
The accumulator in the previous program was total and it is always best to assign an
accumulator a starting value. If you don’t, then your accumulator may start at some
unpredictable value and thus result in a very strange and wrong value. Let me re-
emphasize this point: Always assign your accumulators a starting value. In our program,
total is assigned the starting value zero, and then the user is asked for her first input. If
she enters a value greater than or equal to zero, then the loop executes. The first thing
that happens in the loop is that the value of total is changed. The accumulator is
assigned the value of what it currently is set to — zero — plus the value that the user just
entered. An expression where the variable on the left side of the equal sign also appears
on the right side of the equal sign, is a perfect indicator that the variable on the left is an
accumulator. Next, another value is gotten from the user, and the program jumps back to
4-5
the top of the loop. If the new value is greater than or equal to zero, then the loop repeats
again and the new value is added to the accumulator.
Short-cuts
Accumulators occur very frequently in programs, so frequently in fact, that many
languages offer short-cuts for statements involving accumulators. If total is an
accumulator and you wish to add the value of the variable num to it, you can usually
write, total = total + num;. The Java short-cut to accomplish the same result is:
total += num;. The short-cut allows us to avoid repeating the name of the accumulator
variable, and consists of the operator we wish to use followed by the equal sign. If we
wish to multiply our accumulator by two each time a loop repeats, we can either type,
total = total * 2;, or total *= 2;. The short-cuts work with all the math
operators, +, -, *, /, and a special one, %.
The % operator, or modulus or mod operator, is used when we wish to know the
remainder after dividing two values. For example, if num were an integer variable, then
the statement, num = 7 % 2;, would result in num being assigned the value one because
two goes into seven three times, with one as the remainder. The short-cut operation for
mod is, num %= 2;. The mod operator can also be used to determine if an integer is even
or odd. Even numbers leave no remainder when divided by two, and odd numbers
always have a remainder of one or negative one when divided by two.
Below is a program that gets even numbers from the user and eventually displays their
sum. The program repeats as long as the user enters even numbers.
import javax.swing.*;
public class EvenHalf {
public static void main(String[] args) {
double num, total;
total = 0;
String value;
value = JOptionPane.showInputDialog(
"Enter an even number to continue: ");
num = Double.parseDouble(value);
while (num % 2 == 0) {
total = total + num;
value = JOptionPane.showInputDialog(
"Enter an even number to continue: ");
num = Double.parseDouble(value);
}
System.out.println("The sum is " + total);
System.exit(0);
}
}
4-6
It is interesting to note that the modulus operator in Java doesn’t require both operands to
be integers as some other languages do. This is interesting because the math — Modulo
Arithmetic — which uses this operator, is defined only over the set of integer numbers,
not the real number set. Another pair of special operators are ++ and its opposite, —-.
One of the most frequently occurring accumulation expressions has the form, total =
total + 1;, or total += 1;. Therefore, an even shorter short-cut was devised for it,
total++;. The expression, total++;, tells the computer to increase, or increment, the
variable total by one. It is called the “increment” operator. The “decrement” operator
is used when we wish to decrement a variable by one, total--;. That’s all, there are no
more short-cuts and no, you can’t use expressions like, total+++;, if you wish to
increase it by two. The increment and decrement operators only increase or decrease a
variable by exactly one. However, to make life more interesting, the increment and
decrement operators behave differently when placed before a variable as opposed to after
one, but only when that variable is used as part of a bigger calculation. Basically, we’ve
been looking at the post-increment and post-decrement operators, but there are also the
pre-increment and pre-decrement operators.
In the code below, the variable ans is assigned the value 16, not 17 as you may expect,
because the current value of num1 is first used in the calculation before the variable num1
itself is incremented. This is an example of the post-increment operator used as part of a
bigger calculation.
int ans = 0, num1 = 3;
ans = 13 + num1++;
After these two lines are executed, ans will equal 16 and num1 will equal 4. But if the
second line had read, ans = 13 + ++num1;, then ans would equal 17 and num1 would
still equal 4. You can see how intermixing pre- and post-increment and decrement
operators can make calculations harder to follow. Consequently, the rest of this book will
always uses the post-increment and post-decrement operators, and never as part of a
bigger calculation, so as to avoid confusion and to further stress computer science topics
as opposed to language specific ones.
Skills Check:
4-6. Write a program that repeatedly asks users how old they are and if a user is under
nineteen says, “You’re eligible for a student I.D.”, but the programs ends and
says, “You’ve Graduated! Goodbye”, if a user is nineteen or older.
4-7. Write a program that asks the user to enter a number and then prints it’s square.
The program should do this repeatedly until the user enters zero.
4-8. Write a program that prints the 17 times table from 17 * 1 to 17 *12. The output
should be 1 * 17 = 17, 2 * 17 = 34, etc.
4-9. Write a program that gets positive numbers from the user and when a negative
number is entered displays the average of the numbers entered.
4-7
4-10. Write a program that displays a rocket countdown from 10 to 1 and then displays
“Blast Off!”
4-11. Write a program that gets two numbers from the user, a and b, you may assume
that a<b. It then prints the squares of all the numbers in the inclusive range [a, b].
Random and math classes
Besides the Java keywords, there are many commands that can be very useful. These
commands, often referred to as methods, belong to special classes. A class can be used to
group several related commands together, and can be thought of as a template or
blueprint of how to make something. There is a class called Math that contains methods
for doing special mathematical operations such as the square root of a number, or the sine
or cosine of an angle, etc. There is even a class called Random, that contains methods for
generating random numbers. However, to use the methods in a class you usually must
first make an object of that class, and that means using a reference variable.
A Random object can be made as follows:
Random myNums;
myNums = new Random( );
The first line declares a reference variable that will refer to an object of the Random
class, and the second line creates a Random object and makes the variable, myNums, refer
to it. The two lines are often combined as follows:
Random myNums = new Random( );
The keyword new asks the computer to create an object of a particular class, in this case
the Random class, and the assignment operator makes myNums refer to the newly created
object. To print a random integer you can use the nextInt method like this:
int num = myNums.nextInt( );
System.out.println( num );
Every time you use the nextInt method, you would get a different random integer; it
could even be a negative one. The Random class is part of the java.util package and
you must import it, with the import keyword, in order to use it. However, the Math class
is different from most classes in Java probably because it is used so often. It is
automatically imported, and the designers of Java designed the Math class so that it can,
and must, be used without using a reference variable. To use any of the methods
belonging to the Math class you simply type Math followed by a period and the name of
the method you wish to use. For example to use the method that does exponentiation,
like three to the fifth power, you could type:
double num = Math.pow(3, 5);
4-8
Here are a few of the methods that belong to the Math class:
Method Explanation
Math.abs( a ) Returns the absolute value of a
Math.pow(a,b) and Math.sqrt(a) Returns a double representing the value of
ab
and the square root of a respectively.
Math.sin(rad), Math.cos(rad),
Math.tan(rad)
Returns a double representing the sine,
cosine, or tangent of the radian value rad
Math.asin(a), Math.acos(a),
Math.atan(a)
Returns a double representing the angle
whose sine, cosine, or tangent is
represented by a
Math.ceil(a) Returns a double representing the smallest
integer greater than or equal to a
Math.floor(a) Returns a double representing the largest
integer smaller than or equal to a
Math.round(a) Returns an int or long rounded to the
nearest integer
This program displays ten random numbers between 10 and 99, inclusive, along with
their square root and cube. Unfortunately, the nextInt method usually gives us an
integer in the range [–231
, 231
-1], an integer approximately between negative two billion
and positive two billion. Fortunately, the nextInt method allows us to optionally state
how many numbers are in the range we're interested in. For example, if we wanted
numbers in the inclusive range [1, 6], which has six numbers, then we could say
nextInt(6) and nextInt(6) would give us a random number in the range [0, 5]. To
change the range [0, 5] to the desired range of [1, 6] all we have to do is add one to
whatever value nextInt(6) gave us. If we wanted numbers in the inclusive range [5, 9],
which has five numbers, then we could say nextInt(5) and nextInt(5) would give us a
random number in the range [0, 4]. To change the random number from the range [0, 4]
to the range [5, 9] all we have to do is add five to the number nextInt(5) gave us.
Generally, if we want a random number in the inclusive range [low, high] then we
can calculate the amount of numbers in the range with the formula:
amount = high - low + 1;
Consequently, nextInt(amount) will give us a number in the range [0, amount-1]
and to convert that number to the range [low, high] we simply add the value of low
to the number.
import java.util.*;
public class RandomMath {
public static void main(String[] args){
int n = 10;
final int high=99, low=10;
System.out.println("Here are "+ n +
" random integers and their roots and cubes");
4-9
Random randNum = new Random();
int num;
int amount = high - low + 1;
while(n > 0) {
num = randNum.nextInt( amount );
num += low;
System.out.print(num + " ");
System.out.println(Math.sqrt(num) + " " + Math.pow(num, 3));
n--;
}
}
}
Skills Check:
4-12. Write a program that simulates the rolling of a single die. The program should
display a random value in the range [1, 6].
4-13. Write a program that randomly chooses a number from one to ten and then asks
the user to guess which number was chosen. Your program should also count
how many guesses the user takes.
4-14. Write a program that repeatedly displays positive random integers but stops as
soon as an odd integer is generated. It should then display how many even
numbers were generated before the first odd one occurred. Run your program
several times and see what’s the longest string of even numbers you can generate.
4-15. Many cities have lotteries where a person can try to guess which six numbers
chosen from the range [1, 49] will occur the next time the lottery is held. Write a
program that asks the user how many lucky numbers she’d like and then prints
that many random numbers in the range [1, 49]. Don’t worry if the set of random
numbers contains duplicates.
4-16. Write a program that gets a double from the user and prints its value to the first,
second, third, fourth, fifth, etc, all the way to the fifteenth power.
5-1
Chapter 5
String accumulators
Adding up primitive values using accumulators is very useful, but what about reference
variables. Remember, a reference variable is a variable that will refer to an object, and
that an object is what we get when we make something of a particular class usually using
the new keyword. In this case the something is an object of the String class. The class is
the template or description of a string, and the object is what we get when we actually
make a string.
Reference variables are different from variables for primitive data types like int or
double. A reference variable is given a memory location large enough to place a
reference to another chunk of memory where the actual object is stored. Therefore, when
we make a String type reference variable, the memory location given to us does not, and
will not actually, contain the string data we wish to store in it. It will however, refer to
another location in memory where the string data will be stored as part of a String object.
We say “will”, because when you declare a reference variable, it doesn’t automatically
refer to anything. This is important to understand because it means that initializing our
String type accumulator to a starting value is extremely important. In fact, if we used the
following declaration, String sent; and then tried to use sent as an accumulator, the
Java compiler will complain and output, “variable sent might not have been initialized”.
We must set sent to a value, and if we wish it to be zero, then we use "", a pair of quotes
with nothing between them, often referred to as the null string. The null string is not to
be confused with the Java keyword null which can be assigned to a reference variable
when it is declared to indicate that it definitely doesn’t refer to anything yet.
Strings accumulate differently from numbers. A string accumulator simply appends new
strings to the end of its current string value. The joining of two strings together is called
string concatenation. Below is a program that gets strings from the user until she enters
the string “2Q8”. When she enters “2Q8”, to quit, the loop ends and all the letters she
entered are displayed on the screen. A string accumulator is used and is initialized to "",
zero. Also note that the condition for the while loop does not make use of any of the
comparison operators that were used with int or double.
The String class provides us with a method called equals that compares the current
string value reference by the String variable to another string value. However, we wish
the loop to stop when the two strings are not equal, and that’s what the, ! operator, or
logical-NOT operator, does. The exclamation mark means NOT in Java. The while
loop thus reads, while the letters entered by the user are not equal to "2Q8", continue.
5-2
import javax.swing.*;
public class StringAccumulate {
public static void main(String[] args) {
String sent;
String letters;
sent = "";
letters = JOptionPane.showInputDialog("Enter a word: ");
while (! letters.equals("2Q8")) {
sent = sent + letters;
letters = JOptionPane.showInputDialog("Enter a word: ");
}
System.out.println("The sentence is " + sent);
System.exit(0);
}
}
When you run the above program, all the letters entered by the user will be very close
together. The string accumulator joins each new string together to the old ones without
placing any additional spacing between them. A modification to, sent = sent +
letters;, to make the output more readable could be, sent = sent+letters + " ";,
where we append an additional space after each word. Yes, we could also use the short-
cut, sent += letters + " ";.
Once we’ve accumulated a string, we may also wish to know how many characters it
contains. The String class provides us with a method called length for this purpose.
The length method gives us an integer that represents how many characters are stored in
the String object referenced by our String reference variable. For example the following
code snippet would assign the variable num the value 10, nine for the letters in the persons
first and last name and one for the space between them.
String name = "Gary Singh";
int num = name.length( ); //num = 10
You can then use num wherever you would normally use an integer variable, perhaps to
calculate the average word length of the words the user entered earlier. You would need
an accumulator to count how many words the user entered, and one to calculate the sum
of all the lengths of the words she entered.
5-3
Skills Check:
5-1. Write a program that gets words from the user until she enters “2Q8” and each
time prints the word just entered followed by all the words previously entered.
For example:
Enter a word: Apple
Apple
Enter a word: Cat
CatApple
Enter a word: Dogs
DogsCatApple
Enter a word: 2Q8
5-2. Write a program that gets words from the user until she enters “That’s All!” and
each time displays a letter count of the word. For example:
Enter a word: Apple
5
Enter a word: Cat
3
Enter a word: Dogs
4
Enter a word: That’s All!
5-3. Write a program that gets words from the user until she enters “All Done” and
then calculates and displays the average letter count for all the words. For
example:
Enter a word: Apple
5
Enter a word: Cat
3
Enter a word: Dogs
4
Enter a word: All Done
The average letter count is 4.
i.e. (5 + 3 + 4) / 3
5-4
Searching strings
The use of the JOptionPane class to get input for our programs allows us to get lines of
text as input from the user. We may wish to search through a line of text to see if it
contains a particular word. The String class provides a method called indexOf for this
very purpose. The indexOf method searches through a String object for a specific string
pattern and returns an integer that denotes the start of where in the string the first
occurrence of the pattern was found. However, the integer that represents the location or
index of the start of the pattern will be one less than what we would expect. The
character positions in a string are numbered from zero. The first character in a string is at
position zero, the second at position one, and so on. We’ll see much later that this type of
indexing is used with arrays as well, and most likely is based on a technique called
pointer arithmetic that was used in the C programming language. Here is a simple
program that highlights the use of the indexOf method.
import javax.swing.*;
public class StringFind {
public static void main(String[] args) {
String sent;
sent = "An apple a day keeps the doctor away.";
int pos;
pos = sent.indexOf("apple"); //pos now equals 3
System.out.println("In the phrase, " + sent);
System.out.println("apple can be found after position " + pos);
pos = sent.indexOf("e"); //pos now equals 7
System.out.println("and e can be found after position " + pos);
}
}
For the line, pos = sent.indexOf("apple");, pos is assigned the value 3 because the
"a" of "apple", which was the pattern we were searching for, is the fourth character in the
string, "An apple a day keeps the doctor away. ". Similarly, for the line, pos =
sent.indexOf("e");, pos is assigned the value 7 because the letter "e", the pattern we
were searching for, is the eighth character in the string sent. Note that even if we
repeated the line, pos = sent.indexOf("e");, pos would be assigned the value 7 and
not the value 16 which is the location of the next "e" in the string sent. The method
indexOf always returns the integer corresponding to the start of the first occurrence
of the pattern within the string.
Substrings
We used accumulator variables to add numbers together and to join or concatenate
strings. The opposite of concatenating strings is breaking a string up or working with a
piece of the string. A piece of a string is called a substring. The String class provides a
method called substring to get a piece of a string. The substring method returns a
5-5
new string consisting of all the characters from a particular position all the way to the end
of the original string. The program below is similar to the StringFind program listed
above also remember the first character of a string is at position zero, not one.
import javax.swing.*;
public class StringPiece {
public static void main(String[] args) {
String sent;
sent = "An apple a day keeps the doctor away.";
String words;
int pos;
pos = sent.indexOf("apple"); //pos = 3 now
System.out.println("In the phrase, " + sent);
words = sent.substring(pos);
//words = "apple a day keeps the doctor away."
System.out.println("the substring starting with apple is " +
words);
pos = sent.indexOf("e"); //pos = 7 now
words = sent.substring(pos);
//words = "e a day keeps the doctor away. "
System.out.println("and starting with e is " + words);
}
}
As in the previous program, the line, pos = sent.indexOf("apple");, causes pos to be
assigned the value 3 because the "a" of "apple", which was the pattern we were searching
for, is the fourth character in the string, "An apple a day keeps the doctor away. ".
The next line, words = sent.substring(pos);, causes the variable words to be
assigned the substring starting from index 3, which is the fourth character, all the way to
the end, i. e., "apple a day keeps the doctor away. ".
Skills Check:
5-4. Write a program that gets a sentence from the user and then a word from the user
and tells her where in the sentence the word can be found.
5-5. Write a program that gets a word from the user and an integer position and prints
all the letters that come after that position in the word.
5-6. Write a program that gets a word from the user and prints all the letters from the
middle to the end of the word. Ex: apple would output ple and applejacks would
output jacks.
5-6
Advanced searches and substrings
The indexOf method is very useful for telling us the location of the first occurrence of a
particular pattern. However, what if we wish to find the location of a second or third
instance of the pattern. The indexOf method can be used with an optional integer
indicating where the computer should start searching for the pattern. For example, if you
wished to search for the word "apple" in the second half of a String variable called sent,
you could type something like this:
int middle = sent.length() / 2;
int pos = sent.indexOf("apple", middle);
If you wanted to see if the string stored in a variable called pat occurred a second time in
the variable sent you could use the following lines of code:
int pos;
pos = sent.indexOf(pat);
pos = sent.indexOf(pat, pos+1);
When the last line executes it would have the location of the second instance of the
pattern within sent or -1 to indicate that a second instance of the pattern didn't exist.
Below is a small program that uses the optional starting position with the indexOf
method to count how many times the letter "e" occurs in the variable sent.
public class CountEs {
public static void main(String[] args) {
String sent = "Hello Joe, John's gone home.";
int count = 0;
int pos;
pos = sent.indexOf("e");
while(pos != -1) {
count++;
pos = sent.indexOf("e", pos+1);
}
System.out.println("There are " + count +
" e's in the sentence: " + sent);
}
}
The substring method also has an alternate format. You can not only specify the start
of a substring but its end as well. Note: When you specify the end of a substring the
character at that position is not included in the substring. The substring goes from
the starting location up to but not including the ending location.
5-7
For example, the following lines of code would print John' not John's.
String sent = "Hello Joe, John's gone home.";
String word;
word = sent.substring(11, 16);
System.out.println(word); //John'
Below is a program that demonstrates the use of indexOf and substring with and
without their optional positional values. Comments are included to indicate the resulting
values produced by the program.
public class SubAndIndexExtras {
public static void main(String[] args) {
String sent = "Hello Joe, John's gone home.";
String word;
//substring(start, end) but end not included!
word = sent.substring(11, 17);
System.out.println(word); //John's
int pos;
pos = sent.indexOf("Jo");
// Joe, John's gone home
System.out.println(sent.substring(pos));
pos = sent.indexOf("Jo", pos+1);
System.out.println(sent.substring(pos)); //John's gone home
}
}
Skills Check:
5-7. Write a program that gets words from the user until she enters “2Q8” and each
time prints only the first and last letter of the word.
5-8. Write a program that gets a word from the user and then prints it backwards on
the screen. For example, if the user entered apple, the computer would print elppa
5-9. Write a program that gets a sentence from the user and then tells her how many
words are in the sentence. You may assume that there is exactly one space
between each word in the sentence that the user entered.
5-10. Write a program that gets words from the user until she enters “L8R” and each
time prints only the middle letter of the word.
5-11. Write a program that gets a word from the user and prints each letter of the word
on a separate line.
5-12. Write a program that gets words from the user and as long as the word has four or
more letters prints the second and second last letter of the word. If it has less than
four letters then the program ends.
5-13. Write a program that gets words from the user until she enters “2Q8” and each
time prints a letter at a random position in the word.
5-14. Write a program that gets a sentence from the user and then a word and tells her
how many times the word appears in the sentence.
5-8
String tokens
Whenever we use the showInputDialog method to get input from the user, we receive
the input as a single string. If we had a program that calculated the average of three
numbers, we would have to use the showInputDialog method three times, once for each
number. However, for convenience, a user may wish to enter all three numbers at once
and just type a space between each number. We would then have to use the indexOf
and substring methods to break the string up into pieces or tokens.
A token is anything separated by a delimiter. A common delimiter is a space, and often a
comma. Breaking a string up into tokens is a fairly common occurrence, and to simplify
this process, Java has a class called StringTokenizer. The StringTokenizer class is also
part of the java.util package. It takes a string and a delimiter and then provides several
methods that help to return individual tokens from the string.
When the StringTokenizer object is made, the programmer specifies the string to use and
which delimiter to use. She can then use the methods hasMoreElements and nextToken
to process the string. The hasMoreElements method returns true if there are any tokens
left in the string and the nextToken method returns the next token as a String object.
You can think of a StringTokenizer object as a cookie jar and the tokens as cookies.
Once the cookie jar is created you can check if there are any cookies in the jar by using
the method hasMoreElements. If there are more cookies in the jar you can remove one
with the method nextToken. Below is a program that gets several words from the user,
all at once, and then displays each word on a separate line on the screen.
import javax.swing.*;
import java.util.*;
public class StringTokens {
public static void main(String[] args) {
String input;
input = JOptionPane.showInputDialog("Enter several words: ");
StringTokenizer st = new StringTokenizer(input, " ");
String word;
while (st.hasMoreElements() ) {
word = st.nextToken();
System.out.println(word);
}
System.exit(0);
}
}
5-9
Skills Check:
5-15. Write a program that gets a sentence from the user and then prints each word of
the sentence on a separate line. Ex: Apples are good for you.
Apples
are
good
for
you.
5-16. Write a program that gets a sentence from the user and prints only the first and
last word.
6-1
Chapter 6
Selection
Repetitive tasks are certainly well suited for computers, but when dealing with many
problems, we also need to decide between two or more courses of action or whether a
certain action should be taken at all. Selection is simply the process of choosing if a
statement or block of statements should be executed. In Java, one of the keywords used
to implement selection is, if. Basically, we say, “if this condition is true, then execute
these statements, otherwise skip over them”. The format is very similar to a while loop.
if ( condition ) {
Java statement;
Java statement;
}
The keyword if is followed by a condition enclosed in parenthesis, and then an open
brace, {, and one or more Java statements followed by semi-colons and finally a close
brace, }. The condition has the same format and function as it did with loops. If the
comparison between the two things in the condition evaluate to true, then the statement(s)
between the braces are executed, otherwise they are skipped over. Below is a program
that gets integers from the user until she enters zero. Each time a number is entered, the
program checks to see if the number is even, and only if it is, then the program prints half
of the number.
import javax.swing.*;
public class IfEven {
public static void main( String [] args) {
String value;
value=JOptionPane.showInputDialog("Enter a number, zero to exit");
int number = Integer.parseInt(value);
while(number != 0) {
if (number % 2 == 0) {
System.out.println("Half is "+ (number/2) );
}
value = JOptionPane.showInputDialog("Another number: ");
number = Integer.parseInt(value);
}
System.exit(0);
}
}
Again we used a seeded while loop, and the value zero was used as our sentinel. The
special modulus operator, %, which gives us the remainder after a division, was used to
see if the number was even. All even numbers when divided by two have zero as the
remainder. If the number was even, then half its value was printed. If the number was
not even, then the statement belonging to the if block of code was skipped and the next
value was read in from the user.
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook
ICS3MeBook

More Related Content

What's hot

Software Testing - Boundary Value Analysis, Equivalent Class Partition, Decis...
Software Testing - Boundary Value Analysis, Equivalent Class Partition, Decis...Software Testing - Boundary Value Analysis, Equivalent Class Partition, Decis...
Software Testing - Boundary Value Analysis, Equivalent Class Partition, Decis...priyasoundar
 
How To Write A Test Case In Software Testing | Edureka
How To Write A Test Case In Software Testing | EdurekaHow To Write A Test Case In Software Testing | Edureka
How To Write A Test Case In Software Testing | EdurekaEdureka!
 
Requirements engineering scenario based software requirement specification
Requirements engineering scenario based software requirement specificationRequirements engineering scenario based software requirement specification
Requirements engineering scenario based software requirement specificationWolfgang Kuchinke
 
White Box Testing
White Box TestingWhite Box Testing
White Box TestingAlisha Roy
 
Tareas de ingenieria de requerimientos
Tareas de ingenieria de requerimientosTareas de ingenieria de requerimientos
Tareas de ingenieria de requerimientosnenyta08
 
Error detection recovery
Error detection recoveryError detection recovery
Error detection recoveryTech_MX
 
Procedimientos especiales
Procedimientos especialesProcedimientos especiales
Procedimientos especialesAnel Sosa
 
Software cost estimation
Software cost estimationSoftware cost estimation
Software cost estimationHaitham Ahmed
 
Ingenieria de software - Unidad 3 arquitecturas de software
Ingenieria de software - Unidad 3 arquitecturas de softwareIngenieria de software - Unidad 3 arquitecturas de software
Ingenieria de software - Unidad 3 arquitecturas de softwareJosé Antonio Sandoval Acosta
 
Estimating Software Maintenance Costs
Estimating Software Maintenance CostsEstimating Software Maintenance Costs
Estimating Software Maintenance Costslalithambiga kamaraj
 
Introduction to Software Review
Introduction to Software ReviewIntroduction to Software Review
Introduction to Software ReviewPhilip Johnson
 
Software Testing Life Cycle (STLC) | Software Testing Tutorial | Edureka
Software Testing Life Cycle (STLC) | Software Testing Tutorial | EdurekaSoftware Testing Life Cycle (STLC) | Software Testing Tutorial | Edureka
Software Testing Life Cycle (STLC) | Software Testing Tutorial | EdurekaEdureka!
 
Delphi cost estimation model
Delphi cost estimation modelDelphi cost estimation model
Delphi cost estimation modelShashwat Shriparv
 
Estructura selectiva doble con Java
Estructura selectiva doble con JavaEstructura selectiva doble con Java
Estructura selectiva doble con JavaNora O. Martínez
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl TechniquesDave Cross
 
Pruebas de aplicaciones web
Pruebas de aplicaciones webPruebas de aplicaciones web
Pruebas de aplicaciones webpaulinaaillon
 
Crear conexion a servidor en MySQL Workbench
Crear conexion a servidor en  MySQL WorkbenchCrear conexion a servidor en  MySQL Workbench
Crear conexion a servidor en MySQL WorkbenchJair Ospino Ardila
 

What's hot (20)

software quality
software qualitysoftware quality
software quality
 
Software Testing - Boundary Value Analysis, Equivalent Class Partition, Decis...
Software Testing - Boundary Value Analysis, Equivalent Class Partition, Decis...Software Testing - Boundary Value Analysis, Equivalent Class Partition, Decis...
Software Testing - Boundary Value Analysis, Equivalent Class Partition, Decis...
 
How To Write A Test Case In Software Testing | Edureka
How To Write A Test Case In Software Testing | EdurekaHow To Write A Test Case In Software Testing | Edureka
How To Write A Test Case In Software Testing | Edureka
 
Software quality assurance
Software quality assuranceSoftware quality assurance
Software quality assurance
 
Requirements engineering scenario based software requirement specification
Requirements engineering scenario based software requirement specificationRequirements engineering scenario based software requirement specification
Requirements engineering scenario based software requirement specification
 
White Box Testing
White Box TestingWhite Box Testing
White Box Testing
 
Tareas de ingenieria de requerimientos
Tareas de ingenieria de requerimientosTareas de ingenieria de requerimientos
Tareas de ingenieria de requerimientos
 
Error detection recovery
Error detection recoveryError detection recovery
Error detection recovery
 
Procedimientos especiales
Procedimientos especialesProcedimientos especiales
Procedimientos especiales
 
Software cost estimation
Software cost estimationSoftware cost estimation
Software cost estimation
 
Ingenieria de software - Unidad 3 arquitecturas de software
Ingenieria de software - Unidad 3 arquitecturas de softwareIngenieria de software - Unidad 3 arquitecturas de software
Ingenieria de software - Unidad 3 arquitecturas de software
 
Estimating Software Maintenance Costs
Estimating Software Maintenance CostsEstimating Software Maintenance Costs
Estimating Software Maintenance Costs
 
Prolog2010
Prolog2010Prolog2010
Prolog2010
 
Introduction to Software Review
Introduction to Software ReviewIntroduction to Software Review
Introduction to Software Review
 
Software Testing Life Cycle (STLC) | Software Testing Tutorial | Edureka
Software Testing Life Cycle (STLC) | Software Testing Tutorial | EdurekaSoftware Testing Life Cycle (STLC) | Software Testing Tutorial | Edureka
Software Testing Life Cycle (STLC) | Software Testing Tutorial | Edureka
 
Delphi cost estimation model
Delphi cost estimation modelDelphi cost estimation model
Delphi cost estimation model
 
Estructura selectiva doble con Java
Estructura selectiva doble con JavaEstructura selectiva doble con Java
Estructura selectiva doble con Java
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 
Pruebas de aplicaciones web
Pruebas de aplicaciones webPruebas de aplicaciones web
Pruebas de aplicaciones web
 
Crear conexion a servidor en MySQL Workbench
Crear conexion a servidor en  MySQL WorkbenchCrear conexion a servidor en  MySQL Workbench
Crear conexion a servidor en MySQL Workbench
 

Similar to ICS3MeBook

Python_Crash_Course_2nd_Edition.pdf
Python_Crash_Course_2nd_Edition.pdfPython_Crash_Course_2nd_Edition.pdf
Python_Crash_Course_2nd_Edition.pdfDamien Raczy
 
Ict impotant deped
Ict impotant depedIct impotant deped
Ict impotant depeditsomichael
 
Computer Hardware Servicing Learner's Material Grade 10
Computer Hardware Servicing Learner's Material Grade 10Computer Hardware Servicing Learner's Material Grade 10
Computer Hardware Servicing Learner's Material Grade 10Bogs De Castro
 
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniquesScope, binding, papameter passing techniques
Scope, binding, papameter passing techniquesCareerMonk Publications
 
Algorithms andcomplexity
Algorithms andcomplexityAlgorithms andcomplexity
Algorithms andcomplexityHieu Pham
 
introduction to DL network deep learning.ppt
introduction to DL network deep learning.pptintroduction to DL network deep learning.ppt
introduction to DL network deep learning.pptQuangMinhHuynh
 
introduction to deep Learning with full detail
introduction to deep Learning with full detailintroduction to deep Learning with full detail
introduction to deep Learning with full detailsonykhan3
 
Numerical solutions of linear algebraic systems using matlab
Numerical solutions of linear algebraic systems using matlabNumerical solutions of linear algebraic systems using matlab
Numerical solutions of linear algebraic systems using matlabSave the Children International
 
Analog_and_digital_signals_and_systems.pdf
Analog_and_digital_signals_and_systems.pdfAnalog_and_digital_signals_and_systems.pdf
Analog_and_digital_signals_and_systems.pdfKrishanVyas1
 
Emona tims-analog-communication-part1 2
Emona tims-analog-communication-part1 2Emona tims-analog-communication-part1 2
Emona tims-analog-communication-part1 2Subhajit Sahu
 
Laboratory manual
Laboratory manualLaboratory manual
Laboratory manualAsif Rana
 
A Beginner's Guide to R.pdf
A Beginner's Guide to R.pdfA Beginner's Guide to R.pdf
A Beginner's Guide to R.pdfVeevThummuri
 
Microcontroladores: Programación del microcontrolador PIC en C
Microcontroladores: Programación del microcontrolador PIC en CMicrocontroladores: Programación del microcontrolador PIC en C
Microcontroladores: Programación del microcontrolador PIC en CSANTIAGO PABLO ALBERTO
 
thesis_Zhiyuan Lin
thesis_Zhiyuan Linthesis_Zhiyuan Lin
thesis_Zhiyuan LinZhiyuan Lin
 
The Java Learning Kit Chapter 1 – Introduction Copyri.docx
The Java Learning Kit Chapter 1 – Introduction Copyri.docxThe Java Learning Kit Chapter 1 – Introduction Copyri.docx
The Java Learning Kit Chapter 1 – Introduction Copyri.docxarnoldmeredith47041
 
Python for Everybody
Python for EverybodyPython for Everybody
Python for Everybodyvishalpanday2
 
Matloff programming on-parallel_machines-2013
Matloff programming on-parallel_machines-2013Matloff programming on-parallel_machines-2013
Matloff programming on-parallel_machines-2013lepas Yikwa
 
Tieng anh chuyen_nganh_vien_thong_-_bai_tap
Tieng anh chuyen_nganh_vien_thong_-_bai_tapTieng anh chuyen_nganh_vien_thong_-_bai_tap
Tieng anh chuyen_nganh_vien_thong_-_bai_tapMinh Tự Nguyễn
 

Similar to ICS3MeBook (20)

Python_Crash_Course_2nd_Edition.pdf
Python_Crash_Course_2nd_Edition.pdfPython_Crash_Course_2nd_Edition.pdf
Python_Crash_Course_2nd_Edition.pdf
 
Ict impotant deped
Ict impotant depedIct impotant deped
Ict impotant deped
 
Computer Hardware Servicing Learner's Material Grade 10
Computer Hardware Servicing Learner's Material Grade 10Computer Hardware Servicing Learner's Material Grade 10
Computer Hardware Servicing Learner's Material Grade 10
 
Nguyễn Nho Vĩnh
Nguyễn Nho VĩnhNguyễn Nho Vĩnh
Nguyễn Nho Vĩnh
 
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniquesScope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
 
Algorithms andcomplexity
Algorithms andcomplexityAlgorithms andcomplexity
Algorithms andcomplexity
 
introduction to DL network deep learning.ppt
introduction to DL network deep learning.pptintroduction to DL network deep learning.ppt
introduction to DL network deep learning.ppt
 
introduction to deep Learning with full detail
introduction to deep Learning with full detailintroduction to deep Learning with full detail
introduction to deep Learning with full detail
 
Numerical solutions of linear algebraic systems using matlab
Numerical solutions of linear algebraic systems using matlabNumerical solutions of linear algebraic systems using matlab
Numerical solutions of linear algebraic systems using matlab
 
Analog_and_digital_signals_and_systems.pdf
Analog_and_digital_signals_and_systems.pdfAnalog_and_digital_signals_and_systems.pdf
Analog_and_digital_signals_and_systems.pdf
 
Emona tims-analog-communication-part1 2
Emona tims-analog-communication-part1 2Emona tims-analog-communication-part1 2
Emona tims-analog-communication-part1 2
 
Laboratory manual
Laboratory manualLaboratory manual
Laboratory manual
 
A Beginner's Guide to R.pdf
A Beginner's Guide to R.pdfA Beginner's Guide to R.pdf
A Beginner's Guide to R.pdf
 
Microcontroladores: Programación del microcontrolador PIC en C
Microcontroladores: Programación del microcontrolador PIC en CMicrocontroladores: Programación del microcontrolador PIC en C
Microcontroladores: Programación del microcontrolador PIC en C
 
thesis_Zhiyuan Lin
thesis_Zhiyuan Linthesis_Zhiyuan Lin
thesis_Zhiyuan Lin
 
The Java Learning Kit Chapter 1 – Introduction Copyri.docx
The Java Learning Kit Chapter 1 – Introduction Copyri.docxThe Java Learning Kit Chapter 1 – Introduction Copyri.docx
The Java Learning Kit Chapter 1 – Introduction Copyri.docx
 
Python for Everybody
Python for EverybodyPython for Everybody
Python for Everybody
 
Python for everybody
Python for everybodyPython for everybody
Python for everybody
 
Matloff programming on-parallel_machines-2013
Matloff programming on-parallel_machines-2013Matloff programming on-parallel_machines-2013
Matloff programming on-parallel_machines-2013
 
Tieng anh chuyen_nganh_vien_thong_-_bai_tap
Tieng anh chuyen_nganh_vien_thong_-_bai_tapTieng anh chuyen_nganh_vien_thong_-_bai_tap
Tieng anh chuyen_nganh_vien_thong_-_bai_tap
 

ICS3MeBook

  • 1. AP COMPUTER SCIENCE USING JAVA ICS3M Copyright 2004 by Terence Prezens. All rights reserved. No part of this book may be reproduced in any way or by any means without the permission of Terence Prezens.
  • 2. i Preface Java is an excellent language for learning about computer science. It’s also a very powerful language, and its popularity is probably due to its strong ties to the Internet. In fact, when you talk of the Internet and the growing popularity of e-commerce, it is hard to avoid discussing Java. The power and popularity of Java is one reason why it is a good choice as the language of instruction for high school computer science. You’ll be learning something real, something that is current, and yes, fashionable. Another reason to use Java is its graphics capabilities. One big attraction to computer science is computer games. Everyone likes to play them and many wish they could create their own. Java has an extensive graphics library that is part of the language, and within a lesson or two, you can create some fairly basic but interesting pictures and animations. Lastly, Java is the choice of many universities. If you wish to continue your interest in computer science at the university level, then this book will prepare you well. The contents of this book will attempt to cover all the topics suggested by the ministry of education, pertaining to a grade eleven computer science course. Furthermore, it will cover them in the manner suggested by the College Board so as to prepare you to write the Advance Placement Computer Science A exam. The AP Computer Science exam is typically administered in May, and usually consists of two parts. Part one consists of 40 multiple choice questions and lasts one-and-a-half hours. Part two consists of four free response questions and also lasts one-and-a-half hours. The exam is marked by the College Board, and each paper is given a ranking of one to five, relative to all the other papers. Generally, Canadian and American universities will accept a three or higher, and consequently, allow you to skip the first year computer science course or at least the first half course in computer science. The AP computer science exam will be administered only in Java, commencing in the 2003/2004 school year.
  • 3. Table of Contents Chapter 1 What is a computer .................................................................................. 1-1 Number systems....................................................................................... 1-1 ASCII....................................................................................................... 1-2 The modern computer.............................................................................. 1-2 Controlling the computer......................................................................... 1-3 Programming life cycle............................................................................ 1-6 Chapter 2 Input and output....................................................................................... 2-1 Our first program ..................................................................................... 2-1 Testing and debugging............................................................................. 2-2 Analyzing the object oriented code.......................................................... 2-3 Variables .................................................................................................. 2-4 Objects, packages of them ....................................................................... 2-5 Chapter 3 Variable types .......................................................................................... 3-1 Primitive data types.................................................................................. 3-1 Primitive variables ................................................................................... 3-3 Input and output....................................................................................... 3-5 Fancy printing.......................................................................................... 3-7 Commenting your program...................................................................... 3-9 Chapter 4 Simple repetition...................................................................................... 4-1 Accumulators........................................................................................... 4-4 Short-cuts................................................................................................. 4-5 Random and math classes........................................................................ 4-7 Chapter 5 String accumulators ................................................................................. 5-1 Searching strings...................................................................................... 5-4 Substrings................................................................................................. 5-4 Advanced searches and substrings........................................................... 5-6 String tokens ............................................................................................ 5-8 Chapter 6 Selection................................................................................................... 6-1 Two choice selection................................................................................ 6-2 Compound conditions.............................................................................. 6-3 Multiple choice selection ......................................................................... 6-5 Counted loops .......................................................................................... 6-6
  • 4. Chapter 7 Methods and modular programming........................................................ 7-1 Applets..................................................................................................... 7-1 Using methods ......................................................................................... 7-3 Graphic methods...................................................................................... 7-4 Mouse interaction..................................................................................... 7-6 Advanced applets..................................................................................... 7-9 Summary of Graphic Methods............................................................... 7-12 Chapter 8 Our own methods..................................................................................... 8-1 Call by value ............................................................................................ 8-4 Call by reference...................................................................................... 8-5 Procedures and functions......................................................................... 8-6 Chapter 9 File input and output................................................................................ 9-1 Errors and exceptions............................................................................... 9-1 File output................................................................................................ 9-2 File input.................................................................................................. 9-5 System input............................................................................................. 9-8 Chapter 10 Statistics................................................................................................. 10-1 Arrays..................................................................................................... 10-1 Arrays and methods ............................................................................... 10-3 Sorting and searching............................................................................. 10-5 Related lists............................................................................................ 10-8 Two dimensional arrays....................................................................... 10-10 Appendix A Installing Java ......................................................................................... A-1 Appendix B Installing jEdit..........................................................................................B-1 Appendix C Installing JCreator....................................................................................C-1
  • 5. 1-1 Chapter 1 What is a computer? A computer is an electronic device that processes numerical information. Yes, it is true that computers can process words and manipulate pictures and play songs, but all these other types of information must first be converted into numbers. Computers are composed of wires and electronic circuits that control them. A wire can either be on or off. It either has electricity flowing through it or it doesn’t. We can represent this on/off nature of a wire by assigning it a 1 for on and a 0 for off. Suddenly, we have numbers where before we had just wires. Number systems This number system of on’s and off’s, 1’s and 0’s, is called the Binary number system. Every single wire, or every single 1 or 0, is called a bit. And to make our lives more manageable, we generally talk about groups of bits; four or eight bits are called a nibble or a byte respectively. If we have four wires — a nibble — they can generate many different patterns of 1’s and 0’s, binary numbers. In fact, they can generate 24 , or 16, different binary numbers: 00002, 00012, 00102, 00112, 01002, 01012, 01102, 01112, 10002, 10012, 10102, 10112, 11002, 11012, 11102, and 11112. A subscript 2 after each number indicates that the patterns are binary numbers, not decimal numbers. We can use these binary numbers to represent decimal numbers. We can let 00002 represent zero, and 00012 represent one, and 00102 represent two and 00112 represent 3 and so on, all the way too 11112 which would represent fifteen. If we need bigger numbers, we simply get more wires, bits. It turns out that the number of patterns we can make with n number of bits is 2n . If we have a byte of information, then we can have 28 patterns, and because one of the patterns represents the zero, a byte of information can represent numbers as big as 28 -1, or 255. Besides the binary number system, another popular number system in the computer world is the Hexadecimal number system. It deals with groups of four bits at a time, a nibble. Since each nibble can represent 16, 24 , patterns, each hexadecimal digit can be a value between 0 and 15. Because it is confusing to write a single hexadecimal digit like 15 using what seems to be two digits, the hexadecimal digits 10 to 15 are written as A, B, C, D, E, and F. A hexadecimal number like 2B16 would represent 2 * 16 + 11, or 43 in decimal.
  • 6. 1-2 ASCII Characters like ‘A’, ‘B’, etc. are also stored in the computer as numbers. The computer uses a standard called American Standard Code for Information Interchange (ASCII). This standard has assigned each character on your keyboard a numerical value. The upper case letters ‘A’ through ‘Z’ have been assigned the values 65 through 90, and the lower case letters ‘a’ through ‘z’ have been assigned the values 97 through 122. Even the digits ‘0’ through ‘9’ have ASCII values 48 through 57. It is the existence of the ASCII standard that allows us to tell the computer to make comparisons between words, for example, when we’re trying to alphabetize a list of names. The modern computer The computer you buy at the store generally comes in two boxes, one for the monitor and one for the computer case and its attachments. Usually the case is upright, and called a tower. The tower is where all the interesting computing in going on. Inside the case there is a large rectangular piece of plastic with quite a bit of metal etchings on it. This is the motherboard. On this piece of plastic, all the key components are placed. The most import component is the Central Processing Unit (CPU). It is the brain of the computer and controls all the other components. The CPU comes in various speeds and some of the more popular lines of CPUs are the Pentium by Intel, the Athlon by AMD, and the PowePC by Apple. Also on the motherboard are smaller narrow strips of plastic with components — memory chips — attached to them. These are the computer’s random access memory (RAM), and they too come in various speeds and capacities. Another section of memory chips called read only memory (ROM), is where important instructions are kept that are executed when the computer is turned on. The metal etchings on the motherboard connect the CPU, memory and all the other components on the motherboard together. This set of metal lines that allows all the components to send and receive data is called a bus. Near the back of the motherboard are a few slots where you can plug in expansion cards. These cards could be internal modems, sound cards, video cards, or the increasingly popular network card. There are also a couple of little plugs attached to the motherboard where you can plug in your keyboard and your mouse. Most of the remaining components on the motherboard help the CPU and all the other components to communicate. Inside the case there is also the power supply, a hard drive and floppy drive for saving files, and probably a CD-ROM or DVD drive as well. These components are connected to the motherboard by cables, and the with the exception of the power supply, are called peripherals. The final important peripheral that would make this computer complete is not in the tower, and must usually be bought separately. It is a printer.
  • 7. 1-3 Skills Check: 1-1. How many bits are there in one byte and what is the biggest decimal value that can be represented by one byte? 1-2. Name three different number systems used in computer science. 1-3. How are letters stored in a computer? 1-4. If a computer were to alphabetize the words "apple" and "Orange" which word would come last and why? 1-5. What is the major difference between RAM and ROM? 1-6. What is the name given to the set of wires that connects the computers memory with its CPU and where can these wires be found? Controlling the computer Remember that a computer is a machine. It consists of wires and tiny electronic components. The modern CPU consists of a few million of a particular component called a transistor. The CPU is the brain of the computer and these transistors basically act as on/off switches allowing electricity to either flow through a particular wire or not. Generally the more transistors a CPU has the more powerful it is. Unfortunately, electricity moving through transistors gives off heat and therefore more transistors also means more heat. Consequently, many CPUs must have fans and other devices to keep them cool and prevent them from overheating. We write programs to tell a computer what to do. A program is essentially a list of instructions telling the computer what to do next. This list usually results in various different wires turning on or off at different times. Luckily, we don’t have to write specific instructions for turning on or off individual wires, but essentially, that is what’s happening. We can think of that level of programming as the micro level, and it is far beyond the scope of this book. We’ll concern ourselves more with a higher level, even higher than machine language. The machine language is the language a program must be written in if the CPU is to understand it. Each type of CPU uses a different machine language. A CPU made by Intel understands a different machine language than one made by Apple. We can write programs very close to machine language by using a language called Assembly Language. Assembly language uses mnemonic English, like abbreviations, to represent individual machine language instructions. There is one assembly language instruction for each of the machine language instructions. A program called an assembler takes the assembly language program and converts it into machine language.
  • 8. 1-4 Below is a table of assembly language instructions, along with their machine language equivalent, written as a decimal number and a description of the instruction. These instructions are not for any particular CPU, and usually when we talk about computers and certainly machine language, we use the hexadecimal number system or the binary number system. Machine Language Assembly Language Description 18 SUB A, B -subtract the contents of memory location B from the contents of A and store the result in A 50 ADD A, B -add the contents of memory location B to the contents of A and store the result in A 64 JMP A -jump to the memory location A and execute the program instructions starting there 67 JE A -same as JMP but only if the last comparison instruction found both values to be equal 68 JG A -same as JMP but only if the last comparison instruction found the left value to be greater 69 JL A -same as JMP but only if the last comparison instruction found the left value to be less 70 JNE A -same as JMP but only if the last comparison instruction found the two values to be unequal 182 MOV A, #n -move the value n into the memory location A 183 MOV A, B -move the contents of the memory location B into the memory location A 195 CMP A, B -compare the contents of memory location A with the contents of B Many years ago, writing programs in assembly language was the only way to control a computer. Consequently, programming was left to a select few, and took quite a bit of time. A simple program to add two numbers, like 23 and 47, using the previously described assembly language would look like this: 100 MOV 200, #23 ;store 23 into memory location 200 103 MOV 201, #47 ;store 47 into memory location 201 106 MOV 202, 200 ;copy the value 23 into memory location 202 109 ADD 202, 201 ;add 23 and 47 and store the result in 202 On the left, I have included the actual memory locations where each instruction of the program would be stored. In memory location 100, the MOV command is stored; in 101, the value 200; and in 102, the value 23. On the right, is some helpful documentation explaining each line.
  • 9. 1-5 The same program would be even harder to read if we had to read it in machine language. 100 182 200 23 103 182 201 47 106 183 202 200 109 50 202 200 Assembly is what we call a low level language. Java is an example of a high level language. Programming in assembler can produce very fast programs but it is very time consuming, and assembler programs can be very hard to fix should an error occur. High level languages, like Java, are easier to learn because they are similar to English. There are many different high level programming languages: Fortran, Pascal, Turing, C/C++, and BASIC. The problem is that the computer only understands machine language, and doesn’t know anything about Java or any other high level language. Therefore, we need some way of translating the high level language into machine language. Often, programmers refer to programs as code, and throughout the rest of the book, I’ll use code, program, and even language, interchangeably. We will call the program written in a high level language the source code, and the same program after it has been converted into machine language the object code. There are two ways to convert source code to object code. Both ways require a program, and that program is either called an interpreter or a compiler, depending upon how it translates the source code. An interpreter takes the source code and translates it one line at a time into object code, and then immediately executes that line of object code. It then translates the next line and so on. If you wish to execute your program a second time, then the interpreter starts again with the first line of the source code, translates it, and then executes it, and so on. This translation and then execution that takes place every time you execute your program can slow down the execution of your program. However, a compiler takes the file you created with your source code in it, and translates all the source code into object code. It creates a new file and stores all the object code in it. The next time you wish to execute your program, you can just execute the file containing the object code, and no translation is needed. The only problem is that not all CPUs understand the same machine language. Remember that Intel CPUs and Apple CPUs have different machine languages so the file containing the object code created on one computer may not work on another. Here is where Java shines, at least in theory. Java programs are compiled into a machine code for a virtual machine. By a virtual machine, I mean a machine that really doesn’t exist, and the machine code is called bytecode. This means that for any computer to run your Java program, it must still convert your bytecode into machine code for its CPU. To do this, it runs a Java
  • 10. 1-6 interpreter. The interpreter takes the file containing the machine code for the virtual machine, and translates and executes each line just like any other interpreter. But the virtual machine code is much closer to real machine code, than high level code like Java, and so the translation and execution of the virtual code is pretty fast. The interpreter can also be added as a plug-in to a web browser, and this allows your browser to execute Java programs regardless of which type of computer was used to create the Java program. A Java program written to run in a web browser is called a Java Applet. Programming life cycle Programming is basically problem solving. It can however be broken down into five stages: problem definition and analysis, design, implementation, testing, and maintenance. Unfortunately, most of the problems covered in this book will not require a great deal of time to be spent on defining or analyzing the problem. This is primarily to get you quickly started on learning the Java language and some of the fundamentals of computer science. However, it is important to note that sometimes the most important and difficult stage of programming is defining and analyzing a problem. If you don’t clearly understand the problem, it is very hard to find a solution. Designing a solution for a problem can occur in various ways. We call the set of step-by- step instructions to solve a particular problem an algorithm. An algorithm can be written in plain English but is usually written in a sort of point form and is called pseudocode, pseudo meaning false. For example, the pseudocode for an algorithm for making a pizza may look something like this: Preheat oven Prepare crust Put sauce and toppings on crust Cook pizza An alternative way of representing an algorithm is by representing it graphically by using a flowchart. Four of the basic flowchart symbols are: Start / Stop Process / Calculate Comparison Input / Output
  • 11. 1-7 For example, the flowchart of an algorithm to get two numbers from a user and display the sum could look like this: The implementation stage should occur only after we have formulated an algorithm. This doesn’t always happen, especially when dealing with very small problems. Generally, in an introductory course, this is where most student programmers begin their programming life cycle. At this stage, we type in our algorithm using a specific programming language like Java. This is sometimes called coding the algorithm. Next, we try to execute our program and unless we’re very lucky, or working with a very simple program, this leads us to the next stage, testing. The first time a program is run it generally has some errors. Programmers call these errors bugs, and the process of correcting them is called debugging. This stage can be the most frustrating stage and often turns away many a student programmer. There are two types of errors that can occur. One type of error is a compile-time error, an error that occurs when the compiler tries to convert your Java source code into bytecode. Your program may be trying to use a command that belongs to a package of commands that you forgot to include in your program, or your program may have a simple syntax error. Syntax errors are a type of compile-time error and occur when your program violates a rule of the programming language. For example, if you forget to put a semi-colon at the end of a Java statement, you will probably get at least one syntax error when the compiler tries to translate your program into bytecode. The second type are run-time errors, errors that occur when your program is running. For example, if a user enters two values, the second being a zero, and your program is suppose to divide the first by the second, this will cause a run-time error because computers can’t divide anything by zero. In Java run-time errors are also called exceptions, and we’ll see how to deal with them much later. Add numbers Display sum Stop Start Get two values
  • 12. 1-8 Another error that is sometimes only noticed at run-time is a logic error. Logic errors are much more difficult to find and correct because they are caused when you design the actual algorithm incorrectly. Finally, once the program has been debugged and tested for accuracy, it enters the final stage, maintenance. We quickly became aware of the maintenance stage with the Year 2000 problem. We found that many important large programs were still being used even though the original programmers had changed companies or even retired. Once a large program has been implemented and tested, it seems only natural that if any minor modifications are needed, they should simply be added to the original program. Often these minor modifications lead to new bugs and we must debug the code, perhaps make more modifications, debug some more, and so on. Some programs just never end! Skills Check: 1-7. What important component, found in a CPU, controls whether a wire is on or off? 1-8. What advantages do higher level programming languages offer over assembly language and vice versa? 1-9. Write an assembly language program similar to the one found in this chapter but that evaluates 20427 minus 8315. You may use any memory addresses you wish for the program. You should also assume that each assembly language instruction uses one memory location and each of its arguments requires one memory location as in the example given in this chapter. 1-10. What is the difference between a compiler and an interpreter and which does Java use? 1-11. Explain what bytecode is and how it differs from traditional object code. 1-12. Why was Java originally created? 1-13. Describe the five stages of a program's life cycle. 1-14. What is the difference between a syntax error and a logic error and when does each occur? 1-15. Using the assembly language instructions listed in this chapter write a program that calculates 17 * 12.
  • 13. 2-1 Chapter 2 Input and output (I/O) Before we start programming, it is important to clarify a few terms. Firstly, when I talk about input, I mean information moving from somewhere into the computer, or more specifically, the CPU. If information is being typed into the keyboard and therefore being sent into the computer, that information is called input. Likewise, if information is coming from a file on a disk, and going into the computer, that is also called input. The designation of whether information is input or output is relative to the computer, not the peripheral or object sending or receiving the information. This notion will become very important later when we discuss file input and output, more commonly referred to as file I/O. If a printer is receiving information and printing it out, it is called output because the information is going out of the computer. Therefore, output is any information moving from the computer to somewhere else, like a printer, disk drive, or even the monitor. Output from a printer is called a hardcopy but output on a monitor is called a softcopy. Our first program Now it’s time to write our first program. Below you’ll find the program listing for a program that asks the user to enter her name and then welcomes her with the word "Hello" followed by her name. This is a variation of the typical program that most people find in programming books. Most books use a program that doesn’t ask for any user input and simply says "Hello World". I have included the notion of user input because in Java, input from the keyboard is not the simplest thing to do. The reason being that Java was designed more for the Web and therefore graphical input seems to have been the priority. Consequently, we’ll skip over the messy standard keyboard input commands, and use a more graphical keyboard and mouse method. We will revisit the input problem later when we discuss input from files: import javax.swing.*; public class HelloUser { public static void main(String [] args) { String name; name = JOptionPane.showInputDialog("Please enter your name: "); System.out.println("Hello " + name); System.exit(0); } } The above program can be entered using any text editor, but must be saved in a file called HelloUser.java. You can use your favorite editor to enter the Java code but be sure the editor saves it as a text file. If you use your favorite word processor to enter the code, then the previous point becomes very important because, by default, word processors
  • 14. 2-2 don’t save files as plain text. The Windows application Notepad can be used to enter the program but remember it must be saved as HelloUser.java not HelloUser.txt. You must also make sure you name the file exactly as shown with all the letters in their proper case. The H of Hello must be uppercase and so must be the U of User; the rest must all be lowercase. If you haven’t already done so, this might be a good time to check the appendix and install a Java editor. Hopefully, you already have the Java SDK, Software Development Kit, installed on your computer. If not, then definitely take a break now and check the appendix, and install both the SDK and an editor. There are many Java editors and even very elaborate programs that combine editors with other program development tools. An Integrated Development Environment or IDE is a program that usually combines an editor with a compiler and various tools to help you create and debug your program. An IDE can make Java programming easier and faster for knowledgeable programmers. However, this book is an introduction to programming and will assume that you're using a very simple Java text editor to enter your programs. Testing and debugging We have our Java program saved in a file called HelloUser.java, and we have the Java SDK installed on our computer. Now what? We need to translate the Java code, our source code, into machine language, object code. To do this we need a compiler. The Java SDK comes with a compiler called javac. To compile our program, we must go to the command prompt and enter, javac HelloUser.java, and the compiler will create a new file called HelloUser.class that will contain the machine code. However, the machine code will be for the Java Virtual Machine, the Java interpreter, and, therefore, still can’t be directly executed. To run our program, we must enter at the command prompt, java HelloUser. This will run our program. If either the javac or the java command fail, then refer to the appendix regarding the installation of the Java SDK to confirm that the SDK was properly installed. Even if the SDK was properly installed, you could still encounter some problems when you try to compile your Java program. You have now entered the debugging phase. If you didn’t type in the Java code exactly as shown, then there may be one or two syntax errors. Remember syntax errors are the easy ones to fix. You may have forgotten a semi-colon or made a typo. Double-check your code against the listing in the book and resave your program and try compiling it again. If all goes well, you should see something similar to the figure below when you run your program.
  • 15. 2-3 You can enter your name and press enter, or click on the OK button, and the input box will disappear, and the phrase “Hello” followed by whatever you typed-in should appear on the screen. You’ve just written your first Java program and a pretty good-looking one at that. Skills Check: 2-1. Enter and run the program HelloUser. 2-2. Try introducing different errors into the program so that you can become familiar with the error messages the java compiler generates. Try removing a semi-colon or two. Try changing a capital letter to a small one. Try removing one or two braces from the program, the brace is the '{' or '}' character. Analyzing the object oriented code Java is an Object Oriented language. It is a language based on describing things to the computer and associating certain properties and commands with those things. The keyword class is used to indicate that the programmer is about to describe a new thing. A class is like a blue print or template of something that we will later create. When a programmer needs to use something like what is described by a particular class, she makes one or more of those things, and when they’re created, they’re referred to as objects. You can think of a class as the recipe for a cake and the actual cake as the object.
  • 16. 2-4 In the terminology of Object Oriented Programming, the properties of an object are called attributes and the commands associated with it are called behaviours. This is a very simple definition of Object Oriented Programming, or OOP, but it will be expanded upon throughout the book. In our program, we made a class called HelloUser with the line, public class HelloUser {. Whenever you write a program in Java you must make a class. The opening brace, {, indicates the start of our description of the class. There is a corresponding closing brace, }, at the end of our program to indicate the end of our description. Below the, public class HelloUser {, line we have the first behaviour associated with our class. The behaviour is called main. Behaviours are called methods in Java, and are indicated by their name followed by parenthesis, ie. main( ). If the method requires certain information to execute properly, then that information appears between the parenthesis, ie main( String [] args). The open and close braces are then used to enclose the Java statements that belong to the method. We’ll leave the public static void stuff for later, but for now, just know that you must include them as shown. Between the braces of the method, main, are three Java statements. It is important to note that each statement must end with a semi-colon. Forgetting a semi- colon is one of the most common mistakes. Variables The first line in the method, String name;, declares a variable called name. Variables are how we define the attributes of objects in Java. A variable is a block of memory in the computer where we can store information. The computer has millions of these blocks, and to help us use them, we can assign them names. The computer keeps track of matching the name we give a block with its actual memory address, which is just some large number. Good programmers always try to give their variables mnemonic names. A mnemonic variable name is one where the name indicates how the variable will be used. If you were going to use a variable to store the sum of a set of numbers, then a good mnemonic name would be sum. Besides using mnemonic names for variables, there are also some Java rules we must abide by when naming variables or anything else in Java. The names we use for our program class, variables, and later for our methods, are all referred to as identifiers. Identifiers created in Java must begin with either a letter, a dollar sign or the underscore, _, and then can be followed by any number of letters, dollar signs, underscores, and even digits. However, we may not use any of the Java keywords, reserved words, or special values as identifiers.
  • 17. 2-5 Below is a list of the words that may not be used as identifiers. abstract default if private this boolean do implements protected throw break double import public throws byte else instanceof return transient case extends int short try catch final interface static void char finally long strictfp volatile class float native super while const for new switch continue goto package synchronized -const and goto are reserved words while true, false and null are special Java values. When we ask for a memory block, we must also tell the computer what type of information we plan on storing in the memory. This allows the computer to give us a memory block big enough to hold our information. The first line of the main method asked the computer for a memory block big enough to hold information of the type String and to call it name. The String type is used for holding strings. A string is any set of letters, numbers, and symbols, usually enclosed in quotes. For example: “apple”, “111 Somewhere”, and even “3245” are all examples of strings. Objects, packages of them The second line, name = JOptionPane.showInputDialog("Please enter your name:");, is where we tell the computer to get input from the user. The name= part says that whatever the user enters, store it in the memory location that we called name. On the right side of the equal sign, we cause the graphical dialog window to appear with the message "Please enter your name: ". The dialog window is an example of Object Oriented Programming. The creators of Java have made many useful classes for us to use in our programs. The JOptionPane class has the associated method showInputDialog that will display a dialog window for us, and all it needs to know is what we wish the dialog to say. To use a variable or method that is a part of a class, we write the name of the class, followed by a period, and then the name of the variable or method. The second last line of the main method, System.out.println("Hello " + name);, caused the phrase "Hello" followed by the users input to appear on the screen. This is not graphical, but if we wanted to, we could have easily made it so by using the JOptionPane class and one of its other associated methods. This program uses the JOptionPane class to get input from the user and, therefore, the last line, System.exit(0);, is needed to end the program. Whenever your Java program uses JOptionPane you must use System.exit(0) to end your program or it won't end until you press CTRL-C, the break key. That brings us to the very first line of our program, import javax.swing.*;. This line makes the JOptionPane class available to us.
  • 18. 2-6 There are so many classes in Java, and we will eventually make many new ones ourselves, so we need some way of organizing them. This is done using a concept called packages. A package is a group of related classes that are placed together, and whenever you need to use a particular class, you can either import just it, or all the classes in the package that contains it. The package that contains JOptionPane is the swing package, and it is located in the javax directory. The asterisk at the end of the line indicates that we wish to import all the classes in the swing package, and then last but not least, we have the semi- colon. You may be wondering when we’re going to make these things called objects. We made a class called HelloUser and it used a class called JoptionPane, but where were all the objects? This is where the keyword, static, comes in. If a programmer makes a class, and puts the keyword static before a variable or method in the class, then she can use the variable or method of the class without having to first make an object of that class. This little fact makes our life a little easier when programming, but perhaps a little harder when we’re trying to learn about OOP. However, there was at least one object created and it was of type String. It was created when we used the showInputDialog method, and a reference to it was assigned to the variable name. But references and objects being created by methods will have to wait for a later chapter. Be patient and don’t worry about OOP; all its intricacies will be explained in time. That was a lot of explanation for a six-line program, but future examples will have more code and will now require less explanation. Skills Check: 2-3. What is the difference between a hardcopy and a softcopy? 2-4. What is the name of the program that is the Java compiler and what is the name of the interpreter? 2-5. What file extension do Java source files end with and what do Java bytecode files end with? 2-6. What is the difference between a class and an object? 2-7. Whenever we write a program in Java what are we also defining? 2-8. When talking about object oriented programming we often talk about attributes and behaviours. What are these referred to as in Java? 2-9. What are the rules governing the use of identifiers in Java? 2-10. Describe the concept of a package in Java.
  • 19. 3-1 Chapter 3 Variable types There are two kinds of variables: variables for primitive data types, and reference variables. The latter will be discussed in greater depth later on. However, we did already use a reference variable in our first programming example: import javax.swing.*; public class HelloUser { public static void main(String [] args) { String name; name = JOptionPane.showInputDialog("Please enter your name: "); System.out.println("Hello " + name); System.exit(0); } } The variable name was a reference variable. A reference variable is a variable that will refer to an object. Remember that an object is what we get when we make something of a particular class. In this case, the something was an object of the String class, and we used the reference variable name to refer to it. Primitive data types The simplest type of variable is one used with one of the primitive data types. A primitive data type is one that is not a class data type, and essentially denotes a set number of bytes in the computer’s memory that must be reserved for it. We saw in chapter one, that the amount of bits used by a computer dictates the number of patterns that can be represented, and therefore the largest value that can be stored. The formula was 2n - 1, where n was the number of bits. Primitive data types basically tell the computer what is the largest value the programmer may need to store in a particular location of the computers memory. In Java, the primitive data types are: char, byte, short, int, long, float, double and boolean. When you declare a variable of any of these types, the computer reserves just enough memory for you to store exactly one value of that type. It is very important to remember that only one value can be stored at a time in the memory location reserved for the primitive variable. In the table below is a list of the primitive data types, and the number of bytes the computer must reserve for each type, along with an example of the type and possible range of values that can be stored in it.
  • 20. 3-2 Primitive Type Memory Requirement Type of value and range char 16 bits, (2 bytes) -any single character ex: char letter = ‘A’; byte 8 bits, (1 byte) -any integer from –128 to 127 ex: byte num = -43; short 16 bits, (2 bytes) -any integer from –32,768 to 32,767 ex: short num = -43; int 32 bits, (4 bytes) -any integer from –231 to 231 -1 ex: int num = -43; long 64 bits, (8 bytes) -any integer from –263 to 263 -1 ex: long num = -43; float 32 bits, (4 bytes) -any real number from 3.4e-38 to 3.4e+38 ex: float num = (float)3.14; double 64 bits, (8 bytes) -any real number from 1.7e-308 to 1.7e+308 ex: double num = 3.14; boolean Not specified -either the value true or the value false ex: boolean answer = true; As you can see, the amount of memory reserved for a particular data type dictates the range of values it can store. This goes back to Chapter 1 where we discussed the fact that computers use the Binary numbers system, and the number of bits the computer uses dictates the number of different binary patterns that can be formed, and thus the largest number that can be represented. The relationship was that for n bits we could make 2n different patterns, and if we were just looking at positive numbers, then we could represent a number as big as 2n -1. We needed the minus one to take into account that one of the patterns represented zero. In order to deal with negative numbers as well, computers use one of the n bits to indicate if the number is positive or negative, thus we only have n-1 bits for the size or magnitude of the number. Therefore the range of numbers we can represent can only go from –2n-1 to 2n-1 -1. This method is called two’s complement but will not be discussed any further in this book. The computer uses a different method for representing real numbers, but this method also depends upon the number of bits it uses. Therefore, variables of the double data type can store much larger numbers than variables that are declared as float. The boolean data type is not affected by the number of bits used to represent it because it can only have one of two values, and this is possible with as little as one bit — we could use 0 for false and 1 for true. The char data type, which can store a single character, will not be used in the rest of the book, and instead, whenever we need a character or characters, we will use the String data type. This will alleviate some of the confusion when dealing with strings which require double quotes, and single characters which require single quotes, ie ‘x’ versus "x". This is also the recommended course of action by the AP Committee for computer science.
  • 21. 3-3 Furthermore, to adhere to the AP Committee and to emphasize the concepts of computer science as opposed to the Java language, the remainder of this book will use only three of the primitive data types, int, double, and boolean. Primitive variables Remember that variables are just a way of naming memory locations in the computer. This is especially true when dealing with primitive data types. Below is an illustration of how the computer’s memory changes when we declare a variable, and again, when we assign it a value. Declaring a variable is when we ask the computer to set aside memory for us to later store some information in and give that memory a name. Initializing a variable is when we actually place a value into the reserved memory location. Note: only the middle column, the column labeled “Value” actually represents the computer’s memory. The other columns were added so that you can follow along with what’s going on in the computer. Also, the memory addresses in this example were chosen arbitrarily. MEMORY BEFORE JAVA STATEMENTS MEMORY AFTER Variable Value Address int num1; int num2; Variable Value Address 1009 1009 1008 1008 1007 1007 1006 1006 1005 num2 1005 1004 1004 1003 1003 1002 1002 1001 num1 1001 1000 1000 On the left, we see that the computer’s memory is just like a bunch of empty boxes, each large enough to hold one byte of information, ie. 8 bits, or 8 wires that can be on or off. Initially, these boxes may have some value in them, but we don’t know what that value is. When the interpreter sees the line, int num1;, it tells the computer that four bytes are required to store a value, and that the start of that chunk of memory must be called num1, as shown in the table on the right. This is what happens when we declare a variable, and in this case, the computer has reserved the memory locations 1001, 1002, 1003 and 1004. Furthermore, we can now refer to the four memory locations collectively as num1. A similar thing happens when the interpreter executes the second Java statement, int num2;. Now we have two chunks of memory each big enough to hold a single integer value, four bytes.
  • 22. 3-4 The next table shows us how memory changes when we store a value in each of these chunks. This is where we initialize the variables. Remember initializing a variable is when we place an initial value in the memory reserved for the variable. JAVA STATEMENTS MEMORY num1 = 3; num2 = 7; Variable Value Address 1009 7 1008 1007 1006 num2 1005 3 1004 1003 1002 num1 1001 1000 When we assign a value to a variable, it is placed in the chunk of memory associated with that variable and is actually stored as a group of bits. In the case of integers, four bytes, the equivalent of 32 bits, are used, and the number three for example would be stored as, 000000000000000000000000000000112. That’s 30 zeros followed by 2 ones; you can see why I chose to simply write it in decimal in the table. However, always remember that all things are stored in the computer using bits. Also, always remember that only one value can occupy a primitive variable at any given time. If we initialize a variable and then later in our program try to assign it a different value the new value will replace the previous one and the previous one will be lost. Below is a small program that uses int variables and demonstrates how to store a value in a variable, and how to use arithmetic operators to manipulate a value in a variable. public class Numbers { public static void main(String[] args) { int num1; num1 = 5; int num2 = 2, sum; sum = num1 + num2; System.out.println(sum); int answer; answer = num1 / num2; System.out.println(answer); } } For the above program we don’t need to import any special packages. All the Java functionality we need is automatically provided for us.
  • 23. 3-5 Certain Java classes are used so frequently that the Java compiler always makes them available. The program starts by defining a new class. The class is called Numbers and it contains one method called main. The main method starts by declaring a variable called num1 that can store one integer. At this point, the computer reserves enough memory — four bytes — and calls this chunk of memory num1. However, the computer does not set the contents of num1 to zero, and so at this point the value stored in num1 is something, but we don’t know what. Since num1 has some unknown value in it, we initialize it by storing the number five in it on the next line. Next, two more variables of type int are declared. The variable sum is similar to the variable num1 but when num2 is declared, the value two is also placed into the memory chunk labeled num2. Often programmers will combine the declaration and initialization of a variable on the same line. Next, we assign the variable sum a value but this value is the sum of the two other variables. Hence, the value seven will be stored in sum and consequently be displayed on the screen when the next line executes. All the common math operators are available in Java, +, -, /, and * for multiplication. The next three lines declare another variable, answer, and assign it the quotient of the first two variables, and then unexpectedly displays the value two. Usually, when we divide five by two we get 2.5, not two, but 2.5 is not an integer answer. The variable we’re trying to store the quotient into, is an int type variable. Consequently, Java truncates the .5 and stores just the two into answer. Even more interesting is the fact that if answer had been declared as a double instead of an int, the program would still display two and not 2.5. The reason is that both num1 and num2 are ints and Java always truncates quotients if the values on both sides of the division sign are integers. Skills Check: 3-1. What is it that primitive data types essentially ask the computer to do. 3-2. Write a program that evaluates 20427 minus 8315. Use the integer variables, n1 and n2, and assign to each variable one of the values. Store the result of the calculation in the integer variable, answer, and display the result. 3-3. Write a program that evaluates 27832 divided by 3. Use three integer variables to represent the arguments and the result, and display the result. Your program should then also perform the same calculation but using three double variables and display the result. Why are the two answers different? Input and output (I/O) Programs have limited usage if they cannot interact with a user — the person who has run the program. Output is the term used when information travels from the CPU out to somewhere else, like the monitor, perhaps to enable the user to see the result of a calculation. Input refers to information entering the CPU, perhaps resulting from the user typing something on the keyboard. In our first code example, we received input from the user via the keyboard, namely their name, and sent output to the monitor to greet them.
  • 24. 3-6 The input received by the computer was treated as a String, a sequence of characters. However, a String is not a primitive data type, and unfortunately, if we use the Java class JOptionPane to get input from the user, we always get the input returned to us as a String. Luckily, Java provides us with several classes, one for each primitive data type that will convert a String into a primitive value, if possible. Below is a program that gets two integers from the user and displays the average value. Remember that integer division always truncates or rounds down the result, so we’ll need to tell the computer that we definitely want the result to be calculated as a double. import javax.swing.*; public class Average { public static void main(String[] args) { int num1, num2; String value; value = JOptionPane.showInputDialog("Enter first value: "); num1 = Integer.parseInt(value); value = JOptionPane.showInputDialog("Enter second value: "); num2 = Integer.parseInt(value); double avg; avg = (double) (num1 + num2) / 2; System.out.println(“The average is ” + avg); System.exit(0); } } In the above example, we declared a total of three primitive variables and one reference variable, value. We used value to get the first integer entered by the user, and then we used the Java class Integer and its method parseInt to extract the int value from the String type variable and assign it to num1. We then did the same thing for the second integer, but assigned its int value to num2. The third primitive variable, avg, for average, was assigned the resulting average of the two numbers. The average was calculated by adding the int value stored in the memory location referred to as num1 to the value in num2. The sum was then converted to a double and then divided by 2 resulting in a double type value of 2.5. The line System.out.println, was then used to output the value stored in the variable avg, to the screen, along with some user-friendly information. The first important thing to note in the previous example was the way we could extract primitive type data from a String type variable using Integer.parseInt or Double.parseDouble. The second is how we can force a calculation involving integers to be done, as a double, by placing the word double enclosed in parenthesis in the calculation. However, the Java syntax: (double)(num1 + num2), may look as though we’re multiplying double by the result of num1 and num2 but this is completely incorrect. In fact, Java and most other languages require you to use the asterisk to indicate multiplication in calculations and will generate a syntax error if you wrote something like this, ans = 3 (num1 + num2 ), or, ans = (a + b) (c +d).
  • 25. 3-7 Skills Check: 3-4. Write a program that gets an integer from the user and displays double its value. Then your program should reuse the variables you already declared and get another integer from the user but display half its value. 3-5. Write a program that gets two integers, num1 and num2, from the user and displays their product. 3-6. Write a program that gets 3 real numbers from the user, a, b, and c, all doubles, and calculates and displays the result of the expression (a + b) / c. Fancy printing If you'd prefer the output of your program had a similar appearance to the input then you can use the JOptionPane.showMessageDialog method. The output of the Average program above could have been written as follows: JOptionPane.showMessageDialog(null, “The average is ” + avg); The showMessageDialog method works similarly to the showInputDialog method except that it doesn't allow the user to type any information it just displays information. It must also have the Java value null placed before the string to be displayed and only strings can be displayed. If you want to display a number by itself then you have to place two quotes with nothing between them followed by a plus sign before the number. For example to display avg by itself you would type: JOptionPane.showMessageDialog(null, “” + avg); Whether you use the showMessageDialog method or the println method to display text you may wish to display several lines of text at once. You can display several lines of text at the same time by placing the escape sequence "n" between each string to be displayed. Below is an example using the showMessageDialog method with its corresponding output. JOptionPane.showMessageDialog(null, “Thenaveragenisn” + 5/2);
  • 26. 3-8 You may also need to print answers to calculations using a specified number of digits after the decimal point or perhaps print answers as monetary values. Java provides a special class called NumberFormat that can help you format your numbers when you output them. The program FancyOutput listed below shows how you can print an answer to at most three decimal places with the method setMaximumFractionDigits and also how to display an answer as a dollar value. import javax.swing.*; import java.text.*; public class FancyOutput { public static void main(String[] args) { int num1, num2; num1=5; num2=3; double answer; answer = (double) num1/num2; JOptionPane.showMessageDialog(null, "The answer is " + answer); NumberFormat nf; nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(3); System.out.println(num1 + "/" + num2 +"=" + nf.format(answer)); nf=NumberFormat.getCurrencyInstance(); System.out.println("The monetary answer is " + nf.format(answer)); System.exit(0); } } The output of the above program is: 5/3=1.667 The monetary answer is $1.67
  • 27. 3-9 The program must first get a NumberFormat object with the line: NumberFormat nf; nf = NumberFormat.getNumberInstance(); However, to use NumberFormat classes we must tell the computer to include the package java.text.*. You can import as many packages of classes as you need for your program. The program then uses the method setMaximumFractionDigits to ensure that at most three digits will be displayed after the decimal. If you wanted at least three digits you could use the method setMinimumFractionDigits to specify that as well. Next, the method format is used to actually create a string that uses the numeric answer but is formatted the way we want. To display a dollar value we must get a NumberFormat object with the line: nf = NumberFormat.getCurrencyInstance(); However, for dollar values all we need to use is the format method to create a string with the number formatted the way we want. This is accomplished with the line: System.out.println("The monetary answer is " + nf.format(answer)); Commenting your program As our programs get longer, and especially if we work in a group on a particular problem, then commenting or documenting a program becomes very helpful. To comment a program means to write a line or lines of text that are ignored by the computer but are meant to be helpful to other programmers who may read the code of your program. Java provides two methods for commenting a program. The characters, //, are used to indicate a single line comment is beginning, and the characters, /*, and, */, are used to enclose a multi-line comment. The Average program may have been commented as follows: /* A program that gets two integers from the user and displays the average of the two with the precision of arithmetic using the double data type. */ import javax.swing.*; public class AverageDocs { public static void main(String[] args) { int num1, num2; //the first and second integers String value; //temporary variable to hold users input value = JOptionPane.showInputDialog("Enter first value: "); num1 = Integer.parseInt(value); //convert String type to int value = JOptionPane.showInputDialog("Enter second value: "); num2 = Integer.parseInt(value);
  • 28. 3-10 double avg; //average of two integers entered by user avg = (double) (num1 + num2) / 2; System.out.println("The average is " + avg); System.exit(0); } } As you can see, commenting can make programs a lot easier to read and understand. Skills Check: 3-7. Write a program that gets the subtotal of a restaurant bill from the user and then calculates the final total of the bill including a 15% tax. 3-8. Write a program that asks the user to enter the radius of a circle and then displays the circumference of the circle with at most one digit after the decimal. Note: C = 2 * PI * RADIUS and PI = 3.14. 3-9. Write a program that asks the user to enter how much the food portion of the bill comes to and calculates 15% tax on it. It then asks the user to enter how much the beverage bill comes to and calculates 12% tax on it. Finally it prints the grand total including the food, beverages and taxes.
  • 29. 4-1 Chapter 4 Simple repetition One of the reasons computers were created was so we wouldn’t have to perform repetitive tasks. It makes sense, therefore, that one of the first things we should learn to do is create a program that can perform a repetitive task. A loop is used to repeat a statement or block of statements, and by block of statements, I mean Java statements enclosed in a pair of braces as shown below. There are basically two types of loops: conditional loops and counted loops. In this chapter, we’ll discuss conditional loops; loops that continue while a particular condition evaluates to true. A Java keyword that indicates that a statement or block of statements must be repeated is while. The format looks like this: while ( condition ) { Java statement; Java statement; } The keyword while is followed by a condition, enclosed in parenthesis, and then an open brace, {, and one or more Java statements followed by semi-colons and finally a close brace, }. The loop will continue to repeat as long as the condition evaluates to the boolean value of true. Consequently, if we wanted an infinite loop, a loop that repeats forever, we could replace the condition with the special Java value true. Below is an example of an infinite loop that repeatedly displays the word "apple" on the screen until the user presses CTRL-C. The keyboard combination CTRL-C is the break key and asks a Java program to stop executing. while ( true ) { System.out.println("apple"); } Infinite loops are generally not very useful. Usually the condition is an expression that consists of a variable, a comparison operator, and either a value or another variable. If the comparison between the two things evaluates to true, then the loop repeats.
  • 30. 4-2 There are several comparison operators in Java as shown in the table below. Operator Description == -evaluates to true if both operands are equal != -evaluates to true if the operands are not equal < -evaluates to true if the operand on the left is less than the one on the right > -evaluates to true if the operand on the left is greater than the one on the right <= -evaluates to true if the operand on the left is less than or equal to the one on the right >= -evaluates to true if the operand on the left is greater than or equal to the one on the right Some examples of conditions are: A) num < 5, would result in true if the value in the variable num was less than 5. B) num == num2, would result in true if the value in both variables was the same. Note: the == operator for checking to see if two primitive values are the same is often confused with the = operator used for assigning a value to a variable. In some languages this can lead to very odd behaving programs, so always double check your comparison operators when making a condition that checks for equality. C) num != num2, would evaluate to true if the values in num and num2 were different. Also note that the previously mentioned comparison operators only work as described when dealing with primitive data types. They behave a little differently when comparing reference type variables. Below is a program that gets positive integers from the user, and outputs the square of the number entered. It stops when the user enters a negative number. Therefore, a negative number is used to signal that the user is finished her input, and when we use a value to indicate the end of a set of input, it is called a sentinel. In this case, the sentinel value is fixed at anything less than zero, and will not change at any time while the program is executing. If a variable is going to keep the same value throughout a program, then we can use what is called a constant to represent it. We indicate that a variable’s value will remain constant by using the Java keyword final and placing it before the variable’s declaration as shown below with the constant minValue. Note: the constant’s value does not have to be immediately assigned to it, but once any value has been assigned to a variable declared as final, then its value cannot be changed.
  • 31. 4-3 import javax.swing.*; public class WhileSquares { public static void main(String[] args) { int num, squareNum; final int minValue = 0; String value; value = JOptionPane.showInputDialog("Enter an integer: "); num = Integer.parseInt(value); while (num >= minValue) { squareNum = num * num; System.out.println("The square is " + squareNum); value = JOptionPane.showInputDialog("Enter an integer: "); num = Integer.parseInt(value); } System.out.println("The End! "); System.exit(0); } } The above program uses what’s referred to as a seeded while loop. A seeded while loop is a loop that repeats as long as a particular condition is true and the condition depends on a particular variable, called the seed. The seed is given a value just before the loop begins. In the above case, num, is the seed and it is given a value by the user. Generally, the seed is also given a value again at the end of each repetition of the loop, that way the seed has a new value each time the loop repeats. In our program, the user enters a value for num and then we compare it to the value zero. If num is greater than or equal to zero, then the loop executes. Namely, it calculates the square of the number and outputs it. Next, it gets a new value for the seed, num, and then jumps back to the top of the loop and tries to repeat the loop by first checking the condition of the loop. If the new number entered is greater than or equal to zero, then the loop repeats again. If it is negative, then the loop ends and the program outputs, "The End! ". The use of the constant minValue in the above program also helps us to write code that doesn’t use magic numbers. If the condition of the while loop had been written as, (num >= 0), then the 0 would be an example of a magic number. Magic numbers are numbers that can sometimes be found in loops, calculations, or other parts of a program. The use of magic numbers, especially ones that repeat in several parts of a program, make modifying programs very difficult, and it is recommended that you use constants instead. If you use constants, then the magic number only has to be changed in one spot. Skills Check: 4-1. Define a conditional loop. 4-2. What is a seeded while loop and what part does a sentinel value play? 4-3. What is the difference between a variable and a constant?
  • 32. 4-4 4-4. Write a program that gets negative integers from the user and displays their absolute value, their positive value. Your program should end when a positive number is entered. 4-5. Write a program that gets pairs of numbers from the user and displays their product. The program should end if the first number the user enters is negative. Accumulators One of the most common tasks computers perform in a loop is to add up, or accumulate values. We may wish to have the user enter several positive values and then output the sum of those numbers. An accumulator is a variable that changes with each repetition of a loop. An accumulator might change by a constant value each time the loop repeats, or perhaps by a varying value entered by the user. For example, the code below uses an accumulator, total, to calculate the sum of several positive values and displays the sum when the user enters a negative number. Here again, a negative number is used as our sentinel, or signal, to end the loop. import javax.swing.*; public class Accumulate { public static void main(String[] args) { double num, total; total = 0; String value; value = JOptionPane.showInputDialog("Enter a number: "); num = Double.parseDouble(value); while (num >= 0) { total = total + num; value = JOptionPane.showInputDialog("Enter a number: "); num = Double.parseDouble(value); } System.out.println("The sum is " + total); System.exit(0); } } The accumulator in the previous program was total and it is always best to assign an accumulator a starting value. If you don’t, then your accumulator may start at some unpredictable value and thus result in a very strange and wrong value. Let me re- emphasize this point: Always assign your accumulators a starting value. In our program, total is assigned the starting value zero, and then the user is asked for her first input. If she enters a value greater than or equal to zero, then the loop executes. The first thing that happens in the loop is that the value of total is changed. The accumulator is assigned the value of what it currently is set to — zero — plus the value that the user just entered. An expression where the variable on the left side of the equal sign also appears on the right side of the equal sign, is a perfect indicator that the variable on the left is an accumulator. Next, another value is gotten from the user, and the program jumps back to
  • 33. 4-5 the top of the loop. If the new value is greater than or equal to zero, then the loop repeats again and the new value is added to the accumulator. Short-cuts Accumulators occur very frequently in programs, so frequently in fact, that many languages offer short-cuts for statements involving accumulators. If total is an accumulator and you wish to add the value of the variable num to it, you can usually write, total = total + num;. The Java short-cut to accomplish the same result is: total += num;. The short-cut allows us to avoid repeating the name of the accumulator variable, and consists of the operator we wish to use followed by the equal sign. If we wish to multiply our accumulator by two each time a loop repeats, we can either type, total = total * 2;, or total *= 2;. The short-cuts work with all the math operators, +, -, *, /, and a special one, %. The % operator, or modulus or mod operator, is used when we wish to know the remainder after dividing two values. For example, if num were an integer variable, then the statement, num = 7 % 2;, would result in num being assigned the value one because two goes into seven three times, with one as the remainder. The short-cut operation for mod is, num %= 2;. The mod operator can also be used to determine if an integer is even or odd. Even numbers leave no remainder when divided by two, and odd numbers always have a remainder of one or negative one when divided by two. Below is a program that gets even numbers from the user and eventually displays their sum. The program repeats as long as the user enters even numbers. import javax.swing.*; public class EvenHalf { public static void main(String[] args) { double num, total; total = 0; String value; value = JOptionPane.showInputDialog( "Enter an even number to continue: "); num = Double.parseDouble(value); while (num % 2 == 0) { total = total + num; value = JOptionPane.showInputDialog( "Enter an even number to continue: "); num = Double.parseDouble(value); } System.out.println("The sum is " + total); System.exit(0); } }
  • 34. 4-6 It is interesting to note that the modulus operator in Java doesn’t require both operands to be integers as some other languages do. This is interesting because the math — Modulo Arithmetic — which uses this operator, is defined only over the set of integer numbers, not the real number set. Another pair of special operators are ++ and its opposite, —-. One of the most frequently occurring accumulation expressions has the form, total = total + 1;, or total += 1;. Therefore, an even shorter short-cut was devised for it, total++;. The expression, total++;, tells the computer to increase, or increment, the variable total by one. It is called the “increment” operator. The “decrement” operator is used when we wish to decrement a variable by one, total--;. That’s all, there are no more short-cuts and no, you can’t use expressions like, total+++;, if you wish to increase it by two. The increment and decrement operators only increase or decrease a variable by exactly one. However, to make life more interesting, the increment and decrement operators behave differently when placed before a variable as opposed to after one, but only when that variable is used as part of a bigger calculation. Basically, we’ve been looking at the post-increment and post-decrement operators, but there are also the pre-increment and pre-decrement operators. In the code below, the variable ans is assigned the value 16, not 17 as you may expect, because the current value of num1 is first used in the calculation before the variable num1 itself is incremented. This is an example of the post-increment operator used as part of a bigger calculation. int ans = 0, num1 = 3; ans = 13 + num1++; After these two lines are executed, ans will equal 16 and num1 will equal 4. But if the second line had read, ans = 13 + ++num1;, then ans would equal 17 and num1 would still equal 4. You can see how intermixing pre- and post-increment and decrement operators can make calculations harder to follow. Consequently, the rest of this book will always uses the post-increment and post-decrement operators, and never as part of a bigger calculation, so as to avoid confusion and to further stress computer science topics as opposed to language specific ones. Skills Check: 4-6. Write a program that repeatedly asks users how old they are and if a user is under nineteen says, “You’re eligible for a student I.D.”, but the programs ends and says, “You’ve Graduated! Goodbye”, if a user is nineteen or older. 4-7. Write a program that asks the user to enter a number and then prints it’s square. The program should do this repeatedly until the user enters zero. 4-8. Write a program that prints the 17 times table from 17 * 1 to 17 *12. The output should be 1 * 17 = 17, 2 * 17 = 34, etc. 4-9. Write a program that gets positive numbers from the user and when a negative number is entered displays the average of the numbers entered.
  • 35. 4-7 4-10. Write a program that displays a rocket countdown from 10 to 1 and then displays “Blast Off!” 4-11. Write a program that gets two numbers from the user, a and b, you may assume that a<b. It then prints the squares of all the numbers in the inclusive range [a, b]. Random and math classes Besides the Java keywords, there are many commands that can be very useful. These commands, often referred to as methods, belong to special classes. A class can be used to group several related commands together, and can be thought of as a template or blueprint of how to make something. There is a class called Math that contains methods for doing special mathematical operations such as the square root of a number, or the sine or cosine of an angle, etc. There is even a class called Random, that contains methods for generating random numbers. However, to use the methods in a class you usually must first make an object of that class, and that means using a reference variable. A Random object can be made as follows: Random myNums; myNums = new Random( ); The first line declares a reference variable that will refer to an object of the Random class, and the second line creates a Random object and makes the variable, myNums, refer to it. The two lines are often combined as follows: Random myNums = new Random( ); The keyword new asks the computer to create an object of a particular class, in this case the Random class, and the assignment operator makes myNums refer to the newly created object. To print a random integer you can use the nextInt method like this: int num = myNums.nextInt( ); System.out.println( num ); Every time you use the nextInt method, you would get a different random integer; it could even be a negative one. The Random class is part of the java.util package and you must import it, with the import keyword, in order to use it. However, the Math class is different from most classes in Java probably because it is used so often. It is automatically imported, and the designers of Java designed the Math class so that it can, and must, be used without using a reference variable. To use any of the methods belonging to the Math class you simply type Math followed by a period and the name of the method you wish to use. For example to use the method that does exponentiation, like three to the fifth power, you could type: double num = Math.pow(3, 5);
  • 36. 4-8 Here are a few of the methods that belong to the Math class: Method Explanation Math.abs( a ) Returns the absolute value of a Math.pow(a,b) and Math.sqrt(a) Returns a double representing the value of ab and the square root of a respectively. Math.sin(rad), Math.cos(rad), Math.tan(rad) Returns a double representing the sine, cosine, or tangent of the radian value rad Math.asin(a), Math.acos(a), Math.atan(a) Returns a double representing the angle whose sine, cosine, or tangent is represented by a Math.ceil(a) Returns a double representing the smallest integer greater than or equal to a Math.floor(a) Returns a double representing the largest integer smaller than or equal to a Math.round(a) Returns an int or long rounded to the nearest integer This program displays ten random numbers between 10 and 99, inclusive, along with their square root and cube. Unfortunately, the nextInt method usually gives us an integer in the range [–231 , 231 -1], an integer approximately between negative two billion and positive two billion. Fortunately, the nextInt method allows us to optionally state how many numbers are in the range we're interested in. For example, if we wanted numbers in the inclusive range [1, 6], which has six numbers, then we could say nextInt(6) and nextInt(6) would give us a random number in the range [0, 5]. To change the range [0, 5] to the desired range of [1, 6] all we have to do is add one to whatever value nextInt(6) gave us. If we wanted numbers in the inclusive range [5, 9], which has five numbers, then we could say nextInt(5) and nextInt(5) would give us a random number in the range [0, 4]. To change the random number from the range [0, 4] to the range [5, 9] all we have to do is add five to the number nextInt(5) gave us. Generally, if we want a random number in the inclusive range [low, high] then we can calculate the amount of numbers in the range with the formula: amount = high - low + 1; Consequently, nextInt(amount) will give us a number in the range [0, amount-1] and to convert that number to the range [low, high] we simply add the value of low to the number. import java.util.*; public class RandomMath { public static void main(String[] args){ int n = 10; final int high=99, low=10; System.out.println("Here are "+ n + " random integers and their roots and cubes");
  • 37. 4-9 Random randNum = new Random(); int num; int amount = high - low + 1; while(n > 0) { num = randNum.nextInt( amount ); num += low; System.out.print(num + " "); System.out.println(Math.sqrt(num) + " " + Math.pow(num, 3)); n--; } } } Skills Check: 4-12. Write a program that simulates the rolling of a single die. The program should display a random value in the range [1, 6]. 4-13. Write a program that randomly chooses a number from one to ten and then asks the user to guess which number was chosen. Your program should also count how many guesses the user takes. 4-14. Write a program that repeatedly displays positive random integers but stops as soon as an odd integer is generated. It should then display how many even numbers were generated before the first odd one occurred. Run your program several times and see what’s the longest string of even numbers you can generate. 4-15. Many cities have lotteries where a person can try to guess which six numbers chosen from the range [1, 49] will occur the next time the lottery is held. Write a program that asks the user how many lucky numbers she’d like and then prints that many random numbers in the range [1, 49]. Don’t worry if the set of random numbers contains duplicates. 4-16. Write a program that gets a double from the user and prints its value to the first, second, third, fourth, fifth, etc, all the way to the fifteenth power.
  • 38. 5-1 Chapter 5 String accumulators Adding up primitive values using accumulators is very useful, but what about reference variables. Remember, a reference variable is a variable that will refer to an object, and that an object is what we get when we make something of a particular class usually using the new keyword. In this case the something is an object of the String class. The class is the template or description of a string, and the object is what we get when we actually make a string. Reference variables are different from variables for primitive data types like int or double. A reference variable is given a memory location large enough to place a reference to another chunk of memory where the actual object is stored. Therefore, when we make a String type reference variable, the memory location given to us does not, and will not actually, contain the string data we wish to store in it. It will however, refer to another location in memory where the string data will be stored as part of a String object. We say “will”, because when you declare a reference variable, it doesn’t automatically refer to anything. This is important to understand because it means that initializing our String type accumulator to a starting value is extremely important. In fact, if we used the following declaration, String sent; and then tried to use sent as an accumulator, the Java compiler will complain and output, “variable sent might not have been initialized”. We must set sent to a value, and if we wish it to be zero, then we use "", a pair of quotes with nothing between them, often referred to as the null string. The null string is not to be confused with the Java keyword null which can be assigned to a reference variable when it is declared to indicate that it definitely doesn’t refer to anything yet. Strings accumulate differently from numbers. A string accumulator simply appends new strings to the end of its current string value. The joining of two strings together is called string concatenation. Below is a program that gets strings from the user until she enters the string “2Q8”. When she enters “2Q8”, to quit, the loop ends and all the letters she entered are displayed on the screen. A string accumulator is used and is initialized to "", zero. Also note that the condition for the while loop does not make use of any of the comparison operators that were used with int or double. The String class provides us with a method called equals that compares the current string value reference by the String variable to another string value. However, we wish the loop to stop when the two strings are not equal, and that’s what the, ! operator, or logical-NOT operator, does. The exclamation mark means NOT in Java. The while loop thus reads, while the letters entered by the user are not equal to "2Q8", continue.
  • 39. 5-2 import javax.swing.*; public class StringAccumulate { public static void main(String[] args) { String sent; String letters; sent = ""; letters = JOptionPane.showInputDialog("Enter a word: "); while (! letters.equals("2Q8")) { sent = sent + letters; letters = JOptionPane.showInputDialog("Enter a word: "); } System.out.println("The sentence is " + sent); System.exit(0); } } When you run the above program, all the letters entered by the user will be very close together. The string accumulator joins each new string together to the old ones without placing any additional spacing between them. A modification to, sent = sent + letters;, to make the output more readable could be, sent = sent+letters + " ";, where we append an additional space after each word. Yes, we could also use the short- cut, sent += letters + " ";. Once we’ve accumulated a string, we may also wish to know how many characters it contains. The String class provides us with a method called length for this purpose. The length method gives us an integer that represents how many characters are stored in the String object referenced by our String reference variable. For example the following code snippet would assign the variable num the value 10, nine for the letters in the persons first and last name and one for the space between them. String name = "Gary Singh"; int num = name.length( ); //num = 10 You can then use num wherever you would normally use an integer variable, perhaps to calculate the average word length of the words the user entered earlier. You would need an accumulator to count how many words the user entered, and one to calculate the sum of all the lengths of the words she entered.
  • 40. 5-3 Skills Check: 5-1. Write a program that gets words from the user until she enters “2Q8” and each time prints the word just entered followed by all the words previously entered. For example: Enter a word: Apple Apple Enter a word: Cat CatApple Enter a word: Dogs DogsCatApple Enter a word: 2Q8 5-2. Write a program that gets words from the user until she enters “That’s All!” and each time displays a letter count of the word. For example: Enter a word: Apple 5 Enter a word: Cat 3 Enter a word: Dogs 4 Enter a word: That’s All! 5-3. Write a program that gets words from the user until she enters “All Done” and then calculates and displays the average letter count for all the words. For example: Enter a word: Apple 5 Enter a word: Cat 3 Enter a word: Dogs 4 Enter a word: All Done The average letter count is 4. i.e. (5 + 3 + 4) / 3
  • 41. 5-4 Searching strings The use of the JOptionPane class to get input for our programs allows us to get lines of text as input from the user. We may wish to search through a line of text to see if it contains a particular word. The String class provides a method called indexOf for this very purpose. The indexOf method searches through a String object for a specific string pattern and returns an integer that denotes the start of where in the string the first occurrence of the pattern was found. However, the integer that represents the location or index of the start of the pattern will be one less than what we would expect. The character positions in a string are numbered from zero. The first character in a string is at position zero, the second at position one, and so on. We’ll see much later that this type of indexing is used with arrays as well, and most likely is based on a technique called pointer arithmetic that was used in the C programming language. Here is a simple program that highlights the use of the indexOf method. import javax.swing.*; public class StringFind { public static void main(String[] args) { String sent; sent = "An apple a day keeps the doctor away."; int pos; pos = sent.indexOf("apple"); //pos now equals 3 System.out.println("In the phrase, " + sent); System.out.println("apple can be found after position " + pos); pos = sent.indexOf("e"); //pos now equals 7 System.out.println("and e can be found after position " + pos); } } For the line, pos = sent.indexOf("apple");, pos is assigned the value 3 because the "a" of "apple", which was the pattern we were searching for, is the fourth character in the string, "An apple a day keeps the doctor away. ". Similarly, for the line, pos = sent.indexOf("e");, pos is assigned the value 7 because the letter "e", the pattern we were searching for, is the eighth character in the string sent. Note that even if we repeated the line, pos = sent.indexOf("e");, pos would be assigned the value 7 and not the value 16 which is the location of the next "e" in the string sent. The method indexOf always returns the integer corresponding to the start of the first occurrence of the pattern within the string. Substrings We used accumulator variables to add numbers together and to join or concatenate strings. The opposite of concatenating strings is breaking a string up or working with a piece of the string. A piece of a string is called a substring. The String class provides a method called substring to get a piece of a string. The substring method returns a
  • 42. 5-5 new string consisting of all the characters from a particular position all the way to the end of the original string. The program below is similar to the StringFind program listed above also remember the first character of a string is at position zero, not one. import javax.swing.*; public class StringPiece { public static void main(String[] args) { String sent; sent = "An apple a day keeps the doctor away."; String words; int pos; pos = sent.indexOf("apple"); //pos = 3 now System.out.println("In the phrase, " + sent); words = sent.substring(pos); //words = "apple a day keeps the doctor away." System.out.println("the substring starting with apple is " + words); pos = sent.indexOf("e"); //pos = 7 now words = sent.substring(pos); //words = "e a day keeps the doctor away. " System.out.println("and starting with e is " + words); } } As in the previous program, the line, pos = sent.indexOf("apple");, causes pos to be assigned the value 3 because the "a" of "apple", which was the pattern we were searching for, is the fourth character in the string, "An apple a day keeps the doctor away. ". The next line, words = sent.substring(pos);, causes the variable words to be assigned the substring starting from index 3, which is the fourth character, all the way to the end, i. e., "apple a day keeps the doctor away. ". Skills Check: 5-4. Write a program that gets a sentence from the user and then a word from the user and tells her where in the sentence the word can be found. 5-5. Write a program that gets a word from the user and an integer position and prints all the letters that come after that position in the word. 5-6. Write a program that gets a word from the user and prints all the letters from the middle to the end of the word. Ex: apple would output ple and applejacks would output jacks.
  • 43. 5-6 Advanced searches and substrings The indexOf method is very useful for telling us the location of the first occurrence of a particular pattern. However, what if we wish to find the location of a second or third instance of the pattern. The indexOf method can be used with an optional integer indicating where the computer should start searching for the pattern. For example, if you wished to search for the word "apple" in the second half of a String variable called sent, you could type something like this: int middle = sent.length() / 2; int pos = sent.indexOf("apple", middle); If you wanted to see if the string stored in a variable called pat occurred a second time in the variable sent you could use the following lines of code: int pos; pos = sent.indexOf(pat); pos = sent.indexOf(pat, pos+1); When the last line executes it would have the location of the second instance of the pattern within sent or -1 to indicate that a second instance of the pattern didn't exist. Below is a small program that uses the optional starting position with the indexOf method to count how many times the letter "e" occurs in the variable sent. public class CountEs { public static void main(String[] args) { String sent = "Hello Joe, John's gone home."; int count = 0; int pos; pos = sent.indexOf("e"); while(pos != -1) { count++; pos = sent.indexOf("e", pos+1); } System.out.println("There are " + count + " e's in the sentence: " + sent); } } The substring method also has an alternate format. You can not only specify the start of a substring but its end as well. Note: When you specify the end of a substring the character at that position is not included in the substring. The substring goes from the starting location up to but not including the ending location.
  • 44. 5-7 For example, the following lines of code would print John' not John's. String sent = "Hello Joe, John's gone home."; String word; word = sent.substring(11, 16); System.out.println(word); //John' Below is a program that demonstrates the use of indexOf and substring with and without their optional positional values. Comments are included to indicate the resulting values produced by the program. public class SubAndIndexExtras { public static void main(String[] args) { String sent = "Hello Joe, John's gone home."; String word; //substring(start, end) but end not included! word = sent.substring(11, 17); System.out.println(word); //John's int pos; pos = sent.indexOf("Jo"); // Joe, John's gone home System.out.println(sent.substring(pos)); pos = sent.indexOf("Jo", pos+1); System.out.println(sent.substring(pos)); //John's gone home } } Skills Check: 5-7. Write a program that gets words from the user until she enters “2Q8” and each time prints only the first and last letter of the word. 5-8. Write a program that gets a word from the user and then prints it backwards on the screen. For example, if the user entered apple, the computer would print elppa 5-9. Write a program that gets a sentence from the user and then tells her how many words are in the sentence. You may assume that there is exactly one space between each word in the sentence that the user entered. 5-10. Write a program that gets words from the user until she enters “L8R” and each time prints only the middle letter of the word. 5-11. Write a program that gets a word from the user and prints each letter of the word on a separate line. 5-12. Write a program that gets words from the user and as long as the word has four or more letters prints the second and second last letter of the word. If it has less than four letters then the program ends. 5-13. Write a program that gets words from the user until she enters “2Q8” and each time prints a letter at a random position in the word. 5-14. Write a program that gets a sentence from the user and then a word and tells her how many times the word appears in the sentence.
  • 45. 5-8 String tokens Whenever we use the showInputDialog method to get input from the user, we receive the input as a single string. If we had a program that calculated the average of three numbers, we would have to use the showInputDialog method three times, once for each number. However, for convenience, a user may wish to enter all three numbers at once and just type a space between each number. We would then have to use the indexOf and substring methods to break the string up into pieces or tokens. A token is anything separated by a delimiter. A common delimiter is a space, and often a comma. Breaking a string up into tokens is a fairly common occurrence, and to simplify this process, Java has a class called StringTokenizer. The StringTokenizer class is also part of the java.util package. It takes a string and a delimiter and then provides several methods that help to return individual tokens from the string. When the StringTokenizer object is made, the programmer specifies the string to use and which delimiter to use. She can then use the methods hasMoreElements and nextToken to process the string. The hasMoreElements method returns true if there are any tokens left in the string and the nextToken method returns the next token as a String object. You can think of a StringTokenizer object as a cookie jar and the tokens as cookies. Once the cookie jar is created you can check if there are any cookies in the jar by using the method hasMoreElements. If there are more cookies in the jar you can remove one with the method nextToken. Below is a program that gets several words from the user, all at once, and then displays each word on a separate line on the screen. import javax.swing.*; import java.util.*; public class StringTokens { public static void main(String[] args) { String input; input = JOptionPane.showInputDialog("Enter several words: "); StringTokenizer st = new StringTokenizer(input, " "); String word; while (st.hasMoreElements() ) { word = st.nextToken(); System.out.println(word); } System.exit(0); } }
  • 46. 5-9 Skills Check: 5-15. Write a program that gets a sentence from the user and then prints each word of the sentence on a separate line. Ex: Apples are good for you. Apples are good for you. 5-16. Write a program that gets a sentence from the user and prints only the first and last word.
  • 47. 6-1 Chapter 6 Selection Repetitive tasks are certainly well suited for computers, but when dealing with many problems, we also need to decide between two or more courses of action or whether a certain action should be taken at all. Selection is simply the process of choosing if a statement or block of statements should be executed. In Java, one of the keywords used to implement selection is, if. Basically, we say, “if this condition is true, then execute these statements, otherwise skip over them”. The format is very similar to a while loop. if ( condition ) { Java statement; Java statement; } The keyword if is followed by a condition enclosed in parenthesis, and then an open brace, {, and one or more Java statements followed by semi-colons and finally a close brace, }. The condition has the same format and function as it did with loops. If the comparison between the two things in the condition evaluate to true, then the statement(s) between the braces are executed, otherwise they are skipped over. Below is a program that gets integers from the user until she enters zero. Each time a number is entered, the program checks to see if the number is even, and only if it is, then the program prints half of the number. import javax.swing.*; public class IfEven { public static void main( String [] args) { String value; value=JOptionPane.showInputDialog("Enter a number, zero to exit"); int number = Integer.parseInt(value); while(number != 0) { if (number % 2 == 0) { System.out.println("Half is "+ (number/2) ); } value = JOptionPane.showInputDialog("Another number: "); number = Integer.parseInt(value); } System.exit(0); } } Again we used a seeded while loop, and the value zero was used as our sentinel. The special modulus operator, %, which gives us the remainder after a division, was used to see if the number was even. All even numbers when divided by two have zero as the remainder. If the number was even, then half its value was printed. If the number was not even, then the statement belonging to the if block of code was skipped and the next value was read in from the user.