Вы находитесь на странице: 1из 136


+ + + +

Introduction to
Java Programming

+ + + +
Java Programming Intro Table of Contents ii

Chapter One Overview of Programming

Computer System 1

Overview of Programming 3

Chapter Two Introduction to Java


Introduction to Java 5

Objects 15

Basic Structures 15

Chapter Three Variables and Assignments

Variables 20

Assignments 22

Chapter Four Input and Output

Using Dialog Boxes 25

Using the Console 27

Chapter Five Data Types

Numbers 30

Integers 30

Floating-Point Numbers 31

Boolean 33

Characters 36

Chapter Six Expressions

Types of Expressions 39

Expressions within Expressions 39

Comparison Operators 40

Building skills for success

Java Programming Intro Table of Contents iii

Chapter Seven Simple Flow of Control

General Forms 44

Condition is True or False 44

else 45

If inside If 48

If-else-If 50

Chapter Eight Program Style

Comments 53

Legal Characters 54

import 55

Chapter Nine Using Logical Expressions

Logical Operators 60

Writing Logical Operators 63

Chapter Ten Special Operators

Bitwise Operators 65

Other Operators 65

Chapter Eleven The ‘switch’ statement

switch 68

Comments on switch 70

Chapter Twelve Order of Precedence

Precedence 72

Building skills for success

Java Programming Intro Table of Contents iv

Chapter Thirteen Looping

While-loop 75

Do-while-loop 75

For-loop 75

Chapter Fourteen Programming Using Methods

Introduction 80

Declaring 81

Calling 82

Object-Oriented Programming 82

Vocabulary 83

Chapter Fifteen Classes

Concepts 89

Creating 90

Declaration 91

Chapter Sixteen Strings

Overview 105

Comparison 106

Conversion 107

Concatenation 107

Building skills for success

Java Programming Intro Table of Contents v

Chapter Seventeen Inheritance

Concepts 114

Abstract Classes 115

Polymorphism 116

Interfaces 118

Collections 119

Chapter Eighteen Arrays

Introduction 122

Declaring 122

Initialization 124

Multi-dimensional 125

Building skills for success

Overview of
Programming + + + +

Computer System

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.

Building skills for success

Java Programming Intro Chapter 1 Overview of Programming 2

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.

Building skills for success

Java Programming Intro Chapter 1 Overview of Programming 3

Programming is ...
... a craft. At its simplest, it comes down to getting a computer to do what you want it
to do (or what your user wants it to do). As a programmer, you are part listener, part
advisor, part interpreter, and part dictator.

The knowledge becomes out of date as new techniques, languages, and environments
are developed. Changing market forces may render the experience obsolete or
irrelevant. Given the speed at which Web-years fly by, this can happen pretty
quickly. Here's a small list of the guidelines to prevent this sad fact:

• Learn at least one new language every year. Different languages solve
the same problems in different ways. By learning several different approaches,
you can help broaden your thinking and avoid getting stuck in a rut.
• Read a technical book each quarter. Just to stay live :)
• Take classes. Look for interesting courses at your local community college
or university.
• Stay current. Subscribe to trade magazines and other journals.

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. Designing

Building skills for success

Java Programming Intro Chapter 1 Overview of Programming 4

a 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.

Building skills for success

Introduction to
Java Programming + + + +


Java is an object-oriented programming language with a Basic Structures
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.
Java Programming Intro Chapter 2 Introduction to Java Programming 6

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

In Java we distinguish between applications, which are programs that perform the
same functions as those written in other programming languages, and applets, which
are programs that can be embedded in a Web page and accessed over the Internet.
Our initial focus will be on writing applications. When a program is compiled, a byte
code is produced that can be read and executed by any platform that can run Java.

When compiling you use “javac <classname>.java” and when interpreting java
bytecodes use “java <classname>”.

Steps in compiling and executing java programs:

1. Open a text editor

Building skills for success

Java Programming Intro Chapter 2 Introduction to Java Programming 7

2. Example of a text editor is the MS Notepad

Building skills for success

Java Programming Intro Chapter 2 Introduction to Java Programming 8

3. Create your java source code

Building skills for success

Java Programming Intro Chapter 2 Introduction to Java Programming 9

4. Save the code with the same filename as your class name.

Building skills for success

Java Programming Intro Chapter 2 Introduction to Java Programming 10

5. Open command prompt by typing ‘cmd’ in Run.

Building skills for success

Java Programming Intro Chapter 2 Introduction to Java Programming 11

6. This would open a command prompt.

Building skills for success

Java Programming Intro Chapter 2 Introduction to Java Programming 12

7. Create a path of the JDK binary folder.

Building skills for success

Java Programming Intro Chapter 2 Introduction to Java Programming 13

8. Compile your java source code using ‘javac’ and press Enter key

Building skills for success

Java Programming Intro Chapter 2 Introduction to Java Programming 14

9. 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.

10. Congratulations! You have created your Java program.

Building skills for success

Java Programming Intro Chapter 2 Introduction to Java Programming 15

What Are Objects

Java is an object-oriented programming language. But what are objects? An object
is a self-contained entity which has its own private collection of properties (ie.
data) and methods (ie. operations) that encapsulate functionality into a reusable
and dynamically loaded structure. After a class definition has been created as a
prototype, it can be used as a template for creating new classes that add
functionality. Objects are programing units of a particular class. Dynamic loading
implies that applications can request new objects of a particular class to be supplied
on an 'as needed' basis. Objects provide the extremely useful benefit of reusable
code that minimizes development time.

The Basic Structure of a Java Application

Previously you wrote a simple 'hello world!' application to test the development
environment. Now comes the explanation of the basic structure of Java applications
using it as an example. Applications are stand alone and are invoked (or executed)
by using a Java interpreter.
* The HelloWorldApp class implements an application that
* displays "Hello World!" to the standard output.
public class HelloWorldApp
public static void main(String[] args)
// Display Hello World! now
System.out.println("Hello World!");

Building skills for success

Java Programming Intro Chapter 2 Introduction to Java Programming 16

The first four lines is a comment on the application's function. Comments are not
required but are extremely useful as documentation within the source. Other notes
and doc files may get lost but these stay right where they are most useful. A long
comment starts with a /* or /** and ends with a */ Short one line comments begin
with // and end with the <return>.
The fifth line starts with the reserved word public. This indicates that objects
outside the object can invoke (or use) it. The reserved word class indicates that we
are building a new object with the name that follows. HelloWorldApp is the object
name (your choice) and is case sensitive. Java 'style' is to capitalize the first letter of
each word only. The line concludes with an opening curly bracket that marks the
start of the object definition.
Line six is an invocation of an initialization method (or procedure in older
languages). static indicates that it calls the class and not an 'instance' of the class.
The concept of 'instance' will be discussed later in the tutorials. The method's name
is main and the reserved word void indicates that no result is returned back. Main
has arguments (aka parameters) in round brackets. String[] indicates the variable
type is an array and args is a reserved word indicating that it is the command line
values that are being passed over to main. The line finishes with an opening bracket
for the main method.
Line eight invokes the println method of the system.out object. What is to be printed
is passed in the argument as a string parameter. Note that each Java statement
concludes with a semicolon.
Finally closing curly brackets are used for the main and for the object definition.

The Basic Structure of a Java Applet

Here is the explanation of the basic structure of a Java applet using the one that you
wrote to test your environment. Applets are placed in HTML documents and are
invoked (or executed) from within a Java aware browser such as MSIE, Netscape or
* The HelloWorld class implements an applet that
* displays "Hello World!" within an HTML document.
import java.awt.Graphics;
import java.applet.Applet;
public class HelloWorld extends Applet
public void init() // Initialize the canvas

Building skills for success

Java Programming Intro Chapter 2 Introduction to Java Programming 17

public void paint(Graphics g) // Display Hello World! now

g.drawString("Hello World!",50,25);
Line five uses the reserved word import which indicates that objects from an
external class (Graphics) is going to be used. Line seven uses the reserved word
extends to indicate that the class being created is a subclass of the Applet class. This
demonstrates how Java code is easily reused and extended.
Line nine starts the override (change) of the java.applet.Applet class init method.
Line eleven invokes the resize method of the Applet object and sets the window to a
specific value. Note the all important statement ending semicolon.
Line 13 is another method override declaration. This time it is the paint method of
the Applet object. It is being passed an object of class Graphics and called g. Line 15
tells the Graphics object g to invoke its method drawString using the string "Hello
World! and positioning it at point 50,25 in the previously assigned window.
Once the applet object is created it is referenced from an html document's applet
element. For example the above could be referenced by:
<applet code="HelloWorld.class></applet>

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
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"
// 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

Building skills for success

Java Programming Intro Chapter 2 Introduction to Java Programming 18

your programs for compilation. Whether they execute correctly is a whole different
issue ;-[


1. Compile and execute the code below.

import java.io.*;

public class ExerOne{

public static void main(String [] args){
BufferedReader r=new BufferedReader(new

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

System.out.println("Want to talk some more?");
System.out.println("Answer y for yes or n for no.");

char answerLetter;

}catch(Exception ex){};

if (answerLetter == 'y')
System.out.println("Nice weather we are having.");


2. Make a java program that print in the screen the following statements:
Java is great!!!
Java for one.
Java for all.
Follow the steps in compiling and executing java programs given earlier.

3. Here is another sample of a Java applet, try to compile and execute the
following code. Explore the code and take note of the objects used.

import javax.swing.*;

public class SampleApplet extends JApplet{

public void init(){

Building skills for success

Java Programming Intro Chapter 2 Introduction to Java Programming 19

JLabel myFirstLabel = new JLabel(“Hello out there!”);


Building skills for success

Variables and
Assignments + + + +



+ + + +

Variables are places in memory to store values. There are
different kinds of variables, and every language offers
slightly different characteristics.
Java Programming Intro Chapter 3 Variables and Assignments 21

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
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,
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.

Building skills for success

Java Programming Intro Chapter 3 Variables and Assignments 22

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

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).


1. Give the declaration for a variable called count of type int. The variable
should be initialized to zero in the declaration.

Building skills for success

Java Programming Intro Chapter 3 Variables and Assignments 23

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.

Building skills for success

Input / Output
+ + + +

Using Dialog Boxes

Using the Console

+ + + +

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'

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 Output 25

Dialog Box Output

This is very similar to the first program, but it actually does something. The
additional parts are described below.

1 // Description: This program shows a message in a dialog box.

// File: dialogOutput/SecondProgram.java
2 // Author: Michael Maus
3 // Date: 29 Mar 2005
4 import javax.swing.*;
public class SecondProgram {
7 public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Hello Earthling");
10 }
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

Building skills for success

Java Programming Intro Chapter 4 Input and Output 26

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.

Dialog Box Input-Output

This is similar to the previous program, but it also gets input from the user.

1 // Description: This program gets a string from a dialog box.

// File: dialogInputOutput/ThirdProgram.java
2 // Author: Michael Maus
3 // Date: 29 Jan 2005
4 import javax.swing.*;
public class ThirdProgram {
7 public static void main(String[] args) {
String humanName; // A local variable to hold the name.
9 humanName = JOptionPane.showInputDialog(null, "What's your name,
JOptionPane.showMessageDialog(null, "Take me to your leader, " +
11 humanName);
12 }
13 }

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).

Building skills for success

Java Programming Intro Chapter 4 Input and Output 27

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

Using Console:

Output to console just use System.out.println(“Contents here”);

Input imports the BufferedReader Class


import java.io.*;

public class Sample1 {

BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Please enter your name:”);
String name = “”;
try {
name = r.readLine();
} catch(Exception ex){};
System.out.println(“Your name is ”+name);

Building skills for success

Java Programming Intro Chapter 4 Input and Output 28


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

System.out.println(“Hello “ + firstInitial + ‘ ‘ + lastInitial + ‘!’);

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.

Building skills for success

Data Types CHAPTER
+ + + +



Every variable must have a data type. A variable's data Floating-Point

type determines the values that the variable can contain Boolean
and the operations that can be performed on it. Integers
can contain only integral values (both positive and
negative). You can perform arithmetic operations, such as + + + +
addition, on integer variables.
Java Programming Intro Chapter 5 Data Types 30

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 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.

How Java stores integers in memory

Java stores all integers in memory as binary numbers.
type Size Range
name bytes bits minimum Maximum
byte 1 8 -128 +127
short 2 16 -32,768 +32,767
int 4 32 -2,147,483,648 +2,147,483,647
long 8 64 -9,223,372,036,854,775,808 +9,223,372,036,854,775,807

Building skills for success

Java Programming Intro Chapter 5 Data Types 31

How to write integer literals

Here is how to write decimal integer literals (constants).
• int literals are written in the usual decimal notation, like 34 or -222.
• long literals are written by adding an L (or lowercase l altho this is almost
impossible to distinguish from the digit 1), eg, 34L or -222L.
• There is no way to write a literal byte or short, altho sometimes Java will
automatically cast an int literal to the appropriate type.

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 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

Java floating-point types

type Size Range Precision
name bytes bits approximate in decimal digits
float 4 32 +/- 3.4 * 1038 6-7
double 8 64 +/- 1.8 * 10308 15

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.

Building skills for success

Java Programming Intro Chapter 5 Data Types 32

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

Infinity and NaN

No exceptions are generated by floating-point operations. Instead of an interruption
in execution, the result of an operation may be positive infinity, negative infinity, or
NaN (not a number). Division by zero or overflow produce infinity. Subtracting two
infinities produces a NaN. Use methods in the wrapper classes (Float or Double) to
test for these values.

Converting Strings to Numbers

To convert a string value to a number (for example, to convert the String value in a
text field to an int), use these methods. Assume the following declarations:
String s; int i; long l; float f; double d;
type Example statement
Int i = Integer.parseInt(s);
long l = Long.parseLong(s);
float f = Float.parseFloat(s);
double d = Double.parseDouble(s);

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

Building skills for success

Java Programming Intro Chapter 5 Data Types 33

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);

For example, to convert a string containing the hexadecimal number "F7" to an

integer, call
i = Integer.parseInt("F7", 16)

The primitive type boolean has only two possible values: true and false.

Boolean literals - true and false

The two values are written with the reserved words true and false.

Building skills for success

Java Programming Intro Chapter 5 Data Types 34

Booleans in control statements

The if, for, while, and do statements all require boolean values. Usually these are
written as boolean valued expressions, using operators which produce boolean

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.

Other operators and methods returning boolean values

• The instanceof operator.
• Many methods return boolean values, eg, equals, and methods that begin
with "is". If you are writing your own boolean method, starting the name with
"is" is a good practice.
• Less common logical operators: &, |, and ^ with boolean operands. These
are generally used with bits. || (or) and && (and) are preferred to | and &
because they are short-circuit operators that can stop the evaluation when
one of the operands determines the resulting value.

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 {

Building skills for success

Java Programming Intro Chapter 5 Data Types 35

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 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.

Building skills for success

Java Programming Intro Chapter 5 Data Types 36

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 class static methods

Character Class Methods
Character class is used mostly for static methods to test char values.
b = Character.isDigit(c) true if c is digit character.
b = Character.isLetter(c) true if c is letter character.
b = Character.isLetterOrDigit(c) true if c is letter or digit.
b = Character.isLowerCase(c) true if c is lowercase char.
b = Character.isUpperCase(c) true if c is uppercase char.
b = Character.isWhitespace(c) true if c is space, tab, ....
c = Character.toLowerCase(c) Lowercase version of c.
c = Character.toUpperCase(c) Uppercase version of c.

ANSI/ASCII and Extended Latin Sections of Unicode

Unicode attempts to represent the characters in all current human languages, as well
as numerous special symbols. The most common implmentation of it uses 16 bits,
which is 65,536 characters (many are not yet assigned a graphic). The first 128 codes
are identical to ANSI/ASCII (American National Standards Institute / American
Standard Code for Information Interchange). Of the ASCII codes, the first 32 are
control codes. The first 256 codes are the same as ISO-8859-1 (Latin-1), which
includes ASCII of course. Below is a table which shows this common first part of the
Unicode character set. The table below is in HTML, so the actual characters that are
displayed are determined by your browser, not Java.

Building skills for success

Java Programming Intro Chapter 5 Data Types 37

+0 +1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15

32 ! " # $ % & ' ( ) * + , - . /
48 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
64 @ A B C D E F G H I J K L M N O
80 P Q R S T U V W X Y Z [ \ ] ^ _
96 ` a b c d e f g h i j K l m n o
112 P q r s t u v w x y z { | } ~ 
128 € ‚ ƒ „ … † ‡ ˆ ‰ Š ‹ Œ Ž
144 ‘ ’ “ ” • – — ˜ ™ š › œ ž Ÿ
160 ¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬ ® ¯
176 ° ± ² ³ ´ µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿
192 À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï
208 Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß
224 À á â ã ä å Æ ç è é ê Ë ì í î ï
240 Ð ñ ò ó ô õ Ö ÷ ø ù ú Û ü ý þ ÿ


1. Write a program that reads in a four digit number (like 1998) and that outputs
the number one digit per line, like so:


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.

Building skills for success

Expressions CHAPTER
+ + + +

Types of Expressions

Expressions within

Expressions are the basic way to create values. Comparison Operators

Expressions are created by combining literals (constants), + + + +
variables, and method calls by using operators.
Parentheses can be used to control the order of
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:

sum = expr1 + expr2;

In the preceding line, expr1 can be something as simple as the variable x or as

complex as (4 + 5) * 2 * 5 / 7 + x / y. The same goes for expr2, of course. And, in fact, the
first example containing expr1 and expr2 is an expression itself!
But no matter how complicated, all expressions can be classified into one of three
main categories:

• Numerical expressions combine numbers, variables, or constants using

mathematical operators. An example is 2 + 3 / x.
• Assignment expressions assign a value to a variable. An example is num = 3.
• Logical expressions are unique in that they result in a value of true or false. An
example is x < 3 (which reads "x is less than 3").

Expressions Within Expressions

In the previous chapter, whether you were aware of it or not, you used lots of
numerical and assignment expressions as you learned about mathematical
operators. And if you look closely at some of those expressions, you'll make a neat
discovery: Like a bunch of boxes that fit into each other, expressions often contain
other simpler expressions. For example, look at the following assignment expression:

num = (5 - x) * (2 + y);

This is an assignment expression because it assigns a value to the variable num.

However, the stuff on either side of the equals sign contains these other expressions:


(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:

Building skills for success

Java Programming Intro Chapter 6 Expressions 40

(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

Building skills for success

Java Programming Intro Chapter 6 Expressions 41

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

This expression results in a value of true, because 3 does not equal 4.

The other logical expressions work similarly. Table 8.2 lists a number of logical
expressions and the results they produce.
Table 8.2 Examples of Logical Expressions.
Expression Result
3 + 4 == 7 true
3 + 4 != 7 false
3 + 4 != 2 + 6 true
3 + 4 < 10 true
3 + 4 <= 10 true
3 + 4 == 4 + 4 false
3 + 4 > 10 false
3 + 4 >= 7 true
3 + 4 >= 8 false

Building skills for success

Java Programming Intro Chapter 6 Expressions 42


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.*;

public class ExerTwo{

public static void main (String[] args){
System.out.println("Enter the number of goals:");
BufferedReader r=new BufferedReader(new

String goalInput="";
int goals;

}catch(Exception ex){};


System.out.println("Oh Well");

Building skills for success

Simple Flow
of Control
+ + + +

General Forms

Condition is True or False

Both C++ and Java support several different kinds of else

if inside if
statements designed to alter or control the logical flow of
the program, although in some cases, the behavior of If-else-if
those statements differs between Java and C++. + + + +

The ability to alter the logical flow of the program is often

referred to as Flow of Control.
Java Programming Intro Chapter 7 Simple Flow of Control 44

if Statement - Overview

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

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
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.

Condition is true or false

The value of condition must be true or false (ie, a boolean value). It is often a
if (marks < 60) {
JOptionPane.showMessageDialog(null, "This is terrible");
} else {
JOptionPane.showMessageDialog(null, "Not so bad");

Building skills for success

Java Programming Intro Chapter 7 Simple Flow of Control 45

The code above will display one of two dialogs, depending on teh value of marks.

'else' Not Required

'else' is not required

It is not necessary to have the else part of an if statement. Maybe only 50% of the time
there is an else part.

The if statement without an else has this form:
if (condition) {
do this if the condition is true

Here is a paintComponent() method with an if statement without an else clause.
public void paintComponent(Graphics g) {
super.paintComponent(g); // draw background etc.
if (marks < 50) {
g.drawString("Score = " + marks, 10, 50);
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.

'if' Statement - Braces

Braces { } not required for one statement

If the true or false part of and if statement has only one statement, you do not need
to use braces (also called "curly brackets").

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
one statement to do if condition is false

Building skills for success

Java Programming Intro Chapter 7 Simple Flow of Control 46

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.
public void paintComponent(Graphics g) {
super.paintComponent(g); // call parent to paint background
if (marks < 50) {
g.setColor(Color.red); // bad marks in red
g.setColor(Color.black); // good marks in black
g.drawString("Score = " + marks, 10, 50);
and now without braces. Altho correct, it is not as safe a style.
public void paintComponent(Graphics g) {
super.paintComponent(g); // call parent to paint background
if (marks < 50)
g.setColor(Color.red); // bad marks in red
g.setColor(Color.black); // good marks in black
g.drawString("Score = " + marks, 10, 50);

Example 2 - only a true part

If there is only a true part of the if statement, it only needs braces if there is more than
one statment.
public void paintComponent(Graphics g) {
if (marks < 50)
g.setColor(Color.red); // bad marks in red
g.drawString("Score = " + marks, 10, 50);
If the if condition is false, this will not set the color, so the default color will be used

Building skills for success

Java Programming Intro Chapter 7 Simple Flow of Control 47

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

What is a statement?
A statement is a part of a Java program. We have already seen some simple
• 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' Statement - Indentation

Indent to make programs readable

There are several meathods to make programs readable. How can you easily make
the reader see which statements are inside the true part and false part of an if
The best way to show this is to indent the statements that are inside. To do this you
move the statements to the right by a few spaces. People commonly use two,
three, or four spaces. Choose one number (eg, I use 2 or 3), and use it for all
Java doesn't care about your indentation -- it is for humans (including yourself!).

Example 1 - No indentation - BAD BAD BAD

Here is the paintComponent() method from a previous page without indentation. This
is small, so it's easy to see which statements are in the true and false parts. If the if
statement is much larger, it will be unreadable without indentation.
public void paintComponent(Graphics g) {
if (marks < 50)
g.drawString("Score = " + marks, 10, 50);

Building skills for success

Java Programming Intro Chapter 7 Simple Flow of Control 48

Example 2 - No indentation and no line breaks

Even a very short method is almost unreadable when you take out the line breaks
and spaces. Here is the same method:
public void paintComponent(Graphics g) {super.paintComponent(g);if (marks<50)
g.setColor(Color.red);else g.setColor(Color.black);g.drawString("Score = " + marks,10,50);}

'if' Statement - if inside if

if inside if
You can put an if statement inside another if statement.

Example -- series of tests

This code is correctly indented, but ugly and hard to read. It also can go very far to
the right if there are many tests.
if (score < 35)
if (score < 50)
if (score < 60)
if (score < 80)

Nearest 'else'
If you use braces, there is no problem with deciding which else goes with which if For
if (age < 24) {
if (height > 200) {
c = Color.red;
} else {

Building skills for success

Java Programming Intro Chapter 7 Simple Flow of Control 49

c = Color.blue;
Because the true and false parts are both single statements, you might want to leave
out the braces and write:
if (age < 24)
if (height > 200)
c = Color.red;
else // DANGER: which 'if' goes with this 'else'
c = Color.blue;
But this is WRONG, because 'else' always goes with the nearest 'if' when there are no
braces. This code is the same as:
if (age < 24) {
if (height > 200)
c = Color.red;
c = Color.blue;

Advice: Always use braces on if statements

These kinds of errors are very hard to find. This is another good reason to always
use braces.

Watch out for semicolons on your if statements

Why does the following code always say it thinks the user is lying?
String ageStr = JOptionPane.showInputDialog(null, "How old are
int age = Integer.parseInt(ageStr);
if (age > 120 || age < 0);
System.out.println("I think you're lying about your age!");
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.

Building skills for success

Java Programming Intro Chapter 7 Simple Flow of Control 50

'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.

Example -- series of tests

This code is correctly indented, but ugly and hard to read. It also can go very far to
the right if there are many tests.
if (score < 35)
if (score < 50)
if (score < 60)
if (score < 80)

Example -- using 'else if' style

Here is the same example, using a style of writing the if immediately after the else.
This is a common exception to the indenting rules, because it results in much more
readable programs:
if (score < 35)
else if (score < 50)
else if (score < 60)
else if (score < 80)

Building skills for success

Java Programming Intro Chapter 7 Simple Flow of Control 51

Some programming languages recognize this as a common kind
structured-programming construction, and have a special 'elseif'
statement. This would be a nice thing to add to Java.


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.

Building skills for success

Program Style + + + +


Legal Characters


The goal of good programming style is to make the + + + +

program human readable, not only for the programmer
developing the program, but for the programmer who will
maintain the code later, and for a user who wants to know
if the program will perform the tasks which he/she needs.
Java Programming Intro Chapter 8 Program Style 53

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).

Spaces and blank lines

One of the most effective ways to make a program readable is to put spaces in at key
points. There are several styles for doing this. Even more important is to put blank
lines in your program. These should separate sections of code. There should be a
blank line between each "paragraph" of code. By paragraph, I mean a group of
statements that belong together logically; there is no Java concept of paragraph.

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.

/* ... */ comments -- multiple lines

After the /* characters, Java will ignore everything until it finds a */. This kind
of comment can cross many lines, and is commonly used to "comment out"
sections of code -- making Java code into a comment while debugging a
program. For example,
/* Use comments to describe variables or sections of the
They are very helpful to everyone who reads your programs:
your teacher, your boss, but especially yourself!
javadoc comments
Comments that start with /** are used by the javadoc program to produce
HTML documentation for the program. The Java documentation from Sun
Microsystems is produced using javadoc. It is essential to use this kind of
comment for large programs.

Building skills for success

Java Programming Intro Chapter 8 Program Style 54

Best Practices
• Don't write comments to document obvious statements. Assume the reader
knows Java.
• Every comment has the potential to create an inconsistency between what the
comment says, and what the code does. One cause of "software rot" is that
code is changed over time, but comments are not updated. To avoid this, keep
comments next to the code that is documented so that they may be more
easily synchonized.

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, ...).

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

Using Uppercase, Lowercase, and "Camelcase" Letters

The conventions for the use of upper- and lowercase is not enforced by compilers,
but it is so widely observed, that it should have been. Camelcase is the practice of
capitalizing the first letter of successive words in multi-word identifiers. Camelcase is
much preferred in the Java community over the use of underscores to separate
words, or even worse, no distinction made at word boundaries.
Class and interface names - Start with uppercase

Building skills for success

Java Programming Intro Chapter 8 Program Style 55

Class and interface names start with an uppercase letter, and continue in
lowercase. For multiple words, use camelcase. Eg, Direction, LogicalLayout,
Variable and method names - Lowercase
Lowercase is used for variable and method names. If a name has multiple
words, use camelcase. Eg, top, width, topLeft, roomWidth, incomeAfterTaxes.
Constants - All uppercase, use _ to separate words
The names of constants (typically declared static final) should be in all
uppercase. For example, BorderLayout.NORTH. When constant names are made
from multiple words, use an underscore to separate words, eg,

Readable names are more important than most comments

Java doesn't care if your names are readable, but it's really important to make your
names readable to humans.
I once worked on a project where we had to distribute the source code so that it
could be compiled on another machine, but we didn't want to reveal our algorithms.
We deleted all comments and indentation, and wrote a small program to change all
variable names to combinations of "I", "1", "O", and "0", figuring that it would be too
much effort for them to decode it. For example, the semi-readable
LogicalGapInfo topBorder =
m_logicalLayout.getGapInfo(LogicalLayout.AXIS_V, 0);
Could be translated into
I001O I00I0 = O1001.OI001(O1OOI.IO010, 0);

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
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.

Building skills for success

Java Programming Intro Chapter 8 Program Style 56

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
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

Example: import all classes in a package

The JOptionPane class is in the swing package, which is located in the javax
import javax.swing.*; // Make all classes visible altho only one is used.

class ImportTest {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Hi");

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.

Building skills for success

Java Programming Intro Chapter 8 Program Style 57

Example: import only one class in a package

import javax.swing.JOptionPane; // Make a single class visible.

class ImportTest {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Hi");

Example: Use explicit qualification instead of import

There is no need to use import when names are fully qualified. You will see some
programs in this style, but it isn't as common because it makes source programs
more congested and harder to read.
class ImportTest {
public static void main(String[] args) {
javax.swing.JOptionPane.showMessageDialog(null, "Hi");

import FAQ
1. Q: Does importing all classes in a package make my object file (.class or .jar)

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: This shows good intentions, but ...

o It's hard to remember to remove classes when they are no longer used,
so the import list is surprisingly often wrong. It can seriously slow
down reading because unusual or unexpected class imports make me
look for that class, only to discover that it must have been used in an
earlier version.

Building skills for success

Java Programming Intro Chapter 8 Program Style 58

o Explicit class imports permit accidentally defining classes with names

that conflict with the standard library names. This is very bad. Using
"*" to import all classes prevents this dangerous naming accident.
o It's annoying to always update this list.
4. Q: I've imported java.awt.*, why do I also need java.awt.event.*?

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?

A: All classes in the java.lang package are visible without an import.

6. Q: Is the order of the imports important?

A: No. Group them for readability.

Static imports in Java 5

Java 5 added an import static option that allows static variables (typically constants)
to be referenced without qualifying them with a class name. For example, after
import static java.awt.Color;
It would then be possible to write
Color background = RED;
instead of
Color background = Color.RED;

Adding this "feature" wasn't the best idea because it leads to name pollution and
confusion about which class constants come from. Even Sun (see References below)
basically advises not to it!

Building skills for success

Using Logical
+ + + +

Logical Operators

Writing Logical Expressions

+ + + +
Java Programming Intro Chapter 9 Using Logical Expressions 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
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

(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
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)


(4 + 1 == 5) || (7 + 2 == 9)

Building skills for success

Java Programming Intro Chapter 9 Using Logical Expressions 61

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

(5 + 7 == 12) ^ (4 + 3 == 8)

evaluates to true, whereas these expressions evaluate to false:

(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)

is false; however, the expression

!(4 + 3 == 5)

is true.

Example: Using Logical Operators

Take a look at the following expression:

(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.

Example: Using Multiple Logical Operators

Just as with mathematical operators, you can use multiple logical operators to
compare several logical expressions. For example, look at this expression:

Building skills for success

Java Programming Intro Chapter 9 Using Logical Expressions 62

(4 == 4) && (5 == 5) && (6 == 6)

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.

Example: Combining Different Comparison and Logical Operators

Again, just like mathematical operators, there's no restriction on how you can
combine the different comparison and logical operators, although if you build a very
complex expression, you may have trouble evaluating it yourself. Check out this

(3 < 5) && (2 == 2) && (9 > 6)

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:

((3 < 5) && (2 == 1)) || (7 == 7)

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:

((3 < 5) && (2 == 1)) || (7 == 7)

((true) && (false)) || (7 == 7)

Building skills for success

Java Programming Intro Chapter 9 Using Logical Expressions 63

false || (7 == 7)

false || true


Writing Logical Expressions

You wouldn't write expressions such as

(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

(num < 9) && (num > 15)

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.

Building skills for success

Special Operators + + + +

Bitwise Operators

Other Operators

+ + + +
Java Programming Intro Chapter 10 Special 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.

The bitwise operators

Operator Name Example Result Description
a&b and 3&5 1 1 if both bits are 1.
a|b or 3|5 7 1 if either bit is 1.
a^b xor 3^5 6 1 if both bits are different.
~a not ~3 -4 Inverts the bits.
Shifts the bits of n left p positions. Zero
n << p 3 <<< 2 12 bits are shifted into the low-order
Shifts the bits of n right p positions. If n is
n >> p 5 >> 2 1 a 2's complement signed number, the sign
bit is shifted into the high-order positions.
right Shifts the bits of n right p positions. Zeros
n >>> p -4 >>> 28 15
shift are shifted into the high-order positions.

Use: Packing and Unpacking

A common use of the bitwise operators (shifts with ands to extract values and ors to
add values) is to work with multiple values that have been encoded in one int. Bit-
fields are another way to do this. For example, let's say you have the following
integer variables: age (range 0-127), gender (range 0-1), height (range 0-128). These
can be packed and unpacked into/from one short (two-byte integer) like this (or
many similar variations).
int age, gender, height;
short packed_info;
// packing
packed_info = (((age << 1) | gender) << 7) | height;

Building skills for success

Java Programming Intro Chapter 10 Special Operators 66

// unpacking
height = packed_info & 0x7f;
gender = (packed_info >>> 7) & 1;
age = (packed_info >>> 8);

Use: Setting flag bits

Some library functions take an int that contains bits, each of which represents a
true/false (boolean) value. This saves a lot of space and can be fast to process. [needs

Use: Shift left multiplies by 2; shift right divides by 2

On some older computers it was faster to use shift instead of multiply or divide.
y = x << 3; // Assigns 8*x to y.
y = (x << 2) + x; // Assigns 5*x to y.

Use: Flipping between on and off with xor

Sometimes xor is used to flip between 1 and 0.
x = x ^ 1; // Or the more cryptic x ^= 1;
In a loop that will change x alternately between 0 and 1.

Obscure use: Exchanging values with xor

Here's some weird code. It uses xor to exchange two values (x and y). This is
translated to Java from an assembly code program, where there was no available
storage for a temporary. Never use it; this is just a curiosity from the museum of
bizarre code.
x = x ^ y;
y = x ^ y;
x = x ^ y;

Don't confuse && and &

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.

Building skills for success

The ‘switch’
+ + + +


comments on switch

+ + + +
Java Programming Intro Chapter 11 The ‘switch’ statement 68

switch Statement - Overview

Purpose of switch: select one of many possible statements to execute

The if statement allows you to select one of two sections of code to execute based on a
boolean value (only two possible values). The switch statement allows you to choose
from many statements based on an integer value.

Equivalent to cascading ifs

A switch can be rewritten with a series of cascading if statements, but in some cases
the switch statement is easier to read, and in a some compilers it can produce more
efficient code.

switch (expr) {
case c1:
statements // do these if expr == c1
case c2:
statements // do these if expr == c2
case c2:
case c3:
case c4: // Cases can simply fall thru.
statements // do these if expr == any of c's
statements // do these if expr != any above

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.

Building skills for success

Java Programming Intro Chapter 11 The ‘switch’ statement 69

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
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.
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.

Example - Random comment

/** Returns a random ambiguous compliment. */
public static String ambiguousCompliment() {
String result; // The generated insult which will be returned
int which = (int)(Math.random() * 4); // Should result in 0 to 3.

switch (which) {
case 0: result = "You look so much better than usual.";
case 1: result = "Your work is up to its usual standards.";
case 2: result = "You're quite competent for so litte experience.";
default: result = "Oops -- something is wrong with this code.";
return result;
Always include a default clause in your switch statement as a general policy of
defensive programming - assume there will be bugs in your code and make sure they
are caught. In fact the function above does have a bug in it that would be caught by
the default clause!

Where to use switch - not that many places

The ability of switch to choose between many sections of code seems to make it more
powerful than if. However, selecting sections of code depending on specific integer
values turns out not to be very common. If you are handling some specific coded

Building skills for success

Java Programming Intro Chapter 11 The ‘switch’ statement 70

values (eg, the number of the button that was clicked in a JOptionPane), or or
processing characters (whose codes are treated like numbers), you will not use it.

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.

It is error-prone and a common source of bugs - forgetting

break or default silently ignores errors. Some other
languages have eliminated these dangerous situations.


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”.

Building skills for success

Order of
+ + + +


+ + + +
Java Programming Intro Chapter 12 Order of Precedence 72

Order of Precedence

The operators in Java, shown in order of precedence - from highest to

Priority Operators Operation Associativity
[] array index
1 () method call Left
. member access

++ pre- or postfix increment

-- pre- or postfix decrement
+- unary plus, minus
2 ~ bitwise NOT Right
! boolean (logical) NOT
(type) type cast
new object creation

3 */% multiplication, division, remainder Left

+- addition, substraction
4 Left
+ string concatenation

<< signed bit shift left

5 >> signed bit shift right Left
>>> unsigned bit shift right

< <= less than, less than or equal to

6 > >= greater than, greater than or equal to Left
instanceof reference test

Building skills for success

Java Programming Intro Chapter 12 Order of Precedence 73

== equal to
7 Left
!= not equal to

& bitwise AND

8 Left
& boolean (logical) AND

^ bitwise XOR
9 Left
^ boolean (logical) XOR

| bitwise OR
10 Left
| boolean (logical) OR

11 && boolean (logical) AND Left

12 || boolean (logical) OR Left

13 ?: conditional Right

= assignment
*= /= += -= %=
14 <<= >>= >>>= combinated assignment Right
&= ^= (operation and assignment)

Building skills for success

+ + + +


do-while loop

Often in programming a number of statements need to 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

Loops - 'while' and 'for'

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;
while {i < names.length) (
for statement - traditional three part
If you want to repeat a block of statements a fixed number of times, the for
loop is the right choice. It's alos used in many other cases where there the
intitialization of a loop, the loop condition, and the loop increment can be
for (int i = 0; i < names.length; i++) (
do..while statement - Test at end
When you want to test at the end to see whether something should be
repeated, the do..while statement is the natural choice.
do (
String ans = JOptionPane.showInputDialog(null, "Do it again
} while (ans.equals("Y"));
for statement - Java 5 data structure iterator
Java 5 introduced what is sometimes called a "for each" statement that
accesses each successive element of an array, List, or Set without the
bookkeeping associated with iterators or indexing.
for (String s : names) (

Building skills for success

Java Programming Intro Chapter 13 Looping 76

Similar to the 'if' statement

There are three general ideas that you will see in many parts of Java.
• use of braces {} to enclose multiple statements.
• indentation
• boolean (true/false) conditions.

Scope of loop indicated with braces {}

If the body of a loop has more than one statement, you must put the statements
inside braces. If there is only one statement, it is not necessary to use braces {}.
However, many programmers think it is a good idea to always use braces to
indicate the scope of statements. Always using braces allows the reader to relax and
not worry about the special single statement case.

Indentation of loops
All statements inside a loop should be indented 2-4 spaces (the same as an if

boolean true/false conditions

True/false (boolean) expressions control both loops and the if statement.

'while' Statement

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

Condition is true or false

The value of condition must be true or false (ie, a boolean value). It is often a
comparison (see example below).

Example: Loop continues while the condition is true

public void paintComponent(Graphics g) {
int count = 0;
while (count < 50) {
g.drawLine(20, count*5, 80, count*5);

Building skills for success

Java Programming Intro Chapter 13 Looping 77

count = count + 1;
g.drawString("Loop is finished. count="+count, 10, 300);
}//end paintComponent
This repeats the drawLine() call 50 times. The first time the while condition is tested,
it is true because the value of count is 0, which is less than 50. After the statements in
the body are done, the while loop comes back to the top of the loop and makes the
test again. Each time the value of count is larger. Finally, count is 50, and the value of
the condition will be false.
When the loop stops, the program continues with the statement after the end of the
loop (the drawLine() call). This will display the string "Loop is finished. count=50".

'for' Statement

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
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.

Here is a loop written as both a while loop and a for loop. First using while:
count = 0;
while (count < 50) {
g.drawLine(20, count*5, 80, count*5);
count = count + 1;

Building skills for success

Java Programming Intro Chapter 13 Looping 78

g.drawString("Loop is finished. count="+count, 10, 300);

And here is the same loop using for:
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


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.

Building skills for success

Using Methods
+ + + +



The word method is commonly used in Object-Oriented Vocabulary
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
Java Programming Intro Chapter 14 Programming Using Methods 80

Methods - Introduction

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

Why use methods?

For reusable code
If you need to do the same thing, or almost the same thing, many times, write
a method to do it, then call the method each time you have to do that task.
To parameterize code
In addition to making reusable code that is the same in all cases, you will
often want to use parameters that change the way the method works.
For top-down programming
A very useful style of programming is called top-down programming. You
solve a big problem (the "top") by breaking it down into little problems. To do
this in a program, you write a method for solving your big problem by calling
on other methods to solve the smaller parts of the problem. And these
methods for solving the simpler problems similarly call on other methods
until you get down to simple methods which solve simple problems
To create conceptual units
Create methods to do something that is one action in your mental view of the
problem. This will make it much easier for you to work with your programs.
To simplify
Because local variables and statements of a method can not been seen from
outside the method, they (and their complexity) are hidden from other parts
of the program, which prevents accidental errors or confusion.

Methods - Example

This example shows a simple method that computes the area of a rectangle:
1. int computeArea(int width, int height) {
2. int area; // This is a local variable
3. area = width * height;
4. return area;
5. }

Building skills for success

Java Programming Intro Chapter 14 Programming Using Methods 81

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.

[access] [static] [type] name( [parameters] ) { body }

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
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)

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.

Building skills for success

Java Programming Intro Chapter 14 Programming Using Methods 82

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

What happens when a method is called

1. Space on the call stack is reserved for the return address, the local variables
and formal parameters, and perhaps other things in the current method that
must be saved.
2. The actual parameters are copied into the formal parameters.
3. Execution is transferred to the beginning of the called method.
4. When the method returns, the return address specifies where to continue
execution in the caller and the caller's state is restored. If the method returned
a value, that value is passed back to the caller.

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.

Building skills for success

Java Programming Intro Chapter 14 Programming Using Methods 83

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.

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..

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
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

Building skills for success

Java Programming Intro Chapter 14 Programming Using Methods 84

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
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.
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
• 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.

Building skills for success

Java Programming Intro Chapter 14 Programming Using Methods 85

• 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

Qualifying a static call

From outside the defining class, an instance method is called by prefixing it with an
object, which is then passed as an implicit parameter to the instance method, eg,
A static method is called by prefixing it with a class name, eg, Math.max(i,j);.
Curiously, it can also be qualified with an object, which will be ignored, but the class
of the object will be used.

Here is a typical static method.
class MyUtils {
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

Why declare a method static

The above mean() method would work just as well if it wasn't declared static, as long as
it was called from within the same class. If called from outside the class and it wasn't

Building skills for success

Java Programming Intro Chapter 14 Programming Using Methods 86

declared static, it would have to be qualified (uselessly) with an object. Even when
used within the class, there are good reasons to define a method as static when it
could be.
• Documentation. Anyone seeing that a method is static will know how to call
it (see below). Similarly, any programmer looking at the code will know that a
static method can't interact with instance variables, which makes reading and
debugging easier.
• Efficiency. A compiler will usually produce slightly more efficient code
because no implicit object parameter has to be passed to the method.

Calling static methods

There are two cases.
Called from within the same class
Just write the static method name. Eg,
// Called from inside the MyUtils class
double avgAtt = mean(attendance);
Called from outside the class
If a method (static or instance) is called from another class, something must
be given before the method name to specify the class where the method is
defined. For instance methods, this is the object that the method will access.
For static methods, the class name should be specified. Eg,
// Called from outside the MyUtils class.
double avgAtt = MyUtils.mean(attendance);
If an object is specified before it, the object value will be ignored and the the
class of the object will be used.

Accessing static variables

Altho a static method can't access instance variables, it can access static variables. A
common use of static variables is to define "constants". Examples from the Java
library are Math.PI or Color.RED. They are qualified with the class name, so you know
they are static. Any method, static or not, can access static variables. Instance variables
can be accessed only by instance methods.

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

Building skills for success

Java Programming Intro Chapter 14 Programming Using Methods 87


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.

Building skills for success

+ + + +




+ + + +
Java Programming Intro Chapter 15 Classes 89

Class and Interface Concepts

Class and Interface Concepts

Here are some of the basic building blocks of Objected-Oriented Programming that
you will become familiar with:
A collection of fields (instance and class variables) and methods.
instance variable (aka field variable or member variable
An instance variable is a variable that is defined in a class, but outside of a
method. There is one copy of the variable for every instance (object) created
from that class.

A common problem is trying to reference an instance variable from a static

method. A static method (eg, main) can only reference static variables in its
own class (or its own local variables).
class variable (aka static variable)
A class variable or static variable is defined in a class, but there is only one
copy regardless of how many objects are created from that class. It's common
to define static final variables (constants) that can be used by all methods, or by
other classes. Color.blue is an example of a static final variable.
When an object is created, a constructor for that class is called. If no
constructor is defined, a default constructor is called. It's common to have
multiple constructors taking different numbers of parameters. Before a
constructor is executed, the constructor for the parent class is called implicitly
if there is no parent constructor called explicitly on the first line.
inner class

Building skills for success

Java Programming Intro Chapter 15 Classes 90

If a class is defined within another class, it is an inner class. There are two
common reasons to do this: to attach an anonymous listener to a control at
the point where the control is being built, and to have access to the fields and
methods of the enclosing class.
override (applies to methods)
If a subclass redefines a method defined in a superclass, the method in the
superclass is overridden. A common use of this is in defining a subclass of
JPanel that you use for graphics. When you define the paintComponent method,
you are overriding the one that is already defined in JPanel. In
paintComponent, but not in most overriding methods, you should call the
method in the parent class with super.paintComponent. The "super" keyword is
how you refer to the overridden parent method. There is no way to explicitly
call the "grandparent's" method if it was overridden by the parent class.
overload (applies to methods)
A method in a class is overloaded if there is more than one method by the
same name. If the same name is used, the methods must different in the
number and/or types of the parameters so that there is no confusion. This
really has nothing to do with classes, only methods.
abstract class
A class which doesn't define all it's methods is called an abstract class. To be
useful, there must be a subclass which defines the missing methods. The "You
must declare this class abstract" error message from the Java compiler is
rather misleading. This usually means that you declared your class to
implement an interface, but failed to write all required methods -- or more
commonly that there's a spelling error in a method header.
An interface is a list of methods that must be implemented. A class that
implements an interface must define all those methods. The method signatures
(prototypes) are listed in the interface. Interfaces may also define public static
final "constants". An interface is essentially the same as an completely
abstract class.

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.

Building skills for success

Java Programming Intro Chapter 15 Classes 91

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 Class Declaration

The left side of the following diagram shows the possible components of a class
declaration in the order they should or must appear in your class declaration. The
right side describes their purposes. The required components are the class keyword
and the class name and are shown in bold. All the other components are optional,
and each appears on a line by itself (thus "extends Super" is a single component).
Italics indicates an identifier such as the name of a class or interface. If you do not
explicitly declare the optional items, the Java compiler assumes certain defaults: a
nonpublic, nonabstract, nonfinal subclass of Object that implements no interfaces.

Building skills for success

Java Programming Intro Chapter 15 Classes 92

The following list provides a few more details about each class declaration
component. It also provides references to sections later in this trail that talk about
what each component means, how to use each, and how it affects your class, other
classes, and your Java program.
By default, a class can be used only by other classes in the same package. The
public modifier declares that the class can be used by any class regardless of
its package. Look in Creating and Using Packages for information about
how to use modifiers to limit access to your classes and how it affects your
access to other classes.
Declares that the class cannot be instantiated. For a discussion about when
abstract classes are appropriate and how to write them, see Writing
Abstract Classes and Methods .
Declares that the class cannot be subclassed. Writing Final Classes and
Methods shows you how to use final and discusses the reasons for using it.
class NameOfClass
The class keyword indicates to the compiler that this is a class declaration and
that the name of the class is NameOfClass.
extends Super
The extends clause identifies Super as the superclass of the class, thereby
inserting the class within the class hierarchy.
How Do These Concepts Translate into Code? in the Object-
Oriented Programming Concepts lesson, showed you a subclass of
Applet and talked briefly about the responsibilities and benefits of subclasses.
Managing Inheritance goes into further detail on this subject.
implements Interfaces
To declare that your class implements one or more interfaces, use the
keyword implements followed by a comma-separated list of the names of the
interfaces implemented by the class. How Do These Concepts Translate
into Code? explained how the ClickMe applet implements an interface.
Details about writing your own interfaces and how to use them can be found
in Getting Started .

Building skills for success

Java Programming Intro Chapter 15 Classes 93

The Class Body

The class body contains all of the code that provides for the life cycle of the objects
created from it: constructors for initializing new objects, declarations for the
variables that provide the state of the class and its objects, methods to implement the
behavior of the class and its objects, and in rare cases, a finalize method to provide for
cleaning up an object after it has done its job.
Variables and methods collectively are called members.

Note: Constructors are not methods. Nor are they members.

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.

Providing Constructors for Your Classes

All Java classes have constructors that are used to initialize a new object of that type.
A constructor has the same name as the class. For example, the name of the Stack
class's constructor is Stack, the name of the Rectangle class's constructor is Rectangle,
and the name of the Thread class's constructor is Thread. Stack defines a single
public Stack() {
items = new Vector(10);
Java supports name overloading for constructors so that a class can have any
number of constructors, all of which have the same name. Following is another
constructor that could be defined by Stack. This particular constructor sets the initial
size of the stack according to its parameter:
public Stack(int initialSize) {
items = new Vector(initialSize);
Both constructors share the same name, Stack, but they have different parameter
lists. The compiler differentiates these constructors based on the number of
parameters in the list and their types.
Typically, a constructor uses its arguments to initialize the new object's state. When
creating an object, choose the constructor whose arguments best reflect how you
want to initialize the new object.
Based on the number and type of the arguments that you pass into the constructor,
the compiler can determine which constructor to use. The compiler knows that when
you write the following code, it should use the constructor that requires a single
integer argument:
new Stack(10);
Similarly, when you write the following code, the compiler chooses the no-argument
constructor or the default constructor:

Building skills for success

Java Programming Intro Chapter 15 Classes 94

new Stack();
When writing your own class, you don't have to provide constructors for it. The
default constructor is automatically provided by the runtime system for any class
that contains no constructors. The default provided by the runtime system doesn't do
anything. So, if you want to perform some initialization, you will have to write some
constructors for your class.
The constructor for the following subclass of Thread performs animation, sets up
some default values, such as the frame speed and the number of images, and then
loads the images:
class AnimationThread extends Thread {
int framesPerSecond;
int numImages;
Image[] images;

AnimationThread(int fps, int num) {

this.framesPerSecond = fps;
this.numImages = num;

this.images = new Image[numImages];

for (int i = 0; i <= numImages; i++) {
// Load all the images.
Note how the body of a constructor is like the body of a method; that is, it contains
local variable declarations, loops, and other statements. However, one line in the
AnimationThread constructor that you wouldn't see in a method is the second line:
This line invokes a constructor provided by the superclass of AnimationThread, namely,
Thread. This particular Thread constructor takes a String that sets the name of Thread.
Often a constructor wants to take advantage of initialization code written in a class's
superclass. Indeed, some classes must call their superclass constructor in order for
the object to work properly. If present, the superclass constructor must be the first
statement in the subclass's constructor: An object should perform the higher-level
initialization first.
You can specify what other objects can create instances of your class by using an
access specifier in the constructors' declaration:

Building skills for success

Java Programming Intro Chapter 15 Classes 95

No other class can instantiate your class. Your class may contain public class
methods (sometimes called factory methods), and those methods can
construct an object and return it, but no other classes can.
Only subclasses of the class and classes in the same package can create
instances of it.
Any class can create an instance of your class.
no specifier gives package access
Only classes within the same package as your class can construct an instance
of it.
Constructors provide a way to initialize a new object. Initializing Instance and
Class Members describes other ways you can provide for the initialization of your
class and a new object created from the class. That section also discusses when and
why you would use each technique.

Declaring Member Variables

Stack uses the following line of code to define its single member variable:
private Vector items;
This declares a member variable and not some other type of variable (like a local
variable) because the declaration appears within the class body but outside of any
methods or constructors. The member variable declared is named items, and its data
type is Vector. Also, the private keyword identifies items as a private member. This
means that only code within the Stack class can access it.

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
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.
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

Building skills for success

Java Programming Intro Chapter 15 Classes 96

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.
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.
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.
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.
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() {

Understanding Instance and Class Members

When you declare a member variable such as aFloat in MyClass:
class MyClass {
float aFloat;
you declare an instance variable. Every time you create an instance of a class, the
runtime system creates one copy of each class's instance variables for the instance.
You can access an object's instance variables from an object as described in Using
Objects .
Instance variables are in contrast to class variables (which you declare using the
static modifier). The runtime system allocates class variables once per class regardless
of the number of instances created of that class. The system allocates memory for

Building skills for success

Java Programming Intro Chapter 15 Classes 97

class variables the first time it encounters the class. All instances share the same
copy of the class's class variables. You can access class variables through an instance
or through the class itself.
Methods are similar: Your classes can have instance methods and class methods.
Instance methods operate on the current object's instance variables but also have
access to the class variables. Class methods, on the other hand, cannot access the
instance variables declared within the class (unless they create a new object and
access them through the object). Also, class methods can be invoked on the class, you
don't need an instance to call a class method.
By default, unless otherwise specified, a member declared within a class is an
instance member. The class defined below has one instance variable--an integer
named x--and two instance methods--x and setX--that let other objects set and query
the value of x:
class AnIntegerNamedX {
int x;
public int x() {
return x;
public void setX(int newX) {
x = newX;
Every time you instantiate a new object from a class, you get a new copy of each of
the class's instance variables. These copies are associated with the new object. So,
every time you instantiate a new AnIntegerNamedX object from the class, you get a new
copy of x that is associated with the new AnIntegerNamedX object.
All instances of a class share the same implementation of an instance method; all
instances of AnIntegerNamedX share the same implementation of x and setX. Note that
both methods, x and setX, refer to the object's instance variable x by name. "But", you
ask, "if all instances of AnIntegerNamedX share the same implementation of x and
setX isn't this ambiguous?" The answer is "no." Within an instance method, the name
of an instance variable refers to the current object's instance variable, assuming that
the instance variable isn't hidden by a method parameter. So, within x and setX, x is
equivalent to this.x.
Objects outside of AnIntegerNamedX that wish to access x must do so through a
particular instance of AnIntegerNamedX. Suppose that this code snippet was in another
object's method. It creates two different objects of type AnIntegerNamedX, sets their x
values to different values, then displays them:
AnIntegerNamedX myX = new AnIntegerNamedX();
AnIntegerNamedX anotherX = new AnIntegerNamedX();
anotherX.x = 2;

Building skills for success

Java Programming Intro Chapter 15 Classes 98

System.out.println("myX.x = " + myX.x());

System.out.println("anotherX.x = " + anotherX.x());
Notice that the code used setX to set the x value for myX but just assigned a value to
anotherX.x directly. Either way, the code is manipulating two different copies of x: the
one contained in the myX object and the one contained in the anotherX object. The
output produced by this code snippet is:
myX.x = 1
anotherX.x = 2
showing that each instance of the class AnIntegerNamedX has its own copy of the
instance variable x and each x has a different value.
You can, when declaring a member variable, specify that the variable is a class
variable rather than an instance variable. Similarly, you can specify that a method is
a class method rather than an instance method. The system creates a single copy of a
class variable the first time it encounters the class in which the variable is defined.
All instances of that class share the same copy of the class variable. Class methods
can only operate on class variables--they cannot access the instance variables defined
in the class.
To specify that a member variable is a class variable, use the static keyword. For
example, let's change the AnIntegerNamedX class such that its x variable is now a class
class AnIntegerNamedX {
static int x;
public int x() {
return x;
public void setX(int newX) {
x = newX;
Now the exact same code snippet from before that creates two instances of
AnIntegerNamedX, sets their x values, and then displays them produces this,
different, output.
myX.x = 2
anotherX.x = 2
The output is different because x is now a class variable so there is only one copy of
the variable and it is shared by all instances of AnIntegerNamedX, including myX and
anotherX. When you invoke setX on either instance, you change the value of x for all
instances of AnIntegerNamedX.
You use class variables for items that you need only one copy of and which must be
accessible by all objects inheriting from the class in which the variable is declared.

Building skills for success

Java Programming Intro Chapter 15 Classes 99

For example, class variables are often used with final to define constants; this is more
memory efficient than final instance variables because constants can't change, so you
really only need one copy).
Similarly, when declaring a method, you can specify that method to be a class
method rather than an instance method. Class methods can only operate on class
variables and cannot access the instance variables defined in the class.
To specify that a method is a class method, use the static keyword in the method
declaration. Let's change the AnIntegerNamedX class such that its member variable x is
once again an instance variable, and its two methods are now class methods:
class AnIntegerNamedX {
int x;
static public int x() {
return x;
static public void setX(int newX) {
x = newX;
When you try to compile this version of AnIntegerNamedX, the compiler displays an
error like this one:
AnIntegerNamedX.java:4: Can't make a static reference to
nonstatic variable x in class AnIntegerNamedX.
return x;
This is because class methods cannot access instance variables unless the method
created an instance of AnIntegerNamedX first and accessed the variable through it.
Let's fix AnIntegerNamedX by making its x variable a class variable:
class AnIntegerNamedX {
static int x;
static public int x() {
return x;
static public void setX(int newX) {
x = newX;
Now the class will compile and the same code snippet from before that creates two
instances of AnIntegerNamedX, sets their x values, and then prints the x values
produces this output:
myX.x = 2
anotherX.x = 2

Building skills for success

Java Programming Intro Chapter 15 Classes 100

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:
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.

Initializing Instance and Class Members

You can use static initializers and instance initializers to provide initial values for
class and instance members when you declare them in a class:
class BedAndBreakfast {
static final int MAX_CAPACITY = 10;
boolean full = false;
This works well for members of primitive data type. Sometimes, it even works when
creating arrays and objects. But this form of initialization has limitations, as follows:

1. Initializers can perform only initializations that can be expressed in an

assignment statement.
2. Initializers cannot call any method that can throw a checked exception.
3. If the initializer calls a method that throws a runtime exception, then it
cannot do error recovery.

If you have some initialization to perform that cannot be done in an initializer

because of one of these limitations, you have to put the initialization code elsewhere.
To initialize class members, put the initialization code in a static initialization block.
To initialize instance members, put the initialization code in a constructor.

Using Static Initialization Blocks

Here's an example of a static initialization block:

Building skills for success

Java Programming Intro Chapter 15 Classes 101

The errorStrings resource bundle must be initialized in a static initialization block.

This is because error recovery must be performed if the bundle cannot be found.
Also, errorStrings is a class member and it doesn't make sense for it to be initialized in
a constructor. As the previous example shows, a static initialization block begins with
the static keyword and is a normal block of Java code enclosed in curly braces {}.
A class can have any number of static initialization blocks that appear anywhere in
the class body. The runtime system guarantees that static initialization blocks and
static initializers are called in the order (left-to-right, top-to-bottom) that they
appear in the source code.

Initializing Instance Members

If you want to initialize an instance variable and cannot do it in the variable
declaration for the reasons cited previously, then put the initialization in the
constructor(s) for the class. Suppose the errorStrings bundle in the previous example is
an instance variable rather than a class variable. Then you'd use the following code to
initialize it:
import java.util.ResourceBundle;
class Errors {
ResourceBundle errorStrings;
Errors() {
try {
errorStrings = ResourceBundle.
} catch (java.util.MissingResourceException e) {
// error recovery code here
The code that initializes errorStrings is now in a constructor for the class.
Sometimes a class contains many constructors and each constructor allows the caller
to provide initial values for different instance variables of the new object. For
example, java.awt.Rectangle has these three constructors:

Building skills for success

Java Programming Intro Chapter 15 Classes 102

Rectangle(int width, int height);

Rectangle(int x, int y, int width, int height);
The no-argument constructor doesn't let the caller provide initial values for
anything, and the other two constructors let the caller set initial values either for the
size or for the origin and size. Yet, all of the instance variables, the origin and the
size, for Rectangle must be initialized. In this case, classes often have one constructor
that does all of the work. The other constructors call this constructor and provide it
either with the values from their parameters or with default values. For example,
here are the possible implementations of the three Rectangle constructors shown
previously (assume x, y, width, and height are the names of the instance variables to be
Rectangle() {
Rectangle(int width, int height) {
Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
The Java language supports instance initialization blocks, which you could use
instead. However, these are intended to be used with anonymous classes, which
cannot declare constructors.
The approach described here that uses constructors is better for these reasons:

• 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.


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

Building skills for success

Java Programming Intro Chapter 15 Classes 103

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

0 10 20 30 40 50 60 70 80 90 100%
| | | | | | | | | | |

Building skills for success

+ + + +





+ + + +
Java Programming Intro Chapter 16 Strings 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.

Related types and classes

String The basic class for strings. String objects can NOT be changed.
char Primitive type for 16-bit Unicode characters.
Character Primarily useful for its utility functions for working with characters.
StringBuffer StringBuffers are used to build or change strings. Conversion between
String and StringBuffer is easy.
StringTokenizer Used to break a String into tokens (words).
BufferedReader Useful for reading and writing text files.
Pattern, JDK 1.4 added java.util.Pattern and Matcher to do regular expression
Matcher matching.

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, "".

Expression Value
1+2 3
"1" + 2 "12"
1 + "2" "12"

Building skills for success

Java Programming Intro Chapter 16 Strings 106

"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.

Upper- and lowercase

To change to uppercase (and similarly to lowercase), Java has two methods,
depending on whether you have a single character (eg, c) or a String (eg, s).

Converting a string to uppercase

s = s.toUpperCase();

Converting a character to uppercase

c = Character.toUpperCase(c);
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.

Comparing objects vs. primitive types

[to be supplied]

Comparing Strings: ==, .equals(), .compareTo(), ...

To compare Strings for equality, don't use ==. The == operator checks to see if two
objects are exactly the same object. Two strings may be different objects, but
have the same value (have exactly the same characters in them). Use the .equals()
method to compare strings for equality. Similarly, use the .compareTo() method to
test for unequal comparisons. For example,
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // CORRECT>

Comparing without regard to case

[to be supplied]

Building skills for success

Java Programming Intro Chapter 16 Strings 107

Converting Numbers to Strings

Vanilla Java: Converting numbers to strings is easy. You can do almost everything
with concatenation, but can get more control using alternatives. The first choice after
concatentation has been DecimalFormat, but as soon as the Java 5 format() and
printf() methods are better documented, they are a better second choice.
Converting Anything to String describes how to convert objects to String.

Number to string conversion alternatives

• Concatenation (+): Anything concatenated to a string is converted to string
(eg, "weight = " + kilograms).
• java.text.DecimalFormat gives you precise control over the formating of
numbers (number of decimal places, scientific notation, locale formatting, ...).
• Individual wrapper class methods, eg, Integer.toString(i). concatenation works
as well for the simple cases, but there are some interesting additional
conversions here.
• printf(), added in Java 5, uses a format for conversion.
• No conversion required. Some common system methods will take any type
and convert it, eg, System.out.println().

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.
int x = 42;
String s;
s = x; // ILLEGAL
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
Precision. The problem with floating-point numbers by concatenation is that you
have no control over the number of decimal places the conversion chooses for you, as
you can see in the above example.

Building skills for success

Java Programming Intro Chapter 16 Strings 108

The java.text.DecimalFormat class provides many ways to format numbers into
strings, including number of fraction digits, using a currency symbol ($12.35),
scientific notation (3.085e24), percentage scaling (33%), locale which defines
national formatting options (3,000.50 or 3.000,50 or 3'000,50 or ...), patterns for
positive, zero, and negative numbers, etc. These notes show only how to specify the
number of fraction digits. Check the Java API documentation for other options.
First, create a DecimalFormat object which specifies the format of the number. The
zero before the decimal point means that at least one digit is produced, even if it is
zero. The zeros after the decimal point specify how many fraction digits are
produced. Then call the format() method of that object, passing the numeric value to
be converted.
The string that is returned by the format() will not contain additional text, other
than an optional currency or percent sign. Specifically, it can not be used to pad
numbers on the left with blanks for use in right alignment of a column of numbers.
Use printf() for this.
This program uses the same formatting object many times.
// File: formatTest/FormatTest.java
// Description: Test default and DecimalFormat formatting.
2 // Author: Michael Maus
3 // Date: 2000-10-27, 2000-11-07, 2005-02-13
4 import java.text.DecimalFormat;
public class FormatTest {
6 public static void main(String[] args) {
7 DecimalFormat twoPlaces = new DecimalFormat("0.00");
for (int i=1; i<=10; i++) {
double val = 1.0 / i;
9 System.out.println("1/" + i + " = " + twoPlaces.format(val) + ", "
+ val);
10 }
11 }

Building skills for success

Java Programming Intro Chapter 16 Strings 109

Produces this output. The first floating point number is converted by a 2 decimal
place DecimalFormat object and the second is the default conversion.
1/1 = 1.00, 1.0
1/2 = 0.50, 0.5
1/3 = 0.33, 0.3333333333333333 // Round down.
1/4 = 0.25, 0.25
1/5 = 0.20, 0.2
1/6 = 0.17, 0.16666666666666666 // Round up.
1/7 = 0.14, 0.14285714285714285
1/8 = 0.12, 0.125 // Half-even round down.
1/9 = 0.11, 0.1111111111111111
1/10 = 0.10, 0.1

Rounding by the half even algorithm

Floating-point numbers may be rounded when they are converted to string (default
conversion, DecimalFormat or the Math.round method, etc). Rounding uses the half even
method which rounds
• To the nearest neighbor.
• If the number is exactly between its neighbors, it is rounded to its even
neighbor. The reason middle values are rounded to the even value, instead of
up as is commonly done, is to prevent an accumulation of errors.

Examples rounding to an integer: 3.1 rounds to 3, 3.8 rounds to 4, 3.5 rounds to 4,

but 4.5 also rounds to 4, 5.5 rounds to 6.

StringBuffer and StringBuilder append() methods - like concatenation

The most efficient way to build strings from parts is to use StringBuffer (all versions,
synchronized), or the essential identical StringBuilder (Java 5, unsynchronized and
therefore slightly faster than StringBuffer). Their many append() methods take
numbers and perform default conversions to string before appending them to their
current value.
StringBuilder sb = new StringBuilder();
int i = 42;
sb.append("Answer = ");
sb.append(i); // Converts i to string and appends to end.
sb.append(", ");

Building skills for success

Java Programming Intro Chapter 16 Strings 110

String s = s.toString(); // s is "Answer = 42, 0.3333333333333333"

Numeric objects: Integer, Double, BigDecimal, BigInteger, ...

Concatenation works with all objects, not just numbers. 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. Many classes override toString() to do something better. When
you write a class whose objects might be converted to a String, write a toString

Various numeric class conversion methods

[This will describe the Integer, etc wrapper class methods, as well as the BigInteger
and BigDecimal conversion methods.]

Converting Anything to String

Summary: Converting any data to strings is easy. You can do almost everything with
concatenation, but can get more control using some of the alternatives.

Converting numbers to strings - See Converting Numbers to Strings

There are many specialized issues with regard to converting numbers (precision,
exponents, currency, locale, ...), which are covered in Converting Numbers to

Summary of conversion alternatives

• Concatenation (+): Concatenate anything to a string and it will automatically
be converted to string.
• toString() is universally used as the method for converting any object into a
• printf() was added in Java 5 to use a format for conversion. Altho it's primarily
used with numbers, it also can be applied to objects of other classes. This isn't
discussed here.
• No conversion required. Some common system methods will take any type
and convert it, eg, System.out.println().

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.

Building skills for success

Java Programming Intro Chapter 16 Strings 111

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.
This conversion to string is made by calling the object's toString() method.

toString() method - Define it for your classes

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.


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

Enter a line of text.

I hate you.
I have rephrased that line to read:
I love you.

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:

I had a dream that name ate a color animal

and said it tasted like food!

Building skills for success

Java Programming Intro Chapter 16 Strings 112

For example, if the user entered Jake for the person’s name, blue for the color,
hamburger for the food, and dog for the animal, the output would be

I had a dream that Jake ate a blue dog

and said it tasted like hamburger!

Don’t forget to put the exclamation mark at the end.

Building skills for success

+ + + +


Abstract Classes



+ + + +
Java Programming Intro Chapter 17 Inheritance 114

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:

Building skills for success

Java Programming Intro Chapter 17 Inheritance 115

// define position locations

private int left;
private int top;
// override a superclass method
public int displayVolume() {
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.
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); }

Building skills for success

Java Programming Intro Chapter 17 Inheritance 116

public abstract void speak(); // abstract method - note no {}

Abstract classes and methods force prototype standards to be followed (ie. they
provide templates).

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
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");

// now reference each as an Animal

ref = aCow;
ref = aDog;
ref = aSnake;

Building skills for success

Java Programming Intro Chapter 17 Inheritance 117

Notice that although each method reference was to an Animal (but no animal objects
exist), the program is able to resolve the correct method related to the subclass
object at runtime. This is known as dynamic (or late) method binding.

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");

// now put them in an array

ref[0] = aCow; ref[1] = aDog; ref[2] = aSnake;

// now demo dynamic method binding

for (int x=0;x<3;++x) { ref[x].speak(); }

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

Building skills for success

Java Programming Intro Chapter 17 Inheritance 118

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
public class WorkingDog extends Dog implements Working
public WorkingDog(String nm)
super(nm); // builds ala parent
public void work() // this method specific to WorkingDog
System.out.println("I can herd sheep and cows");

Building skills for success

Java Programming Intro Chapter 17 Inheritance 119

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
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
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

Building skills for success

Java Programming Intro Chapter 17 Inheritance 120


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 class Person{

private String name;

public Person(){
Name=”No name yet.”;

public Person (String initialName){


public void setName (String newName){


public String getName(){

return name;

public void writeOutput(){

System.out.println(“Name: “ + name);

public boolean sameName(Person otherPerson){

return (this.name.equalsIgnoreCase(otherPerson.name));

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.

Building skills for success

+ + + +





+ + + +
Java Programming Intro Chapter 18 Arrays 122

Arrays -- Introduction

Java arrays are similar to ideas in mathematics

An array can store many similar values in memory. The word "array" in Java means
approximately the same thing as array, matrix, or vector does in math.
Unlike math, you must declare the array and allocate a fixed amount of memory for

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.

Allocating an array object

Create an array using new. This example creates an array of 100 int elements, from
a[0] to a[99].
int[] a; // Declares a to be an array of ints
a = new int[100]; // Allocates an array of 100 ints

Subscripts are enclosed in square brackets []. xi in mathematics is x[i] in
Java, and is pronounced "x-sub-i". The [] brackets are an operator in Java and have a
precedence like other operators.

Building skills for success

Java Programming Intro Chapter 18 Arrays 123

Subscript ranges always start at zero because Java came largely from C++,
which had a good reason for using zero (pointer arithmetic on arrays). It isn't the
way that humans normally count; you'll just have to live with it.

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.

Java idiom for looping over an array

The most common use of .length is in a for loop test condition. For example, the
variable i will go over the entire range of subscripts of the array a.
for (int i=0; i < a.length; i++) { . . .

Example -- adding all elements of an array

These statements add the first n elements of an array. Assume that there are values
in the array already.
int[] a; // Declare an array of ints
a = new int[1000]; // Create an array of 1000 ints.
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

Initial array element values -- zero/null/false

When an array is allocated (with new), all elements are set to an initial value. The
initial value is 0 if the element type is numeric (int, float, ...), false for boolean, and
null for all object types.

Building skills for success

Java Programming Intro Chapter 18 Arrays 124

Array variables are references to arrays

When you declare an array variable, Java reserves only enough memory for a
reference (Java's name for an address or pointer) to an array object. When an array
object is created with new, a reference is returned, and that reference can then be
assigned to a variable. Similarly, you can assign one array variable to another, and it
is only the reference that is copied. For example,
int[] a = new int[] {100, 99, 98};
int[] b;
// "a" points to an array, and "b" doesn't point to anything
b = a; // now b points to the SAME array as "a"
b[1] = 0; // also changes a[1] because a and b are the same array.
// Both a and b point to same array with value {100, 0, 98}

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.

Library methods for arrays

Static methods for manipulating arrays are available in the java.util.Arrays class (
asList(), binarySearch(), equals, fill(), and sort(). In addition there is System.arrayCopy().

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
// 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.

Building skills for success

Java Programming Intro Chapter 18 Arrays 125

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
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

Common array problems

Some common array programming mistakes are:
• Forgetting that array subscripts start with zero.
• Writing a.length() instead of a.length. The length() method is used with Strings,
not arrays.
• Declaring an array with a size. Eg, int[100] a; instead of int[] a = new int[100];.

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.

Building skills for success

Java Programming Intro Chapter 18 Arrays 126

Declare a 2-dimensional array as follows:
int[][] a2; // Declares, but doesn't allocate, 2-dim array.

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.

Processing 2-dimensional arrays

Often 2-dimensional arrays are processed with nested for loops. Notice in the
following example how the rows are handled as separate objects. For example,
int[][] a2 = new int[10][5];
// print array in rectangular form
for (int r=0; r<a2.length; r++) {
for (int c=0; c<a2[r].length; c++) {
System.out.print(" " + a2[r][c]);

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];

Building skills for success

Java Programming Intro Chapter 18 Arrays 127

// 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]);

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.

Building skills for success

Java Programming Intro Chapter 18 Arrays 128

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.

Visualizing two-dimensional arrays

Assume we have an array, a, with three rows and four columns.

a[0][0] a[0][1] a[0][2] a[0][3] Two-dimensional arrays are usually visualized as

a matrix, with rows and columns. This diagram
a[1][0] a[1][1] a[1][2] a[1][3] shows the array a with its corresponding
a[2][0] a[2][1] a[2][2] a[2][3] subscripts.
+-----+ In Java two-dimensional arrays are implemented
| | +-----+-----+-----+-----+ is a one-dimensional array of one-dimensional
|a[0] | -> | [0] | [1] | [2] | [3] arrays -- like this.
| | +-----+-----+-----+-----+
| | +-----+-----+-----+-----+
|a[1] | -> | [0] | [1] | [2] | [3]
| | +-----+-----+-----+-----+
| | +-----+-----+-----+-----+
|a[2] | -> | [0] | [1] | [2] | [3]
| | +-----+-----+-----+-----+

Building skills for success

Java Programming Intro Chapter 18 Arrays 129

Declaring and Allocating a two-dimensional array

Let's declare a board for playing the game of tic-tac-toe. It will have three rows (the
first subscript) and three columns (the second subscript) and contain an int in each
int[][] board = new int[3][3];

Initial values
It's possible to assign initial values to an array when you declare it in a manner very
similar to one-dimensional arrays, but with an extra level of braces. The dimension
sizes are computed by the compiler from the number of values.
int[][] board = new int[][] {{0,0,0},{0,0,0},{0,0,0}};
You must assign values to an element before you use it, either with an initializer as
above or assignment.

Example -- drawing the tic-tac-toe board

It's often easiest to use two-dimensional arrays with nested for loops. For example,
the following code draws the tic-tac-toe board in a paint method. It assumes that a
cell is 10 pixels on a side, and that a positive number represents an X and a negative
number represents a O.
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);


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

Building skills for success

Java Programming Intro Chapter 18 Arrays 130

How many numbers will you enter?

Enter 4 integers one per line:
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):

Int [][] a = new int [4][5];

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):


Building skills for success