Professional Documents
Culture Documents
Overview of Programming
A computer system consists of a set of hardware and software which
processes data in a meaningful way. The personal computer or PC exemplifies a
relatively simple computer system. The Internet exemplifies a relatively complex
computer system.
Even the simplest computer classifies as a computer system, because at least two
components (hardware and software) have to work together. But the real meaning of
"computer system" comes with interconnection. Many computer systems can
interconnect, that is, join to become a bigger system. Interconnecting computer systems
can prove difficult due to incompatibilities, sometimes between differing hardware and
sometimes between different software suites.
Designers of individual different computer systems do not necessarily aim to
interconnect their product with any other system. But systems administrators can
often configure even disparate computers to communicate using a set of rules and
constraints known as protocols; these precisely define the "outside view" of the system.
This outside view effectively defines the way one system connects with another. If two
systems define the same "outside view", they can interconnect and become a larger
computer system.
This "outside view" usually comes in the form of a standard, that is, a document
explaining all of the rules a device or a program must follow. International bodies such
as the IETF or IEEE normally set up or endorse such standards. If an individual system
obeys all of the rules, systems designers say it "complies with" the standard.
It's important to continue investing. Once you feel comfortable with some new
language or bit of technology, move on. Learn another one.
Computer languages influence how we think about a problem, and how we think
about communicating. Every language comes with a list of features - buzzwords such as
static versus dynamic typing, early versus late binding, inheritance models (single,
multiple, or none) - all of which may suggest or obscure certain solutions. Designinga
solution with Lisp in mind will produce different results than a solution based on C-style
thinking, and vice versa. Conversely, and we think more importantly, the language of the
problem domain may also suggest a programming solution.
There is a growing number of good text manipulation languages. Unix
developers often like to use the power of their command shells, augmented with
tools such as awk and sed. People who prefer a more structured tool like the
object-oriented nature of Python. Some people use Tcl as their tool of choice.
My preference is Perl for hacking out short scripts.
For the real projects the languages like Java, C or C++ are nearly inevitable to be used.
Introduction to Java
Programming
Java is an object-oriented programming language with a built-in application
programming interface (API) that can handle graphics and user interfaces and that can
be used to create applications or applets. Because of its rich set of API's, similar to
Macintosh and Windows, and its platform independence, Java can also be thought of as
a platform in itself. Java also has standard libraries for doing mathematics.
Much of the syntax of Java is the same as C and C++. One major difference is
that Java does not have pointers. However, the biggest difference is that you
must write object oriented code in Java. Procedural pieces of code can only be
embedded in objects. In the following we assume that the reader has some
familiarity with a programming language. In particular, some familiarity with
the syntax of C/C++ is useful.
1. Save the code with the same filename as your class name.
Java Programming Intro Chapter 2 Introduction to Java 6
Programming
1. Compile your java source code using ‘javac’ and press Enter key
2. If there are errors you have to edit your source code, save then compile. If
there are no problems, then you can use ‘java’ to run your java program.
Syntax Notation
Throughout this set of tutorials Java language constructs will be given with complete
details of their syntax or makeup. This syntax will be shown in blue and follow these
rules:
Reserved or special keywords will be quoted like "this". The quotes are not
used when you type the word.
Identifiers that can be any combination of characters beginning with a letter
or underscore are written unquoted.
Square brackets indicate an optional entry. The square bracket is not typed as
part of the line.
The vertical bar indicates alternatives. It is not typed
Ellipses (ie ... ) indicates more of the same. It is not typed.
For example, the specification of a class has the following syntax:
["public"] ["abstract"|"final"]"class" class_name
["extends" object_name]
"{"
// properties declarations
// behavior declarations
"}"
The meaning of the reserved words will be explained as you work through the
tutorials. Essentially syntax defines the 'rules' which the compiler will use to check
your programs for compilation. Whether they execute correctly is a whole different
issue ;-[
Exercises
1. Find the errors
import java.io.*;
char answerLetter;
try{
answerLetter=r.readLine().charAt(0);
}catch(Exception ex){};
if (answerLetter == 'y')
System.out.println("Nice weather we are having.");
System.out.println("Good-bye.");
}
}
1. Make a java program that print in the screen the following statements:
Java is great!!!
Java for one.
Java for all.
2. Here is another sample of a Java applet. Explore the code and write
below the objects used.
import javax.swing.*;
Variables and
Assignments
Variables
Variables are places in memory to store values. There are different kinds of variables, and
every language offers slightly different characteristics.
Data Type specifies the kinds of data a variable an store. Java has two general kinds
of data types.
8 basic or primitive types (byte, short, int, long, float, double, char, boolean).
An unlimited number of object types (String, Color, JButton, ...). Java object
variables hold a reference (pointer) to the the object, not the object, which is
always stored on the heap.
Scope of a variable is who can see it. The scope of a variable is related program
structure: eg, block, method, class, package, child class.
Lifetime is the interval between the creation and destruction of a variable. The
following is basically how things work in Java. Local variables and parameters are
created when a method is entered and destroyed when the method returns. Instance
variables are created by new and destroyed when there are no more references to
them. Class (static) variables are created when the class is loaded and destroyed
when the program terminates.
Initial Value. What value does a variable have when it is created? There are several
possibilites.
1. No initial value. Java local variables have no initial value, however Java
compilers perform a simple flow analysis to ensure that every local variable is
assigned a value before it is used. These error messages are usually correct,
Java Programming Intro Chapter 3 Variables and 22
Assignments
but the analysis is simple-minded, so sometimes you will have to assign an
initial value even tho you know that it isn't necessary.
2. User specified initial value. Java allows an assignment of intitial values in the
declaration of a variable.
3. Instance and static variables are given default initial values: zero for numbers,
null for objects, and false for booleans.
Declarations are required. Java, like many languages, requires you to declare
variables -- tell the compiler the data type, etc. Declarations are good because they
help the programmer build more reliable and efficient programs.
Declarations allow the compiler to find places where variables are misused,
eg, parameters of the wrong type. What is especially good is that these errors
are detected at compile time. Bugs that make it past the compiler are harder
to find, and may not be discovered until the program has been released to
customers. This fits the fail early, fail often philosophy.
A declaration is also the perfect place to write comments describing the
variable and how it is used.
Because declarations give the compiler more information, it can generate
better code.
Assignment Statements
Assignment statements use an assignment operator to store a value or the result
of an expression in a variable. Memory allocation is done at the time of
assignment. Primitive datatypes have static allocation with size determined by
their type. Simple examples include first_name = "Fred"; and count +=;
Variables may be assigned an initial value when declared. This is considered
good programming practice. Examples are boolean fileOpenFlag = true;, int
finalScore = null; and final float PI = 3.14159;
Local variables must be assigned a value prior to use. There is no default
assumption. Failure to initialize will cause a compiler error! Field variables (aka
properties) have defaults but initialization is good programming practice.
Arrays are allocated memory dynamically based on their array size through the
use of the new reserved word.
intArray = new int[5]; //previously declared
int markArray = new int[9]; //declaration and allocation at same time
int grades = new int[maxMarks]; //maxMarks must evaluate to positive
integer
Note: Since Java is a strongly typed language, required changes in data type
must be explicitly done with a cast operation. For example a = (int) b; (assumes
a is of type int and b is type char).
Exercises
1. Give the declaration for a variable called count of type int. The variable
should be initialized to zero in the declaration.
2. Write the declaration for two variables called miles and flowRate. Declare
the variable miles to be of type int and initialize it to zero in the declaration.
Declare the variable flowRate to be of type double and initialize it to 50.56
in the declaration.
3. Give a Java assignment that will set the value of the variable interest to the
value of the variable balance multiplied by the value of the variable rate.
The variables are of type double.
4. Write a Java statement that will set the value of the variable amount equal to the
number typed in at the keyboard. Assume that amount is of type double and that
the input is entered on a line by itself.
Java Programming Intro Chapter 4 Input and 25
Output
Input / Output
Input is any information that is needed by your program to complete its execution. There
are many forms that program input may take. Some programs use graphical components
like a popup dialog box to accept and return the character string that is typed by the user.
You are certainly familiar with programs that are controlled simply by clicking the mouse in
a specific area of the screen. Still other programs, like word processing programs, get some
of their input from a file that is stored on the computer's floppy or hard disk drive. Some
programs, like web browsers, get their data from a network connection, while others get
data from devices like scanners, digital cameras and microphones. The possibilities are
limited only by computer scientists' imagination.
Output is any information that the program must convey to the user. The information you
see on your computer screen is being output by one or more programs that are currently
running on your computer. When you decide to print a document, a program is told to send
some output to the printer. Any sound that your computer makes is because some program
sent output to the speakers on your computer. The possibilities for program output are also
limited only by our imaginations.
Java Programming Intro Chapter 4 Input and 26
Output
This is very similar to the first program, but it actually does something. The
additional parts are described below.
// Description: This program shows a message in a dialog box.
1
// File: dialogOutput/SecondProgram.java
2 // Author: Michael Maus
3 // Date: 29 Mar 2005
4 import javax.swing.*;
5
public class SecondProgram {
6
7 public static void main(String[] args)
{ JOptionPane.showMessageDialog(null, "Hello
8
Earthling");
9 }
10
}
11
12
13
14
Line 6 - import
One strength of Java is that it has many libraries or packages of predefined
classes and methods to help you do things. Some of these are automatically
known in every Java program, but you have to explicitly import others. This
import statement tells the compiler that you will be using part of the
Graphical User Interface (GUI) library - everything in javax.swing. Typical
programs have a few import statements.
Line 11 - Display a dialog box
This line displays this dialog box. The
predefined Java class, JOptionPane
contains methods to display dialog
boxes. A method is a group of Java
statements for doing one particular
thing. The "." following the class name
is followed by the name of the method,
showMessageDialog. Every method call
must be followed by a parenthesized
list of comma-separated arguments
(often called parameters) that specify
information the method needs to
perform its task.
The two arguments here are null, which we'll just ignore for the moment, and
"Hello Earthling", which is the message we want to display. Text messages
must be enclosed in quotes. Statements are generally followed by a semicolon.
This is similar to the previous program, but it also gets input from the user.
// Description: This program gets a string from a dialog box.
1
// File: dialogInputOutput/ThirdProgram.java
2 // Author: Michael Maus
3 // Date: 29 Jan 2005
4 import javax.swing.*; public
5
class ThirdProgram {
6
7 public static void main(String[] args) {
String humanName; // A local variable to hold the name.
8
9 humanName = JOptionPane.showInputDialog(null, "What's your name,
Earthling");
10
JOptionPane.showMessageDialog(null, "Take me to your leader, " +
11 humanName);
12 }
13 }
14
15
16
17
18
Line 11 - Declaring a local variable.
This tells the compiler to reserve some memory to hold a String. It's going to
hold a name, so we called the variable (a place in the computer's memory)
"humanName". The syntax for a simple declaration is to write the type of
thing that a variable will hold (String in this case), followed by the variable
name (humanName in this case).
Line 13 - Asking the user for a String.
JOptionPane's showInputDialog
method displays a message in a
dialog box that also accepts user
input. It returns a string that can
be stored into a variable.
This is an assignment statement.
The part to the right of the "="
must produce a value, and this
value is then stored in the variable
on the left (humanName).
Line 15 - Putting two strings together (concatenation)
Concantenation, indicated by the plus
sign (+), puts two strings together to
build a bigger string, which is then
passed as a parameter. The plus sign
(+) is also used for addition of
numbers.
Using Console:
Example:
import java.io.*;
}
Exercises
1. Give a Java statement that will display a window on the screen with the
message I Love You.
2. Write a complete Java program that will ask the user for the initials of the
user’s first and last name, and then output a greeting that says “Hello”
followed by the user’s initials and an exclamation mark. For example, if the
user’s initials are J and B, then the output greeting would be:
Hello J B!
If the user’s initials are stored in the two variables firstInitial and lastInitial,
both of type char, then the above output can be produced by the following
statement:
Be sure to note that the blank symbol is output after firstInitial. The use of the
plus sign in this way will be discussed later. In this exercise use the console to
accept input and display output.
Data Types
CHAPTER
5
+ + + +
+ + + +
Java Programming Intro Chapter 5 Data Types 30
Numbers
There are two general kinds of numbers in Java and most other programming
languages: binary integers and binary floating-point numbers (sometimes called
real numbers). Although these numbers are stored in the computer as binary
numbers, you will usually use decimal numbers in your Java source program, and
the Java compiler will translate them to the correct binary form.
Numbers in Java
Integers
Floating-point
Strings to Numbers
Integers
Integers are whole numbers, for example, -35, 0, 2048, ......Integers are represented
in binary inside the computer, and in decimal in Java source programs. Java
automatically converts decimal numbers you write in your source program into
binary numbers internally.
Four (or five) kinds of primtive integers and two integer classes.
Primitive types. There are four types of integers in Java: byte, short, int,
long. The most common is int.
char! Technically, char is an unsigned integer type although it is almost exclusively
used to store characters. Making it integer is largely because of Java's legacy from
C++. Don't use char for integers unless you are sure of what you're doing.
Classes. In addition to the primitive types, there are two classes used for integers.
Integer - Primarily useful for utility methods and to put in the Collections
data structure classes.
BigInteger - Used where unbounded arithmetic is important.
Hexadecimal literals
You can write an int in hexadecimal by prefixing the hexadecimal number with the
digit zero followed by the letter x, "0x" or "0X". The hexadecimal digits are 0-9 and
the letters a-f in upper- or lowercase.
int i;
i = 0x2A; // assigns decimal 42 to i.
The shame of integer arithmetic
Operations may produce numbers which are too large (overflow) to be stored in an
int. No error is caused in this case; the result is simply an incorrect number (one of
the shames of modern computer arithmetic). Division by zero will cause an execution
exception (ArithmeticException). Use BigInteger to prevent arithmetic overflow.
Floating-point
Floating-point numbers are like real numbers in mathematics, for example, 3.14159,
-0.000001. Java has two kinds of floating-point numbers: float and double, both
stored in IEEE-754 format. The default type when you write a floating-point literal is
double.
Limited precision
Because there are only a limited number of bits in each floating-point type, some
numbers are inexact, just as the decimal system can not represent some numbers
exactly, for example 1/3. The most troublesome of these is that 1/10 can not be
represented exactly in binary.
Floating-point literals
There are two types of notation for floating-point numbers. Any of these numbers
can be followed by "F" (or "f") to make it a float instead of the default double.
Standard (American) notation which is a series of digits for the integer
part followed by a decimal point followed by a series of digits for the fraction
part. Eg, 3.14159 is a double. A sign (+ or -) may precede the number.
Scientific notation which is a standard floating-point literal followed by the
letter "E" (or "e") followed by an optionally signed exponent of 10 which is
used as a multiplier (ie, how to shift the decimal point). Generally scientific
notation is used only for very large or small numbers.
Scientific Standard
1.2345e5 123450.0
1.2345e+5 123450.0
1.2345e-5 0.000012345
If s is null or not a valid representation of a number of that type, these methods will
throw (generate) a NumberFormatException. See below.
Handling NumberFormatExceptions
Put number conversions inside a try . . . catch statement so that you can do
something if bad input is entered. The conversion method will throw a
NumberFormatException when there is bad input. Catch the
NumberFormatException, and do something to handle this error condition. Put your
conversion in the try clause, and the error handling in the catch clause. Here is an
example of the kind of utility function you might write to do this checking.
//--- Utility function to get int using a dialog. public static int getInt(String mess) {
int val;
while (true) { // loop until we get a valid int
String s = JOptionPane.showInputDialog(null, mess);
try {
val = Integer.parseInt(s);
break; // exit loop with valid int >>>>>>>>>>>>>>>>>>>>>>
}catch (NumberFormatException nx) {
JOptionPane.showMessageDialog(null, "Enter valid integer");
}
}
return val;
}//end getInt
Non-decimal Integers
Convert integers with some base (radix) other than 10 by using these two methods.
Typically these will be hexadecimal (base 16) or binary (base 2) numbers.
type Example statement
int i = Integer.parseInt(s, radix);
long l = Long.parseLong(s, radix);
Comparison operators
Comparison operators are used to compare two primitive values (rarely objects).
Op Name Meaning
i < j less than 6 < 24 is true.
i <= j less than or equal 6 <= 24 is true.
i == j equal 6 == 24 is false.
i >= j greater than or equal 10 >= 10 is true.
i > j greater than 10 > 10 is false.
i != j not equal 6 != 24 is true.
Logical operators
Op Name Meaning
a && b and The result is true only if both a and b are true.
a || b or The result is true if either a or b is true.
!a not true if a is false and false if a is true.
Boolean variables
You can declare boolean variables and test them. For example, this simple bubble
sort keeps looping until there were no exchanges, which means that everything must
be sorted. This is only an example, not a good way to sort.
void bubbleSort(int[] x, int n) {
boolean anotherPass; // true if something was out of order do {
anotherPass = false; // assume everything sorted for (int i=0; i<n-1; i++) {
if (x[i] > x[i+1]) {
int temp = x[i]; x[i] = x[i+1]; x[i+1] = temp; // exchange
anotherPass = true; // something wasn't sorted, keep going
}
}
} while (anotherPass);
}
Unicode
Unicode is a system of encoding characters. All characters and Strings in Java use
the Unicode encoding, which allows truly international programming.
About Unicode
The Unicode effort is not coordinated with Java. At the time that Java was
started, all 50,000 defined Unicode characters could be reprensented with 16
bits (2 bytes). Consequently, Java used the 2-byte (sometimes called UTF-16)
representation for characters.
However, Unicode, now at version 4.0, has defined more characters than fit
into two bytes. To accommodate this unfortunate occurrance, Java 5 has
added facilities to work with surrogate pairs, which can represent characters
with multiple character codes. As a practical matter, most Java programs are
written with the assumption that all characters are two bytes. The characters
that don't fit into two bytes are largely unused, so it doesn't seem to be a
serious deficiency. We'll see how this works out in the future.
ASCII. Most programming languages before Java (C/C++, Pascal, Basic, ...)
use an 8-bit encoding of ASCII (American Standard Coding for Information
Interchange). ASCII only defines the first 128 characters, and the other 128
values are often used for various extensions.
All of the world's major human languages can be represented in Unicode
(including Chinese, Japanese, and Korean).
The first 64 characters of Unicode have the same values as the equivalent
ASCII characters. The first 128 characters are the same as ISO-8895-1 Latin-1.
Unicode Fonts
Altho Java stores characters as Unicode, there are still some very practical operating
system problems in entering or displaying many Unicode characters. Most fonts
display only a very small subset of all Unicode characters, typically about 100
different characters.
Character
Exercises
1. Write a program that reads in a four digit number (like 1998) and that outputs
the number one digit per line, like so:
1
9
9
8
Your prompt should tell the user to enter a four-digit number and can then
assume that the user follows directions. Your program will not read the
number as a value of type int, but as four characters of type char.
2. Write a complete Java program that will read in two values of type double
and output the sum of the two numbers. Use the class JOptionPane to do
input and output using windows.
Expressions CHAPTER
6
+ + + +
Types of Expressions
Expressions within
Expressions
Expressions
are the basic way to create Comparison Operators
values. Expressions are created by combining literals
+ + + +
(constants), variables, and method calls by using
operators. Parentheses can be used to control the order of
evaluation.
Java Programming Intro Chapter 6 Expressions 39
Types of Expressions
To put it simply, an expression is a line of code that can be reduced to a value or that
assigns a value. For example, you know that the addition operator adds one
expression to another, like this:
num = (5 - x) * (2 + y);
num
(5 - x) * (2 + y)
Both of the above lines are numerical expressions because they can be reduced to a
numerical value (assuming that you know the values of num, x, and y.
But, wait a second-you're not done yet. You can still find more sub-expressions. Look
at the multiplication operation. Can you see that it's multiplying two expressions
together? Those two expressions look like this:
(5 - x)
(2 + y)
And the above simplified expressions contain yet more sub-expressions. Those
expressions are:
Expressions are what programmers like to call recursive, meaning that the definition
of an expression keeps coming back on itself. An expression contains expressions
that contain other expressions, which themselves contain other expressions. How
deep you can dig depends on the complexity of the original expression. But, as you
saw demonstrated, even the relatively simple expression num = (5 - x) * (2 + y) has four
levels of depth.
Comparison Operators
Now that you've dug into the secrets of expressions, it's time to learn about a new
type of operator. So far, you've gotten some practice with mathematical operators,
which enable you to build various types of numerical and assignment expressions.
Another type of operator you can use to build expressions is the comparison
operator. Comparison operators are used to create logical expressions, which, if you
recall, result in a value of true or false. Table 8.1 lists the logical expressions used in
Java programming. C and C++ programmers will find these operators very familiar.
Table 8.1 Java's Logical Operators.
Operators Description
== Equal to
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
!= Not equal to
Example: Using Comparison Operators
Just how do you use comparison operators? As their name suggests, you use them to
compare two expressions, with the result of the comparison being either true or false.
For example, look at this logical expression:
3 == 2 + 1
The result of the above expression is true because the == operator determines
whether the expressions on either side are equal to each other. If you were to change
the expression to
3 == 2 + 2
the result would be false. That is, 3 does not equal 4. However, the previous sentence
suggests a way to rewrite the expression, like this:
3 != 2 + 2
Suppose goals is a variable of type int. Fill in the if-else statement with
an expression that outputs the word Wow if the value of the variable goals
is greater than 10 and the words Oh Well if the value of goals is at most 10.
import java.io.*;
String goalInput="";
int goals;
try{
goalInput=r.readLine();
}catch(Exception ex){};
goals=Integer.parseInt(goalInput);
if( )
System.out.println("Wow");
else
System.out.println("Oh Well");
}
}
Simple Flow
of Control
CHAPTER
7
+ + + +
General Forms
if Statement - Overview
Purpose
The purpose of the if statement is to make decisions, and execute different parts of
your program depending on a boolean true/false value. About 99% of the flow
decisions are made with if. [The other 1% of the decisions use the switch/case
statement.]
General Forms
The if statement has this form:
do these statements
if (condition) {
do this clause if the condition is true
}
do these statements afterwards
or
do these statements
if (condition) {
do this clause if the condition is true
} else {
do this clause if the condition is false
}
do these statements afterwards
It is good programming style to always write the curly braces, {}, altho they are not
needed if the clause contains only a single statement.
Form
The if statement without an else has this form:
if (condition) {
do this if the condition is true
}
Example
Here is a paintComponent() method with an if statement without an else clause.
When the paintComponent() method begins, the Graphics context g uses Color.black by
default. Therefore there is no need to set the color to black.
Form
The if statement doesn't need braces if there is only one statement in a part. Here
both the true and false parts have only one statement:
if (condition)
one statement to do if condition is true
else
one statement to do if condition is false
Example 1 - true and false parts
Here is a paintComponent() method both with and without braces which is possible
only because each clause contains only one statement.
If the if condition is false, this will not set the color, so the default color will be used
(black).
Should you always use braces?
If there is one statment, many programs use braces to make the code more
robust. This is a safer practice because any later addition of a statement to one of
the clauses will require braces. If you don't have the braces with multiple statements,
the compiler may not give any error message, but your code will not do what was
expected.
What is a statement?
A statement is a part of a Java program. We have already seen some simple
statements:
Assignment statement (eg, x = 1;).
Method call statement (eg, g.setColor(Color.red);).
if statement.
There are about ten kinds of statements. Many of them use braces for grouping
statements in the same way that the if statement uses braces.
if inside if
You can put an if statement inside another if statement.
Nearest 'else'
If you use braces, there is no problem with deciding which else goes with which if For
example,
if (age < 24) {
It's the semicolon! if you put a semicolon directly after the condition in an if
statement, Java thinks it's finished with the body of the statement. The indentation
of the next line, which is so important to human readers, is ignored by Java.
This is another error that's harder to make if you always follow the condition by an
opening brace.
'if' Statement - 'else if' style
Series of tests
It is common to make a series of tests on a value, where the else part contains only
another if statement. If you use indentation for the else part, it isn't easy to see that
these are really a series of tests which are similar. It is better to write them at the
same indentation level by writing the if on the same line as the else.
Exercises
1. Suppose salary and deductions are variables of type double that have
been given values. Write an if-else-statement that outputs OK and sets the
variable net equal to salary minus deductions. If, however, salary is less
than deductions, the if-else-statement simply outputs the word Crazy, and
does not change the value of any variables.
2. Suppose number is a variable of type int that has been given a value. Write
a multibranch if-else-statement that outputs the word High if number is
greater than 10, outputs Low if number is less than 5 and output So-so if
number is anything else.
CHAPTER 8
Program Style
+ + + +
Comments
Legal Characters
import
Comments
Computer programs are read by both computes and humans. You write
Java instructions to tell the computer what to do. You must also write comments
to explain to humans what the program does. Of course, Java can't understand
them because they are written in English, or Spanish, or Thai, or ... .
Java ignores all comments. There is, however, a program called javadoc which
reads certain kinds of comments and produces HTML documentation (see below).
Java comments
// comments -- one line
After the two // characters, Java ignores everything to the end of the line. This
is the most common type of comment.
//--- local variables ---
int nquest; // number of questions.
int score; // count of number correct minus number wrong.
Identifier Names
Getting the names of things right is extremely important. It makes a huge difference
in readability. Many IDEs support refactoring, and specifically renaming. I will
sometimes rename classes several times before I hit on exactly the obvious name. It's
worth the effort.
Legal Characters
Every name is made from the following characters, starting with a letter:
Letters: a-z, A-Z, and other alphabetic characters from other languages.
Digits: 0-9
Special: _ (underscore)
No names can be the same as a Java keyword (eg, import, if, ...).
Examples
Apple This is a legal name. Lowercase implies it's a variable or method.
Apple This is a different legal name. Uppercase implies it's a class or interface.
APPLE Yet a different legal name. All uppercase implies it's a constant.
Topleft Legal, but multiple words should be camelcase.
top_left Better, but camelcase is preferred to _ in Java.
topLeft Good Java style
top left ILLEGAL - no blanks in a name
Import ILLEGAL - same as the Java keyword
import
Following the optional package declaration, you can have import statements, which
allow you to specify classes that can be referenced without qualifying them with their
package.
Packages are directories / folders that contain the Java classes, and are a way of
grouping related classes together. For small programs it's common to omit a package
specification (Java creates what it calls a default package in this case).
NetBeans 4.0 uses packages in several ways.
The project name is used for the package name.
A directory / folder is created with this project name. This directory name is
the name of your package.
A package declaration is inserted into each source file.
When you build a main project, the double-clickable .jar file will use this
project/package/directory name.
Syntax
The package-path is a dot-separated series of nested packages, eg, java.awt or
java.awt.event. You can import (make visible) either a single class or all classes in
package with the "*" wildcard character.
Suggestion: Use only the first wildcard case below. It is by far the most common
usage.
import package-path.*; // Makes all classes in package visible.
import package-path.class; // Makes only class visible.
import static package-path.*; // Makes all static variables in all
classes in package visible.
import static package-path.class; // Makes all static variables in class
visible.
class ImportTest {
Common imports
There are 166 packages containing 3279 classes and interfaces in Java 5. However,
there are only a few packages that are used in most programming. GUI programs
often use the first three imports.
import java.awt.*; Common GUI elements.
import java.awt.event.*; The most common GUI event listeners.
import javax.swing.*; More common GUI elements. Note "javax".
import java.util.*; Data structures (Collections), time, Scanner, etc classes.
import java.io.*; Input-output classes.
import java.text.*; Some formatting classes.
import java.util.regex.*; Regular expression classes.
Example: import only one class in a package
import javax.swing.JOptionPane; // Make a single class visible.
class ImportTest {
import FAQ
1. Q: Does importing all classes in a package make my object file (.class or .jar)
larger?
A: No, import only tells the compiler where to look for symbols.
2. Q: Is it less efficient to import all classes than only the classes I need?
A: No. The search for names is very efficient so there is no effective difference.
3. Q: Doesn't it provide better documentation to import each class explicitly?
A: The wildcard "*" only makes the classes in this package visible, not any of
the subpackages.
5. Q: Why don't I need an import to use String, System, etc?
Logical Operators
+ + + +
60
Logical Operators
The comparison operators enable you to compare two expressions. But another type
of operator-logical operators-supercharges comparison operators so that you can
combine two or more logical expressions into a more complex logical expression.
Even if you've never programmed a computer before, you're already familiar with
logical operators because you use them in everyday speech. For example, when you
say, "Do you have a credit card or ten dollars in cash?" you're using the logical
operator OR. Similarly, when you say, "I have a dog and a cat," you're using the AND
operator. Table 8.3 lists Java's logical operators and what they mean.
Table 8.3 Java's Logical Operators.
Operator Description
&& AND
|| OR
^ Exclusive OR
! NOT
The AND (&&) operator requires all expressions to be true for the entire expression
to be true. For example, the expression
(3 + 2 == 5) && (6 + 2 == 8)
is true because the expressions on both sides of the && are true. However, the
expression
(4 + 3 == 9) && (3 + 3 == 6)
is false because the expression on the left of the && is not true. Remember this when
combining expressions with AND: If any expression is false, the entire expression is
false.
The OR operator (||) requires only one expression to be true for the entire
expression to be true. For example, the expressions
(3 + 6 == 2) || (4 + 4 == 8)
and
(4 + 1 == 5) || (7 + 2 == 9)
are both true because at least one of the expressions being compared is true. Notice
that in the second case both expressions being compared are true, which also makes
an OR expression true.
The exclusive OR operator (^) is used to determine if one and only one of the
expressions being compared is true. Unlike a regular OR, with an exclusive OR, if
both expressions are true, the result is false (weird, huh?). For example, the
expression
(5 + 7 == 12) ^ (4 + 3 == 8)
(5 + 7 == 12) ^ (4 + 3 == 7)
(5 + 7 == 10) ^ (4 + 3 == 6)
The NOT (!) operator switches the value of (or negates) a logical expression. For
example, the expression
(4 + 3 == 5)
!(4 + 3 == 5)
is true.
(4 + 5 == 9) && !(3 + 1 = 3)
Is this expression true or false? If you said true, you understand the way the logical
operators work. The expressions on either side of the && are both true, so the entire
expression is true. If you said false, you must go to bed without any dinner.
This expression gives a result of true because each expression to the left and right of
each AND operator is true. However, this expression yields a value of false:
(4 == 4) && (5 == 6) && (6 == 6)
Remember that, when using AND, if any sub-expression is false, the entire
expression is false. This is kind of like testifying in court. To be true, it's got to be the
truth, the whole truth, and nothing but the truth.
Here you've used four different comparison and logical operators in the same
complex expression. But because you're comparing the sub-expressions with the
AND operator, and because each of the sub-expressions is true, the result of the
above expression is true.
Now, look at this expression:
Yep, things are getting tricky. Is the above expression true or false? (Hey, give it a
shot. You've got a fifty-fifty chance.) Ready for the answer? The above expression is
true. First, look at the parentheses. The outermost parentheses, on the left, group the
two expressions being compared by the AND operator into a single expression, so
evaluate it first. The value 3 is less than 5, but 2 does not equal 1, so the entire
expression on the left of the OR operator is false. On the right of the OR operator,
however, 7 does indeed equal 7, so this sub-expression is true. Because one of the
expressions in the OR comparison is true, the entire expression is true. Here's how
the expression breaks down, step-by-step:
false || true
true
(4 + 5 == 9) && !(3 + 1 == 3)
in your programs. They would serve no purpose because you already know how the
expressions evaluate. However, when you use variables, you have no way of knowing
in advance how an expression may evaluate. For example, is the expression
true or false? You don't know without being told the value of the numerical variable
num. By using logical operators, though, your program can do the evaluation, and,
based on the result-true or false-take the appropriate action. In the next chapter,
which is about if and switch statements, you'll see how your programs can use logical
expressions to make decisions.
CHAPTER
10
Special Operators + + + +
Bitwise Operators
Other Operators
+ + + +
65
Bitwise Operators
Java's bitwise operators operate on individual bits of integer (int and long) values. If
an operand is shorter than an int, it is promoted to int before doing the operations.
It helps to know how integers are represented in binary. For example the decimal
number 3 is represented as 11 in binary and the decimal number 5 is represented as
101 in binary. Negative integers are store in two's complement form. For example, -4
is 1111 1111 1111 1111 1111 1111 1111 1100.
Don't confuse &&, which is the short-circuit logical and, with &, which is the
uncommon bitwise and. Altho the bitwise and can also be used with boolean
operands, this is extremely rare and is almost always a programming error.
The ‘switch’
statement
CHAPTER
11
+ + + +
switch
comments on switch
+ + + +
68
Syntax
switch (expr) {
case c1:
statements // do these if expr == c1
case c4:// Cases can simply fall thru. statements // do these if expr == any of c's break;
...
default:
statements // do these if expr != any above
}
switch
The switch keyword is followed by a parenthesized integer expression and
cases enclosed in braces.. The case corresponding to the value of the
expression is executed next. If there is no such case, the default clause is
executed. If there is no default clause, execution continues after the end of the
switch statement.
case
The case keyword is followed by an integer constant and a colon. This begins
the statements that are executed when the switch expression has the case
value.
default
If no case value matches the expression value, execution continues here. This
is the "else" of the switch statement. This is written as the last case be
convention. It typically isn't followed by break because execution just
continues out the bottom of switch if this is the last clause.
break
The break statement causes execution to exit to the statement after the end of
the switch. If there is no break, execution flows thru into the next case.
switch (which) {
Comments on switch
Java's if statement, which was taken directly from C++ to increase its attractiveness
to C++ programmers, is not well loved.
It doesn't allow ranges, eg case 90-100:. Many other languages do.
It requires integers and doesn't allow useful types like String. Many other
languages do.
Exercises
1. Write a code that outputs One if the user inputs 1, Two if the user inputs 2,
Three if the user inputs 3, and outputs Go if the user inputs other numbers.
Use the switch statement.
2. Write a code that accepts a number from 1 to 12 as input. The code will output
January if the user inputs 1, February if the user inputs 2, March if the
user inputs 3 and so on. I f the user inputs a number not included in the given
range the code will output the statement “Sorry, no such month”.
Order of
Precedence
CHAPTER
12
+ + + +
Precedence
+ + + +
Java Programming Intro Chapter 12 Order of 72
Precedence
Order of Precedence
+- addition, substraction
4 Left
+ string concatenation
^ bitwise XOR
9 Left
^ boolean (logical) XOR
| bitwise OR
10 Left
| boolean (logical) OR
13 ?: conditional Right
= assignment
*= /= += -= %=
14 <<= >>= >>>= combinated assignment Right
&= ^= (operation and assignment)
|=
Looping
CHAPTER
13
+ + + +
while-loop
for-loop
be run multiple times, this is where loops come in. A
looping structure is basically a structure which allows a + + + +
set of statements to be run either for a fixed number of
times or until some condition is met. Java has three such
looping structures, borrowed from C, the for loop, the
while loop and the do-while loop.
Java Programming Intro Chapter 13 Looping 75
Purpose
The purpose of loop statements is to repeat Java statements many times. There are
several kinds of loop statements in Java.
while statement - Test at beginning
The while statement is used to repeat a block of statements while some
condition is true. The condition had better become false somewhere in the
loop, otherwise it will never terminate.
int i = 0;
Indentation of loops
All statements inside a loop should be indented 2-4 spaces (the same as an if
statement.
'while' Statement
Purpose
The purpose of the while statement is to repeat something many times.
General Form
The while statement has this form:
while (condition) {
statements to repeat while the condition is true
}
'for' Statement
Purpose
The purpose of the for statement is to repeat Java statements many times. It is
similar to the while statement, but it is often easier to use if you are counting or
indexing because it combines three elements of many loops: initialization, testing,
and incrementing.
General Form
The for statement has this form:
for (init-stmt; condition; next-stmt) {
do this each time
}
There are three parts in the for statement.
1. The init-stmt statement is done before the loop is started, usually to initial a
variable.
2. The condition expression is tested at the beginning of each time the loop is
done. The loop is stopped when this boolean expression is false (the same as
the while loop).
3. The next-stmt statement is done at the end of every time through the loop,
and usually increments a variable.
Example
Here is a loop written as both a while loop and a for loop. First using while:
count = 0;
while (count < 50) {
for (count=0; count < 50; count = count+1) { g.drawLine(20, count*5, 80, count*5);
}
g.drawString("Loop is finished. count="+count, 10, 300);
Notice that the for loop is much shorter. It is better when you are counting
something. Later you will see examples where the while loop may be the better
choice.
Exercises
1. Write a program that asks the user to enter the size of triangle to print out (an
integer from 1 to 50) then print the triangle by printing a series of lines with
asterisks. The first line will have one asterisk, the next two, etc., each line
having one more asterisk than the previous line up to the number entered by
the user; on the next line print one less asterisk and continue by decreasing
the number of asterisks by one for each successive line until only one asterisk
is printed. Hint: use nested for loops; the outside loop controls the number of
lines to print and the inside loop controls the number of asterisks to print on a
line. For example, if the user enters 5 the output would be
*
**
***
****
*****
****
***
**
*
2. Create a program that lets the user enter a number greater than zero and
outputs the number given. This procedure will be performed as long as the
number is greater than zero. Use the while loop.
3. Create a program similar to the previous exercise but instead of using a while
loop use the do-while loop.
Programming
Using Methods
CHAPTER
14
+ + + +
Introduction
Declaring
Vocabulary
Programming and is used in Java. It means the same
thing as function, procedure, or subroutine in other OOP
programming languages. Many programmers use these
+ + + +
other terms, especially function, but these notes will use
method
Java Programming Intro Chapter 14 Programming Using 80
Methods
Methods - Introduction
Methods
The word method is commonly used in Object-Oriented Programming and is used in
Java. It means the same thing as function, procedure, or subroutine in other
programming languages. Many programmers use these other terms, especially
function, but these notes will use method
.
Methods - Example
Example
This example shows a simple method that computes the area of a rectangle:
int computeArea(int width, int height) {
int area; // This is a local variable
area = width * height;
return area; 5. }
Line 1 is the method header. The first int indicates that the value this method returns
is going to be an integer. The name of the function is "computeArea", and it has two
integer parameters: width and height.
The body of the method starts with the left brace, "{", on the end of the first line. The
"{" doesn't have to be on the same line as the header, but this is a common style.
The body of this simple function contains a declaration on line 2, an assignment
statement in line 3, and a return statement on line 4. If a method returns a value, then
there must be at least one return statement. A void method (one which does not
return a value), does not require a return statement, and will automatically return at
the end of the method.
Methods - Declaring
Declaration syntax
Notation: Everything between square brackets, "[" and "]", is optional.
If no scope is given, a method has package scope. Other comon values for
scope are public (everyone can see it) and private (can only be seen from within
this class). For small programs don't worry about scope. However, for
access applets you need to declare init() and paintComponent() methods to be public so
that the browser and Java GUI code can see them. If you are writing an
application, you must declare main(...) to be public so the operating system can
call it.
The static keyword is used to declare class methods -- methods that don't
static refer to a specific object. The only method that you will probably declare this
way is main.
Any Java type, including arrays, can be written here to tell what data type
type
value the method returns. Use void if the method doesn't return a value.
Note: There are also other, less frequent, modifiers that we won't discuss here
(protected, synchronized, final, abstract, native)
Parameters
Formal parameters are the parameters that are written in the method definition.
These are the names that you use in your method. Formal parameters are like local
variables that get an initial value at the time the method is called.
Actual parameters or arguments are the values that are written in the method
call. The actual parameter values are copied into the formal parameters, which are
then like initilialized local variables.
Local Variables
Variables that you declare in a method are called local variables. They are created on
a call stack when the method is entered, and they are destroyed when the method
returns. Because objects (eg Strings and arrays) are allocated in the heap, they are
never in the call stack and can be returned from the method.
Methods - Calling
Calling a method
When you call a method outside your class, you must put an object or class name in
front of it, then a dot, then the method call. For example,
g.drawRect(10, 20, 30, 40);
This calls the drawRect method in the class of g (Graphics) with 4 int parameters.
Internally there are five parameters: the Graphics object, and the four int
parameters. The method can then reference all of the fields in the Graphics object
without any special notation.
When you call methods which are defined in your own class, you don't need to write
an object in front of them if they are working on the same fields (the same object).
However, it is sometimes clearer to write this. in front of them to make it clear that
you are calling the method with the current object. [needs examples]
Methods - OOP
Static methods
If your method doesn't use an object of the class it is defined in, but does some work
only on it's parameters, then you can declare the method to be static. Except for
some utility methods and main(...), you should probably not be using static methods.
A good example of a static methods in Java is the Math or Character classes. For
example, the Math.cos(x) method calls the cosine method in the Math class. Cosine
takes only one (primitive) parameter, and it doesn't work on any object. Make a call
to a static method by putting a class name and a dot in front of the method call.
Signature
The signature of a method is its name and types of its parameters. The signature is
used to select which method is to be called in a class. When you define more than
one method by the same name in a class, there must be a difference in the number or
types of the parameters. When there is more than one method with the same name,
that name is overloaded.
Overriding
You override a method when you define a method that has the same name as in a
parent class. A good example of this is when you define a JApplet you write an init()
method. The JApplet class already has an init() method which you are overriding.
When the browser calls init(), it will then call your version of the method. In this case
you need to write init() because the init() in JApplet does nothing. Similarly, JPanel's
paintComponent() method is overridden when you declare a JPanel for drawing.
All calls go to your new method, and not to the method by the same name in the
parent class. To call the method in the parent class, as you must do in the first line of
paintComponent(), prefix the call with super..
Overloading
A method name is overloaded when there are two or more methods by the same
name in a class. At first it sounds like overloading methods would produce a lot of
confusion, but it really reduces the confusion.
You can also define a method in one class that has the same signature (name and
parameters) as the method in a different class. This is not called overloading, and
there can be no confusion because the object in front of the method identifies which
class the method is in.
Methods - Vocabulary
access modifier
There may be an access modifier at the front of a method header. The
access modifier tells which other methods can call this method.
keyword Access
If you don't give an access modifier, every other method in this
package can call it. This is usually called package access and is
none
probably the most common type of access. This is like giving your
friends your telephone number.
Everyone can call it. You should use public if you want someone
outside your package to call the method. Some common methods
public that are declared public are paint(), init(), actionPerformed(),
adjustmentValueChanged(), and main(). This is like making your phone
number public -- anyone can call you.
private No one outside this class can call it. This is like only letting your
family call you.
Everyone in this package and any child classes can use it. You won't
protected want to use this unless you are devoloping classes that you expect
others to use for inheritance.
actual parameter
The values in the method call are the actual parameters. When a call is
made, the values of the actual parameters are copied into the formal
parameters.
formal parameter
The parameters in the header of a method definition are the formal
parameters. Formal parameters are like local variables that get their values
from the actual parameters.
local variable
Local variables are variables that are declared in a method. Local variables
can only be used in that method (no other methods can access them). They
are created when a method is called, and destroyed when the method returns.
method
A method is a way to put a group of statements together to do something.
method body
Amethod body is the part of the method that contains the declarations of
local variables and the statements. For a non-void function, it must contain at
least one return statement.
method definition
A method definition has two parts: a method header, and a method body.
method header
A method header comes at the beginning and gives the following
information:
access modifier
return type
method name
formal parameters
Need to add: return type, return statement, signature, static/class methods, instance
methods, overriding, overloading, ... However, each entry should really be marked
both by area (methods, awt, ...), and by level (beginning, intermediate, or advanced).
Hmmm, that will have to come later.
Static/Class methods
There are two types of methods.
Instance methods are associated with an object and use the instance
variables of that object. This is the default.
Static methods use no instance variables of any object of the class they are
defined in. If you define a method to be static, you will be given a rude
message by the compiler if you try to access any instance variables. You can
access static variables, but except for constants, this is unusual. Static
methods typically take all they data from parameters and compute something
from those parameters, with no reference to variables. This is typical of
methods which do some kind of generic calculation. A good example of this
are the many utility methods in the predefined Math class. (See Math and
java.util.Random).
Example
Here is a typical static method.
class MyUtils {
...
//=================================================
mean
public static double mean(int[] p) {
int sum = 0; // sum of all the elements for (int i=0; i<p.length; i++) {
sum += p[i];
}
return ((double)sum) / p.length;
}//endmethod mean
...
}
The only data this method uses or changes is from parameters (or local variables of
course).
Alternate call
What's a little peculiar, and not recommended, is that an object of a class may be
used instead of the class name to access static methods. This is bad because it creates
the impression that some instance variables in the object are used, but this isn't the
case.
Exercises
Write a program that allows the user to convert either from degrees Celcius to
Fahrenheit or degrees Fahrenheit to Celcius. Use the following formulas
degreesC=5(degreesF – 32)/9
degreesF=(9(degreesC)/5) + 32
Prompt the user to enter a temperature and either a ‘C’ or ‘c’ for Celcius or an ‘F’
or ‘f’ for Fahrenheit, if anything other than ‘C’, ‘c’, ’F’, ‘f’ is entered, print an error
message and ask the user to reenter a valid selection. Create two methods, one for
converting the temperature to Fahrenheit if Celcius is entered, and one for
converting Celcius if Fahrenheit is entered. Ask the user to enter ‘0’ or ‘q’ to quit
or any other key to repeat the loop and perform another conversion.
Classes CHAPTER
15
+ + + +
Concepts
Creating
Declaration
+ + + +
Java Programming Intro Chapter 15 Classes 89
Creating Classes
Now that we've covered how to create and use objects, and how objects are cleaned
up, it's time to show you how to write the classes from which objects are created.
This section shows you the main components of a class through a small example that
implements a last-in-first-out (LIFO) stack. The following diagram lists the class and
identifies the structure of the code.
This implementation of a stack uses another object, a Vector, to store its elements.
Vector is a growable array of objects and does a nice job of allocating space for new
objects as space is required. The Stack class makes use of this code by using a Vector to
store its elements. However, it imposes LIFO restrictions on the Vector-- that is, you
can only add elements to and remove elements from the top of the stack.
The Stack class defines one member variable in its body to contain its elements--the
items Vector. It also defines one constructor--a no-argument constructor--and three
methods: push, pop, and isEmpty.
super("AnimationThread");
this.framesPerSecond = fps;
this.numImages = num;
This is a relatively simple member variable declaration, but declarations can be more
complex. You can specify not only type, name, and access level, but also other
attributes, including whether the variable is a class or instance variable and whether
it's a constant. Each component of a member variable declaration is further defined
below:
accessLevel
Lets you control which other classes have access to a member variable by
using one of four access levels: public, protected, package, and private. You
control access to methods in the same way. Controlling Access to
Members of a Class covers access levels in detail.
static
Declares this is a class variable rather than an instance variable. You also
use static to declare class methods. Understanding Instance and Class
Members later in this lesson talks about declaring instance and class
variables.
final
Indicates that the value of this member cannot change. The following variable
declaration defines a constant named AVOGADRO, whose value is Avogadro's
number (6.022 * 1023) and cannot be changed:
final double AVOGADRO = 6.022e23;
It's a compile-time error if your program ever tries to change a final variable.
By convention, the name of constant values are spelled in uppercase letters.
transient
The transient marker is not fully specified by The Java Language
Specification but is used in object serialization which is covered in
Object Serialization to mark member variables that should not be
serialized.
volatile
The volatile keyword is used to prevent the compiler from performing certain
optimizations on a member. This is an advanced Java feature, used by only a
few Java programmers, and is outside the scope of this tutorial.
type
Like other variables, a member variable must have a type. You can use
primitive type names such as int, float, or boolean. Or you can use reference
types, such as array, object, or interface names.
nam
e A member variable's name can be any legal Java identifier and, by convention,
begins with a lowercase letter. You cannot declare more than one member
variable with the same name in the same class, but a subclass can hide a
member variable of the same name in its superclass. Additionally, a member
variable and a method can have the same name. For example, the following
code is legal:
public class Stack
{ private Vector items;
// a method with same name as a member
variable public Vector items() {
...
}
}
Again, changing x through myX also changes it for other instances of AnIntegerNamedX.
Another difference between instance members and class members is that class
members are accessible from the class itself. You don't need to instantiate a class to
access its class members. Let's rewrite the code snippet from before to access x and
setX directly from the AnIntegerNamedX class:
...
AnIntegerNamedX.setX(1);
System.out.println("AnIntegerNamedX.x = " + AnIntegerNamedX.x());
...
Notice that you no longer have to create myX and anotherX. You can set x and retrieve
x directly from the AnIntegerNamedX class. You cannot do this with instance members,
you can only invoke instance methods from an object and can only access instance
variables from an object. You can access class variables and methods either from an
instance of the class or from the class itself.
All of the initialization code is in one place, thus making the code easier
to maintain and read.
Defaults are handled explicitly.
Constructors are widely understood by the Java community, including
relatively new Java programmers, while instance initializers are not
and may cause confusion to others reading your code.
Exercises
Create a class that graphs the grade distribution (number of A’s, B’s, C’s, D’s, F’s)
horizontally by printing lines with proportionate numbers of
asterisks corresponding to the percentage of grades in each category. Write
methods to set the number of each letter grade; read the number of each letter
grade, return the total number of grades, return the percent of each letter grade
as a whole number between 0 to 100, inclusive; and draw the graph. Set it
up so that 50 asterisks correspond to 100% (each one corresponds to 2%),
include a scale on the horizontal axis indicating each 10% increment from 0
to 100%, and label each
line with its letter grade. For example, if there are 1 A’s, 4 B’s, 6 C’s, 2 D’s, and 1 F,
the total number of grades is 14, the percentage of A’s is 7, percentage of B’s is 29,
percentage of C’s is 43, percentage of D’s is 14, and percentage of F’s is 7. The A
row would contain 4 asterisks (7% of 50 rounded to the nearest integer), the
B row 14, the C row21, the D row 7, and the F row 4, so the graph would look
like this.
0 10 20 30 40 50 60 70 80 90 100%
| | | | | | | | | | |
**************************************************
****A
**************B
*********************C
*******D
****F
Strings CHAPTER
16
+ + + +
Overview
Comparison
Conversion
Concatenation
+ + + +
105
String Overview
Strings are sequences of Unicode characters. In many programming languages
strings are are stored in arrays of characters. However, in Java strings are a separate
object type, String. The "+" operator is used for concatenation, but all other
operations on strings are done with methods in the String class.
String literals
To write a constant string, put the characters between double quotes, eg "abc".
Escape Character
There are some characters that can't be written directly in a string. The backslash
('\') character preceeds any of these special characters. For example, if a string
contains a double quotes, put a backslash ('\') in front of each internal double quote,
eg "abc\"def\"ghi". The other most common escape character is the newline
character, which is written as "n" following the backslash. For example, the following
string will produces two output lines. Note that the compiler replaces the backslash
plus character with the one desired character. Eg, "\n".length() is one.
System.out.println("This is the first\nand this is the second line.");
The "empty" string
The String equivalent of 0, is the string with no characters, "".
Concatenation
Expression Value
1+2 3
"1" + 2 "12"
1 + "2" "12"
"1" + 2 + 3 "123"
1 + 2 + "3""33"
Putting two strings together to make a third string is called concatenation. In Java
the concatenation operator is '+', the same operator as for adding numbers. If either
operand is a String, Java will convert the other operand to a String (if possible) and
concatenate the two.
c = Character.toUpperCase(c);
Converting a character to uppercase
Of course, you don't have to assign these values back to themselves -- you can use the
values where you want.
String Comparison
Strings can not be compared with the usual <, <=, >, or >= operators, and the ==
and != operators don't compare the characters in the strings.
Concatenation (+)
The most common idiom to convert something to a string is to concatenate it with a
string. If you just want the value with no additional text, concatenate it with the
empty string, one with no characters in it ("").
If either operand of a concatenation is a string, the other operand is converted to
string, regardless of whether it is a primitive or object type.
s = "" + x;// Converts int 42 to String "42" s = x + " is OK"; // Assigns "42 is OK" to s.
s = "" + 3.5;// Assigns "3.5" to s
s = "" + 1.0/3.0; // Assigns "0.3333333333333333" to s
Concatenation (+)
The most common idiom to convert something to a string is to concatenate it with a
string. If you just want the value with no additional text, concatenate it with the
empty string, one with no characters in it ("").
If either operand of a concatenation is a string, the other operand is converted to
string, regardless of whether it is a primitive or object type.
Card c = ...; // Assume Card is a class that defines a playing card. String s;
...
s = c;// ILLEGAL
s = "" + c;// Might assign "Three of Hearts" to s
s = c + " is trouble"; // Assigns "Three of Hearts is trouble" to s.
When Java needs to convert an object to a String, it calls the object's toString()
method. Because every class (object type) has the class Object as an ancestor, every
class inherits Object's toString() method. This will do something to generate a string
from an object, but it will not always be very useful. If the child class doesn't override
toString(), the default probably won't print anything interesting. Just as many of the
Java library classes override toString() to produce something more useful, you
should also override toString() in your classes.
Exercises
1. Write a program that reads in a line of text and then outputs that line of text
with the first occurrence of “hate” changed to “love”. For example, a
possible sample dialog might be
You can assume that the word “hate” occurs in the input. If the word “hate”
occurs more than once in the line, then your program will only replace the
first occurrence of “hate”.
2. Write a program that asks the user to enter the first name of a friend or
relative, a favorite color, a favorite food, and a favorite animal, then print the
following two lines with the user’s input replacing the items in italics:
Concepts
Abstract Classes
Interfaces
Collections
+ + + +
Java Programming Intro Chapter 17 114
Inheritance
Inheritance
Inheritance is the capability of a class to use the properties and methods of
another class while adding its own functionality. An example of where this could be
useful is with an employee records system. You could create a generic employee
class with states and actions that are common to all employees. Then more specific
classes could be defined for salaried, commissioned and hourly employees. The
generic class is known as the parent (or superclass or base class) and the specific
classes as children (or subclasses or derived classes). The concept of inheritance
greatly enhances the ability to reuse code as well as making design a much simpler
and cleaner process.
Inheritance in Java
Java uses the extends keyword to set the relationship between a child class and a
parent class. For example:
public class GraphicsBox extends Box
The GraphicsBox class assumes or inherits all the properties of the Box class and
can now add its own properties and methods as well as override existing methods.
Overriding means creating a new set of method statements for the same method
signature (name and parameters). For example:
// define position locations
private int left;
private int top;
// override a superclass method
public int displayVolume() {
System.out.println(length*width*height);
System.out.println("Location: "+left+", "+top);
}
When extending a class constructor you can reuse the superclass constructor and
overriden superclass methods by using the reserved word super. Note that this
reference must come first in the subclass constructor. The reserved word this is used
to distinguish between the object's property and the passed in parameter.
GraphicsBox(l,w,h,left,top)
{
super (l,w,h);
this.left = left;
this.top = top;
}
public void showObj()
{System.out.println(super.showObj()+"more stuff here");}
The reserved word this can also be used to reference private constructors which
are useful in initializing properties.
Special Note:You cannot override final methods, methods in final classes, private
methods or static methods.
Abstract Classes
As seen from the previous example, the superclass is more general than its
subclass(es). The superclass contains elements and properties common to all of the
subclasses. The previous example was of a concrete superclass that objects can be
made from. Often, the superclass will be set up as an abstract class which does not
allow objects of its prototype to be created. In this case only objects of the subclass
are used. To do this the reserved word abstract is included in the class definition.
Abstract methods are methods with no method statements. Subclasses must
provide the method statements for their particular meaning. If the method was one
provided by the superclass, it would require overriding in each subclass. And if one
forgot to override, the applied method statements may be inappropriate.
public abstract class Animal // class is abstract
{
private String name;
public Animal(String nm)
{ name=nm; }
public String getName() // regular method
{ return (name); }
public abstract void speak(); // abstract method - note no {}
}
Abstract classes and methods force prototype standards to be followed (ie. they
provide templates).
Polymorphism
Polymorphism is the capability of an action or method to do different things
based on the object that it is acting upon. This is the third basic principle of object
oriented programming. We have already used two types of polymorphism
(overloading and overriding). Now we will look at the third: dynamic method
binding.
Assume that three subclasses (Cow, Dog and Snake) have been created based on the
Animal abstract class, each having their own speak() method.
public class AnimalReference
{
public static void main(String[] args)
Animal ref // set up var for an Animal
Cow aCow = new Cow("Bossy"); // makes specific objects
Dog aDog = new Dog("Rover");
Snake aSnake = new Snake("Earnie");
Arrays of Subclasses
As with arrays of primitive types, arrays of objects allow much more efficient
methods of access. Note in this example that once the array of Animals has been
structured, it can be used to store objects of any subclass of Animal. By making the
method speak() abstract, it can be defined for each subclass and any usage will be
polymorphic (ie. adapted to the appropriate object type at runtime). It now becomes
very easy to rehearse the speak() method for each object by object indexing.
public class AnimalArray
{
public static void main(String[] args)
Animal[] ref = new Animal[3]; // assign space for array
Cow aCow = new Cow("Bossy"); // makes specific objects
Dog aDog = new Dog("Rover");
Snake aSnake = new Snake("Earnie");
Casting Objects
One of the difficulties of using a superclass array to hold many instances of subclass
objects is that one can only access properties and methods that are in the superclass
(ie. common to all). By casting an individual instance to its subclass form one can
refer to any property or method. But first take care to make sure the cast is valid buy
using the operation instanceof. Then perform the cast. As an example from above:
if (ref[x] instanceof Dog) // ok right type of object
{
Dog doggy = (Dog) ref[x]; // cast the current instance to its subclass
doggy.someDogOnlyMethod();
}
Interfaces
Java does not allow multiple inheritance (ie a subclass being the extension of
more than one superclass. To tie elements of different classes together Java uses an
interface. Interfaces are similar to abstract classes but all methods are abstract
and all properties are static final.As an example, we will build a Working
interface for the subclasses of Animal. Since this interface has the method called
work(), that method must be defined in any class using Working.
public interface Working
{
public void work();
}
When you create a class that uses an interface, you reference the interface with the
reserved word implements. Any class that implements an interface must include
code for all methods in the interface. This ensures commonality between interfaced
objects.
public class WorkingDog extends Dog implements Working
{
public WorkingDog(String nm)
{
super(nm); // builds ala parent
}
public void work() // this method specific to WorkingDog
{
speak();
System.out.println("I can herd sheep and cows");
}
}
Collections
Collections is a unifying philosophy that adds operational functionality, and
dynamic growth to object classes. The unification is through interfaces that each
collection object has. Functionality such as searches, sorts, insertion and deletion use
highly efficient algorithms. And mixtures of objects may be handled in a collection
class.
The collection interfaces are Collection, List, Set, and SortedSet. Collection is at
the top of this hierarchy and includes the methods add(), clear(), contains(0),
isEmpty(), remove(), size() as well as other less common ones. List extends
Collection for classes that are a sequence of elements (similar to an array). It also
overrides appropriate methods. Set extends Collection with methods that prevent
duplicate objects. SortedSet extends Set to keep all contained objects in a sorted
manner.
Classes which implement the appropriate interfaces include AbstractList, ArrayList,
LinkedList, HashSet, and TreeSet. ArrayList is very similar to arrays but with
methods for adding and removing items built-in. It is also dynamic(ie size does not
have to be declared at compile time). Other methods in ArrayList include
lastIndexOf(obj) to return position, get(index) to return object at a specific position,
and toArray() for converting a collection back to a regular array.
As an example of how specific objects can be located for access:
for (int x=0; x<emp.size; x++) // by index number
if (emp.get(x) instanceof Staff) // emp can be of several types
Staff s = (Staff) emp.get(x); // cast it to new Staff object
Exercises
1. Give the definition of a class named Doctor whose objects are records for a
clinic’s doctors. This class will be a derived class of the class Person given
below. A Doctor record has the doctor’s name (inherited from the class
Person), specialty (e.g. “Pediatrician,” “Obstetrician,” “General Practitioner,”
etc., so use type String, and office visit fee (use type double). Write a driver
program to test all your methods.
public Person(){
Name=”No name yet.”;
}
2. Create a base class called Vehicle that has the manufacturer’s name (type
String), number of cylinder’s in the engine (type int), and owner (type
Person given in #1). Then create a class called Truck that is derived from
Vehicle and has additional properties, the load capacity in tons (type double
since it may contain a fractional part) and towing capacity in tons (type int).
Write a driver program that tests all your methods.
Arrays CHAPTER
18
+ + + +
Introduction
Declaring
Initialization
Multi-dimensional
+ + + +
122
Arrays -- Introduction
Declaring an array
An array variable is like other variables -- you must declare it, which means you must
declare the type of elements that are in an array. All elements must be the same type.
Write the element type name, then "[]", then the name of the array variable. The
declaration only allocates space associated with a variable name for a reference to an
array, but doesn't create the actual array object.
String[] args;// args is an array of Strings int[] scores;// scores is an array of ints
JButton[] bs;// bs is an array of JButtons
Unlike some languages, never put the size of the array in the declaration because an
array declaration only tells Java that the variable is an array and the element type.
Subscript checking
Java always checks subscript legality to be sure the subscript is >= 0, and less
than the number of elements in the array. If the subscript is outside this range, Java
throws ArrayIndexOutOfBoundsException. This is far superior to the behavior of C and
C++, which allow out of range references. Consequently, Java programs are far less
susceptible to bugs and security flaws than C/C++.
Length of an array
Each array has a constant (final) instance variable that has its length. You can find
out how many elements an array can hold by writing the array name followed by
.length. In the previous example, a.length would be 100. Remember that this is the
number of elements in the array, one more than the maximum subscript.
int sum = 0;// Start the total sum at 0. for (int i=0; i<a.length; i++) {
sum = sum + a[i]; // Add the next element to the total
}
Array Initialization
When you declare an array, you can can also allocate a preinitialized array object in
the same statement. In this case, do not give the array size because Java counts the
number of values to determine the size. For example,
// Java 1.0 style -- shorter, but can be used ONLY IN DECLARATIONS
String[] days = {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};
The above way is the most common way to declare and initialize arrays.
Arrays -- Intermediate
Anonymous arrays
Java 2 added anonymous arrays, which allow you to create a new array of values
anywhere in the program, not just in an initialization in a declaration.
// This anonymous array style can also be used in other statements.
String[] days = new String[] {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};
You can also use anonymous array syntax in other parts of the program. For
example,
// Outside a declaration you can make this assignment.
x = new String[] {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"};
You must be careful not to create these anonymous arrays in a loop or as local
variables because each use of new will create another array.
Dynamic allocation
Because arrays are allocated dynamically, the initialization values may arbitrary
expresssions. For example, this call creates two new arrays to pass as parameters to
drawPolygon.
g.drawPolygon(new int[] {n, n+45, 188}, new int[] {y/2, y*2, y}, 3);
C-style array declarations
Java also allows you to write the square brackets after the variable name, instead of
after the type. This is how you write array declarations in C, but is not a good style
for Java. C declaration syntax can get very ugly with part of the declaration before
the variable, and part after. Java has a much nicer style where all type information
can be written together without the use of a variable, and there are times when only
the Java notation is possible to use.
int[] a; // Java style -- good
int a[]; // C style -- legal, but not Java style
Arrays -- 2-dimensional
Multi-dimensional arrays
Java, as with most languages, supports multi-dimensional arrays - 1-dimensional, 2-
dimensional, 3-dimensional, ... This discusses 2-dimensional arrays, but the same
principles apply to higher dimensions.
2-dimensional arrays
2-dimensional arrays are usually represented in a row-column approach on
paper, and the terms "rows" and "columns" are used in computing.
Arrays of arrays
There are two ways to implement 2-dimensional arrays. Many languages reserve a
block of memory large enough to hold all elements of the full, rectangular, array
(number of rows times number of columns times the element size). Java doesn't do
this. Instead Java builds multi-dimensional arrays from many one-dimensional
arrays, the so-called "arrays of arrays" approach. [C++ supports both styles.]
There are a couple of interesting consequences of this: Rows may be different sizes.
Also, each row is an object (an array) that can be used independently.
Declaration
Declare a 2-dimensional array as follows:
int[][] a2; // Declares, but doesn't allocate, 2-dim array.
Allocation
As with all arrays, the new keyword must be used to allocate memory for an array.
For example,
int[][] a2 = new int[10][5];
This allocates an int array with 10 rows and 5 columns. As with all objects, the values
are initialized to zero (unlike local variables which are uninitialized).
This actually allocates 6 objects: a one-dimensional array of 5 elements for each of
the rows, and a one-dimensional array of ten elements, with each element pointing
to the appropriate row array.
Uneven rows
One consequence of arrays of arrays is that each row can be a different size ("ragged"
arrays). For example, we could create a lower triangular array, allocating each row
"by hand" as follows.
int[][] tri;
tri = new int[10][]; // allocate array of rows for (int r=0; r<tri.length; r++) {
tri[r] = new int[r+1];
}
// print the triangular array (same as above really) for (int r=0; r<tri.length; r++) {
for (int c=0; c<tri[r].length; c++) { System.out.print(" " + tri[r][c]);
}
System.out.println("");
}
Array - Maximum
Finding the maximum is basically the same as finding the minimum; remember the
first value, then look through all the other elements. Whenever a larger (smaller)
value is found, that becomes the new maximum (minimum).
There is one common variation on this -- sometimes it isn't the maximum value that
is desired, but the index of the maximum value (eg, so it can be changed).
//==================================================
=== max
public static int max(int[] t) {
int maximum = t[0]; // start with the first value for (int i=1; i<t.length; i++) {
if (t[i] > maximum) {
maximum = t[i]; // new maximum
}
}
return maximum;
}//end method max
To make this work with object types (eg String), you will have to change the type
declarations of course, but you will also have to change the comparison to use
.compareTo(), which must be defined for that object type.
A minor problem with this algorithm is what to do if there are absolutely no
elements in the array -- t.length is zero? This will produce an error when we try to
get that first element. One solution is to throw an Exception. Another is to change
this to return the index, and when there are no elements return an impossible index
(eg, -1). Many programmers won't worry about this case because it will be impossible
for their program. However, you should always think about the possibility of an
empty array.
Loop direction
Very rarely you will find a programmer who prefers to write loops that go from high
to low. Of course it makes no difference in this algorithm, however, there are
machines in which that can save a few nanoseconds. This is enough harder for
humans to read that it is generally considered antisocial without a good reason (and
it's not common to find a good reason).
Arrays -- Multi-dimensional
All arrays in Java are really linear, one-dimensional arrays. However, you can easily
build multi-dimensional arrays from these, and Java has features in the language to
help you do this.
These examples all use two-dimensional arrays, but the same syntax and coding can
easily be extended to arrays of any dimension. By convention two dimensional arrays
have rows (horizontal) and columns (vertical). The first subscript selects the row
(which is a one-dimensional array itself), and the second subscript selects the
element in that row/array.
for (int row=0; row<3; row++) { for (int col=0; col<3; col++) {
if (board[row][col] > 0) { // draw X g.drawLine(col*10, row*10 , col*10+8, row*10+8);
g.drawLine(col*10, row*10+8, col*10+8, row*10 );
} else if (board[row][col] < 0) { // draw O g.drawOval(col*10, row*10, 8, 8);
}
}
}
Exercises
1. Write a program that reads in a list of int values one per line and outputs
their sum as well as all the numbers read in with each number annotated to
say what percentage it contributes to the sum. Your program will ask the user
how many integers there will be, create an array of that length, and then fill
the array with the integers input. A possible dialogue is
How many numbers will you enter?
4
Enter 4 integers one per line:
2
1
1
2
The sum is 6.
The numbers are:
2 33.3333% of the sum.
1 16.6666% of the sum.
1 66.6666% of the sum.
2 33.3333% of the sum.
Use a method that takes the entire array as one argument and returns the sum
of the numbers in the array.
2. Write a code that will fill the array a (declared in what follows) with numbers
typed in at the keyboard. The numbers will be input five per line, on four lines
(although your solution need not depend on how the input numbers are
divided into lines):
3. Write a method definition for a void method called display such that the
following invocation will display the contents of the array a in #2, and will
display it in the same format as we specified for the input there (that is, four
lines of five numbers per line):
display(a);