You are on page 1of 187

Java Programming 2: The Java Programming Language

Lesso n 1: J ava Pro gram m ing Co nst ruct s


Befo re Yo u Start: Wo rking Sets
Selecting a Wo rking Set
Windo ws Settings

Fundamental Pro gramming Co nstructs


Basic Algo rithm Co nstructs
What and Where?

Applicatio ns
Our First Applicatio n
The System Class
A Clo ser Lo o k at main
Do cumentatio n and Co mments

Lesso n 2: T o o ls o f Pro gram m ing: Applicat io ns and Co m pile rs


Applicatio n GUIs
Mo re o n Pro gramming Co nstructs
Statements and Expressio ns
Primitive Data Types
Valid Identifiers (aka. Variable Names)

Lesso n 3: Prim it ive Dat a T ype s, Variable s, and Expre ssio ns


Bits and Pieces in Memo ry
Variables
Primitive Data Types
Strings
Literals

Memo ry: variable names and values


Optio nal Reading: The Bus

Lesso n 4: Out put : St rings, Fo nt s, and Num be rs


Strings
Investigating Strings
Using Strings
Manipulating Strings

Fo nts
Numbers

Lesso n 5: Arit hm e t ic Ope rat io ns: T he Basics


Calculatio ns and Operato rs
Variables and a Pro gram to Dissect
Defaults

Added Attractio ns
Increment Statements

Lesso n 6 : Arit hm e t ic Ope rat io ns: Pre ce de nce and Ope rand T ype s
Executing Tasks in the Co rrect Order
Operato rs and Precedence
Remainder
Precedence
Operand Types
Type Co nversio n/Casting
Mo re o n String Co ncatenatio n
Fo rmats

Lesso n 7: De cisio ns: Lo gic


Lo gic: and, o r, no t
Examples Using Lo gic
Nested Ifs Versus Lo gic Statements
Lo gic Statements Versus If Statements

Lesso n 8 : De cisio ns: Dangling and Swit ching


Matching Who Gets What
Dangling Elses
Object equivalence
The Instance o f Operato r

Switch Statements
What's next?

Lesso n 9 : Int ro duct io n t o Arrays


What are Arrays?
So me Fab Examples
Index Po ssibilities

Syntax and Java Implementatio n fo r Arrays


Declaring a Variable to Refer to an Array
Memo ry

Lesso n 10 : Lo o ps
Repetitio n: fo r Lo o ps
Intro ductio n to Lo o ps
fo r
start
sto p
increment

Lesso n 11: Cre at ing Arrays


Creating, Initializing, and Accessing
What are Arrays again?
Creating Arrays (revisited)
Sho rtcut fo r Creating Arrays

Lesso n 12: T wo -Dim e nsio nal Arrays


Mo re Abo ut Arrays
Wo rking With Two -Dimensio nal Arrays
Ragged Arrays
Using Arrays
Co pying Arrays

Co mmo n Mistakes

Lesso n 13: T he Ot he r Lo o ps
Repetitio n: while, do -while
Enhanced Fo r Lo o ps
while
do -while

Infinite Lo o ps
Optio nal Fo r Lo o p

Branching Statements
General

Lesso n 14: T racing Co de


Ho w Did I Get Here?
Arrays fo r Metho ds--Reminder
Always Lo o k Befo re Passing (o r Hiring)

Nested fo r
Tracing do -while
Tracing Decisio ns
Mo re Abo ut Flo w Co ntro l
Summary o f Co ntro l Co nstructs
Branching
Repetitio n/Lo o ps

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Java Programming Constructs
Welco me to OST's Java 2 co urse!

Course Objectives
When yo u co mplete this co urse, yo u will be able to :

demo nstrate kno wledge o f basic algo rithm co nstructs in Java.


develo p and co mpile Java applicatio ns that utilize primitive data types, statements, expressio ns, and GUIs.
o utput and manipulate strings, fo nts, and numbers.
apply decisio n lo gic and o peratio nal precedence to Java co de.
implement multidimensio nal arrays, lo o ps, and branching statements.
trace co de fo r better so ftware quality.

When yo u co mplete this lesso n, yo u will be able to :


Lesson Objectives
Identify the co ntro l co nstructs used in structured pro gramming.
use the main metho d to start a Java applicatio n.
access Java do cumentatio n.
create a new Java pro ject with a class that prints specific text.

In this co urse, yo u'll learn mo re in-depth co ncepts and syntax o f the Java Pro gramming language. Thro ugho ut this co urse,
yo u'll learn by building examples using the Eclipse Java Develo pment Enviro nment which is supplied as a Learning Sandbo x.
Co mpletio n o f this co urse gives yo u a basic understanding o f Object Oriented techniques in Java as well as using the Eclipse
IDE.

Fro m beginning to end, yo u will learn by do ing yo ur o wn Java pro jects, within o ur Eclipse Learning Sandbo x we affectio nately
call "Ellipse". These pro jects will add to yo ur po rtfo lio and pro vide needed experience. Besides a bro wser and internet
co nnectio n, all so ftware is pro vided o nline by the O'Reilly Scho o l o f Techno lo gy.

Learning with O'Reilly School of T echnology Courses


As with every O'Reilly Scho o l o f Techno lo gy co urse, we'll take a user-active appro ach to learning. This means that yo u
(the user) will be active! Yo u'll learn by do ing, building live pro grams, testing them and experimenting with them—
hands-o n!

To learn a new skill o r techno lo gy, yo u have to experiment. The mo re yo u experiment, the mo re yo u learn. Our system
is designed to maximize experimentatio n and help yo u learn to learn a new skill.

We'll pro gram as much as po ssible to be sure that the principles sink in and stay with yo u.

Each time we discuss a new co ncept, yo u'll put it into co de and see what YOU can do with it. On o ccasio n we'll even
give yo u co de that do esn't wo rk, so yo u can see co mmo n mistakes and ho w to reco ver fro m them. Making mistakes
is actually ano ther go o d way to learn.

Abo ve all, we want to help yo u to learn to learn. We give yo u the to o ls to take co ntro l o f yo ur o wn learning experience.

When yo u co mplete an OST co urse, yo u kno w the subject matter, and yo u kno w ho w to expand yo ur kno wledge, so
yo u can handle changes like so ftware and o perating system updates.

Here are so me tips fo r using O'Reilly Scho o l o f Techno lo gy co urses effectively:

T ype t he co de . Resist the temptatio n to cut and paste the example co de we give yo u. Typing the co de
actually gives yo u a feel fo r the pro gramming task. Then play aro und with the examples to find o ut what else
yo u can make them do , and to check yo ur understanding. It's highly unlikely yo u'll break anything by
experimentatio n. If yo u do break so mething, that's an indicatio n to us that we need to impro ve o ur system!
T ake yo ur t im e . Learning takes time. Rushing can have negative effects o n yo ur pro gress. Slo w do wn and
let yo ur brain abso rb the new info rmatio n tho ro ughly. Taking yo ur time helps to maintain a relaxed, po sitive
appro ach. It also gives yo u the chance to try new things and learn mo re than yo u o therwise wo uld if yo u
appro ach. It also gives yo u the chance to try new things and learn mo re than yo u o therwise wo uld if yo u
blew thro ugh all o f the co ursewo rk to o quickly.
Expe rim e nt . Wander fro m the path o ften and explo re the po ssibilities. We can't anticipate all o f yo ur
questio ns and ideas, so it's up to yo u to experiment and create o n yo ur o wn. Yo ur instructo r will help if yo u
go co mpletely o ff the rails.
Acce pt guidance , but do n't de pe nd o n it . Try to so lve pro blems o n yo ur o wn. Go ing fro m
misunderstanding to understanding is the best way to acquire a new skill. Part o f what yo u're learning is
pro blem so lving. Of co urse, yo u can always co ntact yo ur instructo r fo r hints when yo u need them.
Use all available re so urce s! In real-life pro blem-so lving, yo u aren't bo und by false limitatio ns; in OST
co urses, yo u are free to use any reso urces at yo ur dispo sal to so lve pro blems yo u enco unter: the Internet,
reference bo o ks, and o nline help are all fair game.
Have f un! Relax, keep practicing, and do n't be afraid to make mistakes! Yo ur instructo r will keep yo u at it
until yo u've mastered the skill. We want yo u to get that satisfied, "I'm so co o l! I did it!" feeling. And yo u'll have
so me pro jects to sho w o ff when yo u're do ne.

Before You Start: Working Sets


We o rganize o ur pro jects in Working Sets. To create the wo rking sets fo r this co urse, use the do wn arro w beside the
Re d Le af ico n o n the to o lbar. Yo u will use the J ava2_Le sso ns wo rking set fo r the lesso ns, and the
J ava2_Ho m e wo rk wo rking set fo r the exercises after each lesso n.

Selecting a Working Set


When yo u start wo rking o n a co urse, o r if yo u just need to reset yo ur perspective, yo u need to select the
appro priate wo rking set. Click the small do wn arro w beside the Red Leaf ico n o n the to o l bar to see a list o f
co urse gro ups. Fo r this co urse, select the Jave co urse gro up.

If yo u do no t see wo rking sets in yo ur Package Explo rer, set the to p-level elements to wo rking sets:

To co nfigure wo rking sets:


The fo llo wing dialo g appears. Select the wo rking sets yo u want and deselect the o nes yo u do n't want in the
Package Explo rer view, and click OK.

The selected wo rking sets no w appear in the Package Explo rer:


To easily sho w just the wo rking sets fo r this co urse, click the do wn arro w o n the Sho w Wo rking Se t s butto n
in the Package Explo rer, then select J ava, and then J ava2:

If the wo rking sets already exist in the Package Explo rer, they will no t be recreated, but the perspective will still
change.

Ho o ray! Let's get go ing o n so me mo re Java Pro gramming!

Windows Settings
If yo u like, yo u can set yo ur o wn Windo ws mo use, keybo ard, and regio n; fo r example, if yo u are left-handed,
yo u can switch the left and right butto n functio nality o n the mo use, o r change date fields to use date fo rmats
fo r yo ur lo cal regio n. Click the do wn arro w o n the Windo ws Settings butto n at the to p right o f the screen:
We wo n't discuss all o f the details o f these dialo g bo xes, but feel free to ask yo ur instructo r if yo u have
questio ns.
Fundamental Programming Constructs
The o bvio us reaso n that o bject-o riented pro gramming languages use o bjects is due to the po wer that design
principles such as inheritance, info rmatio n hiding and po lymo rphism pro vide the pro grammer. Even tho ugh languages
may be o bject-o riented, mo st also still use the basic co nstructs o f pro gramming and algo rithms develo ped in earlier
pro gramming languages. Java is no exceptio n. In this co urse, we will lo o k into the basic pro gramming co nstructs
used by mo st co mputer languages and ho w Java implements them.

Basic Algorithm Constructs


Pro gram s are co mputer co de that pro vide sequences o f instructio ns - they can be large o r small.

Algo rit hm s are the "recipes" ... the sequence o f steps used to achieve the desired go al.

All algo rithms are made up o f the fo llo wing co nt ro l co nstructs, which direct the flo w o f the pro gram:

sequences (assignment statements, IO calls)


repetitio ns/lo o ps (while, fo r, do )
decisio ns/selectio ns (if/then, switch)
metho d invo catio n

That's it. When we tell a co mputer what to do next, we do it thro ugh these fo ur co nt ro l mechanisms. So all
yo u need to kno w to pro gram is to understand the principles and co nstructs o f Objects, and to understand the
co ntro l co nstructs abo ve. We have seen sequencing and metho d invo catio n in the previo us lesso ns; we will
use them even mo re as the class pro gresses. Ho wever, since what we are "co ntro lling" is what to do with
info rmatio n, and since Objects have info rmatio n in them, in o rder to pro gram we also need to kno w ho w the
co mputer sto res this info rmatio n so that it can access it.

What and Where?


Co nsider:

Algo rithms are what we do to achieve the results we desire.


In o rder to do so mething, o ne must have a t hing to do so met hing to !
In o rder to have a t hing we need to have it so mewhe re .
The whe re in a co mputer is its m e m o ry.

In the first few lesso ns o f this co urse, we will demo nstrate the to o ls and techniques that pro grams use to
determine what is whe re to allo w the algo rithms to do what they are suppo sed to do . We will also see ho w
to represent the pro perties o f Objects as variables so that they can be accessed and used to make
statements, write metho ds, and hence pro vide co mputer legible algo rithms.

Yes, yes, I hear yo u say, aren't these t hings the o bje ct inst ance s that we get fro m o ur Classe s? Yes, but
there is mo re. In o rder to illustrate easily in a hands-o n fashio n, ho wever, we need to intro duce yo u to Java
Applicatio ns first.

Applications
Applicatio ns are co mputer pro grams that are built and run in o rder to execute a specific task o n a co mputer.
Applicatio ns do no t need bro wsers to run in and are o ften called st and-alo ne pro gram s, meaning that they do no t
depend o n any o ther pro gram fo r their executio n. Eclipse is a Java Applicatio n o r stand-alo ne pro gram! Unlike when
making Applets, when yo u create applicatio ns, yo u have to make yo ur o wn "windo ws" o r else view yo ur results fro m
the co m m and windo w o r co nso le . In this co urse, we'll run everything thro ugh Eclipse and view o ur results in the
co nso le it pro vides. In the Java 3 we'll make full-fledged applicatio ns.

Applicatio ns start fro m co mputer co nso les which, unlike Applets, have no bro wser to start them. So the pro grammer o f
an applicatio n has to explicitly start the Classes in the applicatio n. In so me pro gramming languages (e.g., C, C++,
Java), it has been a co nventio n to start applicatio ns with a m ain metho d.
Even tho ugh the m ain m e t ho d must be defined within a Class, it do esn't "belo ng" to any class, it's
Note simply a means by which pro grammers get their o bjects started.

Fo r go o d pro gramming practice, these are the o nly two things sho uld be present in the main metho d:
T ip 1. A message to instantiate a class.
2. A message to get that class started.

Our First Application


Let's get started with an example o f Hello Wo rld in an applicatio n. Make a ne w pro je ct fo r Lesso n 1 fo r this
co urse, call it java2_Le sso n1.

Okay no w select the J ava2_Le sso ns pro ject. Cho o se File | Ne w | J ava Pro je ct . Enter the name
java2_Le sso n1 to differentiate fro m Co urse 1 java1_Lesso n1. Click Finish.
If yo u see the dialo g belo w, go ahead and check the Re m e m be r m y de cisio n bo x and then click No .
If yo u clicked Ye s o n the abo ve dialo g by mistake, select the Windo ws menu and click Pre f e re nce s. When
the dialo g appears, click o n the J ava item o n the left. Then, click the Cle ar butto n as sho wn:

Remember, if yo ur wo rkspace ever gets messed up, yo u can always hit the Re se t But t o n to make things
right again.

No w, let's make the first Class in this pro ject:

Click o n java2_Lesso n1 and then right-click fo r the po pup menu. Cho o se Ne w | Class as yo u did in the first
co urse. In the New Java Class windo w that o pens, So urce f o lde r sho uld be java2_Lesso n1. Enter the
Nam e : He llo Wo rldApp. Since we 're cre at ing an applicat io n, under "Which metho d stubs wo uld yo u
like to create?", cho o se public st at ic vo id m ain(St ring [] args). Yo u can keep "Inherit abstract metho ds"
checked--yo u do n't need it no w, but it do esn't hurt to have it.

Click Finish.
In the resulting co de, remo ve the co mment: // TODO Auto-generated method stub and the symbo l o n
the left, by clicking o n the check bo x symbo l o nce, then, in the suggestio n bo x that o pens, do uble-click o n
Re m o ve t ask t ag:
No w, type the co de sho wn in blue belo w.

CODE TO TYPE: Hello Wo rld Applicatio n


public class HelloWorldApp
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}

No tice that Hello Wo rldApp do es no t extend anything. This is because an applicatio n is no t an applet and in
this case, it is no t go ing to inherit fro m any special class--e xce pt the class o f Obje ct .

By default, all classes in Java inherit fro m the class Obje ct . No thing ever has to extend
Note Object, because every o bject/class inherits fro m the class Object.

No w save the new applicatio n. To save it, right-click in the Edito r Windo w and cho o se Save OR go to the
Eclipse to p menu bar and cho o se File | Save .

And run it. To do that, yo u right-click in the Edito r Windo w and cho o se Run As | J ava Applicat io n OR go to
the Eclipse to p menu bar and cho o se Run | Run As. That sho uld give yo u the o ptio n J ava Applicat io n.

To save and run an applicatio n o r Applet quickly, just go to the Eclipse to o lbar and click this ico n: .
Thro ugho ut the rest o f the co urse, we'll just sho w yo u that ico n with instructio ns to "Save and Run" yo ur
wo rk.

Okay, yo u sho uld no w see the Co nso le tab:

The Eclipse to o l is really po werful and versatile. If yo u ever cho o se Run As and neither a Java
Note Applet no r a Java Application sho ws up, be sure to click in the Editor Window so Eclipse kno ws
yo u're running the Java.

We'll use the co nso le quite o ften to try different lines o f co de and see what happens. In fact, we will use the
same Hello Wo rldApp to test all kinds o f stuff.

T he System Class
So why did the co nso le o pen in o ur Hello Wo rldApp co de abo ve? It o pened because we to ld it to , using the
Syst e m class:

System.out.println("Hello World!");

We kno w that Syst e m is a class because the wo rd System begins with a capital letter and is no t in quo tatio n
marks.

We didn't need to impo rt anything into this He llo Wo rldApp class in o rder to use the Syst e m class, so we
kno w that Syst e m must be in the package java.lang.

Go to the API using the ico n in the Eclipse windo w:


Yo u can always get back to these no tes by clicking o n the O'Reilly tab--it will keep yo ur place when yo u
to ggle back and fo rth.

In the API, click o n the java.lang package, scro ll do wn to the Class Sum m ary, and click the Syst e m class.
Scro ll do wn to the Fie ld Sum m ary o f Syst e m :

In the left m o dif ie r co lumn, we see that all o f the Field variables in Syst e m are Class Variable s (CVs),
because they all have the mo difier st at ic. Because they are CVs, yo u can access them fro m the class itself
(rather than instantiating with ne w).

So we can say: System.out.

Also in the left co lumn is info rmatio n abo ut variable t ype s. We can see that they're Print St re am and
Input St re am Objects. Because they are Obje ct s, they can use the do t o perato r as well.

These Class Variables fo r Syst e m are the st andard input and o ut put reso urces.

On yo ur API page, click o n the Class Variable in link.

Pro grams generally take info rmatio n in and send info rmatio n o ut. The detailed specificatio n will tell us that
st andard in is the keybo ard. Standard Input is data that go es into a pro gram, it's usually text. No t all
pro grams need to use standard input to get info rmatio n, but they can. The st andard o ut put is the co mputer
screen--particularly, the co nso le with which yo u are wo rking.

In the Eclipse enviro nment, a windo w named Co nso le o pened fo r yo u fo r the st andard o ut and st andard
e rro r. In the previo us co urse, we saw an example o f Syst e m .e rr when we go t the null po int e r e rro r. We'll
mess up the main metho d o n purpo se in this lesso n to see mo re.

Go back to the API page so yo u can get to the o ut variable. At the o ut variable, click o n the Print St re am
link. Scro ll do wn the Print St re am class to its metho ds and find print ln().

There are many print ln() signatures listed. Which o ne do yo u think Java is using in o ur applicatio n? Inside
the parentheses o f Syst e m .o ut .print ln(" He llo Wo rld!" ); we see quo tatio n marks, so we kno w we have a
St ring, and so we also kno w the co mpiler will use this o ne:
We do no t say whe re (x,y) to put it, because it's no t in a graphical windo w like an Applet.

Because Syst e m .o ut is o ne o f the t ype o f o bjects o f the class Print St re am , Syst e m .o ut can invo ke
Print St re am metho ds:

Syst e m .o ut .print ln(" He llo Wo rld!" );, where Syst e m .o ut is the co nso le.

A Closer Look at main


Because main is so impo rtant to applicatio ns, let's take a clo ser lo o k. The template that the IDE created fo r
yo u is the standard required template fo r applicatio ns.
Specifically, because all applicatio ns (o ften called apps) are started with the m ain m e t ho d, all applicatio ns
must have a metho d with this exact syntax and wo rding:

CODE TO TYPE: main

public static void main(String[] args){


// what goes here is what will vary
}

Let's edit it no w and see ho w System.err wo rks.

In the Hello Wo rldApp template that was created fo r yo u, remo ve the co de sho wn in blue .

CODE TO REMOVE: Hello Wo rldApp


public class HelloWorldApp
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}

No tice that there are no erro rs sho wing in the Edito r.

Save and Run it.

This time so mething different will happen.

A new windo w will o pen:


If the Run butto n is gray (so it do esn't respo nd when yo u click o n it), select J ava Applicat io n, click the Ne w
launch co nf igurat io n ico n at the to p o f the dialo g, enter the applicatio n name (Hello Wo rldApp) and Pro ject
name (java2_Lesso n1), and then click Run.

Like befo re, yo u wo n't see a bro wser o pen, but this time, yo u'll see the results in the Co nso le tab that
o pened up fo r yo u when yo u ran the applicatio n. In this case, we see an e rro r.

If yo ur results lo o k like tho se belo w o n the left, click OK in the "Java Virtual Machine Launcher" and yo u'll get
the results yo u see belo w o n the right:

It is no t go o d to see re d in the co nso le!

java.lang.No SuchMe t ho dErro r: m ain Exce pt io n in t hre ad " m ain"

That red message is telling yo u that there are pro blems in yo ur co de--it canno t find yo ur m ain metho d
because the syntax is no t co rrect.

This is an example o f a run-t im e e rro r, meaning it canno t be seen as an erro r until yo u try to run the
pro gram.

Eclipse can o nly catch co m pile r e rro rs. Eclipse lo o ks at the co de within the edito r and determines if the
co de there is co rrect. Specifically, until yo u run the applicatio n, Eclipse do es no t kno w that it will be an
applicatio n and so it do es no t kno w that yo u need a m ain m e t ho d.

Put the blue co de back where it belo ngs in Hello Wo rldApp:


CODE TO ADD BACK: Hello Wo rldApp
public class HelloWorldApp
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}

Yo u can save and run it again to ensure that yo u replaced the co de co rrectly, but there's no thing in o ur main
metho d yet, so it isn't very interesting.

Documentation and Comments


In the generated co de yo u see do cum e nt at io n in the fo rm o f co m m e nt s (marked by / and *).

Java co de is inherently hard to read and fo llo w so Do cumentatio n is used to help us understand it. Since
Java o nly allo ws certain syntax in the co de, we can't just write whatever we want anywhere. We use special
character co mbinatio ns to include co mments that allo w us to co mmunicate "no rmally" between lines o f co de.

We saw o ne type o f co mment when we used // and saw that Java wo uld no t pay attentio n to what came after
the // o n that line. There are three types o f co mments pro grammers can use in Java to info rm readers o f their
intentio ns. Let's try them.

CODE TO TYPE: Co mment Types

/** Javadoc comment. Used to automatically generate documentation


that looks like the API pages. The compiler ignores
everything until it sees the ending characters */

public class HelloWorldApp

/* Multi-line comment is ignored by the compiler until


the ending characters */
{
public static void main(String[] args)
{
// Single-line comment is ignored until the end of the line.
System.out.println("Hello World!");
}
}

Save and Run the pro gram if yo u like. It sho uld run the same as befo re, but the co mments will be igno red.

Note The indentatio n in a pro gram is o nly used to make it easier fo r us to read.

Java do es no t reco gnize multiple blank spaces as anything meaningful. It do es no t need (no r even
reco gnize) this indentatio n. In fact, Java igno res any extra spaces. So me pro grammers like to line up the
o pening left bracket { with the clo sing right bracket }. Other pro grammers like to put the o pening left bracket at
the end o f the line that defines what the bracket is o pening (the definitio n o f a class o r a metho d).

In the co de we, the brackets are lined up.

In the template co de, the brackets start directly after the beginning o f the class definitio n line and the metho d
definitio n line.

Again, to Java this makes no difference as lo ng as t he y are t he re ! If they aren't there, Java will co mplain.

Try and remo ve the last "}" fro m Hello Wo rldApp. Click in the Edito r Windo w (anywhere). See the little red
rectangle in the far right co lumn o f the Edito r Windo w? Slo wly mo ve the curso r o ver it so that its finger po ints
right to the rectangle. It tells yo u that yo u need to put the } bracket back:
No w put t he bracke t back in t he co de .

No w, mo ve the two ending brackets so that they are o n the same line and all the way to the left.

Why no t go all o ut? Remo ve all empty lines and mo ve all o f the co de to the left (remo ving indentatio ns):

There sho uldn't be any erro rs indicated, but the co de's kind o f ugly.

Because o ur pro gram is very small no w, we do n't need to use any co mments. The co mpiler will igno re them
anyway, so yo u can delete them o r leave them there; it's up to yo u.

Let's get go ing to the next lesso n where we can make o ur applicatio n o utput mo re interesting and also make so me
ST AT EMENT S!

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Tools of Programming: Applications and Compilers
Lesson Objectives
When yo u co mplete this co urse, yo u will be able to :

demo nstrate the differences between an applicatio n and an applet.


use ano nymo us inner class instantiatio n.
declare primitive data types.
cho o se valid variable names.

Application GUIs
In the Java 1 co urse we learned that Applets displayed in bro wsers inherit their display abilities fro m the Apple t class.
Because o f this inheritance, the Applet class instantiates itself auto matically when the bro wser windo w o pens.

We also learned that applicatio ns are no t sho wn in a bro wser o r windo w by default, so if we want a windo w fo r o utput,
we'll have to create it o urselves. In o rder to do that, we can have the applicatio n inherit fro m the Java class
java.awt .Fram e .

Let's make an applicatio n with a Windo w Fram e to see ho w they differ fro m Applets. Create a new Java Pro ject and
name it java2_Le sso n2. Then, add a new Class and name it Me m o (cho o se to include the m ain m e t ho d st ub like
yo u did in the last lesso n). When the Edito r windo w o pens, click o n the check bo x o n the left o f the "To Do " stub
co mment, and then do uble-click to Re m o ve t ask t ag:

Enter co de fo r Me m o as sho wn belo w in blue :


CODE TO TYPE: Memo Class

import java.awt.event.*;
import java.awt.*;

public class Memo extends Frame {

public String message;

public Memo() {
super("This is a Memo Title");
message = "This is the content of the Memo";
}

public void paint(Graphics g) {


g.drawString(message, 50, 50);
}

public void start () {


setSize (300, 300);
setVisible(true);
}

public static void main(String args[]) {


Memo m;

m = new Memo();
m.start();
}
}

Save and Run it.

Let's trace this pro gram:


Memo .java Results
import java.awt.event.*;
import java.awt.*;

public class Memo extends Frame {

public String message;

public Memo() {
super("This is a Memo Title")4;
message = "This is the content of the Memo"5;
}

public void paint(Graphics g) {


g.drawString(message, 50, 50);
}

public void start () {


setSize (300, 300)7;
setVisible(true)8;
}

public static void main(String args[])1 {


Memo2 m;

m = new Memo()3;
m.start()6;
}
}

1. The pro gram go es to the m ain() metho d.


2. The m ain() declares the Me m o class.
3. An instance o f the class Me m o is created. This transfers co ntro l to the Co nstructo r metho d Me m o ().
4. The Co nstructo r calls the Co nstructo r o f its parent Fram e with the use o f supe r.
5. The Co nstructo r sets the Instance Variable o f m e ssage . (If we do n't call super, then the java co mpiler
auto matically calls super() witho ut parameters. In this case we call it because we want to initialize the super
Class with a String.)
6 . When the Co nstructo r is finished, the pro gram returns to the m ain() metho d, which then invo kes the
instance's st art () metho d.
7. The st art () metho d sets the size o f the Memo Fram e .
8 . Then the st art () metho d sets the Memo Fram e to "visible." In o ther wo rds, the st art () makes the Memo
Fram e o pen a Windo w to display.

Click o n the X in the re d bo x in the upper right co rner o f the created windo w:
That's weird, no thing happened.

That's because the X in the re d bo x in the upper right co rner is no t defined in the Java Frame. It's go o d pro gramming
practice to make sure yo ur applicatio ns wo rk the way peo ple will expect. Yo u can acco mplish this using pro mpts and
menu items.

To clo se the applicatio n (if the pro grammer leaves yo u stranded like this), go to the Co nso le and mo ve yo ur mo use
o ver the ico ns at the to p o f the Co nso le Windo w. The first ico n is a re d rectangle that says, "Terminate." The next is an
X that says, "Remo ve Launch." Click whichever o ne is available to yo u.

If yo u aren't running yo ur applicatio n in Eclipse, the co mmo n key co mmand to sto p an applicatio n is
T ip [Co nt ro l+C].

To understand the Me m o co de, we'll need the help o f the . Imagine that! One aspect o f the co de that really stands
o ut is that Fram e do es no t have a paint metho d--but then neither did Apple t ; bo th classes inherit the metho d fro m the
class Co nt aine r.

Check o ut bo th the Apple t and Fram e Class hierarchies. They bo th inherit fro m Co nt aine r and therefo re inherit the
metho d paint (Graphics g).

Go to the API using the ico n in the Eclipse windo w. Find the java.applet package, scro ll to the Class Sum m ary,
and then click the Apple t class.

Take a lo o k at its hierarchical lineage:


Here yo u can see that he class Applet inherits fro m the class Panel, which inherits fro m Container, which inherits
fro m Component, which inherits fro m Object. Okay, no w go back to the Package s listing in the API. Click the java.awt
package and scro ll do wn to the Class Sum m ary. Click the Fram e class and no te its hierarchical lineage:

Yo u can also see this using Eclipse. In the Me m o class in the Edito r Windo w, highlight the wo rd Fram e , right-click it,
and cho o se "Open Type Hierarchy." The hierarchy displays in the Hierarchy Tab in the left panel:

Bo th the Apple t and Fram e classes inherit fro m Co nt aine r, so they bo th inherit the metho d paint (Graphics g). The
paint () metho d is used less o ften in Frames than it is in Applets.

Go back to the Frame Class API page and scan thro ugh it and check o ut its co nstructo rs. See if yo u can identify the
o ne we used by calling supe r in o ur Me m o co nstructo r. Find o ut where the metho ds that we used (but did no t define)
are defined. Specifically, se t Size and se t Visible . (Hint: Lo o k at Me t ho ds inhe rit e d f ro m class
java.awt .Windo w.)

No w, let's experiment. Edit yo ur Memo class by changing the co de sho wn in blue belo w:
CODE TO EDIT: Memo
import java.awt.event.*;
import java.awt.*;

public class Memo extends Frame {

public String message;

public Memo() {
super("This is a Memo Title");
message = "This is the content of the Memo";
}

public void paint(Graphics g) {


g.drawString(message, 50, 50);
}

public void start ( ) {


setSize (300, 300);
setVisible(false);
}

public static void main(String args[]) {


Memo m;

m = new Memo();
m.start( );
}
}

Save and Run it.

Wait... wait... wait...and...no thing. Hmm.

Open the Co nso le windo w and click in it. See the blinking | at the upper left co rner? It lo o ks like so mething happened
after all. Since yo u said no t to make Frame visible, it didn't.

Click o n the big X to "Remo ve Launch." Change the Memo co de back to t rue .
CODE TO EDIT: Memo
import java.awt.event.*;
import java.awt.*;

public class Memo extends Frame {

public String message;

public Memo() {
super("This is a Memo Title");
message = "This is the content of the Memo";
}

public void paint(Graphics g) {


g.drawString(message, 50, 50);
}

public void start ( ) {


setSize (300, 300);
setVisible(true);
}

public static void main(String args[]) {


Memo m;

m = new Memo();
m.start( );
}
}

Save and Run it to make sure it wo rks like befo re.

Fo r mo st o f o ur lesso ns, we'll use m ain() and the co nso le to test Java pro gramming co nstructs witho ut using a fancy
Fram e . But check o ut the differences between o utput o n the Fram e and o n the co nso le anyway. Generally, users o f
yo ur applicatio n wo n't see the co nso le . Output to the co nso le is used to help pro grammers debug o r trace pro grams.

Let's make o ur pro gram easier fo r users to exit, by adding so me interactio n. In the past, we implemented a listener;
this time we'll sho w yo u a new trick.

Edit the Me m o class's paint () and st art () metho ds as sho wn belo w in blue :
CODE TO EDIT: Memo
import java.awt.event.*;
import java.awt.*;

public class Memo extends Frame {

public String message;

public Memo() {
super("This is a Memo Title");
message = "This is the content of the Memo";
}

public void paint(Graphics g) {


g.drawString(message, 50, 50);

g.drawString("Click anywhere to Exit", 50, 70);


System.out.println("What's this then?");

public void start ( ) {


setSize (300, 300);
setVisible(true);
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e){
setVisible(false);
dispose(); // free up system resources
System.exit(0);
}
});
// Quit the app.
}

public static void main(String args[]) {


Memo m;

m = new Memo();
m.start( );
}
}

Save and Run it. Yo u see the frame defined like this:
Click anywhere in the frame to clo se it.

OBSERVE: Lo o k clo sely at this sectio n o f co de.


public void start ( ) {
setSize (300, 300);
setVisible(true);
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e){
setVisible(false);
dispose();
// free up system resources
System.exit(0);
}
});
// Quit the app.
}

So , ho w did we do that? Well, we adde d a m o use list e ne r using addMo use List e ne r(), but we did it witho ut
implementing the Mo useListener Interface. So where do es it co me fro m? The Mo use Adapt e r class is instantiated
inside the ne w Mo use Adapt e r() co nstructo r, all within the metho d call itself as a parameter o f
addMo use List e ne r().

This type o f instantiatio n is called an anonymous inner class. It's anonymous because we aren't giving the instantiated
class a name. The this.addMo use List e ne r(ne w Mo use Adapt e r(){...}); po rtio n o f the co de means that we are go ing
to create a new Mo useAdapter class and add it to the Frame as a Mo useListener. We can do this because a
Mo useAdapter class implements the Mo useListener interface (so it's a Mo useListener).

Click the ico n in the Eclipse menu. Go to the java.awt .e ve nt package. Scro ll do wn to the Mo useAdapter class.
No te that it implements the Mo useListener interface.

A list e ne r int e rf ace with mo re than o ne metho d to be implemented in Java has a co rre spo nding
Adapt e r class that implements empty versio ns o f the Listener's metho ds. This allo ws us to create an
Note ano nymo us inner class, while o verriding o nly the metho ds we wish. Go ahead and lo o k up o ther
interfaces and find their co rrespo nding adapter classes.

After creating the new Mo use Adapt e r(), inside the curly braces {...} we define the class itself and implement
(o verride) the m o use Pre sse d() metho d. Inside the m o use Pre sse d() metho d, we set the frame to invisible. We also
use the dispo se () metho d fro m the Frame so that native display reso urces o f the o perating system are released and
their memo ry is freed up (we do this when things that implemented classes--like Frame--are go ing away) Then, we call
the System class e xit () metho d to terminate the pro gram. As a result, when the mo use is pressed in the Frame, the
pro gram terminates.

Ano nym o us inne r classe s are handy to o ls fo r adding listeners that perfo rm a single, well-defined task, asso ciated
with a specific co mpo nent. They are also useful if yo u want to create a Butto n to execute a specific task when clicked.
Let's try it. Create a new class in yo ur pro ject called But t o nT e st . Replace the co de in the class with the fo llo wing text:
CODE TO TYPE: Butto nTest

import java.applet.Applet;
import java.awt.Button;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ButtonTest extends Applet {


String msg = "";
public void init() {
Button okButton = new Button("Click Here");

//add an anonymous inner class as an ActionListener.


okButton.addActionListener(new ActionListener() {
// Create the actionPerformed method.
public void actionPerformed(ActionEvent e){
// Whatever you want to happen when the button is pressed
// goes in this method.
msg = "Button Pressed";
repaint();
}
});
add(okButton);
}
public void paint(Graphics g) {
g.drawString(msg, 20, 60);
}
}

This was just an example to sho w the use o f anno nymo us inner classes and Java's ability to actually instantiate a
listener interface, which is no rmally no t po ssible. All interfaces are instantiated using the im ple m e nt s keywo rd. But
there is o ne e xce pt io n to this rule. We can dire ct ly instantiate an interface in Java by using ano nym o us inne r
classe s. Java is smart eno ugh to have the co mpiler create a new class that implements the listener o n the fly.

Ano nymo us inner classes have access to all o f the variables and metho ds o f the class they are created within. In o ur
case, that's all o f the private and no n-private variables and metho ds o f the Memo class, and all o f the no n-private
variables and metho ds o f the Memo Class's ancesto r Classes.

Ano nymo us inner classes are "fire and fo rget." Once it is installed as a Listener, we no lo nger have a handle to the
o bject because they have no reference variable that we can access.

More on Programming Constructs


All languages have syntax and semantics.

Syntax refers to the grammar o r rules o f a language.


Semantics refers to the meaning o f the wo rds o r phrases.

Co mputer languages are no different. Fo r mo re detail, Oracle pro vides a Learning the Java Language Tuto rial . It
pro vides additio nal info rmatio n abo ut the "Language Basics" and o ther to pics.

Statements and Expressions


Because Java is an o bject-o riented language, it includes syntax fo r writing Classes as well as fo r writing
Metho ds wit hin Classes. Here are a few o ther things yo u need to kno w abo ut Java:

A Java pro gram is a co llectio n o f statements (like a sto ry in English is a co llectio n o f sentences).
A statement is a segment o f co de that takes so me actio n in the pro gram.
When we run a pro gram, we say that the co mpiler e xe cut e s statements.
Java statements end in semico lo ns (;).

Statements fo rm a co mplete unit o f executio n. There are vario us kinds o f statements, such as:

de clarat io n st at e m e nt s: Fo r example, int x; (Type VariableName)


e xpre ssio n st at e m e nt s (see next list)
f lo w co nt ro l st at e m e nt s

An expression is Java co de that specifies and evaluates to a single value in the pro gram. Check o ut a few
examples:

assignm e nt e xpre ssio ns: e.g., x = 6 ; (VariableName = Value)


arit hm e t ic e xpre ssio n: e.g., y = x1 + x2;
re lat io n e xpre ssio n: e.g., (x < 7); (pro duces true o r false)
m e t ho d invo cat io ns: e.g., System.o ut.println("hello again");

Primitive Data T ypes


In the examples abo ve we see the use o f variables x, y, x1, and x2. In o rder to have expressio ns, we need
variables. Just like wo rds in languages, variable s in co m put e r language s ne e d t o be de clare d. We
have seen that so metimes Java "canno t reso lve type" because an impo rt that Java needed to be able to find
the class wasn't there. What Java is saying in that message is, "I canno t understand yo u because yo u are
using wo rds (variables o r Objects) that yo u have no t to ld me abo ut--so I canno t parse yo ur statements."

The x's abo ve are no t Objects that need to be impo rted, they are numbers. But they are still things that Java
needs to kno w abo ut. Let's see what Java do es if we use them, but do no t de clare them.

Go to yo ur java2_Lesso n1 pro ject, o pen yo ur He llo Wo rldApp.java class, and add the line sho wn belo w in
blue :

CODE TO EDIT: Hello Wo rldApp


public class HelloWorldApp {

/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Hello World!");
x = 6
}
}

Remember that bo th the right co lumn and the left co lumn can indicate syntax erro rs in yo ur co de. If yo u click
either the "X" erro r indicato r o n the left o r the rectangle o n the right, yo ur edito r wo rkspace sho uld lo o k like
this:
The arro ws po int to the erro rs fo und by the edito r. Let's take a lo o k at the seco nd erro r. Just like sentences
need perio ds, statements require semico lo ns in Java. This erro r message tells yo u exactly that: Synt ax
e rro r, inse rt " ;" t o co m ple t e St at e m e nt .

In the first erro r (x canno t be re so lve d) we see that just like with Objects, Java needs to be info rmed o f the
t ype o f numbers to expect as well. In fact, whenever yo u use a wo rd--o r even a letter--that isn't o ne o f Java's
re se rve d wo rds o r specific syntax characters, yo u need to tell Java what it is. Ho w will Java kno w what yo ur
variable names stand fo r unless yo u tell it?

Eve ry piece o f data in a Java pro gram is classified and sto red in memo ry acco rding to its dat a t ype . If yo u
to o k the Java 1 Co urse, yo u may recall that so me pro perties o f o bjects are no t o ther o bjects (with pro perties
and metho ds o f their o wn), fo r example numbers. In mo st o bject-o riented languages, numbers are
represented differently because they do n't have "metho ds" o f their o wn. Numbers are interpreted as things
that we do things with; they do no t have actio ns o f their o wn. We call them prim it ive dat a t ype s.

Thus, there are two basic catego ries o f data types in Java:

the vario us types o f Classes o f Objects


eight different built-in prim it ive dat a t ype s

Note Primitive data types have a variable name and a single value--no metho ds.

Primitive data types are no t Classes; they are simply a place in co mputer memo ry with a value. In lesso n
three we'll go o ver the different primitive data types and their usage, but fo r no w let's find o ut ho w these
variables are de clare d and nam e d.

Let's fix yo ur Hello Wo rldApp. Edit the new line as sho wn (add the extra line to make it a little mo re interesting):

CODE TO EDIT: Hello Wo rldApp


public class HelloWorldApp {

public static void main(String [] args) {


System.out.println("Hello World");
int x = 6;
System.out.println("The value of x is " + x);
}
}

Nice. The red go es away.

Lo o k at the Syst e m .o ut .print ln statement, and at the st ring co ncat e nat io n in the metho d parameter.
Java will print everything just as it appears inside the quo tatio n marks. In this statement, Java will then
co ncatenate to the String the VALUE o f the x. We included a space inside the quo tes after "is"--if we didn't, the
system wo uld print "The value o f x is6 ". If a variable is no t co ntained within quo tatio n marks, Java will print
the value in memo ry, no t the variable name.

Save and Run the pro gram to verify.

Valid Identifiers (aka. Variable Names)


One impo rtant element o f go o d pro gramming design is the use o f m e aningf ul nam e s fo r yo ur Classes and
variables. In additio n to being meaningful, variable names must also adhere to the syntax rules that enable
Java to parse yo ur co de:

Variable names must begin with a letter and co nsist o f a sequence o f letters o r digits (0 -9 ). In this
co ntext, a letter is defined as A-Z, a-z, _, $.
They are case-sensitive.
They canno t co ntain spaces.
They can be any length.

Here are a few examples o f valid variable names. Since Java is case-sensitive, it will differentiate between the
seco nd and third entries o n the list.

1. identifier
2. user_name
3. User_name
4. _sys_var1
5. $change

Usually, we do no t use undersco re; instead, standard Java style uses capital letters to begin wo rds within
variable names (beginWo rd, tryThis, userName). The co nventio n is to always begin variable names with a
letter, no t ano ther symbo l like "$" o r "_". In fact the do llar sign character, by co nventio n, is never used. A
similar co nventio n exists fo r the undersco re character; while it's technically legal to begin yo ur variable's
name with "_", the practice is disco uraged.

Let's create a Class in Java that we can use to test things in a Pro ject. Make a new pro ject called temp, and
add an Applicatio n (including the main metho d stub) named Test to it.

Because it's a Java Applicatio n it will have the main metho d. Make sure to check the bo x (like we learned in
the last lesso n) so Eclipse will do the wo rk fo r yo u. When the Edito r windo w o pens, remo ve the "To Do " stub
co mment.

Type the T e st class as sho wn:

CODE TO TYPE: Test

public class Test {

public static void main(String[] args) {


int 4tryme;
int HowAboutThis&That;
}
}

Bo th variables have Syntax erro rs. Since we didn't fo llo w the rules, Java do es no t kno w what we want.
So m e t im e s, an explanatio n o f an erro r do esn't explain the erro r clearly. Ho wever, the message will usually
at least tell us which lines co ntain the erro rs, and make them easier to find.

Edit the variable names until there are no erro rs. Do n't wo rry if yo u get any warnings--we're still in testing
mo de.

Acco rding to co nventio n, Class names start with capitals (Applet, Graphics, MyApplet).
T ip Primitive data types, metho ds, and instance and class variable names start with lo wer case letters
(paint, myVariable).

So me wo rds are used by Java fo r its o wn language co nstructs and so they canno t be used by pro grammers
fo r variables. These are called reserved words, o r keywords. Here's a list o f Java keywo rds.

Let's see what happens when we use a keywo rd as a variable name. Change yo ur Test class as fo llo ws:
CODE TO EDIT: Test
public class Test {

public static void main(String[] args) {


int case;
}
}

We go t an erro r message: Synt ax e rro r o n t o ke n " case " , invalid Variable De clarat o r

We'll demo nstrate the value s that primitive data types can have in the next lesso n.

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Primitive Data Types, Variables, and Expressions
Lesson Objectives
When yo u co mplete this co urse, yo u will be able to :

use the str variables and the metho ds available in the String class.
use classes to fo rmat numbers.

Bits and Pieces in Memory

Variables
The Java Pro gramming Language defines the fo llo wing kinds o f variables:

Inst ance Variable s (IVs): Fie lds in Classe s that do no t have the st at ic keywo rd. Each
instance o f the class will have its o wn value fo r its instance variables, so memo ry is needed fo r the
value fo r e ach instance.

Class Variable s (CVs): Fie lds in Classe s that do have the st at ic keywo rd. Instances o f a class
share a co mmo n value fo r its class variables, so class variables take o nly o ne place in memo ry.

Lo cal Variable s: Variables within Class m e t ho d definitio n co de . The values o f local variables
are o nly accessible within the metho ds where they are declared--between the o pening and clo sing
brackets { } o f a metho d.

Param e t e rs: Used in Class m e t ho d definitio n signat ure s (fo rmal parameters) and invo catio ns
(actual parameters). The signatures o f a metho d identify the fo rmal parameter types required fo r
pro per invo catio n o f the defined metho d by o ther metho ds.

Primitive Data T ypes

The value s o f a variable must be defined as a certain t ype . We saw this when we declared all o f o ur variable
types. So far we've declared these types o f variables:

bo o le an
St ring
int
Co lo r
Graphics

So me o f them begin with capital letters and so me with lo wer-case letters. Tho se be ginning wit h capit al
le t t e rs are Objects, and tho se be ginning wit h lo we r-case le t t e rs are primitives. We'll co ver tho se later
in this lesso n.

A data type describes the representatio n, interpretatio n, and structure o f values manipulated by algo rithms o r
o bjects sto red in co mputer memo ry. As intro duced in the previo us lesso n, in Java there are two basic data
type catego ries: primitive data types and Classes. Classes have bo th attributes (pro perties) and actio ns
(metho ds). Primitive data types are "primitive" in that they are basic building blo cks that do no t have the
co mplete o bject structure. The Java language (rather than the metho ds o f a class), defines ho w the values
can be manipulated.

So me languages have no primitive data types. In these languages, e ve ryt hing is an Object.
Note These are called "pure o bject-o riented languages".
Java has eight basic (primitive) element types, because it pro vides fo ur (4) integer types, two (2) decimal-
po int types, o ne (1) char type, and o ne (1) bo o lean type. But in practice, Java uses fo ur basic element types:
integer, decimal point, boolean, and character.

These types allo w us to maximize speed and space. Each type o f element requires a different amo unt o f
space in memo ry. Using smaller numbers o r element types that o ccupy less memo ry space, allo ws fo r mo re
speed because smaller elements require less time to travel fro m memo ry to the CPU. Selecting the
appro priate element type allo ws us to avo id taking up mo re space than necessary so we can maximize
speed. Check o ut the table belo w. It sho ws the fo ur types o f int e ge rs and the amo unt o f space in memo ry
each is allo wed:

Prim it ive Dat a T ype - Int e ge r

Le ngt h Nam e
8 bits byte
16 bits sho rt
32 bits int
6 4 bits lo ng

Because co mputer data is represented by zero s and o nes (base 2), the number o f bits (base 2 numbers)
allo wed will limit the range o f numbers allo wed. One o f the bits will indicate whether the integer is po sitive o r
negative.

Dat a T ype Range


byt e -128 to 127
sho rt -3276 8 to 3276 7
int -2,147,48 3,6 48 to 2,147,48 3,6 47
lo ng -9 ,223,372,0 36 ,8 54,775,8 0 8 to 9 ,223,372,0 36 ,8 54,775,8 0 7

The mo st co mmo n integer type is: int

If yo u type 4, yo u get an int with value 4. Pro grammers usually use int as their default.
To use a lo nger integer, use the type lo ng by adding an L (upper o r lo wer case ) to the end o f the number, like
this:

lo ng myNumber = 123456 78 9 0 0 L;

Let's see what happens when we declare an integer o f a specific type and then give it a value that is no t
allo wed.

In the Java2_Lesso ns fo lder, create a new Pro ject named java2_Le sso n3, and then create a Java
Applicatio n class named Prim it ive T e st .
CODE TO TYPE: testing types
public class PrimitiveTest {

public static void main(String[] args) {


byte x = 344444;
short y = -32769;
int z = 2147483648;
long w = 9000000000000;
long v = 9E8;
}
}

Who o ps. It lo o ks like we've go t so me erro rs. Actually, we had yo u create co de that co ntains erro rs o n
purpo se, to demo nstrate a few co ncepts. Mo ve yo ur mo use o ver the first erro r indicato r:

When yo u mo use o ver an erro r yo u'll see an erro r message; fo r example, the o ne o n the line co ntaining byte
x = 344444 has the erro r:

T ype m ism at ch: canno t co nve rt f ro m int t o byt e

We go t this erro r because we to ld Java that x was a byte, but we gave x a number that is in the int range. It's
impo ssible fo r Java to take the integer value o f 344444 and put it into the memo ry space allo wed fo r a byt e ,
so we get a T ype m ism at ch.

The same lo gic applies to the erro r o n the sho rt variable we declared; the space fo r sho rt is no t big eno ugh:

T ype m ism at ch: canno t co nve rt f ro m int t o sho rt

To co rrect these erro rs in yo ur co de, make the changes sho wn in blue belo w:
CODE TO TYPE: testing types
public class PrimitiveTest {

public static void main(String[] args) {


int x = 344444;
int y = -32769;
int z = 2147483648;
long w = 9000000000000;
long v = 9E8;
}
}

No w, mo use o ver the next erro r symbo l. Yo u see:

T he lit e ral 214 7 4 836 4 8 o f t ype int is o ut o f range

The type is actually o ut o f range by 1. Yo u can verify this by referring back to the table o f the ranges o f values
abo ve.

Changing the number as sho wn belo w and the erro r sho uld go away:

CODE TO TYPE: testing types


public class PrimitiveTest {

public static void main(String[] args) {


int x = 344444;
int y = -32769;
int z = 2147483647;
long w = 9000000000000;
long v = 9E8;
}
}

Since we use co mmas when we write lo nger numbers, yo u may be curio us abo ut whether co mmas are used
in pro gramming using integers, especially the lo nger o nes. Let's find o ut! Change the number as sho wn in
blue belo w:

CODE TO TYPE: testing types


public class PrimitiveTest {

public static void main(String[] args) {


int x = 344444;
int y = -32769;
int z = 2,147,483,647;
long w = 9000000000000;
long v = 9E8;
}
}

Yo u get all kinds o f erro rs no w, but here's the o ne to pay attentio n to :


num be rs canno t co nt ain co m m as

Take the co mmas o ut and the erro rs will go away. No w, what's go ing o n with the lo ng declared variable? The
erro r says:

T he lit e ral 9 0 0 0 0 0 0 0 0 0 o f t ype int is o ut o f range

We declared y as a lo ng; why did it say type int ? Because 9 0 0 0 0 0 0 0 0 0 is o ut o f range fo r an int , we need
to indicate that it's a lo ng by adding the "L" to the end. Otherwise, the default fo r numbers is type int .

Change the co de as sho wn in blue:

CODE TO TYPE: testing types


public class PrimitiveTest {

public static void main(String[] args) {


int x = 344444;
int y = -32769;
int z = 2147483647;
long w = 9000000000000L;
long v = 9E8;
}
}

Finally, we have an erro r o n the line that co ntains the co de lo ng v = 9 E8;. The erro r message says:

T ype m ism at ch: canno t co nve rt f ro m do uble t o lo ng

Change the type as sho wn in blue:

CODE TO TYPE: testing types


public class PrimitiveTest {

public static void main(String[] args) {


int x = 344444;
int y = -32769;
int z = 2147483647;
long w = 9000000000000L;
double v = 9E8;
}
}

Everything sho uld be fine no w. Still, yo u might be wo ndering, "what's a do uble?" The next set o f primitive data
types represent numbers with decimal and expo nent values. Java pro vides two types here: f lo at and
do uble .

Prim it ive Dat a T ype - Flo at ing Po int (De cim al)
De cim al:
Le ngt h Nam e
32 bits flo at
6 4 bits do uble

Here are so me examples o f numbers with decimal values:

3.14

3.1E12 means 3.1 X 10 12 , which is sho rthand fo r 310 0 0 0 0 0 0 0 0 0 0 .

2e12 means 2 X 10 12 (E o r e makes no difference).

12.34f means 12.34 flo ating po int.

-32.0 f means -32.0 flo ating po int.

Similar to the way we used L at the end o f integers to indicate the type Lo ng, yo u can use e o r E (fo r
Expo nents o r po wers o f 10 ), f o r F (fo r Flo at), d o r D (fo r Do uble). Do uble is the default tho ugh, and usually
o mitted. Yo u m ust use the f o r F fo r Flo at types. To find detailed info rmatio n abo ut the ranges fo r bo th o f
these types, visit the Java Language Specificatio n. Fo r o ur purpo ses, just keep in mind that flo at and do uble
allo w big numbers, so big that they aren't likely to co me up fo r us much in o ur wo rk. But it's still go o d to kno w
abo ut them. Here's a ro ugh table o f ranges just so yo u can get the idea:

Dat a T ype Range


flo at +-1.4 * 10 -45 to +-3.4 * 10 38
do uble +-4.9 * 10 -324 to +-1.7 * 10 30 8

A variable must be declared befo re it can be used. Yo u can declare it when yo u first mentio n the variable, o r at
the same time its value is specified. Fo r decimal po int values, do uble is the default if yo u o mit the f . So , what
wo uld happen if yo u typed
float myValue = 12.3;? Give it a try.

Edit the Prim it ive T e st class's m ain metho d as sho wn:

CODE TO TYPE: Can yo u guess what will happen?


public class PrimitiveTest {

public static void main(String args[])


{
float myValue = 12.3;
}
}

Lo o k at the erro r co lumn:

T ype m ism at ch: canno t co nve rt f ro m do uble t o f lo at


Do es that make sense? Yo u're declaring the myValue variable to be a f lo at, but because the 12.3 do es no t
have an f at the end, Java reads it as a do uble.

There are two ways to fix this:

Declare myValue to be a flo at: float myValue =12.3f;


Declare myValue to be a do uble: double myValue = 12.3;

Try bo th so lutio ns in the Edito r Windo w. Be sure to click the mo use so mewhere after each change, so Eclipse
accepts it.

CODE TO EDIT: PrimitiveTest


public class PrimitiveTest {

public static void main(String args[])


{
float myValue = 12.3f;
}
}

OR

CODE TO EDIT: PrimitiveTest


public class PrimitiveTest {

public static void main(String args[])


{
double myValue = 12.3;
}
}

Bo th wo rk fine.

Even Duke has to so rt o ut the right type!

Prim it ive Dat a T ype - Bo o le an (bo o le an)

Bo o leans are used fo r lo gical reaso ning and have o nly two po ssible values: true o r false. No t T o r F, o r
TRUE o r FALSE, o nly t rue o r f alse .

Let's check it o ut! Edit the bo dy (inside the blo ck {}) o f the Prim it ive T e st class's m ain metho d as sho wn:
CODE TO TYPE: bo o leans
public class PrimitiveTest {

public static void main(String args[])


{
boolean testMe = false; // note declaration of lower case boolean
if (!testMe)
System.out.println("testMe might be false but !testMe is " + !testMe
);
}
}

Save and run it. The o utput sho uld be in the co nso le. It sho uld say t e st Me m ight be f alse but
!t e st Me is t rue . In Java the ! means no t (o r the opposite of). So , if t e st Me is true, then !t e st Me is false. If
t e st Me is false, then !t e st Me is true.

Prim it ive Dat a T ype --Charact e r (char):

Characters are just that--single characters. Think o f them as the keys o n yo ur keybo ard. Each key is a
character. In Java, we enclo se characters inside single quo tatio n marks: yo u type 'a' to get a char with value
a:

char myCharacter = 'a';

Here are so me special "escape sequences" o r keystro kes represented in Java:

\t (tab)
\b (backspace)
\n (linefeed)
\r (carriage return)
\f (fo rm feed)
\" (do uble quo te)
\' (single quo te)
\\ (backslash)

These escape sequences are used to allo w Java to define a character being used. The backslash alerts Java
that the next character typed will be used to perfo rm the actio n sho wn in the parentheses.

To define the character m , yo u'd use char myOtherCharacter = 'm'; So , why the single quo tatio n marks,
yo u ask? Edit the T e st class's m ain metho d as sho wn to find o ut:

CODE TO EDIT: PrimitiveTest


public class Test {
public static void main(String args[])
{
char myCharacter = "m";
}
}
See the capital letter at the beginning o f St ring? Do uble quo tatio n marks are fo r a Class in Java called
String in the java.lang package. That's why we use single quo tatio n marks in this case.

Strings
St rings are no t primitive data types--they are a Java class called St ring in the package java.lang. We'll
co ver Strings in the next lesso n.

Literals
A literal is the so urce co de representatio n o f a fixed value. Literals are represented directly in yo ur co de
witho ut requiring co mputatio n. The examples belo w sho w ho w it is po ssible to assign a literal to a variable o f
a primitive type:

boolean result = true;


char capitalD = 'D';
byte b = 42;
short s = 5280;
int i = 100000;

We have set values like this in previo us examples, but no w if yo u hear the wo rd lit e ral, yo u kno w it is just a
fixed value (like a number) to which yo u can set primitive data type variables.

Memory: variable names and values


We need to lo o k carefully at Assignm e nt st at e m e nt s. Co nsider this line o f co de:

T ype variable Nam e = e xpre ssio n;

There are t hre e impo rtant elements fo r yo u to o bserve:

1. The left side o f the = sign is the lo cat io n where the value o f the variable is sto red (variableName is a memo ry
lo cat io n).
T ype variable Nam e ; is declaring the Type o f variable that will be placed into the lo catio n o f variable Nam e . Java
needs to kno w the Type in o rder to determine ho w much space to reserve in memo ry at that lo catio n.

2. In pro gramming languages, a lo cat io n o r an addre ss in memo ry is fo und o n the left side o f the equal sign (=).
It wo rks kind o f like an o ld-scho o l card catalo g in a library:
Yo u lo o k up a title o f a bo o k to get a number fo r where the bo o k is lo cated.

Yo u do n't go to the card catalo g fo r the bo o k itself, but fo r the bo o k's lo catio n. The left side o f an equal sign (=) in
pro gramming languages always indicates o nly the lo catio n o f the value fo r the variable. Because the variableName
tells Java the lo cat io n, just like card catalo g lo catio ns, yo u do n't perfo rm any manipulatio n (arithmetic) o n these
numbers.

The o nly things o n the left side o f an equal sign in Java are the variableName, which is an addre ss, and
Note po ssibly the t ype o f variable that will be placed int o that lo catio n.

3. On the right side o f the equal sign (=) are expressio ns. Expressio ns calculate the value s that will be put into tho se
memo ry lo catio ns.
variable Nam e s (le f t side ) are memo ry lo catio ns where the value s o f e xpre ssio ns (right side ) are sto red o nce
calculated.

When the co mputer sees a variableName o n the right side o f an equal sign (=), it go es and ge t s the value at that
lo catio n.
When it sees a variableName o n the le f t side o f an equal sign (=), it put s the result o f the right side into the address
o f the left side variableName.

What do es the co mputer do when it reads int length = 20;? I'm so glad yo u asked. Actually, it do es two things.
This o ne line could have been written as two :

Declaratio n: int length; At run time, the co mputer go es to a lo catio n o f memo ry and leaves space fo r 32
bits. Fro m then o n, it has the address to this lo catio n thro ugh the variable name le ngt h. Any time that length
is used (in the sco pe {} that it was declared), Java kno ws that it is o f type int .
Assignment: length = 20;. The co mputer go es to the address designated by le ngt h, and at that lo catio n,
put s a value o f 20 .

Optional Reading: T he Bus


Everything in the co mputer is st o re d in memo ry, but everything is do ne in the Ce nt ral Pro ce ssing Unit 's
(CPU's) Arit hm e t ic Lo gic Unit (ALU). In o rder fo r the right info rmatio n to get t o the ALU at the right time,
the CPU also has a Co nt ro l Unit directing things by telling it what to do given yo ur co mpiled co de. The
Co ntro l Unit is what gets the right things at the right time and makes sure they are in the right place. It tells the
co mputer that a certain piece o f info rmatio n in Me m o ry needs to be retrieved and put into a re gist e r fo r the
ALU to use.

The wires that are used to transfer these bits o f info rmatio n (fro m memo ry to the CPU--o r o utput devices,
input devices, etc.) are called the bus. In very early co mputers, buses were as little as 8 bits wide. No w,
suppo se yo u had a variable that was o f type lo ng. Ho w many times wo uld the co ntro l unit have to go back
and fo rth fro m memo ry to retrieve the who le variable? A variable o f type long has 6 4 bits; with a bus that is 8
bits wide, we wo uld need 6 4/8 , o r 8 trips, fo r o ne variable.

Ho w many times wo uld the co ntro l unit have to go back and fo rth fro m memo ry to get the who le variable if it
was o f type byte? A variable o f type byte has 8 bits; with a bus that is 8 bits wide, we wo uld need 8 /8 o r 1 trip
fo r this o ne variable.

Which access wo uld be faster--to get the lo ng o r the byt e ?

We have to make a trade-o ff. We want a smaller number o f bits so that they can travel o n the bus faster, but
smaller numbers o f bits do no t represent numbers as large as we might want to use. To day, buses are mo st
o ften 32 o r 6 4 bits and hence the type int is co mmo nly used fo r integers.

Alright. So no w that we kno w what the primitive data types are , it's time to use them!

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Output: Strings, Fonts, and Numbers
Lesson Objectives
When yo u co mplete this co urse, yo u will be able to :

use classes to fo rmat numbers.


allo cate memo ry space.
assign values to variables.

In the last lesso n we discussed Primitive Types as well as Class types (o bjects). We used the Graphics o bject extensively in the
Java 1 co urse. This lesso n will be devo ted to yet ano ther useful type: the St ring class.

Strings
When yo u want to write text in yo ur Applets and applicatio ns in Java, yo u use the java.lang.St ring class. Use Strings
whenever yo u want to wo rk with so mething mo re than o ne character in length.

Keep in mind that St rings in J ava are immutable, which means that, o nce a String is defined, the characters can't be
changed. And St rings are constant -- o nce created, their values can't be changed. But despite these qualities, yo u
can play with them all yo u want; yo u can create new Strings that are manipulatio ns o f an existing String; yo u just can't
get into the memo ry lo catio n o f a defined St ring and change it there.

Find the String Class. As stated in the API, the String class includes metho ds fo r, amo ng o ther things:

examining individual characters o f the sequence


co mparing strings
searching strings
extracting substrings
creating a co py o f a string with all characters translated to upper o r lo wer case

Investigating Strings
St ring is a Java class in the java.lang package. When we use St rings, we're using inst ance s o f the
St ring Class.

Read the intro ductio n to the St ring Class in the API. Also lo o k at the Me t ho d Sum m ary there, paying
special attentio n to the metho d descriptio ns. The Co nstructo r o f the String Class is o verlo aded; it has 15
different po ssibilities. When we have an o verlo aded metho d, each co nstructo r m ust have a different number
and/o r different types o f parameters, so that Java can identify which unique co nstructo r to use.

Strings allo w us to put text into o ur o utput. In the Hello Wo rld Applet, yo u gave the co mmand:

g.drawString("Hello Wo rld!", 5, 15);

In this co de g indicates an instance o f the Graphics class.

Go to the Graphics class and find the drawSt ring() metho d. There are two instances o f the
drawSt ring() metho d here.

These are their signat ure s:

drawString(AttributedCharacterIterato r iterato r, int x, int y)


drawString(String str, int x, int y)

It appears that the drawSt ring() metho d in Graphics is also o ve rlo ade d.

Which instance o f the drawSt ring() metho d do es Java use fo r o ur g.drawSt ring(" He llo Wo rld!" , 5 , 15 )
call?
The parameters inside the parentheses ( ) o f the metho d call are o f types: String, int, int. They direct Java to
use the seco nd instance o f the drawSt ring() metho d. Specifically, they tell Java to go to the instance g o f
Graphics and in that Graphics instance, call the metho d drawSt ring(St ring st r, int x, int y) by assigning
the values: String str="Hello Wo rld", int x=5, and int y=15. And then, Java "draws" the text fro m the specified
string at po sitio n (x, y) in this graphics co ntext.

Using Strings
String is a class; therefo re, we use the ne w keywo rd to create String o bjects. But, because Strings are used
so much, Java pro vides special co mmands that make it easier to wo rk with them. Fo r example, to add text
into yo ur pro gram, yo u co uld use the ne w co mmand to make an instance o f a St ring and then add yo ur text.
But Java has a special m yNe wSt ring co mmand that do es the same thing:

St ring m yNe wSt ring = " J ava is f un" ;

This sho rtcut is equivilant to the Java statement:

St ring m yNe wSt ring = ne w St ring(" J ava is f un" );

It is impo rtant to no te that All o ther rules abo ut Java o bjects are the same fo r Strings as fo r o ther o bjects.
There is o ne mo re special thing to kno w abo ut Strings. The Java co mpiler is an o ptimizing co mpiler and
kno ws that String o bjects are immutable. Therefo re, when a String o bject is created with a String literal, it is
inernalized with the String class int e rn() metho d. Any o ther String o bjects created with the same String literal
will use that internalized o bject rather than ano ther separate o bject.

Fo r example:

St ring m yFirst St ring = " He llo Wo rld" ;

and

St ring m ySe co ndSt ring = " He llo Wo rld" ;

will no t create two o bjects. Bo th myFirstString and mySeco ndString will po int to the same String o bject in
memo ry.

When yo u print o ut strings, yo u o ften print o ut wo rds mixed with variable values. In o rder to do this, yo u use
co ncat e nat io n, which means appe nding (adding) o ne String to ano ther. Java allo ws us to use the plus (+)
sign to do this.

No w, let's play with so me Strings!

Make a new java2_Le sso n4 pro ject. Create a new Class that extends Applet in this pro ject and name it
De m o St rings.

No tice that this is different fro m previo us lesso ns where we created Classes that were
Note Applicatio ns.
CODE TO TYPE: Demo Strings
import java.applet.Applet;
import java.awt.*;

public class DemoStrings extends Applet {

public void start(){


resize(400,200);
}
public void paint(Graphics g) {
int length = 200;
int width = 400;

g.drawString("The area of this window is the length times the width", 10


, 20);
g.drawString("Our width is " + width + " pixels, and length is " + leng
th, 10, 40);
g.drawString("The area of this rectangle is " + (width * length), 10, 70
);
}
}

Save and Run it.

In drawString, everything that co mes be f o re the first co mma must be part o f a single String. That String may
o r may no t include co ncatenatio n. Co ncatenatio n is indicated by the presence o f the plus (+) sign. The
quo tatio n marks let Java kno w it's a string. The last two parameters o f drawSt ring() are the x and y
co o rdinates that determine its lo catio n o n the Applet. Here's an example:

g.drawSt ring(" Our widt h is " + widt h + " pixe ls, and le ngt h is " + le ngt h , 10 , 4 0 );

Again, we left a space after the wo rd "is" befo re the clo sing quo tatio n marks in the String to make o ur o utput
easier to read. If we didn't leave that space, o ur o utput wo uld lo o k like this:

Our width is40 0 pixels, and length is20 0

In Java yo u can use math expressio ns and they are auto matically cast into Strings. The plus sign (+)
co ncatenates the String o utput to the re sult o f the arithmetic o peratio n.

g.drawSt ring( " T he are a o f t his re ct angle is " + (widt h * le ngt h) , 10 , 7 0 );

Let's try ano ther example:


CODE TO TYPE: Demo Strings
import java.applet.Applet;
import java.awt.*;

public class DemoStrings extends Applet {

public void start(){


resize(400,200);
}

public void paint(Graphics g) {


int length = 200;
int width = 400;

g.drawString("The area of a rectangle is the length times the width", 10


, 20);
g.drawString("Our width is " + width + " and length is " + length, 10,
40);
g.drawString("The perimeter of this rectangle is " + 2*width + 2*length,
10, 70);
}
}

Save and Run it. Lo o k at the o utput carefully. The answer sho uld be 120 0 , but it isn't. The first parameter
o f the Graphics drawSt ring() metho d is a St ring. When Java sees a plus sign (+) within so mething that is
suppo sed to be a St ring, it co ncatenates rather than adding.

Java did just what we to ld it to do --it multiplied the width by 2, and made the result (8 0 0 ) a St ring, because
that is what the parameter required. It then multiplied length by 2, and made the result (4 0 0 ) a St ring,
because that's what the parameter required. Then it co ncatenated these two Strings and go t a result o f
80 0 4 0 0 . But that's no t the result we want. Fo rtunately, Java understands the precedence rule o f "parentheses
first," so we can fix this erro r pretty easily if we change o ur co de so it lo o ks like this:

CODE TO TYPE: Demo Strings

import java.applet.Applet;
import java.awt.*;

public class DemoStrings extends Applet {

public void start(){


resize(400,200);
}

public void paint(Graphics g) {


int length = 200;
int width = 400;

g.drawString("The area of a rectangle is the length times the width", 10


, 20);
g.drawString("Our width is " + width + " and length is " + length, 10,
40);
g.drawString("The perimeter of this rectangle will be " + (2*width + 2*l
ength), 10, 70);
}
}

Manipulating Strings
We can pro bably co me up with so mething a little mo re interesting than arithmetic fo r examples o f St rings.

Edit the De m o St rings Class's paint () metho d as sho wn in blue .


CODE TO EDIT: Demo Strings

import java.applet.Applet;
import java.awt.*;

public class DemoStrings extends Applet {

public void paint(Graphics g) {


int y=15;
String str = "Java is Hot"; // normal String
g.drawString(str, 10, y*1);
String modify = str.replace("v","bb" ).replace('o', 'u').replace("is", "t
he");
g.drawString(str.substring(0,7) + " still" + str.substring(7,11), 10, y*2
);
g.drawString("But used to make: ", 10,y*4);
g.drawString(modify + "t", 10, y*5);
}
}

Save and Run it. Co mpare the metho ds in the co de to the o utput. We can manipulate the defined instance
st r o f St ring, but in do ing so , we make a new String. The o riginal St ring remains the same.

Take a lo o k at the re place () and subst ring() metho ds o f St ring() in the API. Let's try o ut so me o f these
o ther metho ds. Edit Demo Strings as sho wn belo w:

CODE TO TYPE:
import java.applet.Applet;
import java.awt.*;

public class DemoStrings extends Applet {

public void paint(Graphics g) {


int y=15;
String str = "Java is Hot";
g.drawString(str, 10, y*1);

String java = str.substring(0,6);


g.drawString("The method substring - from index 0 to 6 gives: " + java,
10, y*2);

int len = "HotJava".length();


g.drawString("The length of the string HotJava is: " + len, 10, y*4);

String obj = new String("A String is an Object");


g.drawString(obj, 10, y*6); // seeing what it prints when it
is accessed as the object

String word = "Mississippi";


g.drawString(word, 10, y*8);
g.drawString(word.replace('i','a'), 10, y*9);
g.drawString(word.toUpperCase(), 10, y*10);

g.drawString("The original word is still: " + word, 10, y*12);


}
}

Save and Run it. Co mpare the co de to the o utput to see ho w metho ds in St ring wo rk.

Fonts
When pro gramming in Java, we want to be able to co ntro l the way o ur St rings lo o k. Java pro vides to o ls to change
the appearance o f o ur pro grams' o utput. The Graphics class has a setFo nt(Fo nt fo nt) metho d that enables us to set
the fo nt in o ur Graphics area. The Fo nt class allo ws us to create the fo nt that we want to use in its Co nstructo r. Here's
ho w yo u do that in general:

Fo nt (St ring nam e , int st yle , int size )

And here's actual co de we might use to create a new fo nt o bject using the Fo nt class's co nstructo r:

Fo nt bigFo nt = ne w Fo nt (" He lve t ica" , Fo nt .BOLD, 20 );

Let's try it. Start a new J avaFo nt Class in java2_Lesso n4 (again using the java.applet.Applet superclass):

CODE TO TYPE:
import java.applet.Applet;
import java.awt.*;

public class JavaFont extends Applet {


Font bigFont = new Font("Serif", Font.BOLD, 56);
Font smallFont = new Font("Helvetica", Font.PLAIN, 20);

//Make a dark red for O'Reilly School of Technology


private static final Color leafRed = new Color(115, 0, 0);

String line1 = "JAVA";


String line2 = "O'REILLY";

public void paint(Graphics g)


{
// draw the text
g.setColor(leafRed);
g.setFont(bigFont);
g.drawString(line1, 15, 100);
g.setFont(smallFont);
g.drawString(line2, 46, 140);
}
}

Save and Run it and check o ut the results.

No w, let's change the parameter sho wn belo w in blue :


CODE TO TYPE: JavaFo nt
import java.applet.Applet;
import java.awt.*;

public class JavaFont extends Applet {


Font bigFont = new Font("Serif", Font.BOLD, 56);
Font smallFont = new Font("Helvetica", 3, 20);

//Make a dark red for O'Reilly School of Technology


private static final Color leafRed = new Color(115, 0, 0);

String line1 = "JAVA";


String line2 = "O'REILLY";

public void paint(Graphics g)


{
// draw the text
g.setColor(leafRed);
g.setFont(bigFont);
g.drawString(line1, 15, 100);
g.setFont(smallFont);
g.drawString(line2, 46, 140);
}
}

Save and Run it and check o ut the results.

Go to the Fo nt class in the API and lo o k at its co nstructo rs. In o ur J avaFo nt class, go to the line:

Fo nt sm allf o nt = ne w Fo nt (" He lve t ica" , 3, 20 );

Play aro und with it, change the int parameter values, run the co de, and o bserve the results.

Numbers
Altho ugh Java has a Num be r class in the java.lang package, we wo n't be lo o king at it here. In this sectio n we're
actually interested in f o rm at t ing numbers, so we'll investigate the Num be rFo rm at class in the java.t e xt package.

Start a new Num be rsDe m o class in java2_Lesso n4 that again extends Applet:

CODE TO TYPE: NumbersDemo

import java.applet.Applet;
import java.awt.*;

public class NumbersDemo extends Applet {

public void paint(Graphics g) {


double area;
double radius = 12;

g.drawString("Area of a circle = (radius)^2*Pi", 10, 20);


g.drawString("If radius = " + radius, 10, 40);
g.drawString("The circle's area = " + Math.pow(radius,2)*Math.PI, 10, 70);
}
}

Save and Run it.


Okay, but what if we do n't need o ur results to be carried o ut that far, to be such lo ng numbers? We can fix that, using
the java.text.NumberFo rmat class to limit o ur o utput to just two decimal places. Add the blue co de sho wn belo w:

CODE TO EDIT: NumbersDemo


import java.applet.Applet;
import java.awt.*;
import java.text.NumberFormat;

public class NumbersDemo extends Applet {

public void paint(Graphics g) {


NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
double area;
double radius = 12;

g.drawString("Area of a circle = (radius)^2*Pi", 10, 20);


g.drawString("If radius = " + radius, 10, 40);
g.drawString("The circle's Area = " + nf.format(Math.pow(radius,2) * Math.PI),
10, 70);
}
}

Save and Run it.

Ahh, much better--o nly two decimal places. To learn mo re abo ut NumberFo rmat, go to the NumberFo rmat class in the
java.t e xt package in the .

Yo u co uld acco mplish the same task using the De cim alFo rm at Class, lo cated in the java.t e xt package. It's actually
a subclass o f Num be rFo rm at , which indicates that it will perfo rm mo re specific actio ns. A De cim alFo rm at
co mprises a pattern and a set o f symbo ls that yo u define so that the number in yo ur o utput appears just the way yo u
intend it to be.

Edit the Num be rsDe m o class as sho wn here in blue :

CODE TO EDIT: NumbersDemo


import java.applet.Applet;
import java.awt.*;
import java.text.DecimalFormat;

public class NumbersDemo extends Applet {

public void start(){


resize(300,200);
}

public void paint(Graphics g) {


DecimalFormat myFormat1 = new DecimalFormat("###,###.##");
DecimalFormat myFormat2 = new DecimalFormat("###,###");
double area;
double radius = 12;

g.drawString("Area of a circle = (radius)^2*Pi", 10, 20);


g.drawString("If radius = " + radius, 10, 40);
g.drawString("The circle's area = " + myFormat1.format(Math.pow(radius,2)*Math.
PI), 10, 70);
g.drawString("An alternate formatting without decimals ", 10, 95);
g.drawString("The circle's area= " + myFormat2.format(Math.pow(radius,2)*Math.P
I), 10, 110);
}
}

Save and Run it. Co mpare the o utput to the co de.


Go to the DecimalFo rmat class in the java.t e xt package in the API to find o ut mo re.

Altho ugh this lo o ks pretty go o d, co nsider a simple edit. Let's say we want to represent mo ney, so we want exactly two
decimal places again. Edit the Num be rsDe m o class by adding the lines sho wn in blue :

CODE TO EDIT:
import java.applet.Applet;
import java.awt.*;
import java.text.DecimalFormat;

public class NumbersDemo extends Applet {

public void paint(Graphics g) {


DecimalFormat myFormat1 = new DecimalFormat("###,###.##");
DecimalFormat myFormat2 = new DecimalFormat("####,###");
double area;
double radius = 12;
double amountOwed = 12.00;

g.drawString("Area of a circle = (radius)^2*Pi", 10, 20);


g.drawString("If radius = " + radius, 10, 40);
g.drawString("The Circle's Area = " + myFormat1.format(Math.pow(radius,2)*Math.
PI), 10, 70);
g.drawString("An alternate formatting without decimals ", 10, 95);
g.drawString("The Circle's Area = " + myFormat2.format(Math.pow(radius,2)*Math.
PI), 10, 110);
g.drawString("The money owed is " + myFormat1.format(amountOwed), 10, 130);
}
}

No w Save and Run it and co mpare the o utput to the co de.

The number was fo rmatted, but since there were no values after the decimal, the given fo rmat left the digits o ff entirely.
But in so me cases, we want the extra digits even if they are zero s.

We can make Java do e xact ly what we want. We can. We will. We have the po wer!

Edit the Num be rsDe m o Class by adding the two lines as sho wn belo w in blue :
CODE TO EDIT:
import java.applet.Applet;
import java.awt.*;
import java.text.DecimalFormat;

public class NumbersDemo extends Applet {

public void paint(Graphics g) {


DecimalFormat myFormat1 = new DecimalFormat("###,###.##");
DecimalFormat myFormat2 = new DecimalFormat("####,###");
DecimalFormat df1 = new DecimalFormat("####.00");

double area;
double radius = 12;
double amountOwed = 12.00;

g.drawString("Area of a circle = (radius)^2*Pi", 10, 20);


g.drawString("If radius = " + radius, 10, 40);
g.drawString("The circle's area = " + myFormat1.format(Math.pow(radius,2)*Math.
PI), 10, 70);
g.drawString("An alternate formatting without decimals ", 10, 95);
g.drawString("The circle's area = " + myFormat2.format(Math.pow(radius,2)*Math.
PI), 10, 110);
g.drawString("The money owed is " + df1.format(amountOwed), 10, 130);
}
}

Save and Run it and co mpare the o utput to the co de.

This time, rather than explain it to yo u o urselves, we'll let the API do it. Yo u kno w where to go ! Have fun and go o d luck!

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Arithmetic Operations: The Basics
Lesson Objectives
When yo u co mplete this co urse, yo u will be able to :

pro mpt the user fo r input and return info rmatio n based o n that input.
use arithmetic o perato rs.
use increment statements.
pro cess o perato rs in the pro per o rder.

Calculations and Operators

In a previo us lesso n, we talked abo ut st at e m e nt s. In this lesso n, we'll lo o k mo re clo sely at a particular type o f
statement kno wn as an e xpre ssio n. We'll also lo o k at the o perato rs that Java pro vides and use valid syntax to
perfo rm desired calculatio ns. Java is a high-level language (a language that's clo ser to human language than
co mputer language). Because o f this, it enables us to write expressio ns in a simple fo rm witho ut having to co nsider
everything the co mputer do es to perfo rm the calculatio ns. We'll leave that to the low-level languages.

Variables and a Program to Dissect


Let's get started! Create a t e m p pro ject, and within that pro ject, create an Applet named Calculat io n. No w
type in the fo llo wing co de:

CODE TO TYPE: Calculatio n

// calculate area of rectangle


import java.awt.*;
import java.applet.Applet;

public class Calculation extends Applet {


public void paint(Graphics g) {
int length; //declarations
int width;
int area;

length = 20; // assignments


width = 10;
area = length * width;
g.drawString("Area is " + area, 100, 100);
// display the answer
}
}

Save and Run it.

Let's trace the pro gram to see exactly what's happening in the paint () metho d:

1. We declared three variables as type int :


int length;
int width;
in area;

2. We assigned a value o f 20 to the variable le ngt h. The co mputer go es to lo catio n o f "length"


and, at that lo catio n, put s a value o f 20 .
3. We assigned a value o f 10 to the int widt h (put 10 at lo catio n "width").
4. The co mputer actually perfo rms several steps in the line are a = le ngt h * widt h;:
1. It go es to variable le ngt h's lo catio n in memo ry, ge t its value (20 ), and send it back
o n the bus to the CPU.
2. It go es to variable widt h's lo catio n in memo ry, ge t its value (10 ), and send it back o n
the bus to the CPU.

3. It Multiplies the values it just go t (20 * 10 ) in the CPU's Arithmetic Lo gic Unit (ALU).
4. It go es to variable are a's lo catio n in memo ry o n the bus, and put its calculated value
(20 0 ).
5. It tells the Graphics area g to apply drawSt ring() to the String "Area is ".
6 . It ge t s the value (20 0 ) at lo catio n area. It co ncat e nat e s (+) this to the "Area is" String and gets:
Area is 20 0 .
7. It prints this result at the specified lo catio n (10 0 ,10 0 ) o n the Graphics area o f the Applet.

While we're here, let's try an alternative declaratio n o f the variables. Change the class as sho wn belo w in
blue:

CODE TO EDIT: Calculatio n


// calculate area of rectangle
import java.awt.*;
import java.applet.Applet;

public class Calculation extends Applet {


public void paint(Graphics g) {
int length, width, area; //declarations

length= 20; // assignments


width = 10;
area = length * width;
g.drawString("Area is " + area, 100, 100);
// display the answer
}
}

Save and Run it. It sho uld wo rk exactly the same way.

Yo u can declare variables o f the same type all at o nce like this, but it's go o d pro gramming style to gro up
related variables to gether, while keeping different variables o n separate lines.

Befo re we leave this example, let's lo o k at the multiplicatio n line o nce mo re:

area = length * width;

Note To perfo rm multiplicatio n in Java, yo u must use *.

In Java, yo u canno t use x to indicate multiplicatio n and yo u canno t simply o mit the o perato r, as yo u wo uld
in mathematics, substituting 6 y fo r 6 t im e s y. No r can yo u use parentheses, as in y(6 ), to indicate
multiplicatio n. In Java, parentheses may indicate precedence, as in y * (y+1), where y+1 wo uld be calculated
first and the result multiplied by y. Also , keep in mind that Java uses parentheses in metho ds as well.

Change the Calculatio n class as sho wn belo w:


CODE TO EDIT: Calculatio n

// calculate area of rectangle


import java.awt.*;
import java.applet.Applet;

public class Calculation extends Applet {


public void paint(Graphics g) {
int length, width, area; //declarations

length= 20; // assignments


width = 10;
area = length(width);
g.drawString("Area is " + area, 100, 100);
// display the answer
}
}

The metho d le ngt h(int ) is undefined fo r the type Calculat io n. Java sees parentheses ( ) after the wo rd
le ngt h. The co mpiler kno ws o nly that which is allo wed. Because the o nly allo wed syntax that uses
parentheses ( ) are Metho ds and decisio n co mpariso ns, Java thinks le ngt h(widt h) is a Metho d call. Java
kno ws that width is an int, so it interprets the line area = length(width) as a call to a Metho d named
length, with an int parameter named width. But there is no such metho d, so Java tells yo u that.

Change the line are a = le ngt h * widt h; to are a = le ngt h x widt h;

Hmm, we've go t lo ts o f erro r messages. The mo st pressing erro r message is x canno t be re so lve d. Java
thinks x is a variable name rather than yo ur intended multiplicatio n o perato r.

Change the line o ut to :

are a = 6 widt h;

There's an erro r marker o n the right and red zigzags under width:

Synt ax e rro r o n t o ke n " widt h" , de le t e t his t o ke n

Yo u can see right away that we wo n't be using statements like this to indicate multiplicatio n. Change the line
back to are a = le ngt h * widt h; again and Save the Calculatio n class.

I'm co nfident that yo u no w kno w ho w to use the divisio n (/), additio n (+), and subtractio n (-) o perato rs. We'll
go o ver the o rder in which they are perfo rmed in the next lesso n.

Defaults
So metimes when yo u're defining a class's Fields (IVs and CVs), yo u kno w what the variable's value is go ing
to be befo re anyo ne uses the class. Usually this is because that particular variable's initial value is always the
same. It is o ften called the de f ault value . When the value is kno wn, it is usually specified at the time the
variable is declared. Here, the variable pi is being given a default f lo at value o f 3.14 f :

f lo at pi = 3.14 f ;

Actually, tho ugh, the cho ice o f the math co nstant pi is no t an alto gether great example fo r us to use to define
default variables because it already is a default Class Variable in the Class Mat h, lo cated in the java.lang
package.

Go to the java.lang package and lo o k at the Field Summary o f the Math class.

The Math class gives PI a default value, and also makes it a co nst ant . We discussed co nst ant s in Java in
the first co urse in the series, but let's discuss them a bit mo re no w. Java defines co nstants by using the
m o dif ie rs o f public st at ic f inal:
public: anyo ne can access it.
st at ic: they can access it thro ugh the class name.
f inal: it canno t be changed.

Because it's a Class Variable , it can be accessed thro ugh the Mat h Class; that is, we can access it by saying
Mat h.PI. Because it's public, we can access it fro m any class. Because it's in java.lang, we do n't need to
import anything in o rder to use it.

Let's see the Math class in actio n! Edit the Calculatio n class as sho wn in blue :

CODE TO EDIT: Calculatio n


// calculate area of circle
import java.awt.*;
import java.applet.Applet;

public class Calculation extends Applet {


// make room for display
public void start(){
resize(300,200);
}

public void paint(Graphics g) {


int radius; //declarations
double area;

radius = 50; // assignments


area = Math.PI * Math.pow(radius,2);

g.drawOval(10,10,radius, radius);
g.drawString("My circle's area is " + area, 10, 100);
}
}

Save and Run it.

Also , lo o k at the po w(do uble a, do uble b) metho d o f the Math Class; check o ut o ur call o f Math.po w(radius,2)
and see what it do es.

If yo u do no t specify values in the definitio n o f yo ur class fo r yo ur Inst ance and Class Variable s, Java will
give them default values. That is, Fie lds o f a Class (its Instance and Class Variables) have default values o n
instantiatio n:

Dat a T ype De f ault Value (f o r f ie lds)


byte 0
sho rt 0
int 0
lo ng 0L
flo at 0 .0 f
do uble 0 .0 d
char '\u0 0 0 0 '
String (o r any o bject) null
bo o lean false
Lo cal variable s dif f e r f ro m Inst ance and Class Variable s when it co mes to
assigning default values. The co mpiler never assigns a default value to an uninitialized
WARNING lo cal variable. If yo u canno t initialize yo ur lo cal variable when it is declared, be sure to
assign it a value befo re yo u attempt to use it. Accessing an uninitialized lo cal variable will
result in a co mpile-time erro r. (Do n't wo rry, tho ugh; Eclipse will catch it fo r yo u.)

To illustrate this, change the Calculat io n.java class's paint () metho d by co mmenting o ut the lo cal variable
setting fo r radius. We can just co mment it o ut because we kno w we will put it back.

// radius = 5 0 ; // assignm e nt

This leaves radius witho ut a value. Eclipse tells yo u that:

T he lo cal variable radius m ay no t have be e n init ialize d

Yo u can try, but yo u can't run the pro gram co rrectly until yo u give radius a value--yo u get all kinds o f erro rs in
the co nso le and an empty Applet.

Unco mment the lo cal variable setting and Save the class. I ho pe yo u appreciate ho w Eclipse watches o ut fo r
yo u!

Added Attractions
Let's try mo re expressio ns using o ur Test.java class again.

Increment Statements
Pro grammers like sho rtcuts. Here are a few examples o f ways to increment a variable by 1.

Edit the m ain () metho d as sho wn belo w:

CODE TO EDIT: Test


public class Test {
public static void main(String args[])
{
int n = 10;
System.out.println("After declaring and setting to 10, n is " + n);

n = n + 1;
System.out.println("After n = n + 1, n is " + n);

n++; // an increment expression - if the + is post (after the varia


ble) then it adds after it uses the variable.
System.out.println("After n++, n is " + n);
System.out.println("Seeing n++ WITHIN the println command, Java first US
ES it: " + n++);
System.out.println("After Java uses it in the statement, it then increme
nts");
System.out.println("So without doing anything to n, n is now " + n);

n += 1; // essentially the same as n = n + 1;


System.out.println("After n += 1, n is " + n);
}
}

Save and Run it as an applicatio n.


An incre m e nt e xpre ssio n has the side effect o f incrementing the value o f the variable by 1. That is, it "uses"
the variable and increments it as well.

The lo catio n o f the ++ o perato r matters:

If the o perato r ++ is a suffix (i++), Java use s t he variable f irst and then increments the value.
If the o perato r ++ is a prefix (++i), Java incre m e nt s t he variable value f irst and then uses the
incremented value.

Use the increment expressio n sparingly to reduce co nfusio n (when it's used, it's o ften o nly to increment lo o p
variables). Let's try mo re.

Edit the T e st .java class's m ain () metho d as sho wn.

CODE TO EDIT: Test

public class Test {

public static void main(String[] args) {


int i = 0;
System.out.println("After declaring and setting to 0, i is " + i);
System.out.println();

int j = i++;
System.out.println("After j = i++, i is " + i + " and j is " + j);
System.out.println(" Java USED the i FIRST by setting j to its value of 0"
);
System.out.println(" THEN it incremented i by 1");
System.out.println();

j = ++i; // if the + is pre (before) then it adds before it uses


System.out.println("After j = ++i, i is " + i + " and j is " + j);
System.out.println(" Java incremented the i first by 1, making its value 2
");
System.out.println(" THEN it USED it by giving its value to j");
}
}

Save and Run it as an applicatio n.

In the co nso le, co mpare the o utput and the co de to see ho w the co de wo rks--I kno w yo u're curio us!

So me o ther incrementing sho rtcuts:


i *= 3; is the same as i = i * 3;
i--; is the same as i = i - 1;

Add the fo llo wing lines to see what happens (make sure yo u are between the braces {} in the m ain()
metho d):
CODE TO EDIT: edit main
public static void main(String[] args) {
int i = 1;
System.out.println();
System.out.println("i is " + i);
i +=4;
System.out.println("After i +=4, i is " + i);
System.out.println();
i *=3;
System.out.println("After i *=3, i is " + i);
System.out.println();
i--;
System.out.println("After i--, i is " + i);
System.out.println();
--i;
System.out.println("After --i, i is " + i);
System.out.println();

System.out.println("When first using --i, we get " + --i + " and now that it w
as used i is " + i);
System.out.println("When first using i--, we get " + i-- + " and now that it w
as used i is " + i);

Save and Run it.

Be careful with these; they can get yo u in tro uble if used impro perly.

Yo u're do ing great so far. See yo u in the next lesso n!

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Arithmetic Operations: Precedence and Operand
Types
Lesson Objectives
When yo u co mplete this co urse, yo u will be able to :

use co ncatenatio n and arithmetic o perato rs thro ugh calls to drawString().


use vario us integer o peratio ns in the pro per o rder.

Executing T asks in the Correct Order


Operators and Precedence
Ope rat o rs and Pre ce de nce o f o perato rs are as impo rtant in co mputer languages as they are in
mathematics. In elementary scho o l yo u might have learned precedence using the mnemo nic "My Dear Aunt
Sally," which stands fo r Multiplicatio n, Divisio n, Additio n, Subtractio n. The same o rder o f precedence applies
to co mputers, with a co uple o f additio nal o perato rs; arithmetic o peratio ns are perfo rmed o n co mputers in this
o rder:

1. ( )
2. * / %
3. + -

First , o perato rs in parentheses are executed:

4 + 3 * 2 = 10 , because * has precedence o ver +, BUT


(4 + 3) * 2 = 14, because () has precedence o ver *, so (4 + 3) * 2 = (7) * 2 = 14

t he n, *, /, and % o perato rs are do ne left to right:

4 % 3 * 2 = 2 = (4 % 3) * 2 = 1 * 2 = 2, BUT
4 % (3 * 2) = 4, because () has precedence o ver %, so 4 % (3 * 2) = 4 % 6 = 4

t he n, + and - o perato rs are do ne left to right:

6 + 3 * 4 / 2 - 9,

Let's apply precedence rules to the first expressio n belo w and fo llo w its path:

((6 + ((3 * 4) / 2)) - 9 ) =

((6 + ((12) / 2)) - 9 ) =

((6 + ((6 ))) - 9 ) =

((((12))) - 9 ) = 3

There are actually mo re precedence rules than tho se we've mentio ned so far, but we'll just wo rk with these fo r
no w.

So , can yo u figure o ut the result o f this expressio n?: (6 + 3) * 4 / 2 - 9

Remainder
"%" stands fo r re m ainde r, that is, what is left after yo u divide:
7 % 2 = 1, because 7/2 is 3, with a remainder o f 1
6 % 2 = 0 , because 6 /2 is 3, with a remainder o f 0
16 % 6 = 4, because 16 /6 is 2, with a remainder o f 4
Let's try using % in Java. Open the T e st .java class in o ur t e m p testing pro ject, and edit it as sho wn in blue
belo w:

CODE TO TYPE: testing %


public class Test {
public static void main(String[] args) {
int rem = 2;
int i = 21;
System.out.println("After declaring and setting to 21, i is " + i);
System.out.println();
int j = i % rem;
System.out.println("When i is " + i + " and j is i % " + rem + ", the value
of j is " + j);
--i;
j = i % rem;
System.out.println("When i is " + i + " and j is i % " + rem + ", the value
of j is " + j);
--i;
j = i % rem;
System.out.println("When i is " + i + " and j is i % " + rem + ", the value
of j is " + j);
--i;
j = i % rem;
System.out.println("When i is " + i + " and j is i % " + rem + ", the value
of j is " + j);
--i;
j = i % rem;
System.out.println("When i is " + i + " and j is i % " + rem + ", the value
of j is " + j);
}
}

Save and Run it.

In the Test.java class, change the value o f rem to 3 like this: int re m = 3;.

Save and Run it. When yo u use % 2, the remainders are always 0 o r 1.. When yo u use % 3, the
remainders are 0 , 1, o r 2.

What will the remainders be with % 4? Test it by changing the value o f rem to 4: int re m = 4 ;. Save and Run
it. The result makes perfect sense. If yo u divide by a number, the remainder will be all numbers be t we e n 0
and t he num be r - 1, because a remainder can never be larger than the number by which yo u are dividing.

Suppo se yo u want to calculate: a num be r % n. The po ssible results fo r different values o f n wo uld lo o k like
this:

n Po ssible Re m ainde rs
2 0 ,1
3 0 ,1,2
4 0 ,1,2,3
5 0 ,1,2,3,4
... ...
n 0 ,1,2,3,4, ... , n-1

The % functio n is also called mo dulo , o r m o d.

Precedence
Let's verify o ur precedence examples fro m abo ve, while Java helps yo u remember so me algebra in the
pro cess.

Edit the T e st class as sho wn in blue belo w:

CODE TO TYPE: precedence verificatio n


public class Test {
public static void main(String[] args) {
int x;
x = 4 + 3 * 2;
System.out.println("When x = 4 + 3 * 2 the answer is " + x);
System.out.println();
x = (4 + 3) * 2;
System.out.println("When x = (4 + 3) * 2 the answer is " + x);
System.out.println();
x = 4 % 3 * 2;
System.out.println("When x = 4 % 3 * 2 the answer is " + x);
System.out.println();
x = 4 % (3 * 2);
System.out.println("When x = 4 % (3 * 2) the answer is " + x);
System.out.println();
x = 6 + 3 * 4 / 2 - 9;
System.out.println("When x = 6 + 3 * 4 / 2 - 9 the answer is " + x);
System.out.println();
x = (6 + 3) * 4 / 2 - 9;
System.out.println("When x = (6 + 3) * 4 / 2 - 9 the answer is " + x);
}
}

Save and Run it.

When yo u aren't sure abo ut the effect a particular Java functio n will have o n yo ur pro gram, yo u can
T ip test it in a small pro gram like we did here.

Operand T ypes
When yo u divide integers by integers, yo u ge t integers, no t fractio ns. Java t runcat e s the result o f integer
divisio n so that the results are always integers as well. Fo r example:

1 / 2 is 0 --the answer (0 .5) is t runcat e d to 0 .


16 / 5 is 3--the answer (3.2) is t runcat e d to 3.
11 / 2 is 5--the answer (5.5) is t runcat e d to 5.

Let's test the abo ve examples. Edit the T e st class as sho wn belo w:

CODE TO TYPE: Integer Divisio n


public class Test {
public static void main (String args[]) {
int b = 1;
int c = 2;
float d = b/c;
System.out.println("For integers, " + b + "/" + c + " is " + b/c);
System.out.println("If we make the answer a float, we get " + d);
}
}

Save and Run it.


Zero ? What the heck?

Yo u to ld Java that b was 1 (an int) and c was 2 (an int), and Java thinks yo u mean it. Then, in the first
Syst e m .o ut .print ln, yo u give b/c, which is 1/2, which is 0 .5--since bo th are ints, Java truncates the result to
0.

In the statement f lo at d = b/c;, Java sees that d is declared to be a flo at (decimal number) so Java says to
itself, "Ok, I will leave space fo r a flo at." Then, o n the right side, it sees b/c (that is, b divided by c), so Java
perfo rms that task. Since b is 1 and c is 2, the result is 1/2 and since bo th are integers, Java truncates to 0 .
But since yo u to ld Java to enter the answer in a place that is a f lo at , Java cast s the integer answer to a
flo at. That means it to o k the integer answer and gave it a flo at (decimal) value. But , the integer answer it sees
is 0 , so it gives yo u 0 .0 Java always do es exactly what yo u tell it to do (so lo ng as it can understand yo ur
instructio ns).

Let's experiment in o ur Applet testing class. In the t e m p Pro ject, edit the Calculat io n.java class as sho wn
belo w. Also remo ve the radius = 5 0 ; line.

CODE TO TYPE:
import java.awt.*;
import java.applet.Applet;

public class Calculation extends Applet {

public void paint(Graphics g) {


int diameter = 50;
int radius = 1/2 * diameter;
double area;

area = Math.PI * Math.pow(radius,2);

g.drawOval(10,10,radius, radius);
g.drawString("My circle's area is " + area, 10, 100);
}
}

Save and Run it.

So what happened? Our result is an area o f 0 .0 and no thing is drawn. It seems we made a very co mmo n
mistake. It's lo cated o n this line:

int radius = 1/2 * diam e t e r;

In Java, 1/2 times anyt hing will be 0 , because 1/2 is integer divisio n and 0 .0 times anything is 0 . So in o ur
experiment, no thing is drawn, and we get an area o f 0 .0 . So what do es the fo llo wing yield?:

int half = 20 0 0 0 *(1/2)

We can fix it. There are a co uple o f ways to make it wo rk; here's o ne o f them:

Co mment o ut the line int radius = 1/2 * diam e t e r;, so Java do esn't see it when it tries to run. Everywhere
radius appears in the co de, change it to diam e t e r/2 as sho wn belo w:

CODE TO EDIT:
import java.awt.*;
import java.applet.Applet;

public class Calculation extends Applet {

public void paint(Graphics g) {


int diameter = 50;
// int radius = 1/2 * diameter;
double area;

area = Math.PI * Math.pow(diameter/2,2);

g.drawOval(10,10,diameter/2, diameter/2);
g.drawString("My circle's area is " + area, 10, 100);
}
}

Save and Run it.

Who o pee! It wo rks. That's because we used diam e t e r/2 within the actual parameters fo r Mat h.po w and
g.drawOval.

T ip T he Ro le o f Expre ssio ns: Anywhere yo u can put an integer, yo u can put an integer expressio n.

This means that if I can put an integer so mewhere, I can also put so mething that e valuat e s to an integer. The
same is true fo r o ther types as well. Expressio ns always evaluate to so mething in Java, so to Java, typing in
an expressio n is just like typing the result o f the expressio n in the same space.

T ype Conversion/Casting
Java can tempo rarily convert an integer into a String. This is called cast ing. Java auto matically casts fo r us
when we call metho ds with different parameters fro m tho se specified.

Co nsider the metho d Mat h.po w(). We invo ked it with Math.po w(radius,2) where radius and 2 are int s in o ur
co de earlier:

public st at ic do uble po w(do uble a,do uble b)

It can also can be called with Math.po w(4,2).

The idea here is that no info rmatio n is "added"--that is, if we have the number 2 then it do es no t hurt to make
it 2.0 fo r co mputatio n in the metho d. Tempo rarily using a number with decreased precisio n fo r the purpo se o f
perfo rming the metho d o r o peratio n, then co nverting it to a mo re precise number, do es no t alter the
expressio n's accuracy.

Pro grammers can perfo rm t ype co nve rsio n o r cast ing to o .

When an o perato r manipulates a mixture o f int and f lo at (o r do uble ) values, any integers are tempo rarily
co nverted to f lo at fo r the purpo se o f the calculatio n. Fo r example:

7 / 2.0 => 7.0 / 2.0 => 3.5

In Java, if o ne o f the variables in an expressio n is a decimal (flo at o r do uble), then it perfo rms aut o m at ic
cast ing and makes the who le expressio n a flo at o r do uble.

No w let's change the Calculat io n.java class back to what it was (when it did no t wo rk), but let's suppo se
that we need mo re precise variables, so we're go ing to set them to do uble s:

CODE TO EDIT: Calculatio n

import java.awt.*;
import java.applet.Applet;

public class Calculation extends Applet {

public void paint(Graphics g) {


double diameter = 50;
double radius = 1/2 * diameter;
double area;

area = Math.PI * Math.pow(radius,2);

g.drawOval(10, 10, radius, radius);


g.drawString("My circle's area is " + area, 10, 100);
}
}

Let's fix the first erro r we see at o ur call to drawOval. Our call to drawOval is no t happy because o ur act ual
param e t e rs do no t match o ur f o rm al param e t e rs in the actual call: g.drawOval(10 , 10 , radius, radius);
fo rmal params: drawOval(int x, int y, int width, int height).

x and y are set to 10 , and 10 is an int, so that's OK; width and height are set to the value o f radius--but radius
is a do uble , and the metho d specificatio n states int .

No pro blem. We'll do o ur o wn "fo rced" co nversio n. We'll tell Java that, just fo r no w, we want it to lo o k at
radius as if it were an int:
CODE TO EDIT: Calculatio n

import java.awt.*;
import java.applet.Applet;

public class Calculation extends Applet {

public void paint(Graphics g) {


double diameter = 50;
double radius = 1/2 * diameter;
double area;

area = Math.PI * Math.pow(radius,2);

g.drawOval(10, 10, (int)radius, (int)radius);


g.drawString("My circle's area is " + area, 10, 100);
}
}

Save and Run it. Rat s. We go t all zero es. It lo o ks like we still have the 1/2 giving us the result o f 0 .

Ano ther way to "fo rce" a cast is to take a specific number and change it to the desired type. Fo r example,
make the 2 in 1/2 a 2.0 (o r the 1 a 1.0 ). If Java sees a decimal in the expressio n, it will perfo rm the who le
o peratio n as a decimal.

Change the metho d as sho wn in blue :

CODE TO EDIT: Calculatio n

import java.awt.*;
import java.applet.Applet;

public class Calculation extends Applet {

public void paint(Graphics g) {


double diameter = 50;
double radius = 1/2.0 * diameter;
double area;

area = Math.PI * Math.pow(radius,2);

g.drawOval(10, 10, (int)radius, (int)radius);


g.drawString("My circle's area is " + area, 10, 100);
}
}

Save and Run it. Sweet!

There are rules go verning which types can be co nverted to which o ther types. The general idea is to prevent
any lo ss o f accuracy. Fo r example, yo u wo uldn't take an int (which can have 32 bits in memo ry) and cast it
"do wn" to a byt e (which has o nly 8 bits in memo ry). If we did cast an int to a byte, all but the lo west bits o f
data wo uld be discarded in the co nversio n. By dro pping the higher bits o f data, yo u might lo se valuable
info rmatio n and the precisio n o f the o riginal value wo uld be diminished.

WARNING Larger types canno t be cast to smaller types witho ut po tential info rmatio n lo ss.

Fo r mo re info rmatio n, see Legal Co nversio ns.


Edit the T e st .java class as sho wn belo w:

CODE TO EDIT: Test


public class Test {

public static void main (String args[]) {


System.out.println("((float)(10+11)/2) is " + ((float)(10+11)/2));
System.out.println();
System.out.println("(float)(10+11)/2 is " + (float)(10+11)/2);
System.out.println();
System.out.println("((float)(10+11/2)) is " + ((float)(10+11/2)));
System.out.println();
System.out.println("(float)(10+11/2) is " + (float)(10+11/2));
System.out.println();
System.out.println("(float)10+11/2 is " + (float)10+11/2);
}
}

Save and Run it. Co mpare the co de to the results to see if it is what yo u expected:

In the first two expressio ns we can see that the o utermo st parentheses are no t necessary. But co mparing the
seco nd and third expressio ns, we see that the parentheses indeed do make a difference there:
(flo at)(10 +11)/2 makes 21 a flo at and then divides 21.0 by 2 and gets 10 .5--but (flo at)(10 +11/2) do es all the int
arithmetic (no te precedence, so parentheses first and in the parentheses, divisio n first), gets a result o f 10 +5
o r 15, and t he n makes it a flo at--15.0 .

Since the parameter is a String fo r the drawString metho d, Java sees the plus sign + as co ncatenatio n. Thus,
it casts the integers as Strings to co ncatenate them into o ne String fo r the parameter.

(flo at)10 +11/2 first makes 10 a flo at (fo llo wing parentheses and left-to -right precedence), and so we get 10 .0 ,
then it do es the integer arithmetic fo r 11/2 and gets 5; T he n, it co ncat e nat e s the two numbers (10 .0 and 5)
to get 10 .0 5, because the plus sign + is in a place where the parameter is a St ring.

The fo llo wing co de results in o nly 3 po ssibilities: 0 , 1 o r 2:

rint = (int )(Mat h.rando m () * 3);

Lo o k up java.lang.Mat h and its metho d rando m () in the . Using info rmatio n yo u find there, try to figure
o ut why the o nly po ssible results in this case are 0 , 1 o r 2.
Mat h.rando m ( ) returns a do uble value with a po sitive sign, greater than o r equal to 0 .0 and less than 1.0 . If
we multiply this by an integer (n), we get a number greater than o r equal to 0 .0 and le ss t han n. So if the
number is 3, we get a number greater than o r equal to 0 .0 and le ss t han 3.0 (fo r example 2.9 9 9 9 9 9 ). No w,
we cast that result to an (int) and ultimately we get 0 , 1, o r 2, because the cast will truncate the number and
leave us with o nly tho se three po ssibilities.

If we had multiplied the rando m number by 16 , we wo uld get a number fro m 0 to 15. Ho w wo uld we change it
to get a number fro m 1 to 16 ?

Easy: rint = (int )(Mat h.rando m () * 16 ) + 1 ;

More on String Concatenation


We learned earlier in the lesso n that, when the parameter is a St ring, the plus sign + signifies co ncatenatio n.
The same happens in the fo llo wing line:

g.drawSt ring(" Are a is " + are a, 10 0 , 10 0 );

but Java first co nverts the area number into a String, then co ncatenates it.

Co nsider the differences between these lines:

g.drawSt ring(" Answe r is " + 1 + 2, 10 0 , 120 );

and

g.drawSt ring(" Answe r is " +(1+2), 10 0 , 130 );

Put them into yo ur Calculatio n.java applet and run it.

Formats
Here's an example that demo nstrates a way to co ntro l the number o f decimal places yo ur numbers display:

Edit the Calculat io n.java class to make the circle again. Use the co de belo w so that it sho ws o nly 2 decimal
places:

CODE TO TYPE: java.text.NumberFo rmat


import java.awt.*;
import java.applet.Applet;
import java.text.*;

public class Calculation extends Applet {

public void paint(Graphics g) {


NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);

double diameter = 52;


double radius = 1/2.0 * diameter;
double area;

area = Math.PI * Math.pow(radius,2);

g.drawOval(10,10, (int)radius, (int)radius);


g.drawString("My circle's area is " + nf.format(area), 10, 100);
}
}

Save and Run it.

The class Num be rFo rm at in the java.t e xt package also puts co mmas in the number.
Ano ther fo rmatting class is java.t e xt .De cim alFo rm at . Feel free to go to the API and check it o ut!

Fo r reference, here is a link to Oracle's o nline tuto rial and the Java Language Specificatio n bo o k chapter o n Types, Values and
Variables.

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Decisions: Logic
Lesson Objectives
When yo u co mplete this co urse, yo u will be able to :

evaluate each dice ro ll and use lo gic statements and flo w co ntro l pro perly.
use lo gic o perato rs and expressio ns.

In the Java 1 co urse we learned abo ut if st at e m e nt s, which use bo o leans (true o r false) to make decisio ns. In this lesso n,
we'll dig a little deeper and use lo gic to decide when expressio ns are true o r false.

Logic: and, or, not


Java pro vides these three Lo gic Operato rs:

&& - and
|| - or
! - no t

While o ther languages may allo w results o ther than bo o le an in co mpariso ns, Java only allo ws the result o f t rue o r
f alse . The o nly allo wable data type that can result fro m the co nditio n o f an if statement is a bo o le an, so all
co mpariso ns in Java must result in either t rue o r f alse .

In the figure belo w, suppo se that b1 and b2 are statements. The truth values o f the lo gic expressio ns using and, o r,
and no t are as sho wn in the table belo w:

To read this table, select a ro w and read the values. Fo r instance, if b1 is false and b2 is true, then b1 || b2 is true.

Here's a demo applet we made fo r yo u to use fo r practice.

It's interesting to co mpare && and || to t rue and f alse , and even mo re so to use co mplex expressio ns that e valuat e
to t rue and f alse . These co nditio nal statements are a tad mo re co mplicated to wo rk with, so let's revisit the co ncept
o f pre ce de nce and make sure we have a clear plan fo r what to do when we enco unter Value 1 || Value 1 && Value 3.
Belo w is the o rder in which o perato rs are perfo rmed. If o perato rs are o n the same line in the chart belo w, then the
co mpiler simply o perates left to right.
Mo re precedence rules exist, but we're go ing to co ver just the mo st co mmo nly used o nes fo r no w.

Examples Using Logic


OBSERVE: Getting an A

if (score > 90 && score < 93)


grade = "A-";

Co nditio n o pe rat o rs o ther than ! (no t ) are binary, that is, they have two o perands (so mething) o n either side o f the
o perato r:

so mething is < so mething else


so mething is == to so mething else
so mething is && o r || with so mething else

In the example abo ve, we see that the variable sco re must be bo t h > 9 0 and < 9 3. Thus, depending o n the t ype o f
sco re , the values that yield t rue wo uld be 9 1 and 9 2 if sco re is a byt e , sho rt , int , lo ng, and anything be t we e n 9 0
and 9 3 (no t including 9 0 o r 9 3) if sco re is a f lo at o r do uble .

Let's test this with a simple main in an applicatio n. Open the T e st .java class in yo ur t e m p pro ject fo lder. Edit it to
ho ld the co de sho wn belo w in blue .

CODE TO TYPE: Getting an A

public class Test {


public static void main (String args[]) {
int score = 96;
String grade = "unknown";

if (score > 90 && score < 93)


grade = "A-";
System.out.println("Given the input, your grade is " + grade);
}
}

Save and Run it.

No w, change the sco re fro m 9 6 to 9 3:


CODE TO TYPE: Getting an A

public class Test {


public static void main (String args[]) {
int score = 93;
String grade = "unknown";

if (score > 90 && score < 93)


grade = "A-";
System.out.println("Given the input, your grade is " + grade);
}
}

Save and Run it.

No w, change the sco re fro m 9 3 to 9 2 and run it again. Were tho se the results yo u expected?

Let's try wo rking with the same semantics (meaning), but using the syntax we no rmally see in mathematics. Change
the main as sho wn belo w:

CODE TO TYPE: Test


public class Test {
public static void main (String args[]) {
int score = 92;
String grade = "unknown";

if (90 < score < 93)


grade = "A-";
System.out.println("Given the input, your grade is " + grade);
}
}

Mo ve yo ur curso r o ver the erro r; yo u'll see this:

We go t that particular erro r message as a result o f pre ce de nce rules. Java evaluates lo gic expressio ns fro m left to
right. Co nsider the expressio n: (9 0 < sco re < 9 3); with sco re = 9 2, which beco mes (9 0 < 9 2 < 9 3). It evaluates 9 0 < 9 2
and gets the result t rue . Java then sees: t rue < 9 3, which has no meaning.

The erro r message "T he o pe rat o r < is unde f ine d f o r t he argum e nt t ype (s) bo o le an, int " makes sense no w.
We were trying to co mpare a bo o lean with an integer using "<".
Because lo gic o perato rs are binary, expressio ns such as (a < b < c) must be expressed this way: (a < b
Note && b < c)

Let's ro ll the dice and get mo re experience with lo gic.

Create a java2_Le sso n7 pro je ct . In it, create a new Applet class called Craps. Enter the co de as sho wn belo w:

CODE TO TYPE: Craps

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class Craps extends Applet implements ActionListener {


private Button die1, die2;
private int value1 = 0, value2 = 0;

public void init() {


die1 = new Button("Die1");
add(die1);
die1.addActionListener(this);
die2 = new Button("Die2");
add(die2);
die2.addActionListener(this);
}

public void paint(Graphics g) {


int total;
total = value1 + value2;
g.drawString("Die 1 is " + value1 + " Die 2 is " + value2, 40, 50);
g.drawString("Total is " + total, 40, 65);
if (total==7)
g.drawString ("You won!" , 50, 90);
}

public void actionPerformed(ActionEvent event) {


if (event.getActionCommand().toString() == "Die1")
value1 = (int)(Math.random() * 6) + 1;
else
value2 = (int)(Math.random() * 6) + 1;
repaint();
}
}

Save and Run it (click o n the different die butto ns to "ro ll"). Observe the co de as yo u run it to see the different uses
o f if :

1. The act io nPe rf o rm e d() metho d is used to determine which but t o n was clicked (Die1 e lse Die2).
2. The paint () metho d is used to determine if yo u hit the lucky number: (t o t al==7 ).

Add a line at the end o f the paint () metho d as sho wn belo w:


CODE TO EDIT: Craps
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class Craps extends Applet implements ActionListener {


private Button die1, die2;
private int value1 = 0, value2 = 0;

public void init() {


die1 = new Button("Die1");
add(die1);
die1.addActionListener(this);
die2 = new Button("Die2");
add(die2);
die2.addActionListener(this);
}

public void paint(Graphics g) {


int total;
total = value1 + value2;
g.drawString("Die 1 is " + value1 + " Die 2 is " + value2, 40, 50);
g.drawString("Total is " + total, 40, 65);
if (total==7)
g.drawString ("You won!" , 50, 90);
if (die1 == die2)
g.drawString ("You won again!" , 50, 100);
}

public void actionPerformed(ActionEvent event) {


if (event.getActionCommand().toString() == "Die1")
value1 = (int)(Math.random() * 6) + 1;
else
value2 = (int)(Math.random() * 6) + 1;
repaint();
}
}

Save and Run it. Keep clicking o n o ne butto n until it has the same value as the o ther (yo u can never ro ll a 0 , so
yo u have to ro ll bo th at least o nce).

Ho w many times will yo u have to ro ll until yo u see the You have won again! message? Are there any pro babilities
experts o ut there? Unfo rtunately, expertise in pro babilities wo n't help us here, and I'll lay do wn a millio n do llars that
yo u will ne ve r see the You have won again! message with the co de abo ve. Why, yo u ask? Because we've made an
erro r--in o ur reaso ning. die 1 can ne ve r be == die 2, because t he y are dif f e re nt o bje ct s!

Let's fix that pro blem. Instead o f inst ance s o n either side o f the equals signs ==, let's get o ur pro gram to use the
value s o f tho se instances. Edit yo ur co de as sho wn in blue belo w:
CODE TO EDIT: Craps
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class Craps extends Applet implements ActionListener {


private Button die1, die2;
private int value1 = 0, value2 = 0;

public void init() {


die1 = new Button("Die1");
add(die1);
die1.addActionListener(this);
die2 = new Button("Die2");
add(die2);
die2.addActionListener(this);
}

public void paint(Graphics g) {


int total;
total = value1 + value2;
g.drawString("Die 1 is " + value1 + " Die 2 is " + value2, 40, 50);
g.drawString("Total is " + total, 40, 65);
if (total==7)
g.drawString ("You won!" , 50, 90);
if (value1 == value2)
g.drawString ("You won again!", 50, 100);
}

public void actionPerformed(ActionEvent event) {


if (event.getActionCommand().toString() == "Die1")
value1 = (int)(Math.random() * 6) + 1;
else
value2 = (int)(Math.random() * 6) + 1;
repaint();
}
}

Save and Run it. Hmm, it lo o ks like we'll need an additio nal if in case bo th values are 0 o r an additio nal lo gic
o perato r such as:

if ((value 1 == value 2) && (value 1 !=0 ))

Change the paint ( ) metho d as sho wn belo w:


CODE TO EDIT: Craps
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class Craps extends Applet implements ActionListener {


private Button die1, die2;
private int value1 = 0, value2 = 0;

public void init() {


die1 = new Button("Die1");
add(die1);
die1.addActionListener(this);
die2 = new Button("Die2");
add(die2);
die2.addActionListener(this);
}

public void paint(Graphics g) {


int total;
total = value1 + value2;
g.drawString("Die 1 is " + value1 + " Die 2 is " + value2, 40, 50);
g.drawString("Total is " + total, 40, 65);
if (total==7)
g.drawString ("You won!" , 50, 90);
if ((value1 == value2) && (value1 !=0))
g.drawString ("You won again!" , 50, 100);
}

public void actionPerformed(ActionEvent event) {


if (event.getActionCommand().toString() == "Die1")
value1 = (int)(Math.random() * 6) + 1;
else
value2 = (int)(Math.random() * 6) + 1;
repaint();
}
}

Save and Run it. Keep clicking o n o ne butto n until it has the same value as the o ther. Much better!

&& and || are co nsidered Lazy o pe rat o rs because they do as little wo rk as po ssible. In an &&, bo th
o perato rs must be t rue fo r the expressio n to be t rue , if the first is f alse , Java will no t even bo ther to lo o k
T ip at the seco nd. In an ||, o nly o ne o perato r needs to be t rue fo r the expressio n to be t rue , so if the first is
t rue , Java will no t even lo o k at the o ther. So , if we put the expressio n mo st likely to be f alse first in && and
the expressio n mo st likely to be t rue first in ||, we might save pro cessing time.

Let's try ano ther example. Add the lines in blue to the end o f the paint ( ) metho d as sho wn:
CODE TO TYPE: Craps co de
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class Craps extends Applet implements ActionListener {


private Button die1, die2;
private int value1 = 0, value2 = 0;

public void init() {


die1 = new Button("Die1");
add(die1);
die1.addActionListener(this);
die2 = new Button("Die2");
add(die2);
die2.addActionListener(this);
}

public void paint(Graphics g) {


int total;
total = value1 + value2;
g.drawString("Die 1 is " + value1 + " Die 2 is " + value2, 40, 50);
g.drawString("Total is " + total, 40, 65);
if (total==7)
g.drawString ("You won!" , 50, 90);
if ((value1 == value2) && (value1 !=0))
g.drawString ("You won again!" , 50, 100);
if ((total=2) || (total=7))
g.drawString ("You won in yet another way!" , 50, 110);
}

public void actionPerformed(ActionEvent event) {


if (event.getActionCommand().toString() == "Die1")
value1 = (int)(Math.random() * 6) + 1;
else
value2 = (int)(Math.random() * 6) + 1;
repaint();
}
}

Save and Run it. This time it do esn't co mpile:

Check o ut either side o f the ||. On the left, we have t o t al = 2. This is no t a co mpariso n statement that will result in t rue
o r f alse . Because we used a single equals sign= instead o f two o f them ==, it's an assignm e nt st at e m e nt , so it
sho uldn't be inside o f the if co nditio n. But actually, we want Java to co mpare rather than to assign.

We can fix that. Change the = o n bo th sides to == as sho wn belo w:


CODE TO TYPE: Craps

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class Craps extends Applet implements ActionListener {


private Button die1, die2;
private int value1 = 0, value2 = 0;

public void init() {


die1 = new Button("Die1");
add(die1);
die1.addActionListener(this);
die2 = new Button("Die2");
add(die2);
die2.addActionListener(this);
}

public void paint(Graphics g) {


int total;
total = value1+value2;
g.drawString("Die 1 is " + value1 + " Die 2 is " + value2, 40, 50);
g.drawString("Total is " + total, 40, 65);
if (total==7)
g.drawString ("You won!" , 50, 90);
if ((value1 == value2) && (value1 !=0))
g.drawString ("You won again!" , 50, 100);
if ((total==2) || (total==7))
g.drawString ("You won in yet another way!" , 50, 110);
}

public void actionPerformed(ActionEvent event) {


if (event.getActionCommand().toString() == "Die1")
value1= (int)(Math.random() * 6) + 1;
else
value2= (int)(Math.random() * 6) + 1;
repaint();
}
}

Save and Run it.

We've sure go t a lo t o f parentheses in o ur co de, but that's o kay. Even tho ugh they're no t all necessary, they help us
make sense o f the co de when we read it, so we may as well keep them there.

T ip If precedence standards already dictate that a co mmand will be executed, parentheses are no t necessary.

Go into the edito r and experiment; take o ut so me o f sets o f parentheses to see what happens.

Yo ur assignment fo r this lesso n will be to ro ll the dice and then define the vario us co mbinatio ns o f dice ro lls as they
are used in the craps game. Keep this in mind as we go thro ugh the lesso n. Do yo u kno w what it means to ro ll "snake
eyes" (1 and 1)? In craps, if yo u ro ll a 1 and 1 o n yo ur first ro ll, yo u've "crapped o ut" (yo u lo se). Can yo u tell so meo ne
using o ur Java pro gram if they have crapped o ut?
Fo r mo re info rmatio n o n Craps, here's a Wikipedia article . Fo r an enhanced versio n o f o ur craps game, with so und
and images, click here .

Nested Ifs Versus Logic Statements


Nested if s are nice when yo u want to reduce the number o f if statments that Java has to go thro ugh. In o ther wo rds,
Java sto ps go ing thro ugh the nested if s as so o n as it finds a true statement. Let's try an example.

Mo st peo ple are familiar with this grading scale:

A: 10 0 -9 0
B: 8 9 -8 0
C: 79 -70
D: 6 9 -6 0
F: belo w 6 0

We have two ways to implement such a grade scale. Let's make a quick little main metho d to test them. Create a new
class in java2_Lesso n7 (o r java2_Lesso n7/src) called Testing. Type the co de in blue belo w:

CODE TO TYPE: Testing.java

import java.util.Scanner;

public class Testing {

public static void main(String[] args) {

int score;
String grade;
Scanner scan = new Scanner(System.in);

System.out.print("Enter a grade to test: ");


score = scan.nextInt();

if (score >= 90)


grade = "A";
else if (score >= 80)
grade = "B";
else if (score >= 70)
grade = "C";
else if (score >= 60)
grade = "D";
else
grade = "F";
System.out.println("For a score of " + score + ", the grade is " + grade);
}
}

Save and Run it. The class will pro mpt yo u fo r a sco re in the co nso le to the left:
Click in t he co nso le , and then e nt e r a number when it pro mpts. (Fo r this class, yo u'll need to Run As again to test
a different number.)

So metimes co de is easier to read if yo u use lo gic instead o f lo ts o f nested if s. Let's try an example using lo gic.
Replace the nested if in T e st ing.java as sho wn belo w:

CODE TO EDIT: Testing.java

import java.util.Scanner;

public class Testing {

public static void main(String[] args) {

int score;
String grade;
Scanner scan = new Scanner(System.in);

System.out.print("Enter a grade to test: ");


score = scan.nextInt();

if (score < 60) grade = "F";


if (score >= 60 && score < 70) grade = "D";
if (score >= 70 && score < 80) grade = "C";
if (score >= 80 && score < 90) grade = "B";
if (score >= 90) grade = "A";
System.out.println("For a score of " + score + ", the grade is " + grade);
}
}

Save and Run it.

Who o ps. We go t an erro r:


Why didn't we get this same erro r when we used the nested if instead o f lo gic? Because o ur nested if versio n ended
in an e lse that initialized the variable. When a pro gram ends in e lse , even when a sco re isn't defined, we still get a
value. In this case, after all the e lse statements were exhausted, the default grade o f F was assigned.

Add the blue co de belo w:

CODE TO EDIT: Testing.java

import java.util.Scanner;

public class Testing {

public static void main(String[] args) {

int score;
String grade;
Scanner scan = new Scanner(System.in);

System.out.print("Enter a grade to test: ");


score = scan.nextInt();

if (score < 60) grade = "F"; else grade = "unknown";


if (score >= 60 && score < 70) grade = "D";
if (score >= 70 && score < 80) grade = "C";
if (score >= 80 && score < 90) grade = "B";
if (score >= 90) grade = "A";
System.out.println("For a score of " + score + ", the grade is " + grade);
}
}

Save and run it.

No w o ur pro gram wo rks. We are assured o f a value fo r grade ; if the sco re is kno wn, Java o verwrites the "unkno wn"
string. Altho ugh this metho d wo rks, it isn't preferred. Java has to check to o many things even tho ugh it might already
have the answer it needs. This can slo w the co mputer do wn. We try to avo id making the co mputer do mo re wo rk than
is necessary.

There are a lo t o f ways to use if statements. The statement that gets executed when the if 's co nditio nal is true, can be
ano ther if co nditio n. Here's ano ther way yo u might write yo ur grading pro gram;
OBSERVE: If co nditio n as statement
if (score < 80)
if (score < 60)
grade = "F";
else if (score < 70)
grade = "D";
else
grade = "C";
else if (score <= 100)
if (score < 90)
grade = "B";
else
grade = "A";

Logic Statements Versus If Statements


Co nsider a metho d that determines whether a year is a leap year. The Grego rian calendar stipulates that a year is a
leap year if it is divisible by 4, unless it is also divisible by 10 0 . If it is divisible by 10 0 then it is a leap year if and o nly if it
is also divisible by 40 0 . Fo r example, 19 0 0 was no t a leap year, but 20 0 0 was.

Here is the algo rithm fo r this using just o ne lo gic statement:

Leap Year Lo gic


(year % 100 != 0 && year % 4 == 0) || (year % 100 == 0 && year % 400 == 0)

Let's use it!

Edit the T e st ing class's m ain metho d as fo llo ws:

CODE TO TYPE: leap lo gic


import java.util.Scanner;

public class Testing {

public static void main(String[] args) {

int year;
boolean leap;
Scanner scan = new Scanner(System.in);

System.out.print("Enter a year to test: ");


year = scan.nextInt();

leap = (year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 ==
0);

System.out.println("It is " + leap + " that " + year + " is a leap year.");
}
}

Save and Run it. Try running it with different values fo r the year to test the expressio n.

The co de wo rks, but it's no t easy fo r o thers to read. Let's break up the &&s and ||s to get an algo rithm that's easier to
read. Peo ple generally kno w that a leap year is divisable by 4, so let's begin o ur algo rithm there:

1. Divide the year by 4. The remainder sho uld be 0 (year % 4 == 0 ).


2. If it is divisible by 4, then see if it is divisible by 10 0 .
3. If it is divisible by 10 0 , then see if it is divisible by 40 0 --in which case it is a leap year.
4. If it is no t divisible by 10 0 , but it was divisible by 4, it is a leap year.
5. If it was no t even divisible by 4 at all, it was no t a leap year.

Let's make this into an algo rithm using if s. Edit the main metho d to use if s rather than the single lo gic statement, like
this:

CODE TO EDIT: Testing


import java.util.Scanner;

public class Testing {

public static void main(String[] args) {

int year;
boolean leap;
Scanner scan = new Scanner(System.in);

System.out.print("Enter a year to test: ");


year = scan.nextInt();

if (year % 4 == 0)
if (year % 100 == 0) // if divisible by 100 must be divisible by 400
leap = (year % 400 == 0); // i.e., if year is divisible by 400 then th
is is true
else
leap = true;
else
leap = false;

System.out.println("It is " + leap + " that " + year + " is a leap year.");
}
}

Save and Run it. Try it a few mo re times to test the expressio n, using different values fo r the year. Here's the if 's
flo wchart:
Our co de co uld have lo o ked like this:

A very tidy alternative

if (year % 4 == 0)
if (year % 100 == 0)
if (year % 400 == 0)
leap = true;
else

leap = false;
else
leap = true;
else

leap = false;

Can yo u match the if s with the pro per e lse s?

We even have Duke leaping!

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Decisions: Dangling and Switching
Lesson Objectives
When yo u co mplete this co urse, yo u will be able to :

use nested if o r case statements to return different results based o n user input.
use if, else, and switch statements seperately and in co njunctio n with o ne ano ther when appro priate.

Matching Who Gets What


Dangling Elses
In the co de fro m the previo us lesso n, we initally used two if s and two matching e lse s Later we used three
if s and three matching e lse s. But If s do no t require e lse s. It's po ssible to have nested if s witho ut having the
same number o f e lse s. Such a situatio n is referred to as a dangling e lse . When a dangling e lse o ccurs
and the brackets are no t used, running that co de may give the wro ng results.

Create a new java2_Le sso n8 pro ject with a new T e st ing class applicatio n in it. Enter the co de as sho wn
belo w:

CODE TO TYPE: dangling else

public class Testing {

public static void main(String[] args) {

int score = 85;


String grade = "?";

if (score < 80)


if (score < 70)
grade = "C";
else
grade = "B";

System.out.println("For a score of " + score + ", the grade is " + grade


);
}
}

Save and Run it.

Wait a minute. This sco re sho uld result in a different grade. We want o ur pro gram to give a B if the sco re is
greater than 8 0 , but Java is sho wing it did no t execute the e lse co nditio n. The e lse was executed with the
second if , and Java did no t give a B fo r sco re > 80 . Even tho ugh Java do esn't reco gnize indentatio n, we can
still lo o k at the way the o ur co de is indented to get a clear idea o f what happened:

The e lse is attached to the indented if and is no t applied to the first if . So Java has no thing to do if the sco re
is less than 8 0 .

T ip An e lse will always match with the ne are st if , unless the use o f brackets specifies o therwise.

Indentatio n do es no t matter to Java. Braces ({} ) and semico lo ns (;) tell Java where things start and sto p.

Change the co de as sho wn belo w in blue:

CODE TO TYPE: dangling else

public class Testing {

public static void main(String[] args) {

int score = 85;


String grade = "?";

if (score < 80)


{ if (score < 70)
grade = "C"; }
else
grade = "B";

System.out.println("For a score of " + score + ", the grade is " + grade


);
}
}

Save and Run it. That's much better.

See if yo u can determine which if statement co rrespo nds to the e lse statement in the fo llo wing co de:

Which IF do es ELSE belo ng to ?

if (condition1)
if (condition2)
statement1
else
statement2
In the co de abo ve, the e lse is asso ciated with the seco nd if , despite its po sitio n directly belo w the first o ne.
The flo w chart belo w gives yo u a mo re detailed lo o k:

To asso ciate the e lse with the first if , add braces aro und all the statements co ntained between the first if and
the e lse .

Using Braces to Specify Flo w

if (condition1)
{
if (condition2)
statement1
}
else
statement2

Object equivalence

Ano ther co mmo n erro r no vice pro grammers make when using co nditio nal statements is the use o f == with
St rings. Let's edit the T e st ing class again to see ho w that happens:

CODE TO EDIT: Testing


public class Testing {

public static void main(String[] args) {

String stringLiteral = "are they the same";


String stringObject = new String ("are they the same");
System.out.println("stringLiteral == stringObject? " + (stringLiteral == st
ringObject));
}
}

The bo o lean expressio n (st ringLit e ral == st ringObje ct ) is embedded in the Syst e m .o ut .print ln. If yo u
o nly need to use a value o nce and do n't need to save it in memo ry, this is a co mmo n technique.
In Java, anywhere yo u can put a variable o f a certain type, yo u can put an e xpre ssio n that
T ip results in that type (except o n the left side o f an equal sign, because that is a memo ry lo cat io n).

Save and Run it.

Java tells us they are no t the same because == is o bje ct e quivale nce and the two Obje ct s st ringLit e ral
and st ringObje ct are no t the same o bjects. They do no t access the sam e place in m e m o ry.

Add the line o f co de sho wn belo w in blue :

CODE TO EDIT:
public class Testing {

public static void main(String[] args) {


String stringLiteral = "are they the same";
String stringObject = new String ("are they the same");
System.out.println("stringLiteral == stringObject? " + (stringLiteral =
= stringObject));
System.out.println("The sequence of characters is the same is " + strin
gLiteral.equals(stringObject));
}
}

Save and Run it.

Go to the java.lang package and lo o k up the St ring class. Check o ut the metho ds there--we discussed
them in the first co urse, but they're really impo rtant in Java, so it's go o d to refresh yo ur memo ry.

T he Instance of Operator
Befo re we leave this discussio n o f if s, and switch to swit ch, let's lo o k at ano ther handy o perato r that Java
pro vides.

In Java so metimes a metho d receives a co llectio n o f o bjects. Yo u kno w the o bjects are an instance o f a
Class, but yo u do n't necessarily kno w which Class. Fo r example, in event handling, bo th T e xt Fie lds and
But t o ns use the Act io nList e ne r interface. When an Act io nEve nt o ccurs, ho w do es the listener kno w
which o ne triggered the event?

Let's edit o ur Driving class in the Driving.java file. We used this example in the Java 1 co urse, but here it is
again, just in case:

Click he re t o do wnlo ad T he Driving Pro je ct

Open Driving.java to allo w a user to re se t t he age t o 0 with the click o f a Butto n. Add the co de sho wn in
blue belo w:

CODE TO EDIT: Driving.java


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class Driving extends Applet


implements ActionListener {

private TextField ageField;


private int age = 0;

public void init() {

Label l = new Label("Enter your age"); // the "l" is a lower-case "L," n


ot a One.
add(l); // Same with this "l."

ageField = new TextField(3);


add(ageField);
ageField.addActionListener(this);

Button reset = new Button("Reset");


add(reset);
reset.addActionListener(this);
}

public void paint(Graphics g) {


if ( ! (age < 100) )
{
g.drawString ("Are you kidding me!", 30, 70);
g.drawString ("Delete some of those numbers." , 30, 80);
}
else if (age > 15)
{
g.drawString ("Congratulations", 50, 50);
g.drawString ("You may drive", 50, 70);
}
else
{
g.drawString ("Wait a few years", 50, 50);
g.drawString ("You may not drive yet", 50, 70);
}
g.drawString("Age is " + age, 50, 90);
}

public void actionPerformed(ActionEvent event) {


if (event.getSource() instanceof Button)
{
age = 0;
ageField.setText("");
}
else if (event.getSource() instanceof TextField)
if (ageField.getText().length() == 0)
age = 0;
else
age = Integer.parseInt(ageField.getText());
repaint();

}
}

Save and Run it.

No w if the event.getSo urce() is an instance of the Butto n Class, then (event.getSo urce() instanceof Butto n) will
be true. We also put in an e lse that tests to see if event.getSo urce is an instance o f the TextField class. If it is,
then it retrieves the number we typed.

We'll see mo re o f inst ance o f as the co urse pro gresses.

Switch Statements
The if statement is a po werful and co mmo nly used co ntro l co nstruct in pro gramming. A similar co nstruct is the
swit ch st at e m e nt . Switch statements can pro vide clarity and allo w fo r a greater number o f executio n paths.

In general, the fo rmat fo r swit ch statements is:

OBSERVE: switch statements


switch (expr1) {
case expr2:
statements;
break;
case expr3:
statements;
break;
default:
statements;
break;
}

In this example, expressio ns (e xpr1, e xpr2, e xpr3, etc.) must be co nstants: int , byt e , sho rt o r char. (These can be
co nvertible via casting to int (auto matic pro mo tio n).)

Let's lo o k at an example using if s, in o rder to co mpare the two co nstructs. In the java2_Le sso n8 Pro ject, make a new
class named Days, and type in the co de belo w:
CODE TO TYPE: Days.java

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class Days extends Applet implements ActionListener{

private TextField dayField;


private int day;

public void init() {


dayField=new TextField(2);
add(dayField);
dayField.addActionListener(this);
}

public void paint(Graphics g) {

g.drawString("Give a number from 1 to 7", 5, 80);

if (day == 1)
g.drawString("Monday", 50, 50);
else
if (day == 2)
g.drawString("Tuesday", 50, 50);
else
if (day == 3)
g.drawString("Wednesday", 50, 50);
else
if (day == 4)
g.drawString("Thursday", 50, 50);
else
if (day == 5)
g.drawString("Friday", 50, 50);
else
if (day == 6)
g.drawString("Saturday", 50, 50);
else
if (day == 7)
g.drawString("Sunday", 50, 50);
else
g.drawString("Please follow directions", 5, 50);
}

public void actionPerformed(ActionEvent event) {


if (event.getSource()==dayField)
day=Integer.parseInt(dayField.getText());
repaint();
}
}

Save and Run it.

No w, let's do the same thing in the next example using a swit ch statement instead o f the nested if s and e lse s. Edit
Days.java as sho wn in blue belo w:
CODE TO EDIT: Days
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class Days extends Applet implements ActionListener{

private TextField dayField;


private int day;

public void init() {


dayField=new TextField(2);
add(dayField);
dayField.addActionListener(this);
}

public void paint(Graphics g) {

g.drawString("Give a number from 1 to 7", 5, 80);

switch (day) {
case 1: g.drawString("Monday", 50, 50); break;
case 2: g.drawString("Tuesday", 50, 50); break;
case 3: g.drawString("Wednesday", 50, 50); break;
case 4: g.drawString("Thursday", 50, 50); break;
case 5: g.drawString("Friday", 50, 50); break;
case 6: g.drawString("Saturday", 50, 50); break;
case 7: g.drawString("Sunday", 50, 50); break;
default: g.drawString("Please follow directions", 5, 50); break;
}
}

public void actionPerformed(ActionEvent event) {


if (event.getSource()==dayField)
day=Integer.parseInt(dayField.getText());
repaint();
}
}

Save and Run it.

Bo th examples sho uld pro duce the same o utput. No tice that after each case , the line ends in a semi-co lo n, and then
has a bre ak;:

Case Syntax
switch (day) {
case 1: g.drawString("Monday", 50, 50); break;
...
default: g.drawString("Please follow directions", 5, 50); break;
}
next code

Here's what's happening:

The bre ak statement tells Java to escape fro m the current co ntro l co nstruct; that is, to leave the swit ch
statement and co ntinue with the ne xt co de .
The co ntro l statement swit ch go es do wn the list o f cases until if finds a case that matches the number that
was entered (o r sees the de f ault ).
The instructio ns fo r the particular case are executed, and then if it sees bre ak, it exits the swit ch.
If it do es no t see a bre ak, it co ntinues do wn the list and do es the rest o f the cases as well.
If it do es no t see a bre ak, it co ntinues do wn the list and do es the rest o f the cases as well.

If we edit the Days applet, we can o bserve what's happening fro m a different angle. First we'll change the applet so that
it mo ves thro ugh each day witho ut user input. And since we wo n't have user input, we'll remo ve the List e ne r and its
metho d act io nPe rf o rm e d( ).

Edit yo ur pro gram as sho wn belo w in blue :

CODE TO EDIT: lo o p thro ugh the days


import java.applet.Applet;
import java.awt.*;

public class Days extends Applet {


private int day;

public void start(){


setSize(200,900);
}

public void paint(Graphics g) {


for (day = 1; day < 8; day++)
{
g.drawString("Day is " + day, 50, 100*day);
switch (day) {
case 1: g.drawString("Monday", 50, 100*day + 10); break;
case 2: g.drawString("Tuesday", 50, 100*day + 20); break;
case 3: g.drawString("Wednesday", 50, 100*day + 30); break;
case 4: g.drawString("Thursday", 50, 100*day + 40); break;
case 5: g.drawString("Friday", 50, 100*day + 50); break;
case 6: g.drawString("Saturday", 50, 100*day + 60); break;
case 7: g.drawString("Sunday", 50, 100*day + 70); break;
default:g.drawString("Not a day", 50, 790);
}
}
}
}

Save and Run it.


To get this o utput we used a f o r lo o p. We will co ver f o r lo o ps in mo re detail later; fo r no w yo u just need to
understand that the fo r lo o p REPEATS actio ns o ver and o ver again for numbers running fro m so me initial number to
so me final number. The initial number in this case is 1, defined by day = 1, and the final number is day < 8 , o r 7 , with
the day incrementing by 1 each time.

Here we went thro ugh the days and set them o ne at a time--day = 1, then day = 2, then day =3, etc.

If yo u do no t use the bre ak statement, Java will co ntinue do wn thro ugh all o f the cases after the first true o ne.

Co mment o ut the bre ak statements as sho wn:

CODE TO TYPE:
import java.applet.Applet;
import java.awt.*;

public class Days extends Applet {

private int day;

public void paint(Graphics g) {

for (day = 1; day < 8; day++)


{
g.drawString("Day is " + day, 50, 100*day);
switch (day) {
case 1: g.drawString("Monday", 50, 100*day + 10); // break;
case 2: g.drawString("Tuesday", 50, 100*day + 20); // break;
case 3: g.drawString("Wednesday", 50, 100*day + 30); // break;
case 4: g.drawString("Thursday", 50, 100*day + 40); // break;
case 5: g.drawString("Friday", 50, 100*day + 50); // break;
case 6: g.drawString("Saturday", 50, 100*day + 60); //break;
case 7: g.drawString("Sunday", 50, 100*day + 70); // break;
default: g.drawString("Not a day", 50, 790);
}
}
}
}

Save and Run it.


No rmally Java wo uld o utput o nly o ne day at a time with so mething like:
Day is 2
Tuesday

But here we have a lo o p to do each day, and no break, so Java prints all the days that co me af t e r as well.

Sometimes a particular case is valid and all o f the fo llo wing cases are valid as well. Using the bre ak can allo w
pro grammers to have many o ptio ns.

The java tuto rial co ntains two examples using the break. When yo u click o n the link, the first tuto rial example yo u see
has so mething to print at each case. We'll be go ing o ver the seco nd tuto rial example here in this lesso n. It illustrates a
situatio n when it is useful to "fall thro ugh". In this sense, vario us inputs can activate a situatio n.

In java2_Lesso n8 , create a new applicatio n class named Swit chDe m o 2. T ype Swit chDe m o 2 as sho wn in blue
belo w.

CODE TO TYPE: SwitchDemo 2.java


public class SwitchDemo2 {
public static void main(String[] args) {

int month = 2;
int year = 2000;
int numDays = 0;

switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
numDays = 31;
break;
case 4:
case 6:
case 9:
case 11:
numDays = 30;
break;
case 2:
if ( ((year % 4 == 0) && !(year % 100 == 0))
|| (year % 400 == 0) )
numDays = 29;
else
numDays = 28;
break;
default:
numDays = 0;
break;
}
System.out.println("Number of Days = " + numDays);
}
}

Save and Run it.

Since this is an applicatio n, o utput will be seen in the co nso le:


If yo u change m o nt h = ?; to different numbers, then Save and Run, it will give yo u the number o f days fo r vario us
mo nths.

The final bre ak is no t required, because flo w wo uld fall o ut o f the swit ch blo ck anyway. Ho wever (as is seen o n the
tuto rial page), the bre ak is reco mmended to make mo difying the co de easier and less erro r-pro ne.

What's next?
The remaining co ntro l co nstruct to learn abo ut is lo o ps. But befo re discussing them, we'll lo o k at a data
structure called arrays. Arrays are used in lo o ps frequently, and will beco me a familiar to o l yo u'll use to keep
track o f multiple pieces o f data.

Phew! We've co vered a lo t o f material so far. When we add arrays and lo o ping to o ur arsenal, we'll be able to
battle whatever co mes o ur way!

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Introduction to Arrays
Lesson Objectives
When yo u co mplete this co urse, yo u will be able to :

declare arrays.
identify vario us types o f arrays.
create arrays and assign them values.
sto re dtat types and values within arrays.
access array values.

What are Arrays?

We've learned a co uple o f ways to represent info rmatio n in memo ry in o bject-o riented languages. We can use o bjects
such as classe s with specific inst ance s, as well as prim it ive dat a t ype s like int , do uble , and char.

But suppo se we wanted to keep a co llectio n o f such o bjects to gether as a gro up? Well, there are a number o f ways to
do this. We co uld use the J ava Co lle ct io ns Fram e wo rk, but the mo st co mmo nly used repo sito ry fo r a co llectio n o f
pieces o f info rmatio n in Co mputer Science has lo ng been the array co nstruct. An array is a "co ntainer" that ho lds a
fixed number o f values o f a single type; let's lo o k at arrays no w.

Some Fab Examples

A basic array is structured as fo llo ws:

INDICES 0 1 2 3 4
ARRAY beatles: "Jo hn Lenno n" "Paul McCartney" "Geo rge Harriso n" "Ringo Starr" "Geo rge Martin"

Fo r tho se o f yo u who are no t familiar with the histo ry o f the Beatles, George Martin pro duced mo st o f the
Beatles' music in the reco rding studio , and is co nsidered by many to be the "fifth Beatle."

The items in the array are called elements and the "handles" to them are indices--each item is accessed by its
numerical index. The array is named be at le s. It's an array o f elements, all o f which are o f type St ring:

beatles[3] = "Ringo Starr"

beatles[0 ] = "Jo hn Lenno n"

beatles[4] = "Geo rge Martin"

After lo o king at the abo ve elements, can yo u guess which o ne is beatles[2]? In o ther wo rds, which element in
the beatles array is lo cated at index 2? I ho pe yo ur answer was "Geo rge Harriso n"!

Arrays always begin with index 0 . The array's length (the number o f elements that an array can ho ld) is always
equal to the sum o f the highest index in the array plus o ne. So what is the length (o r size ) o f the be at le s
array? Let's check by using actual co de.

Make a new java2_Le sso n9 pro ject. Add an applicatio n class named Be at le J uice . T ype Be at le J uice as
sho wn belo w:
CODE TO TYPE: BeatleJuice

public class BeatleJuice {

public static void main(String[] args) {


String[] beatles; // declares an array of Strings

beatles = new String[5]; // allocates memory for 5 Strings

beatles[0] = "John Lennon"; // initialize first element at index 0


beatles[1] = "Paul McCartney"; // initialize second element
beatles[2] = "George Harrison"; // etc.
beatles[3] = "Ringo Starr";
beatles[4] = "George Martin";

System.out.println("Element at index 0: " + beatles[0]);


System.out.println("Element at index 1: " + beatles[1]);
System.out.println("Element at index 2: " + beatles[2]);
System.out.println("Element at index 3: " + beatles[3]);
System.out.println("Element at index 4: " + beatles[4]);

System.out.println("\nSize of the beatles array is " + beatles.length);


}
}

Save and Run it.

Did yo u no tice what \n did in the System.o ut.println o utput? Try putting a few mo re \ns in there to see mo re.

Index Possibilities

Let's try ano ther example:


If x = 1, What is beatles[x], beatles[2*x], beatles[x + 1]? We can find o ut by tweaking the co de fro m o ur first
example.

Edit the co de as sho wn belo w:


CODE TO EDIT: BeatleJuice

public class BeatleJuice {


public static void main(String[] args) {
String[] beatles; // declares an array of Strings

beatles = new String[5]; // allocates memory for 5 Strings

beatles[0] = "John Lennon"; // initialize first element


beatles[1] = "Paul McCartney"; // initialize second element
beatles[2] = "George Harrison"; // etc.
beatles[3] = "Ringo Starr";
beatles[4] = "George Martin";

System.out.println("Element at index 0: " + beatles[0]);


System.out.println("Element at index 1: " + beatles[1]);
System.out.println("Element at index 2: " + beatles[2]);
System.out.println("Element at index 3: " + beatles[3]);
System.out.println("Element at index 4: " + beatles[4]);
System.out.println("Element at index 5: " + beatles[5]);

System.out.println("\nSize of the beatles array is " + beatles.length);


int x = 1;
System.out.println();
System.out.println("When x=" + x + ", the element at beatles[x] is " + b
eatles[x]);
System.out.println("When x=" + x + ", the element at beatles[2*x] is " +
beatles[2*x]);
System.out.println("When x=" + x + ", the element at beatles[x+1] is " +
beatles[x+1]);
}
}

Save and Run it.

No w let's check o ut a slick (and dangero us) use o f increments (i++):


If x = 1
What is beatles[x++]?
What is beatles[++x]?
Let's try putting increments into o ur existing pro gram. Edit the co de as sho wn belo w:
CODE TO EDIT: BeatleJuice

public class BeatleJuice {


public static void main(String[] args) {
String[] beatles; // declares an array of Strings

beatles = new String[5];

beatles[0] = "John Lennon";


beatles[1] = "Paul McCartney";
beatles[2] = "George Harrison";
beatles[3] = "Ringo Starr";
beatles[4] = "George Martin";

System.out.println("Element at index 0: " + beatles[0]);


System.out.println("Element at index 1: " + beatles[1]);
System.out.println("Element at index 2: " + beatles[2]);
System.out.println("Element at index 3: " + beatles[3]);
System.out.println("Element at index 4: " + beatles[4]);

System.out.println("\nSize of the beatles array is " + beatles.length);


int x = 1;
System.out.println();
System.out.println("When x=" + x + ", the element at beatles[x] is " + b
eatles[x]);
System.out.println("With x=" + x + ", the element at beatles[x++] is " +
beatles[x++]);
System.out.println("After use and then increment, x is now " + x);
System.out.println("With x=" + x + ", Element at beatles[++x] is " + bea
tles[++x]);
System.out.println("After increment and then use, x is now " + x);
}
}

Save and Run it.

What is beatles[x++]?

Tricky--the variable x is used first to get the element lo cated at beatles[x], and then x is incremented.

What is beatles[++x]?

The variable x was incremented first to x+1 and then used to get the element lo cated at beatles[x] (where the
value o f x has been increased by 1).

Let's lo o k at ano ther example. This time we have an array named array1 that co nsists o f int (integer values):

INDICES 0 1 2 3 4 5 6 7
ARRAY array1: 42 15 74 6 32 150 724 66

In this array, array1[1] = 15

What is array1[4]?

What is array1[6 ]?

What is array1[8 ]?

What is array1's size?


Let's test yo ur answers. In java2_Lesso n9 , create a new applicatio n class named ArrayDemo . T ype
ArrayDe m o as sho wn belo w:

CODE TO TYPE: ArrayDemo

class ArrayDemo {
public static void main(String[] args) {
int[] array1; // declares an array of integers

array1 = new int[8]; // allocates memory for 8 integers

array1[0] = 42; // initialize first element


array1[1] = 15; // initialize second element
array1[2] = 74; // etc.
array1[3] = 6;
array1[4] = 32;
array1[5] = 150;
array1[6] = 724;
array1[7] = 66;

System.out.println("Size of the array array1 is " + array1.length);


System.out.println();
System.out.println("Element at index 1: " + array1[1]);
System.out.println("Element at index 4: " + array1[4]);
System.out.println("Element at index 6: " + array1[6]);
System.out.println("Element at index 8: " + array1[8]);
}
}

Save and Run it. Yo u'll see this:

Co o l. The two mo st co mmo n exceptio ns any pro grammer ever sees are:

1. ArrayIndexOutOfBo undsExceptio n
2. NullPo interExceptio n

In fact, these kinds o f pro gramming mistakes happen so o ften that Java has a who le class fo r them!

Click o n the API link, go to the java.lang package, scro ll do wn to the Exceptio n Summary, find
ArrayInde xOut Of Bo undsExce pt io n, and click o n it. Read so me o f its descriptio n--I kno w yo u're
interested! We'll discuss Exce pt io n classes in detail in the next co urse. Fo r no w, it's eno ugh to kno w that we
do n't want ArrayInde xOut Of Bo undsExce pt io ns, so we sho uld make sure we pro vide pro per indices
(smaller than the array size).

Note An array's (arrayName) last po ssible element is always arrayName.length -1

A NullPo int e rExce pt io n is mo st co mmo nly enco untered when dealing with arrays because an element o f
an array is null instead o f ho lding a valid reference to an o bject. If we tried to access arrayNam e [0 ] and
arrayNam e [0 ] was null, rather than having a valid reference, we wo uld get the runtime exceptio n,
NullPo int e rExce pt io n thro wn by the Java Virtual Machine. The way to avo id this is to always preface
accessing array elements that are o bject references, with so mething like: if(arrayName[0 ] != null) ...
Substituting as needed to match yo ur co de o f co urse.

Syntax and Java Implementation for Arrays


Declaring a Variable to Refer to an Array
Yo u can declare arrays o f any type, but all o f the elements in an array must be o f the sam e type.

Find the lines o f co de that de clare the arrays in yo ur Be at le J uice .java and ArrayDe m o .java classes:

EXAMPLE: Array Declaratio ns

int [] array1; //this is an array of ints called array1


String [] beatles; //this is an array of Strings called beatles
// The placement of the square brackets [ ] to denote an array is optional--afte
r the type (int []) or after the arrayName (char s[])
// However, convention discourages this form in favor of the brackets after the
array type so the array designation appears with the type designation.

Open yo ur ArrayDe m o class and change the co de as sho wn belo w:

CODE TO TYPE:
class ArrayDemo {
public static void main(String[] args) {
int array1[]; // declares an array of integers

array1 = new int[8]; // allocates memory for 8 integers

array1[0] = 42; // initialize first element


array1[1] = 15; // initialize second element
array1[2] = 74; // etc.
array1[3] = 6;
array1[4] = 32;
array1[5] = 150;
array1[6] = 724;
array1[7] = 66;

System.out.println("Size of the array array1 is " + array1.length);


System.out.println();
System.out.println("Element at index 1: " + array1[1]);
System.out.println("Element at index 4: " + array1[4]);
System.out.println("Element at index 6: " + array1[6]);
System.out.println("Element at index 8: " + array1[8]);
}
}
Save and Run it. No w, just fo r fun, change that line so that there's a space between the type (int array1)
and the brackets [ ], like this:

int array1 [];

Save and Run it again. Yo u can see that having a space befo re the brackets [ ] do esn't affect yo ur result.
Yo u didn't get any erro rs and all is well.

T ip In Java, yo u canno t specify the size o f an array when yo u de clare it, o nly when yo u cre at e it.

If yo u have no t do ne so already, go to ArrayDe m o and re m o ve the line that caused the


ArrayInde xOut Of Bo undsExce pt io n.

Change this line: int array1 []; so it reads: int [8] array1;

It lo o ks like Java do esn't like that. Let's change it back to : int array1 [];

Ahh, all better no w.

Memory
Why did Java co mplain? Because Java was made to be cro ss-plat f o rm , it can't actually set up memo ry o n
machines at co m pile -t im e because it do esn't kno w what kind o f machine it will be running o n. When yo u
de clare a variable to be o f a certain type, the Java co mpiler can check fo r syntax pro blems asso ciated with
the declared variable. But Java canno t reserve space in memo ry when it do esn't kno w what machine it will be
run o n! The length o f an array is established when the array is actually created--at run-t im e --instead.

Find these two impo rtant lines at the beginning o f yo ur ArrayDe m o class:

int [] array1 ; declares that array1 is an array o f int s.

array1 = new int[8]; cre at e s array1 and leaves space fo r 8 int s at run-t im e .

After creatio n, the array's length is fixed. So it makes sense that the indices o f arrays start at 0 . To make o ur
numbers easier to wo rk with, we'll give Java the line array1 = ne w int [10 ];. We kno w that int variables each
take up 32 bits o f space. So fo r 10 int s, we'll need 320 bits. The table belo w is a representatio n o f an array
and the memo ry lo catio n and bits used in memo ry fo r an array that ho lds 10 integers. In the table, X
represents the memo ry lo catio n o f the array:

Indice s: 0 1 2 3 4 5 6 7 8 9
ARRAY
42 15 74 6 32 150 724 66 53 10 0
array1:
Memo ry x = x+ x+ x+ x+ x+ x+ x+ x+ x+ x+
Lo catio ns (0 *32) (1*32) (2*32) (3*32) (4*32) (5*32) (6 *32) (7*32) (8 *32) (9 *32)
(x+32) (x+6 4) (x+9 6 ) (x+128 ) (x+16 0 ) (x+19 2) (x+224) (x+256 ) (x+28 8 )
Uses bit x to
to to to to to to to to to
lo catio ns: (x+32)
(x+6 4) (x+9 6 ) (x+128 ) (x+16 0 ) (x+19 2) (x+224) (x+256 ) (x+28 8 ) (x+320 )

When Java sees that we want array1[6 ], it lo cates array1 and then mo ves o ver 6 *32 (o r 19 2) mo re bits.
Mo st o perating systems are 32 bit, altho ugh newer 6 4-bit versio ns are beco ming available. But until Java is
available in a 6 4 -bit versio n, it will co ntinue to pro cess arrays this way. So all o f the o bjects in an array must
be the same type, to indicate to Java that they're all the same size. And we need to specify the size o f the
array when we create it, so Java kno ws ho w much space to allo w.

Understanding this pro cess also explains why we go t the ArrayInde xOut Of Bo undsExce pt io n exceptio n in o ur
previo us example; we created the array to be o f a certain fixed size and we asked Java to get so mething with an index
bigger than the array allo wed.

This erro r canno t be identified by the co mpiler while yo u are writing the co de. When yo u actually run the co de, yo u give
it the bit lo catio ns. This is called dynam ic allo cat io n o f memo ry.

Array bo undaries are checked at run time to avo id o verflo wing a stack and co rrupting memo ry. Again, because Java is
cro ss-platfo rm, it canno t allo cate memo ry until it is actually running o n a specific machine. Therefo re, all o bjects in
Java are dynam ically allo cat e d
and ArrayInde xOut Of Bo undsExce pt io n , NullPo int e rExce pt io n and such are run-t im e e xce pt io ns rather
than co mpilatio n (o r syntax) erro rs.

int [] a = new int [5] /* leaves space for 5 ints (32* 5 bits) */
Note ho wever
T [] b = new T [5] /*leaves space for 5 references to Ts--not 5 Ts*/

Primitive data types always have exactly the same kno wn size, but different classes may o ccupy different amo unts o f
space. References to memo ry lo catio ns, ho wever, are standardized.

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Loops
Lesson Objectives
When yo u co mplete this co urse, yo u will be able to :

write a fo r lo o p.

Repetition: for Loops

Introduction to Loops

Mo st humans do n't enjo y perfo rming repetitive tasks and will go to great lengths to avo id do ing them. But
that's no t always such a bad thing. In fact, the desire to avo id such drudgery has pro vided us with mo tivatio n
to invent all kinds o f useful to o ls.

Early o n, pro grammers reco gnized the co mputer's ability to execute repetitive tasks. Rather than writing the
same piece o f co de o ver and o ver again and inco prating whatever small changes they wanted (even cutting
and pasting gets o ld quickly), they pro vided co ntro l co nstructs that allo wed them to write co de to repeat a
pro cess...to lo o p aro und.

There are three ways in Java to do lo o ps o r re pe t it io n o f co de :

1. f o r statements
2. while statements
3. do -while statements

Let's go back to the example we used in arrays and check o ut the pro gram first wit ho ut using a lo o p.
Eventually yo u'll feel the po wer o f lo o p co nstructs!

Make a new java2_Le sso n10 pro ject in the J ava2_Le sso ns wo rking set, and create a new
Be at le juice .java class. Edit Be at le juice .java to lo o k like the co de belo w:

CODE TO TYPE: Beatlejuice

class Beatlejuice {
public static void main(String[] args) {
String[] beatles;
beatles = new String[5];

beatles[0] = "John Lennon";


beatles[1] = "Paul McCartney";
beatles[2] = "George Harrison";
beatles[3] = "Ringo Starr";
beatles[4] = "George Martin";

System.out.println("Element at index 0: " + beatles[0]);


System.out.println("Element at index 1: " + beatles[1]);
System.out.println("Element at index 2: " + beatles[2]);
System.out.println("Element at index 3: " + beatles[3]);
System.out.println("Element at index 4: " + beatles[4]);

System.out.println("\nSize of the beatles array is " + beatles.length);


}
}
Save and Run it.

Of co urse we want to give each element in the array its specific name, but ho w many times do we have to type
this:

Syst e m .o ut .print ln(" Ele m e nt at inde x someNumber: " + be at le s[someNumber]);

T e -di-o us! I think we can do better. Edit it as sho wn by making the multiple Syst e m .o ut .print ln calls into a
lo o p:

CODE TO EDIT: Beatlejuice

class Beatlejuice {
public static void main(String[] args) {
String[] beatles;
beatles = new String[5];

beatles[0] = "John Lennon";


beatles[1] = "Paul McCartney";
beatles[2] = "George Harrison";
beatles[3] = "Ringo Starr";
beatles[4] = "George Martin";

for (int i=0; i < beatles.length; i++){


System.out.println("Element at index " + i + ": " + beatles[i]);
}

System.out.println("\nSize of the beatles array is " + beatles.length);


}
}

Save and Run it.

Java gives us exactly the same o utput as the o riginal, but we did much less wo rk. We just reduced five lines o f
co de and to three. Co o l!

No w imagine if everyo ne who WANTED to be a Beatle suddenly WAS a Beatle and we wanted to include all
Beatles in o ur co de. We wo uld have to write tho usands o f new lines o f co de to do that. Or we co uld use the
handy dandy f o r lo o p to do it in just two lines. DO NOT do this right no w, because if yo u did, the lo o p wo uld
go o n fo rever and crash o ur server, and we'd all be really unhappy. Just take a lo o k:

DON'T DO THIS: Co de to List the Names o f tho usands o f beatles

beatles = new String[9999];

for (int i=0; i < beatles.length; i++){


System.out.println("Element at index " + i + ": " + beatles[i]);

No matter ho w m any items there are in an array, o ne o r a billio n, we wo uld still o nly need to have o ne line
f o r (int i=0 ; i < item.le ngt h; i++). No w that's a po werful to o l.

So ho w do es it wo rk specifically? Let's lo o k again at the co de:


OBSERVE: Fo r Lo o p Co de:

for (int i=0; i <


beatles.length; i++)
System.out.println("Element at index " + i + ": " + beatles[i]);

Of co urse every f o r st at e m e nt starts with f o r. The starting and ending po ints are defined in the
parentheses. The incre m e nt in this example is i (i, j, and k are traditio nally used fo r increments). The starting
po int is 0 . So i starts at 0 and the i++ increases i by o ne every step o f the lo o p, until it gets to
be at le s.le ngt h (which in this case is 5 ).

So , first i=0 and it prints "Element at index 0 : Jo hn Lenno n" Then i=1 and it prints "Element at index 1: Paul
McCartney" and so o n.

That's the way all fo r lo o ps wo rk. No matter which lo o p co nstruct yo u cho o se to use, all lo o ps co nsist o f
three majo r parts:

1. Initialize variable to begin.


2. Increment (to get to the next step in the lo o p).
3. Co nditio n to check to end the lo o p.

In Java, the co nditio ns to check in o rder to end the lo o p must return bo o le an values (similar to decisio n
statements). All three lo o p co nstructs in Java (do -while, while, fo r) must co ntain these three parts, but each
co nstruct executes them at different po ints in the co de. If tho se three majo r parts are missing, it may result in
infinite lo o ps.

for
f o r lo o ps have all the three co mpo nents in o ne co nstruct:

f o r(init ialize ; co ndit io n; incre m e nt } {


st at e m e nt s;
...
}

It wo rks like this:

1. The f o r lo o p starts by initializing the "lo o p variable." This is do ne o nce at the beginning o f the
lo o p.
2. The lo o p terminates when the co nditio n beco mes f alse .
3. The increment expressio n is executed after each iteratio n o f the lo o p bo dy.

f o r lo o ps may be the mo st co mmo nly used lo o p co nstruct because they make wo rking with arrays easier.
Let's try o ne o ut by creating an example o f my favo rite grading pro gram. Have yo u ever heard that teachers
grade by thro wing the submitted papers do wn a flight o f steps and each paper's grade is determined by the
step it lands o n? This grading example is so mething like that.

Go to the t e m p Pro ject's default package, and edit the T e st .java class as sho wn belo w:
CODE TO TYPE: Test
class Test {
public static void main(String[] args){
String [] studentGrade = new String[30];
for (int i=0; i < studentGrade.length; i++){ // begin for body (or bloc
k)
switch (i % 5) { // begin switch bloc
k
case 0: studentGrade[i] = "A";
case 1: studentGrade[i] = "B";
case 2: studentGrade[i] = "C";
case 3: studentGrade[i] = "D";
case 4: studentGrade[i] = "F";
} // end switch
System.out.println("The grade for student number " + i + " is " + st
udentGrade[i]);
} // end for
} // end main method
} // end Test class

Save and Run it.

Wo w, that's a pretty ro ugh grading scale. Do n't panic--yo u do n't even get tho se kinds o f grade in this co urse. I
o nly wanted to draw yo ur attentio n to the impo rtance o f bre ak in swit ch statements.

Edit each o f the case s to have a bre ak; after it, like yo u see in the co de belo w:
CODE TO EDIT: Test
class Test {
public static void main(String[] args) {
String [] studentGrade = new String[30];
for (int i=0; i < studentGrade.length; i++){ // begin for body (or bloc
k)
switch (i % 5) { // begin switch block
case 0: studentGrade[i] = "A"; break;
case 1: studentGrade[i] = "B"; break;
case 2: studentGrade[i] = "C"; break;
case 3: studentGrade[i] = "D"; break;
case 4: studentGrade[i] = "F"; break;
} // end switch
System.out.println("The grade for student number " + i + " is " + st
udentGrade[i]);
} // end for
} // end main method
} // end Test class

Save and Run it.

Let's trace this co de:

OBSERVE: Test Class


class Test {
public static void main(String[] args){
String [] studentGrade = new String[30];
for (int i=0; i < studentGrade.length; i++){ // begin for body (or b
lock)

switch (i % 5) { // begin switch block


case 0: studentGrade[i] = "A"; break;
case 1: studentGrade[i] = "B"; break;
case 2: studentGrade[i] = "C"; break;
case 3: studentGrade[i] = "D"; break;
case 4: studentGrade[i] = "F"; break;
} // end switch
System.out.println("The grade for student number " + i + " is " + st
udentGrade[i]);
} // end for
} // end main method
} // end Test class

Here we define an array st ude nt Grade that is a string array o f length 30 . Fo r each number between 0 and 29
it enters the switch statement. Fo r each number i it calculates i% 5 . i%5 can o nly be 0 o r 1 o r 2 o r 3 o r 4, and
fo r each o f these it sets studentGrade[i] = A o r B o r C o r D o r F. Fo r instance, when i=7, i%5 is 2, and so
studentGrade[7] = C.

Grading is a lo t easier with a to o l like this. In a "jumbo " class o f 150 students, the o nly thing yo u need to
change to give that many mo re grades is the length value o f the array:
CODE TO EDIT: Test

class Test {
public static void main(String[] args){
String [] studentGrade = new String[150];
for (int i=0; i < studentGrade.length; i++){ // begin for body (or b
lock)
switch (i % 5) { // begin switch block
case 0: studentGrade[i] = "A"; break;
case 1: studentGrade[i] = "B"; break;
case 2: studentGrade[i] = "C"; break;
case 3: studentGrade[i] = "D"; break;
case 4: studentGrade[i] = "F"; break;
} // end switch
System.out.println("The grade for student number " + i + " is " + st
udentGrade[i]);
} // end for
} // end main method
} // end Test class

Save and Run it.

That was pretty fast, huh? Tho ugh this is kind o f a silly example (a go o d teacher wo uld never do this!), it gave
us a chance to see the f o r in actio n in an array.

Let's lo o k at the m ain() metho d o f o ur Test class to see ho w many times the lo o p variable i is used within
the lo o p, to identify which element in the array (st ude nt Grade [i]) it's handling.

Pro grams usually get their input fro m so me o utside so urce; it can vary in length. Yo u can get yo ur input
using a lo o p, pro cess the input using a lo o p, o r give the o utput using a lo o p. Using lo o ps means yo u do n't
have to wo rry abo ut input and o utput issues, o nly what go es o n inside the lo o p.

T ip Arrays and f o r lo o ps make a go o d team.

Alright. Time to make o ur first slinky and investigate mo re o f the particulars o f the f o r co nstruct. In the
java2_Lesso n10 pro ject, create a new Applet class named Slinky. T ype Slinky as sho wn belo w:
CODE TO TYPE: Slinky

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class Slinky extends Applet implements ActionListener {


private TextField countInput;
private int howManyCircles = 0;

public void init() {

Label l = new Label("How many circles?");


add(l);

countInput = new TextField(3);


add(countInput);
countInput.addActionListener(this);

Button reset = new Button("Reset");


add(reset);
reset.addActionListener(this);
}

public void paint(Graphics g) {


int x = 20;
int y = 20;
for (int count=1; count <= howManyCircles; count ++)
g.drawOval(x+count*5, y+count*5, 50, 50);
}

public void actionPerformed(ActionEvent event) {


if (event.getSource() instanceof Button)
{
howManyCircles = 0;
countInput.setText("");
}
else if (event.getSource() instanceof TextField)
if (countInput.getText().length() == 0)
howManyCircles = 0;
else
howManyCircles = Integer.parseInt(countInput.getText());
repaint();
}
}

Save and Run it.

Experiment and test lo ts o f numbers o f varying sizes. Make sure yo u thro w in so me big o nes--yo u'll pro bably
want to expand the o utput windo w!

We used quite a few different to o ls in this co de:

1. The init () metho d o f the Apple t was called first and made the GUI.
Control constructs: So me sequential pro gramming and metho d invo catio ns.
2. The act io nPe rf o rm e d(Act io nEve nt e ve nt ) metho d implemented the Act io nList e ne r and
waited fo r us to give input.
Control constructs: So me decisio n pro gramming with nested if s and metho d
invo catio ns.
3. The paint (Graphics g) metho d is called fro m the act io nPe rf o rm e d(Act io nEve nt e ve nt )
metho d (via re paint ()), and do es the wo rk.
Control constructs: A f o r lo o p ... f o r (int co unt =1; co unt < = ho wManyCircle s;
co unt ++).

In this f o r lo o p, where did we: initialize the variable, increment it, and check fo r the end o f lo o ping? Which
variables served which purpo se?

The lo o p uses o ne o utside variable (ho wManyCircle s) to determine ho w many circles to make (fro m user
input), but o nce that input is set, all o f the info rmatio n fo r the lo o p is within the paint metho d.

The x and y variables are declared as int within the paint metho d. Since they are used to indicate where to
draw the circles, they are made lo cal to the paint metho d. No o ther metho ds need this info rmatio n, so they
do no t need to be inst ance variable s.

Can we make the co de sho rter by making the two lines into o ne? Edit the Slinky class's paint metho d as
sho wn:

CODE TO TYPE: Slinky.paint()


public void paint(Graphics g) {
int x , y = 20;
for (int count=1; count <= howManyCircles; count ++)
g.drawOval (x+count*5, y+count*5, 50, 50);
}

Save and Run it.

Okay, no w edit it again so it lo o ks like this:

CODE TO TYPE: Slinky.paint()


public void paint(Graphics g) {
int x = 20, y = 20;
for (int count=1; count <= howManyCircles; count ++)
g.drawOval (x+count*5, y+count*5, 50, 50);
}

Save and Run it. Lo o ks fine, runs fine. Go o d.

start
The beginning o f the f o r statement initializes the lo o p co unter variable, like this:

for(int i=0; i < arrayName.length; i++)

OBSERVE: Slinky paint metho d


public void paint(Graphics g) {
int x = 20, y = 20;
for (int count=1; count <= howManyCircles; count ++)
g.drawOval (x+count*5, y+count*5, 50, 50);
}
The variable co unt used in this f o r is called a lo o p variable o r lo o p co unt e r. It is declared inside the
lo o p initializatio n expressio n. Because o f this, the sco pe o f the variable co unt is o nly within the blo ck o f the
lo o p. In this example, the blo ck o f the lo o p is actually o nly o ne line that is repeated. When the lo o p is o ver,
Java will have no clue what co unt is. Peo ple o ften fo rget this and want to print things abo ut the lo o p variable
o utside o f a f o r lo o p. It might help to see an example o f this co mmo n mistake. Edit the Slinky class's paint
metho d by adding a line o f co de:

CODE TO TYPE: Slinky.paint()


public void paint(Graphics g) {
int x = 20, y = 20;
for (int count=1; count <= howManyCircles; count ++)
g.drawOval (x+count*5, y+count*5, 50, 50);
System.out.println("count is now " + count);
}

Yo u never believe me, do yo u! Okay, edit the co de so the lo o p variable is declared o ut side o f the lo o p:

CODE TO EDIT: Slinky.paint()


public void paint(Graphics g) {
int count;
int x = 20, y = 20;
for (count=1; count <= howManyCircles; count ++)
g.drawOval (x+count*5, y+count*5, 50, 50);
System.out.println("count is now " + count);
}

Save and Run it. Lo o ks fine, runs fine.

The value o f co unt printed is 1 mo re than we input, which makes sense because the lo o p sto ps af t e r co unt
<= ho wManyCircles.

This info rmatio n co uld be handy when we ne e d to kno w so mething abo ut the lo o p co unter after we exit the
lo o p. Ho wever, it is usually go o d pro gramming practice to limit the sco pe o f a variable to o nly what is
needed. So , if the lo o p variable in a f o r statement is no t needed o utside o f the lo o p, it's best to declare the
variable in the initializatio n expressio n.

Because the sco pe o f a lo o p variable is limited to within the lo o p and is being used specifically as a co unter
fo r the lo o p, lo o p variables are o ften named i, j, k, o r count.

stop
stop

The seco nd part o f the fo r statement co ntro ls the extent o f the lo o p, as in


fo r(int i=0 ; i < arrayNam e .le ngt h; i++).
To sto p the lo o p, this must return a type bo o le an. The mo st co mmo n erro r pro grammers make in the stop
expressio n is using the arrayName.length when they want to sto p after the last element in the array.

Since the Slinky class did no t use an array, we'll demo nstrate the st o pwith Be at le juice .java. Edit the
Be at le juice .java (in java2_Lesso n10 ) class as sho wn:

CODE TO EDIT: BeatleJuice


class Beatlejuice {
public static void main(String[] args) {
String[] beatles;
beatles = new String[5];

beatles[0] = "John Lennon";


beatles[1] = "Paul McCartney";
beatles[2] = "George Harrison";
beatles[3] = "Ringo Starr";
beatles[4] = "George Martin";

for (int i=0; i <= beatles.length; i++)


System.out.println("Element at index " + i + " : " + beatles[i]);
System.out.println("Size of the beatles array is " + beatles.length);
}
}

Save and Run it.

The pro gram runs until it tries to access beatles[beatles.length]. Nasty. Yo u never want yo ur pro grams to have
erro rs o r exceptio ns.

Take that = sign back o ut (and save).

We did that because the le ngt h o f an array is o ne mo re than the last index. (Because the first index is 0 , the
last must be length-1.)

increment
The last part o f the f o r statement co ntro ls the size o f the "steps" between each o ccurrence o f the lo o p, as in
fo r(int i=0 ; i < arrayName.length; i++).

We want to iterate thro ugh all o f the elements. No rmally, we go thro ugh an array o ne at a time. This
incre m e nt expressio n do esn't have to be i++; it can be any math expressio n. If there is no t an array, we
need to increment acco rding to the lo o p's needs (fo r example, mo ving o ver a certain number o f pixels each
time).

Edit the Be at le juice class and try changing the m ain() metho d's f o r statement to reflect each o f the
examples sho wn. Yo u do no t need to Save and Run after each, but if yo u want to run them make sure there
are no repo rted erro rs first. Experiment with the variety o f expressio ns that are allo wed by typing them in and
seeing there are no erro rs:

CODE TO TEST in BeatleJuice


for (int i=0; i < beatles.length; i = i+1)

for (int i=0; i < beatles.length; i *= 3)

for (int i=0; i < beatles.length; i = 5*i+1)

for (int i=beatles.length; i > 0; i--)

for (int i=beatles.length;; i > beatles.length; i = beatles.length - 2*i)

for (int i=0; i < beatles.length; i = (int)Math.PI * i)

As sho wn in the examples, it is also fine to de cre m e nt at the "increment" co mpo nent (meaning decreasing),
as lo ng as yo u make sure yo u appro ach the st o p state with yo ur decrement. If yo u do n't, yo u co uld get an
infiniite lo o p!

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Creating Arrays
Lesson Objectives
When yo u co mplete this co urse, yo u will be able to :

create an array.
number the values in an array.
use class headers.
use lo o ps and lo gic expressio ns to evaluate data held in arrays.

Creating, Initializing, and Accessing


Let's lo o k at values being set in an array. Create an example using a simple graphical display o f bo xes, and pay
special attentio n to desiging the classes just right.

Ideally, an o bject sho uld kno w everything abo ut itself and do as much fo r itself as po ssible. We'll be using an o bject to
represent the bo x in o ur example. so we need to co nsider the pro perties o f a bo x.

A bo x is, o f co urse, a rectangle. and ultimately, we want the bo x to tell us if it's been clicked. We'll name the first class
Clickable Bo x (even tho ugh it wo n't be clickable just yet). We want this class to implement Mo use List e ne r.
Ho wever, we do n't really need to implement all o f the metho ds in the Mo useListener, so rather than using the default
im ple m e nt Int e rf ace , use an Adapt e r. Every Listener interface in the Java API library that has mo re than o ne
metho d to be implemented, has a co rrespo nding Adapt e r class that can be extended. These Adapter classes
implement all o f the metho ds o f the listener that have empty bo dies (which means that they haven't been implemented
yet).

Make a new java2_Le sso n11 pro ject in the Package Explo rer. Put it in yo ur J ava2_Le sso ns wo rking set. Create a
new class in the pro ject using the settings in the image belo w:
The resulting class will lo o k like this:
import java.awt.event.MouseAdapter;

public class ClickableBox extends MouseAdapter {

public ClickableBox() {
// TODO Auto-generated constructor stub
}
}

So , what variables will we need? Well, a bo x is a rectangle, so at the very least we'll need x, y, height, and width. We are
dealing with screen co o rdinates (as o ppo sed to flo at o r lo ng), so int variables will wo rk just fine. Add the co de in blue
and delete the co de in red as sho wn belo w:
CODE TO TYPE: ClickableBo x
import java.awt.event.MouseAdapter;

public class ClickableBox extends MouseAdapter {

private int x, y, width, height;

public ClickableBox(int x, int y, int width, int height) {


// TODO Auto-generated constructor stub
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
}

The co de we added gives the bo x definitio n and allo ws the co nstructo r Clickable bo x( ) to pass info rmatio n alo ng to
the instance variables.

Currently, we have the basic definitio n o f a bo x. We want this bo x to be able to draw itself o n the screen. There are
vario us ways that Java can draw a Graphics o bject; two metho ds we might use are java.awt .Graphics.drawRe ct ()
and java.awt .Graphics.f illRe ct (). Bo th o f these metho ds will give us functio nality. We also need to kno w what co lo r
to draw in. Type the co de as sho wn in blue belo w:

CODE TO EDIT: ClickableBo x


import java.awt.Color;
import java.awt.event.MouseAdapter;

public class ClickableBox extends MouseAdapter {

private int x, y, width, height;


private Color borderColor, backColor;

public ClickableBox(int x, int y, int width, int height, Color borderColor, Color b
ackColor) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.borderColor = borderColor;
this.backColor = backColor;
}
}

Later, we'll change the co lo r o f a Graphics o bject that's passed to us and set it back when we're do ne. Also , while
we're at it, we'll add so mething that will give us so me co ntro l o ver what is drawn. Edit yo ur co de so it lo o ks like this:
CODE TO EDIT: ClickableBo x
import java.awt.Color;
import java.awt.event.MouseAdapter;

public class ClickableBox extends MouseAdapter {

private int x, y, width, height;


private Color borderColor, backColor, oldColor;
private boolean drawBorder;

public ClickableBox(int x, int y, int width, int height, Color borderColor,


Color backColor, boolean drawBorder) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.borderColor = borderColor;
this.backColor = backColor;
this.drawBorder = drawBorder;
}
}

We'll add mo re later but right no w, let's make this class do so mething. Add a draw() metho d so that this class can
draw itself o n a Graphics o bject. Edit the co de as sho wn in blue belo w:

CODE TO TYPE: ClickableBo x


import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;

public class ClickableBox extends MouseAdapter {

private int x, y, width, height;


private Color borderColor, backColor, oldColor;
private boolean drawBorder;

public ClickableBox(int x, int y, int width, int height, Color borderColor,


Color backColor, boolean drawBorder) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.borderColor = borderColor;
this.backColor = backColor;
this.drawBorder = drawBorder;
}

public void draw(Graphics g) {


oldColor = g.getColor();
g.setColor(backColor);
g.fillRect(x, y, width, height);
if(drawBorder) {
g.setColor(borderColor);
g.drawRect(x, y, width, height);
}
g.setColor(oldColor);
}
}
Save it.

In the draw() metho d, we save the current co lo r o f the Graphics o bject. Then we fill a rectangle with the backgro und
co lo r, then if drawBo rder flag is set (by the co nstructo r), draw the bo rder o n to p o f the filled rectangle. When do ne, we
put the Graphics o bject co lo r back to the way we fo und it using g.setCo lo r(o ldCo lo r).

No w that we have mo st o f o ur instance data, we can generate ge t and se t metho ds (getters and setters) fo r each o f
the fields. Eclipse will do this fo r yo u. Right-click the ClickableBo x.java class in the Package Explo rer, select So urce ,
and cho o se Ge ne rat e Ge t t e rs and Se t t e rs.

This places ge t and se t metho ds fo r each instance field selected after the draw() metho d in yo ur class.

We have eno ugh o f this pro ject do ne to start testing it. So let's create an Applet. Create a new class named
One DArrayApple t in yo ur applet. This class sho uld use java.apple t .Apple t as its Superclass.
The resulting class lo o ks like this:
import java.applet.Applet;

public class OneDArrayApplet extends Applet {

Hmm. It's no t much o f a class yet, but we'll fix that. Since this is ultimately a lesso n o n Arrays, let's use o ne no w. We're
abo ut to hit yo u with a lo t o f stuff right here. Just stay with it and we'll break it do wn afterward.

CODE TO TYPE: ADD The Co de In Blue


import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class OneDArrayApplet extends Applet {


private final int START_X = 25;
private final int START_Y = 70;
private final int BOX_WIDTH = 60;
private final int BOX_HEIGHT = 20;

private ClickableBox[] boxes = new ClickableBox[6];

public void init() {


for (int i = 0; i < boxes.length; i++) {
boxes[i] = new ClickableBox(START_X, START_Y + i * BOX_HEIGHT, BOX_WIDTH,
BOX_HEIGHT, Color.black, Color.red, true);
}
}

public void paint(Graphics g) {


for(int i = 0; i < boxes.length; i++) {
boxes[i].draw(g);
}
}
}

Let's lo o k at the co de in detail:

Instance Fields:

private final int START_X = 25;


private final int START_Y = 70;
private final int BOX_WIDTH = 60;
private final int BOX_HEIGHT = 20;

ClickableBox[] boxes = new ClickableBox[6];

The fields marked f inal are co nst ant s, which means they will never change o nce they're set. In Java, a field marked
final may o nly have its value set o ne time. It do esn't matter where in the class it is set, but it can o nly be set o nce. The
final fields in this class represent the starting lo catio n and size o f the bo xes we are go ing to draw.

The co lo red line in the co de is where we are declaring an array. Clickable Bo x[ ] bo xe s indicates that we have
declared a variable named bo xe s and that it is go ing to co ntain references to Clickable Bo x o bjects. The brackets [ ]
indicate that this is an array variable. As such, it can co ntain mo re than o ne value, using indexes starting with zero [0 ]
up to the length o f the array n, minus o ne [n-1].

We set the bo xes variable = ne w Clickable Bo x[6 ];, which means that we are creating a new instance o f an array
o bject and that the array can o nly co ntain up to 6 references to Clickable Bo x o bjects. The index values we can use in
accessing this array are bo xe s[0 ] thro ugh bo xe s[5 ], because all array indexes start with zero , and this array can
ho ld a to tal o f six o bject references:

OBSERVE: The init() Metho d:


public void init() {
for (int i = 0; i < boxes.length; i++) {
boxes[i] = new ClickableBox(START_X, START_Y + i * BOX_HEIGHT, BOX_WIDTH,
BOX_HEIGHT, Color.black, Color.red, true);
}
}

Note Each element o f the array is an Instance o f ClickableBo x.

In the init () metho d abo ve, we created so me ClickableBo x o bjects. The f o r lo o p will lo o p fro m zero to the size o f the
array minus o ne. The sectio n o f co de bo xe s.le ngt h indicates that we are accessing the le ngt h field o f the bo xe s
o bject. All arrays have a le ngt h field indicating the maximum capacity o f the array. This is no t the last index in the
array, but its to tal capacity; therefo re, the last index in the array is le ngt h - 1.

The f o r lo o p lo o ps fro m 0 thro ugh 5 (< length) and o n each pass, i increments by o ne. On each pass, we assign
bo xe s[i] = ne w Clickable Bo x(...). We pass ST ART _X as the x lo catio n o f all o f the bo xes. This means the bo xes
will line up vertically. We pass ST ART _Y + i * BOX_HEIGHT as the y lo catio n o f the bo x. On each pass, i increments.
When i is zero , the value passed will be 7 0 . When i is o ne, the value passed will be 7 0 + 20 . In successive passes, i
will be 7 0 + 4 0 , then 7 0 + 6 0 , and so o n. This will give the effect o f stacking the bo xes vertically.

The o ther arguments being passed are the size o f the bo xes, the bo rderCo lo r (black), and the backCo lo r (red). Finally,
we tell the ClickableBo x o bjects to draw their bo rder by passing t rue as the drawBo rder argument.

Observe: The paint() Metho d:


public void paint(Graphics g) {
for(int i = 0; i < boxes.length; i++) {
boxes[i].draw(g);
}
}

All o f the wo rk in this metho d is do ne in bo xe s[i].draw(g). We lo o p thro ugh each Clickable Bo x reference and tell
that o bject to draw itself o n the Graphics o bject we are passing to it--the Graphics o bject we received in the paint ()
metho d fo rmal argument.

Save and Run the Applet to check o ut yo ur results:


Red bo xes are co o l, but wo uldn't it be nice to get so me o ther co lo rs in there? Let's create ano ther array. This o ne will
ho ld so me Co lo r o bjects fo r us. While we're at it, let's create a new metho d to change the co lo rs o f the bo xes. Edit
yo ur co de as sho wn belo w:

CODE TO EDIT: OneDArrayApplet


import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class OneDArrayApplet extends Applet {


private final int START_X = 25;
private final int START_Y = 70;
private final int BOX_WIDTH = 60;
private final int BOX_HEIGHT = 20;

private ClickableBox[] boxes = new ClickableBox[6];

private Color[] boxColors = { Color.blue, Color.red, Color.green, Color.cyan,


Color.magenta, Color.yellow };

public void init() {


for (int i = 0; i < boxes.length; i++) {
boxes[i] = new ClickableBox(START_X, START_Y + i * BOX_HEIGHT, BOX_WIDTH,
BOX_HEIGHT, Color.black, Color.red, true);
}
defaultBoxColors();
}

public void paint(Graphics g) {


for(int i = 0; i < boxes.length; i++) {
boxes[i].draw(g);
}
}

public void defaultBoxColors() {


for(int i = 0; i < boxes.length; i++) {
boxes[i].setBackColor(boxColors[i]);
}
}
}
Let's lo o k at the co de we added.

Observe: The bo xCo lo rs[] Array


private Color[] boxColors = { Color.blue, Color.red, Color.green, Color.cyan,
Color.magenta, Color.yellow };

Here we're using a different way to create an array. The list o f Co lo r o bjects inside the { } fills the array as it is made.
This is called an array init ialize r o r array int ializat io n list . The array is created, instantiated, and set to the size o f
the list. Then, it is filled with the values in the list. No te that the semi-co lo n ; after the last } is required. The result is that
bo xCo lo rs[0 ] ho lds a reference to the Co lo r.blue o bject and bo xCo lo rs[5 ] ho lds a reference to the Co lo r.ye llo w
o bject.

Observe: The defaultBo xCo lo rs() Metho d


public void defaultBoxColors() {
for(int i = 0; i < boxes.length; i++) {
boxes[i].setBackColor(boxColors[i]);
}
}

This is virtually identical to the paint () metho d we made earlier, but instead o f drawing each bo x, we set the
backgro und co lo r o f each bo x. The key is that we used the co lo rs fro m the co rrespo nding index in the bo xCo lo rs
array.

Save and Run the Applet to see yo ur results:

So far we've learned that arrays can save us time and effo rt when we need several o f the same kind o f o bject. It's much
easier to create an array o f 10 0 0 int values than it is to create 10 0 0 separate int variables, right?

As pro mised, we're go ing to make the Clickable Bo x clickable, so here we go ! Edit yo ur co de as sho wn belo w:
CODE TO EDIT: ADD The Co de In Blue to the ClickableBo x class:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Container;

public class ClickableBox extends MouseAdapter {


private int x, y, width, height;
private Color borderColor, backColor, oldColor;
private boolean drawBorder, clicked;
private Container parent;

public ClickableBox(int x, int y, int width, int height, Color borderColor,


Color backColor, boolean drawBorder, Container parent) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.borderColor = borderColor;
this.backColor = backColor;
this.drawBorder = drawBorder;
this.parent = parent;
}

public void draw(Graphics g) {


oldColor = g.getColor();
g.setColor(backColor);
g.fillRect(x, y, width, height);
if(drawBorder) {
g.setColor(borderColor);
g.drawRect(x, y, width, height);
}
g.setColor(oldColor);
}

public void mouseReleased(MouseEvent e) {


if(x < e.getX() && e.getX() < x + width &&
y < e.getY() && e.getY() < y + height) {
clicked = true;
parent.repaint();
}
}

public boolean isClicked() {


return clicked;
}

public void setClicked(boolean clicked) {


this.clicked = clicked;
}

// Remaining Getters and Setters left out of listing for brevity.

Save it. Who a! There is a lo t go ing o n here. Let's break it do wn.

Observe: Co ntainers

private Container parent;


We need a way to tell o ur applet to re paint () after the mo use is released o n a bo x. The o nly way to do that is to have a
handle that we can grab to call re paint (). The Applet class and the Frame class are bo th descendents o f the Co ntainer
class, which is itself a descendent o f the Co mpo nent class. Co mpo nent is where the re paint () metho d is defined.

Click the API ico n in the Eclipse menu. Go to the java.awt package. Scro ll do wn to the Co nt aine r class and select
it. In the hierarchy, click java.awt .Co m po ne nt . Scro ll do wn to the re paint () metho ds.

Since graphical Co ntainers are designed to have Graphics areas and to present graphical co ntent, we want to be able
to display o ur class o n any graphical Co ntainer. If we had just passed an Apple t to the co nstructo r, then o nly Applets
wo uld be able to use this class. Even wo rse wo uld be passing a One DArrayApple t to the co nstructo r, because then
o nly Our Applet wo uld be able to use it. By using the po lymo rphism capability o f Java, we have a class that can be
used by any class that descends fro m Co nt aine r.

Observe: The Co nstructo r


public ClickableBox(int x, int y, int width, int height, Color borderColor,
Color backColor, boolean drawBorder, Container parent) {

In the co nstructo r o f Clickable Bo x, we pass a reference to a Co nt aine r. Since o ur applet is a Co nt aine r, we will be
able to pass its t his co nstant to the metho d.

Observe: The mo useReleased() Metho d:


public void mouseReleased(MouseEvent e) {
if(x < e.getX() && e.getX() < x + width &&
y < e.getY() && e.getY() < y + height) {
clicked = true;
parent.repaint();
}
}

The m o use Re le ase d() metho d will be called any time the mo use butto n is released o n this bo x--but o nly if this class
is added to the applet's list o f Mo use List e ne rs. This metho d gets the co o rdinates o f the mo use when its butto n is
released, thro ugh the Mo useEvent metho ds e .ge t X() and e .ge t Y(), then checks to see if tho se co o rdinates are within
this Clickable Bo x instance's area. If they are, we set the clicke d variable to t rue and tell the Applet to re paint ()
itself.

Observe: getters and setters fo r 'clicked' variable


public boolean isClicked() {
return clicked;
}

public void setClicked(boolean clicked) {


this.clicked = clicked;
}

Here we just ro und o ut the class by adding the extra Getter and Setter fo r the clicked variable. No w we'll f ix t he
Apple t so that it can use the new changes in the ClickableBo x class. Edit yo ur co de as sho wn belo w:
CODE TO TYPE: ADD The Co de In Blue To The OneDArrayApplet Class
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class OneDArrayApplet extends Applet {


private final int START_X = 25;
private final int START_Y = 70;
private final int BOX_WIDTH = 60;
private final int BOX_HEIGHT = 20;

private ClickableBox[] boxes = new ClickableBox[6];


private Color[] boxColors = { Color.blue, Color.red, Color.green, Color.cyan,
Color.magenta, Color.yellow };

public void init() {


for (int i = 0; i < boxes.length; i++) {
boxes[i] = new ClickableBox(START_X, START_Y + i * BOX_HEIGHT, BOX_WIDTH,
BOX_HEIGHT, Color.black, Color.red, true, this);
this.addMouseListener(boxes[i]);
}
defaultBoxColors();
}

public void paint(Graphics g) {


for(int i = 0; i < boxes.length; i++) {
if(boxes[i].isClicked()) {
boxes[i].setBackColor(new Color(
(int)(Math.random() * 256),
(int)(Math.random() * 256),
(int)(Math.random() * 256)));
boxes[i].setClicked(false);
}
boxes[i].draw(g);
}
}

public void defaultBoxColors() {


for(int i = 0; i < boxes.length; i++) {
boxes[i].setBackColor(boxColors[i]);
}
}
}

Save and Run yo ur OneDArray applet. Click in different co lo red bo xes to see what happens. No w let's lo o k at ho w
we did it:

Observe: The init() Metho d


public void init() {
for (int i = 0; i < boxes.length; i++) {
boxes[i] = new ClickableBox(START_X, START_Y + i * BOX_HEIGHT, BOX_WIDTH,
BOX_HEIGHT, Color.black, Color.red, true, this);
this.addMouseListener(boxes[i]);
}
defaultBoxColors();
}

In the init () metho d, we have to mo dify the creatio n o f the bo xes so that we can pass the t his co nstant to the new
co nstructo r o f the Clickable Bo x class. We also need to add each bo x to the list o f Mo useListeners fo r this Applet.
Each listener added to the list will be sent any Mo useEvents that are fired o n the applet. Each bo x is a Mo useListener
and will run its m o use Re le ase d() metho d when the mo use butto n is released o n the applet.

Observe: The paint() Metho d


public void paint(Graphics g) {
for(int i = 0; i < boxes.length; i++) {
if(boxes[i].isClicked()) {
boxes[i].setBackColor(new Color(
(int)(Math.random() * 256),
(int)(Math.random() * 256),
(int)(Math.random() * 256))};
boxes[i].setClicked(false);
}
boxes[i].draw(g);
}

We add an if statement to the paint () metho d to see if the bo x abo ut to be painted is clicked. If it is, we change it s
co lo r t o a rando m co lo r and then set its clicke d variable to false.

That's pretty much it fo r this example; if yo u want to have a little fun, just mo dify yo ur One DArray class like this, re-run
it and click the Butto n. See if yo u can figure o ut ho w it wo rks. Edit yo ur co de so it lo o ks like this:
CODE TO TYPE: ADD The Co de In Blue

import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class OneDArrayApplet extends Applet {


private final int START_X = 25;
private final int START_Y = 70;
private final int BOX_WIDTH = 60;
private final int BOX_HEIGHT = 20;

private ClickableBox[] boxes = new ClickableBox[6];


private Color[] boxColors = { Color.blue, Color.red, Color.green, Color.cyan,
Color.magenta, Color.yellow };

private Button resetColors = new Button("Reset Colors");

public void init() {


for (int i = 0; i < boxes.length; i++) {
boxes[i] = new ClickableBox(START_X, START_Y + i * BOX_HEIGHT, BOX_WIDTH,
BOX_HEIGHT, Color.black, Color.red, true, this);
this.addMouseListener(boxes[i]);
}
defaultBoxColors();
resetColors.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
defaultBoxColors();
repaint();
}
});
this.add(resetColors);
}

public void paint(Graphics g) {


for(int i = 0; i < boxes.length; i++) {
if(boxes[i].isClicked()) {
boxes[i].setBackColor(new Color(
(int)(Math.random() * 256),
(int)(Math.random() * 256),
(int)(Math.random() * 256)));
boxes[i].setClicked(false);
}
boxes[i].draw(g);
}
}

public void defaultBoxColors() {


for(int i = 0; i < boxes.length; i++) {
boxes[i].setBackColor(boxColors[i]);
}
}
}

Save and Run it. Click in a few o f the co lo red bo xes, and then click the Reset butto n.

We co uld have put all o f o ur classes into a single .java file. While this might be tempting, yo u must resist. When a
single .java file fo r Java has mo re than o ne class, o nly o ne can be public, and that class must be the applet o r
applicatio n class if they exist. It also must be the class that has the same name as the .java file. The co mpiler will make
separate .class files fro m a single .java file if it co ntains mo re than o ne class. The o nly time it makes any real sense to
put multiple classes in a single file is if they are helper classes that are helping the main class do so mething. We are
using multiple files, because we want o ur co de to be reusable.
What are Arrays again?

An array is an o bject (so rt o f).

Lo o k in the API; yo u'll see that there is an int e rf ace named Array in the java.sql package, as well as a class
named Array in the java.lang.re f le ct package. But when we made the arrays, we did no t use a classname Array--
rather, we used the square brackets []. (There is also a class called ArrayList in the java.ut il package that we will
discuss in a future co urse.)

The array type that we are using here (and in mo st pro gramming languages) is no t a class, but rather a language-
pro vided data structure to ho ld a specified number o f a certain type o f o bjects. It do es no t have a page in the API, and
do es no t have its o wn set o f metho ds. Fo r practical use, yo u might co nsider arrays to be a separate kind o f reference
type fro m o bjects; think o f them as memo ry addresses fo r co llectio ns o f things.

Arrays may be assigned to variables o f type Object and all metho ds o f the Object class may be invo ked fo r arrays.
See: the Java Language Specificatio n.

In the t e m p pro ject fo lder, edit yo ur T e st .java class as sho wn with the co de in blue :

CODE TO TYPE: Test.java

class Test {
public static void main(String[] args) {
int[] testArray = new int[4];
System.out.println(testArray.getClass().getSuperclass());
}
}

Save and Run it and lo o k at the o utput in the Co nso le windo w:

So , the supe r Class o f a variable defined as an array o f ints is Obje ct . As we have seen, arrays have a built-in
length pro perty that's useful in lo o ps and if statements.

Creating Arrays (revisited)

Thanks to Java sho rtcuts, there are a co uple o f ways to create arrays. We've already seen the first metho d
(using ne w), in One DArrayApple t :
Observe: Creating An Array

ClickableBox [] boxes = new ClickableBox[6];

This line is do ing two things:

1. Clickable Bo x[ ] bo xe s is de claring that bo xe s will be the name o f an array ho lding


Clickable Bo x o bjects.
2. bo xe s = ne w Clickable Bo x[6 ]; is cre at ing the array and leaving space in memo ry fo r 6
Clickable Bo x o bject references.

This example o f creating an array is similar to creating inst ance s o f o bje ct s thro ugh the use o f ne w.
Ho wever, after the ne w keywo rd, we do no t see a co nst ruct o r fo r a class, but rather a specificatio n o f the
type o f things being put into the array (in this example, Clickable Bo x o bject references). We co uld have
made an array o f ints o r do ubles just as easily.

Arrays can ho ld prim it ive dat a t ype s o r o bje ct re f e re nce s. Let's try it. Edit the Test.java class in the temp
fo lder as fo llo ws:

CODE TO EDIT: Test.java


class Test {
public static void main(String[] args) {
int[] testArray = new int[4];
String [] myStringArray = new String[6];
Object [] myObjectArray = new Object[5];
Thread [] myThreadArray = new Thread[2];
}
}

See ho w the declaratio n o f the type o f array matches o n the left and right side?

Change T hre ad [ ] m yT hre adArray = ne w T hre ad[2]; to T hre ad [ ] m yT hre adArray = ne w


T hre ads[2]; as sho wn:

CODE TO EDIT: Test.java

class Test {
public static void main(String[] args) {
int[] testArray = new int[4];
String [] myStringArray = new String[6];
Object [] myObjectArray = new Object[5];
Thread [] myThreadArray = new Threads[2];
}
}
The co mpiler do esn't like it! Change it back.

These lines o f co de are creating e m pt y arrays. That is, the lines o nly declare that I have an array o f ints,
Strings, Objects, o r Threads. The lines do no t put element values into each lo catio n. Exce pt fo r
prim it ive dat a t ype s, Java do es put default values in each place. Let's check. Edit the Test.java class in the
temp fo lder as sho wn belo w:

CODE TO EDIT: Test.java


class Test {
public static void main(String[] args) {
int[] myIntArray = new int[4];
double [] myDoubleArray = new double[2];
char [] myCharArray = new char[2];
boolean [] myBooleanArray = new boolean[2];
String [] myStringArray = new String[6];
Object [] myObjectArray = new Object[5];
Thread [] myThreadArray = new Thread[2];
char showMe = '\u0000'; // this is here so you can see what the null characte
r looks like
// I have created the arrays, what does the first eleme
nt in each look like?
System.out.println("The value of myIntArray[0] is " + myIntArray[0]);
System.out.println("The value of myDoubleArray[0] is " + myDoubleArray[0]);
System.out.println("The value of myCharArray[0] is " + myCharArray[0]);
System.out.println("The value of myBooleanArray[0] is " + myBooleanArray[0]);
System.out.println("The value of myStringArray[0] is " + myStringArray[0]);
System.out.println("The value of myObjectArray[0] is " + myObjectArray[0]);
System.out.println("The value of myThreadArray[0] is " + myThreadArray[0]);
System.out.println("The value of showMe is " + showMe); // to compare with th
e char array element
}
}

Save and Run it.

The sho wMe line was put there so yo u co uld see an example o f a null character (the default fo r char). Be
aware that the default fo r any element in an array that ho lds o bjects rather than primitive data types is null.

Fo r Obje ct s, yo u used the new co mmand to create an array, but yo u have no t put anything into the array.

Shortcut for Creating Arrays


Shortcut for Creating Arrays
Ano ther way to create an array is to declare it and simultaneo usly fill it with its initial values:

Creating and Filling an Array Simultaneo usly

String names [] = {"Joe","Sue","Molly","Maggie","Taj"};

The abo ve is equivalent to :

Creating an Array the Lo ng Way

String names [];


names = new String [5];
names[0] = new String ("Joe");
names[1] = new String ("Sue");
names[2] = new String ("Molly");
names[3] = new String ("Maggie");
names[4] = new String ("Taj");

Edit the Test.java class as fo llo ws:

CODE TO EDIT: Test.java

class Test {
public static void main(String[] args) {
String [] names = {"Joe","Sue","Molly","Maggie","Taj"};
for (int i=0; i < names.length; i++)
System.out.println("Name at index " + i + " is " + names[i]);
}
}

Save and Run it.

This wo rks fo r Objects as well. That is, yo u can list the Objects in {} to initialize the array o f so me type o f
o bject--as lo ng as the Objects have been instantiated.

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Two-Dimensional Arrays
Lesson Objectives
When yo u co mplete this co urse, yo u will be able to :

translate the lo gic o f the pseudo -co de into wo rking java co de.
use and evaluate two dimensio nal arrays.
inco rpo rate lo gic, flo w co ntro l, two dimensio nal arrays, and lo o ps.

More About Arrays

Working With T wo-Dimensional Arrays


A two -dimensio nal array is like a grid o f ro ws and co lumns, such as these Po st Office bo xes:

It is represented in Java as an array o f arrays (that is, each entry o f the array is an array!). The fo llo wing
snippet o f co de wo uld create an array with 3 ro ws and 4 co lum ns:

OBSERVE:

int table[][] = new int[3][4];

Each cell in this array has a unique "ro w, co lumn" address:

Co lum n 0 Co lum n 1 Co lum n 2 Co lum n 3


Ro w 0 0 , 0 0, 1 0, 2 0, 3
Ro w 1 1, 0 1, 1 1, 2 1, 3
Ro w 2 2, 0 2, 1 2, 2 2, 3

In this lesso n, we are preparing to make a "matching game," where players will take turns
Note expo sing two hidden bo xes and try to match them fro m the memo ry o f earlier turns.

Let's make a new class similar to the One DArrayApple t fro m the last lesso n. In fact, we'll re use the
Clickable Bo x class fro m that lesso n, o nly this time we're go ing to use a two -dimensio nal array.

In yo ur J ava2_Le sso ns wo rking set, make a new pro ject named java2_Le sso n12. Open yo ur
java2_Le sso n11 pro ject and navigate to yo ur Clickable Bo x class. Co py the Clickable Bo x class by right-
clicking o n the class and selecting Co py. Then, right-click o n yo ur java2_Le sso n12/src/ fo lder and select
Past e .

No w, all we need to do is create a new class in yo ur java2_Le sso n12 pro ject. Right-click o n the pro ject and
select Ne w | Class. Name the new class T wo DArrayApple t and have it extend java.apple t .Apple t , as
sho wn belo w:
The new class will o pen in the edito r. Make an Applet to display a 4x4 grid o f Clickable Bo x o bjects. But this
time, hide the co lo r o f the bo x when it's clicked and unco ver it when it's clicked again. Start with so me
variables we kno w we're go ing to need.

The co de we're go ing to use is similar to that in One DArrayApple t , so we co uld co py that co de and make
the changes belo w to save time:

CODE TO TYPE: ADD the Co de in Blue to the Two DArrayApplet


import java.applet.Applet;

public class TwoDArrayApplet extends Applet {


private final int START_X = 20;
private final int START_Y = 40;
private final int ROWS = 4;
private final int COLS = 4;
private final int BOX_WIDTH = 20;
private final int BOX_HEIGHT = 20;
}
Yo u may reco gnize so me o f this co de fro m the previo us lesso n.

No w, we'll create the array variable:

CODE TO EDIT: ADD the Co de in Blue to the Two DArrayApplet


import java.applet.Applet;

public class TwoDArrayApplet extends Applet {


private final int START_X = 20;
private final int START_Y = 40;
private final int ROWS = 4;
private final int COLS = 4;
private final int BOX_WIDTH = 20;
private final int BOX_HEIGHT = 20;

private ClickableBox boxes[][];


}

Observe: The Placement o f the [ ][ ]


private ClickableBox boxes[][];

In Java, it doesn't matter if yo u put the array declarato rs [ ][ ] after the type (Clickable Bo x) o r
after the variable name (bo xe s) when declaring the variable. It does matter, tho ugh, where yo u
Note place them when accessing the variable. In that case, they must be placed after the variable
name.

The do uble set o f [ ] indicates that we are declaring a two -dimensio nal array. The first brackets deno te the
number o f ro ws in the array and the seco nd deno tes the number o f co lumns. Java allo ws ragge d arrays, but
o nly if we create the array using an initializer list. A ragge d array is an array where ro ws have a varying
number o f co lumns. This info rmatio n will be impo rtant when we discuss ho w to access the number o f
co lumns in each ro w.

We did no t actually create the array instance in the example bo x abo ve, but rather declared that we are go ing
to use a variable named bo xe s, and that will be a two -dimensio nal array o f Clickable Bo x o bjects. It's
co mmo n in Java pro grams to de clare a variable and then de f ine it in the co nstructo r, o r in the case o f an
Applet, in the init () metho d. We co uld have declared it and defined it abo ve by saying:

privat e Clickable Bo x bo xe s[ ][ ] = ne w Clickable Bo x[ROWS][COLS];

or

privat e Clickable Bo x[ ][ ] bo xe s = ne w Clickable Bo x[ROWS][COLS];

Okay, let's add so me functio nality to o ur Applet:


CODE TO EDIT: ADD the Co de in Blue to the Two DArrayApplet
import java.applet.Applet;
import java.awt.Color;

public class TwoDArrayApplet extends Applet {


private final int START_X = 20;
private final int START_Y = 40;
private final int ROWS = 4;
private final int COLS = 4;
private final int BOX_WIDTH = 20;
private final int BOX_HEIGHT = 20;

private ClickableBox boxes[][];


private Color boxColors[][];

public void init() {


boxes = new ClickableBox[ROWS][COLS];
boxColors = new Color[ROWS][COLS];
randomizeColors();
buildBoxes();
}

private void buildBoxes(){


for(int row = 0; row < boxes.length; row++) {
for(int col = 0; col < boxes[row].length; col++) {
boxes[row][col] =
new ClickableBox(START_X + col * BOX_WIDTH,
START_Y + row * BOX_HEIGHT,
BOX_WIDTH,
BOX_HEIGHT,
Color.gray,
boxColors[row][col],
true,
this);
}
}
}

private void randomizeColors() {


int[] chosenColors = {0, 0, 0, 0, 0, 0, 0, 0 };
Color[] availableColors = { Color.red, Color.blue, Color.green,
Color.yellow, Color.cyan, Color.magenta, Color.pink, Color.orange };
for(int row = 0; row < boxes.length; row++) {
for(int col = 0; col < boxes[row].length; col++) {
for(;;) {
int rnd = (int)(Math.random() * 8);
if(chosenColors[rnd] < 2) {
chosenColors[rnd]++;
boxColors[row][col] = availableColors[rnd];
break;
}
}
}
}
}
}

We added a bo xCo lo rs array so that we can separate the co lo rs fro m the bo xes. This allo ws us to co mpact
o ur co de and use lo o ps to create o ur arrays, and also allo ws us to re-rando mize the co lo rs later with
minimal mo dificatio ns to o ur co de.
Observe: The init() Metho d:
public void init() {
boxes = new ClickableBox[ROWS][COLS];
boxColors = new Color[ROWS][COLS];
randomizeColors();
buildBoxes()();
}

In the init () metho d, we use ROWS to define o ur arrays and COLS to define the size o f the arrays. Then we
call the private helper metho ds rando m ize Co lo rs() and buildBo xe s() to set up o ur arrays.

Observe: The rando mizeCo lo rs() Metho d:


private void randomizeColors() {
int[] chosenColors = {0, 0, 0, 0, 0, 0, 0, 0 };
Color[] availableColors = { Color.red, Color.blue, Color.green,
Color.yellow, Color.cyan, Color.magenta, Color.pink, Color.orange };
for(int row = 0; row < boxes.length; row++) {
for(int col = 0; col < boxes[row].length; col++) {
for(;;) {
int rnd = (int)(Math.random() * 8);
if(chosenColors[rnd] < 2) {
chosenColors[rnd]++;
boxColors[row][col] = availableColors[rnd];
break;
}
}
}
}
}

There is a lo t go ing o n in this metho d. First, we set up an array to keep track o f the co lo rs we have already
used. We also set up an array o f 8 co lo rs. In the game we will create in the pro ject, the o bject is to match two
co lo rs. Since we have 16 bo xes, we need 8 co lo rs, with each co lo r used exactly twice. The o utermo st f o r
lo o p iterates thro ugh each ro w; the next f o r lo o p will lo o p thro ugh each co lumn, within each o f the first lo o p's
ro ws. The innermo st f o r(;;) lo o p is an inf init e lo o p. The o nly required parts o f a f o r lo o p within its
parentheses are the semico lo ns. A f o r lo o p with o nly two semico lo ns inside the parentheses is inf init e .

Inside the infinite f o r, we create a rando m number, 0 thro ugh 7. We check to see if the cho se nCo lo rs array
at that index has been used twice. If it has no t, we increment its value to indicate that it has been used. Then
we set the bo xCo lo rs[ro w][co l] to the available Co lo rs[rnd] value. Then, we must bre ak o ut o f the
innermo st lo o p. Witho ut the bre ak statement, this innermo st lo o p wo uld never end. No w we have co de that
will rando mly fill o ur bo xCo lo rs array with 8 co lo rs.

We're using a nested f o r lo o p to lo o p thro ugh the array because there are two dimensio ns in
Note the array. The o ut side f o r lo o p lo o ps o nce after the inside f o r lo o p has co mpleted all o f its
iteratio ns.
Observe: Two Dimensio nal Array length Co nstant:

for(int row = 0; row < boxes.length; row++) {


for(int col = 0; col < boxes[row].length; col++) {

In the o uter 'fo r' lo o p, we access bo xe s.le ngt h in the same way we wo uld access the length o f a o ne-
dimensio nal array. This gives us the number o f ro ws in the array.

The inner lo o p, ho wever, it needs to kno w ho w many co lumns are in each ro w. So we'll mo dify ho w we
access the le ngt h co nstant. Since Java sto res multi-dimensio nal arrays as an array o f arrays, each ro w
actually represents an array. We can access the le ngt h co nstant o f each ro w by using bo xe s[ro w].le ngt h,
which says we want to lo o k at the array sto red at bo xe s[ro w] and get its le ngt h co nstant. Accessing the ro w
and co lumn o f a two -dimensio nal array in this manner allo ws us to parse even ragged arrays. One way to
read the abo ve nested fo r lo o p: f o r e ach ro w in t he array bo xe s, lo o p t hro ugh e ach co lum n o f t hat
ro w.

Observe: The buildBo xes() Metho d:


private void buildBoxes(){
for(int row = 0; row < boxes.length; row++) {
for(int col = 0; col < boxes[row].length; col++) {
boxes[row][col] =
new ClickableBox(START_X + col * BOX_WIDTH,
START_Y + row * BOX_HEIGHT,
BOX_WIDTH,
BOX_HEIGHT,
Color.gray,
boxColors[row][col],
true,
this);
}
}
}

In the buildBo xe s() metho d, we need to access the ro w and co lum n o f the array in o rder to find the
element that needs a value assigned to it. In this case, we are assigning all o f the co lumn values befo re
mo ving o n to the next ro w, because the inner lo o p executes all o f its iteratio ns befo re allo wing the o uter lo o p
to mo ve to its next iteratio n. We create the co lumns o f each ro w by assigning a new Clickable Bo x fo r each
[ro w][co l] o f the array.

Fo r the x value o f the bo xes, we take the ST ART _X, and add to it the co l times the BOX_WIDT H to place the
bo xes next to each o ther o n the ro w auto matically. Fo r the y lo catio n o f the bo xes, we take the ST ART _Y,
add the ro w, and multiply the sum by the BOX_HEIGHT to place the bo xes in ro ws.
CODE TO EDIT: Add the Co de in Blue to the Two DArrayApplet
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class TwoDArrayApplet extends Applet {


private final int START_X = 20;
private final int START_Y = 40;
private final int ROWS = 4;
private final int COLS = 4;
private final int BOX_WIDTH = 20;
private final int BOX_HEIGHT = 20;

private ClickableBox boxes[][];


private Color boxColors[][];

public void init() {


boxes = new ClickableBox[ROWS][COLS];
boxColors = new Color[ROWS][COLS];
//separate building colors so we can add a button later
//to re-randomize them.
randomizeColors();
buildBoxes();
}

public void paint(Graphics g) {


for(int row = 0; row < boxes.length; row ++) {
for(int col = 0; col < boxes[row].length; col++) {
boxes[row][col].draw(g);
}
}
}

private void buildBoxes() {


for(int row = 0; row < boxes.length; row++) {
for(int col = 0; col < boxes[row].length; col++) {
boxes[row][col] =
new ClickableBox(START_X + col * BOX_WIDTH,
START_Y + row * BOX_HEIGHT,
BOX_WIDTH,
BOX_HEIGHT,
Color.gray,
boxColors[row][col],
true,
this);
}
}
}

private void randomizeColors() {


int[] chosenColors = {0, 0, 0, 0, 0, 0, 0, 0 };
Color[] availableColors = { Color.red, Color.blue, Color.green,
Color.yellow, Color.cyan, Color.magenta, Color.pink, Color.orange }
;
for(int row = 0; row < boxes.length; row++) {
for(int col = 0; col < boxes[row].length; col++) {
for(;;) {
int rnd = (int)(Math.random() * 8);
if(chosenColors[rnd] < 2) {
chosenColors[rnd]++;
boxColors[row][col] = availableColors[rnd];
break;
}
}
}
}
}
}

Observe: Two Dimensio nal Array Assignment


public void paint(Graphics g) {
for(int row = 0; row < boxes.length; row ++) {
for(int col = 0; col < boxes[row].length; col++) {
boxes[row][col].draw(g);
}
}
}

Here, we're lo o ping thro ugh the array and telling each bo x to draw itself o n the Graphics o bject g, that we
received in the paint () metho d's parameters.

Save and Run it. It sho uld lo o k so mething like the image belo w, but remember, the co lo rs are rando m:

No w, let's add a Butto n we can click to re-rando mize the co lo rs:


CODE TO EDIT: Add The Co de In Blue To The Two DArrayApplet
import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TwoDArrayApplet extends Applet {


private final int START_X = 20;
private final int START_Y = 40;
private final int ROWS = 4;
private final int COLS = 4;
private final int BOX_WIDTH = 20;
private final int BOX_HEIGHT = 20;

private ClickableBox boxes[][];


private Color boxColors[][];

private Button resetButton;

public void init() {


boxes = new ClickableBox[ROWS][COLS];
boxColors = new Color[ROWS][COLS];
resetButton = new Button("Reset Colors");
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
randomizeColors();
buildBoxes();
repaint();
}
});
add(resetButton);
//separate building colors so we can add a button later
//to re-randomize them.
randomizeColors();
buildBoxes();
}

public void paint(Graphics g) {


for(int row = 0; row < boxes.length; row ++) {
for(int col = 0; col < boxes[row].length; col++) {
boxes[row][col].draw(g);
}
}
}

private void buildBoxes() {


for(int row = 0; row < boxes.length; row++) {
for(int col = 0; col < boxes[row].length; col++) {
boxes[row][col] =
new ClickableBox(START_X + col * BOX_WIDTH,
START_Y + row * BOX_HEIGHT,
BOX_WIDTH,
BOX_HEIGHT,
Color.gray,
boxColors[row][col],
true,
this);
}
}
}

private void randomizeColors() {


int[] chosenColors = {0, 0, 0, 0, 0, 0, 0, 0 };
Color[] availableColors = { Color.red, Color.blue, Color.green,
Color.yellow, Color.cyan, Color.magenta, Color.pink, Color.orange };
for(int row = 0; row < boxes.length; row++) {
for(int col = 0; col < boxes[row].length; col++) {
for(;;) {
int rnd = (int)(Math.random() * 8);
if(chosenColors[rnd] < 2) {
chosenColors[rnd]++;
boxColors[row][col] = availableColors[rnd];
break;
}
}
}
}
}
}

Observe: resetButto n Ano nymo us Inner Class


resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
randomizeColors();
buildBoxes();
repaint();
}
});

We saw this in an earlier lesso n. It's an ano nym o us inne r class that handles the event when the butto n is
pressed. In the act io nPe rf o rm e d() metho d, we rando mize the co lo rs, build the bo xes, and then repaint the
applet. We need to build the bo xes again so that they pick up the new co lo rs.

Save and Run the applet no w. Yo u sho uld be able to click the Re se t Co lo rs butto n and see results
similar to the images belo w. The first image is fro m befo re the butto n was pressed and the seco nd image is
after it was pressed. Again, remember that the co lo rs are rando m.

Since we're m aking a m at ch gam e , we're go ing to want to hide o r m ask t he co lo rs f ro m t he use r.
Then we'll be able to expo se specific bo xes o n each player's turn. We want to be able to mask the co lo r o f a
bo x; unfo rtunately, the Clickable Bo x do esn't have that functio nality. We can either add that functio nality o r
extend it with ano ther class and give t hat class the functio nality. Go o d design dictates that we no t muck
aro und with a class we might already be using in ano ther situatio n, so let's build ano ther class.

Create a new class named Maskable Bo x in yo ur pro ject, as sho wn:


CODE TO TYPE: MaskableBo x
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;

public class MaskableBox extends ClickableBox {


private boolean mask;
private Color maskColor;
Container parent;

public MaskableBox(int x, int y, int width, int height, Color borderColor,


Color backColor, boolean drawBorder, Container parent) {
super(x, y, width, height, borderColor, backColor, drawBorder, parent);
this.parent = parent;
}

public void draw(Graphics g) {


super.draw(g);
if(mask) {
setOldColor(g.getColor());
g.setColor(maskColor);
g.fillRect(getX(), getY(), getWidth(), getHeight());
if(isDrawBorder()) {
g.setColor(getBorderColor());
g.drawRect(getX(), getY(), getWidth(), getHeight());
}
g.setColor(getOldColor());
}
}

public boolean isMask() {


return mask;
}

public void setMask(boolean mask) {


this.mask = mask;
}

public Color getMaskColor() {


return maskColor;
}

public void setMaskColor(Color maskColor) {


this.maskColor = maskColor;
}
}

Save the new class.

Observe: variables in MaskableBo x


private boolean mask;
private Color maskColor;
Container parent;

We need this class to keep track o f when to mask the bo x, and which co lo r to use to mask it. Since we failed
to place a getter and setter fo r the pare nt variable in Clickable Bo x, we need an instance variable here to
keep track o f it. If yo u want, yo u can mo dify yo ur Clickable Bo x class to add the getter (no need fo r a setter)
fo r this variable and then access it later using the getter.

Observe: draw() metho d in MaskableBo x


public void draw(Graphics g) {
super.draw(g);
if(mask) {
setOldColor(g.getColor());
g.setColor(maskColor);
g.fillRect(getX(), getY(), getWidth(), getHeight());
if(isDrawBorder()) {
g.setColor(getBorderColor());
g.drawRect(getX(), getY(), getWidth(), getHeight());
}
g.setColor(getOldColor());
}
}

The draw() metho d first calls supe r.draw(g). If yo u call supe r class in a metho d, it must be the first thing in
the metho d bo dy. We allo w the Clickable Bo x to draw itself. If the m ask variable is set true, we then draw
o ver the bo x. This keeps us fro m having to keep track o f the o riginal co lo r o f the bo x, because we draw o ver it
with the m askCo lo r o nly if the mask is set. No tice ho w we had to use the getters fro m the Clickable Bo x
class? They are privat e in the Clickable Bo x class, so this is the o nly way to access them.

We're almo st there! No w we need to mo dify o ur Two DArrayApplet class. Change all references to
ClickableBo x and make them references to MaskableBo x.

Note We o mitted so me o f the co de to make the listing smaller; do n't remo ve it fro m yo ur class!
CODE TO EDIT: In Two DArrayApplet, Change All ClickableBo x References to MaskableBo x (IN BLUE)
//import statements removed for brevity.
public class TwoDArrayApplet extends Applet {
//variables removed for brevity.
private MaskableBox boxes[][];

public void init() {


boxes = new MaskableBox[ROWS][COLS];
//code removed for brevity.
}

private void buildBoxes() {


for(int row = 0; row < boxes.length; row++) {
for(int col = 0; col < boxes[row].length; col++) {
boxes[row][col] =
new MaskableBox(START_X + col * BOX_WIDTH,
START_Y + row * BOX_HEIGHT,
BOX_WIDTH,
BOX_HEIGHT,
Color.gray,
boxColors[row][col],
true,
this);
}
}
}
//randomizeColors() method removed for brevity.
}

No w mo dify the Two DArrayApplet to give it the functio nality. There's quite a bit go ing o n here, so we will break
it do wn after yo u enter the co de:
CODE TO EDIT: Add The Co de in Blue to the Two DArrayApplet

import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TwoDArrayApplet extends Applet {


private final int START_X = 20;
private final int START_Y = 40;
private final int ROWS = 4;
private final int COLS = 4;
private final int BOX_WIDTH = 20;
private final int BOX_HEIGHT = 20;

private MaskableBox boxes[][];


private Color boxColors[][];

private Button resetButton;

public void init() {


boxes = new MaskableBox[ROWS][COLS];
boxColors = new Color[ROWS][COLS];
resetButton = new Button("Reset Colors");
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
randomizeColors();
buildBoxes();
repaint();
}
});
add(resetButton);
//separate building colors so we can add a button later
//to re-randomize them.
randomizeColors();
buildBoxes();
}

public void paint(Graphics g) {


for(int row = 0; row < boxes.length; row ++) {
for(int col = 0; col < boxes[row].length; col++) {
if(boxes[row][col].isClicked()) {
boxes[row][col].setMaskColor(Color.black);
boxes[row][col].setMask(!boxes[row][col].isMask());
boxes[row][col].setClicked(false);
}
boxes[row][col].draw(g);
}
}
}

private void removeMouseListeners() {


for(int row = 0; row < boxes.length; row ++) {
for(int col = 0; col < boxes[row].length; col++) {
removeMouseListener(boxes[row][col]);
}
}
}

private void buildBoxes() {


removeMouseListeners();
for(int row = 0; row < boxes.length; row++) {
for(int col = 0; col < boxes[row].length; col++) {
boxes[row][col] =
new MaskableBox(START_X + col * BOX_WIDTH,
START_Y + row * BOX_HEIGHT,
BOX_WIDTH,
BOX_HEIGHT,
Color.gray,
boxColors[row][col],
true,
this);
addMouseListener(boxes[row][col]);
}
}
}

private void randomizeColors() {


int[] chosenColors = {0, 0, 0, 0, 0, 0, 0, 0 };
Color[] availableColors = { Color.red, Color.blue, Color.green,
Color.yellow, Color.cyan, Color.magenta, Color.pink, Color.orange };
for(int row = 0; row < boxes.length; row++) {
for(int col = 0; col < boxes[row].length; col++) {
for(;;) {
int rnd = (int)(Math.random() * 8);
if(chosenColors[rnd] < 2) {
chosenColors[rnd]++;
boxColors[row][col] = availableColors[rnd];
break;
}
}
}
}
}
}

Observe: The paint() Metho d


public void paint(Graphics g) {
for(int row = 0; row < boxes.length; row ++) {
for(int col = 0; col < boxes[row].length; col++) {
if(boxes[row][col].isClicked()) {
boxes[row][col].setMaskColor(Color.black);
boxes[row][col].setMask(!boxes[row][col].isMask());
boxes[row][col].setClicked(false);
}
boxes[row][col].draw(g);
}
}
}

In o ur paint () metho d, we added co de similar to o ur One DArrayApple t fro m the previo us lesso n, to
determine if t he bo x we are lo o king at has be e n clicke d. If it has been clicked, we se t it s m askCo lo r
t o black. Next, we perfo rm a little trick with bo o leans--we set its m ask variable to the o ppo site o f what it was
befo re. !bo xe s[ro w][co l].isMask() simply gets the value o f the bo x's m ask variable and takes its no t
value. So , if m ask is t rue , we get false as an answer. Then we se t t he bo x's clicke d variable t o f alse ,
and have t he bo x draw it se lf .
Observe: The remo veMo useListeners() Metho d
private void removeMouseListeners() {
for(int row = 0; row < boxes.length; row ++) {
for(int col = 0; col < boxes[row].length; col++) {
removeMouseListener(boxes[row][col]);
}
}
}

We need to add the bo xes to the applet as Mo use List e ne rs. Listeners are sto red in the applet as a list.
When we run the buildBo xe s() metho d, we need to add new bo xes to this list, because when buildBo xe s()
creates new instances o f the Maskable Bo x class, handles to the o ld versio ns o f tho se o bjects are lo st. The
Apple t class pro vides a metho d (fro m o ne o f its ancesto rs) to remo ve a Mo use List e ne r fro m the list. Our
metho d simply lo o ps thro ugh the array o f bo xes and calls the re m o ve Mo use List e ne r() metho d, remo ving
each o ne fro m the list.

Observe: The buildBo xes() Metho d

private void buildBoxes() {


removeMouseListeners();
for(int row = 0; row < boxes.length; row++) {
for(int col = 0; col < boxes[row].length; col++) {
boxes[row][col] =
new MaskableBox(START_X + col * BOX_WIDTH,
START_Y + row * BOX_HEIGHT,
BOX_WIDTH,
BOX_HEIGHT,
Color.gray,
boxColors[row][col],
true,
this);
addMouseListener(boxes[row][col]);
}
}
}

In the buildBo xe s() metho d, we remo ve all o f the Mo useListeners we might have added befo re. The
re m o ve Mo use List e ne r() metho d pro vided by Apple t thro ws no exceptio ns and do es no thing if the
Mo use List e ne r is null. It's a safe metho d to call.

After we cre at e a bo x inside the inne r f o r lo o p, we add it t o t he apple t as a Mo use List e ne r.

Save and Run it. Click a few bo xes. It sho uld lo o k so mething like the image belo w, but remember, the
co lo rs are rando m:
Ragged Arrays
Yo u can also declare and initialize ragge d arrays with nested initializatio ns. Here we have an array made
fro m three arrays:

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

Observe: two DimArray Declaratio n

int[][] twoDimArray = { {2,1},


{5,4,3},
{9,8,7,6} };

The initializatio n list has changed in this declaratio n. We have the o ut e r se t o f { } brace s, which represents
the o verall array. The co mma-delimited lists o f array initializers in the inner sets o f { } braces build each ro w
o f the array using the co mma-delimited numbers inside o f them, to fo rm the co lumns o f each ro w. ro w 0 o f
the array will have a length o f 2 and will co ntain 2 and 1 as its elements. Ro w 1 will have a length o f 3 and will
co ntain 5, 4, and 3 as its elements. Ro w 2 will have a length o f 4 and will co ntain 9 , 8 , 7, and 6 as its
elements.

Rather than explain, let's wo rk thro ugh it with an experient in Java. Create a class named T e st .java in yo ur
pro ject, as sho wn belo w:
CODE TO TYPE: Add The Co de In Blue
class Test {
public static void main(String[] args) {
int[][] twoDimArray = { {2,1},{5,4,3},{9,8,7,6} };

System.out.println("The length of the array");


System.out.println(" (or the number of rows) = " + twoDimArray.length);
System.out.println("The width of the array");
System.out.println(" (or the number of columns)");
System.out.println(" in twodim[0].length is " + twoDimArray[0].length
);
System.out.println("Which is not the same as");
System.out.println(" in twodim[1].length is " + twoDimArray[1].length
);
System.out.println("Which is not the same as");
System.out.println(" in twodim[2].length is " + twoDimArray[2].length
);
System.out.println("Printing out the array results in:");
for(int row = 0; row < twoDimArray.length; row ++) {
for(int col = 0; col < twoDimArray[row].length; col ++) {
System.out.print(twoDimArray[row][col] + " ");
}
System.out.println();
}
}
}

Save and Run it.

Observe: Printing Out The Array


for(int row = 0; row < twoDimArray.length; row ++) {
for(int col = 0; col < twoDimArray[row].length; col ++) {
System.out.print(twoDimArray[row][col] + " ");
}
System.out.println();
}

Again, Java go es thro ugh all o f the iteratio ns (co lumns) in the inne r lo o p fo r each iteratio n (ro w) o f the
o ut e r lo o p. Java do es no t even o ut the arrays, therefo re they ho ld the same number o f co lumns. Let's test
this:
CODE TO TYPE: Change the Co de in Blue

public class Test {


public static void main(String[] args) {
int[][] twoDimArray = { {2,1},{5,4,3},{9,8,7,6} };

System.out.println("The length of the array");


System.out.println(" (or the number of rows) = " + twoDimArray.length);
System.out.println("The width of the array");
System.out.println(" (or the number of columns)");
System.out.println(" in twodim[0].length is " + twoDimArray[0].length
);
System.out.println("Which is not the same as");
System.out.println(" in twodim[1].length is " + twoDimArray[1].length
);
System.out.println("Which is not the same as");
System.out.println(" in twodim[2].length is " + twoDimArray[2].length
);
System.out.println("Printing out the array results in:");
for(int row = 0; row < twoDimArray.length; row ++) {
for(int col = 0; col < twoDimArray[0].length; col ++) {
System.out.print(twoDimArray[row][col] + " ");
}
System.out.println();
}
}
}

Save and Run it.

Did yo u no tice a pro blem? In the inner f o r lo o p, we addressed a particular ro w's length in two DimArray[]
instead o f the general ro w length fo r the array. Try making this change:

CODE TO TYPE: Change the Co de in Blue


public class Test {
public static void main(String[] args) {
int[][] twoDimArray = { {1,2},{3,4,5},{5,6,7,8} };

System.out.println("The length of the array");


System.out.println(" (or the number of rows) = " + twoDimArray.length);
System.out.println("The width of the array");
System.out.println(" (or the number of columns)");
System.out.println(" in twoDimArray[0].length is " + twoDimArray[0].l
ength);
System.out.println("Which is not the same as");
System.out.println(" in twoDimArray[1].length is " + twoDimArray[1].l
ength);
System.out.println("Which is not the same as");
System.out.println(" in twoDimArray[2].length is " + twoDimArray[2].l
ength);
System.out.println("Printing out the array results in:");
for(int row = 0; row < twoDimArray.length; row ++) {
for(int col = 0; col < twoDimArray[row].length; col ++) {
System.out.print(twoDimArray[row][col] + " ");
}
System.out.println();
}
}
}
The Oracle tuto rial o n arrays has an interesting example o f this usage as well. Check it o ut.

Implementatio n info rmatio n: fo r memo ry sto rage, Java uses ro w-m ajo r o rde r (the ro w is filled
Note and sto red first). Fo r further discussio n, see this Wikipedia entry.

Using Arrays
We need to declare and create arrays just like o ther primitive data types and o bjects, but we also want to pass
them to o ther classes via m e t ho ds. Let's make an example that illustrates passing arrays as parameters. It
will be very similar to the accumulator add() metho d o f o ur Se t MyArray class, except we will pass the array
rather than having the array be accessible as an inst ance variable . Go ahead and edit Test.java as sho wn:

CODE TO TYPE: passing arrays

public class Test {


int total;

public static void main(String[] args){


int[] table = new int[12]; // instantiate the array table
for (int i=0; i < table.length; i++)
table[i] = 1; // populate the array table with
all 1s
total = sum(table); // call the method sum and pass t
he array table
System.out.println("The total is " + total);
}

public int sum(int [] array) {


total = 0;
for (int s=0; s < array.length; s++) // when the index s equals the
length, loop will stop
total = total + array[s]; // find the sum of all of t
he elements in the array
return total;
}
}

Check o ut the erro r. We admit, we did this to yo u o n purpo se to remind yo u abo ut the use o f the m ain()
metho d .

In an applicatio n, the class that m ain () is lo cated in is no t instantiated unless yo u instantiate it specifically.
t o t al is an instance variable o f the Test class and is no t marked static, and the main metho d is marked static;
a static metho d can never access a no n-static variable. t o t al requires the class to be instantiated with the
ne w keywo rd in o rder fo r to tal to exist.

CODE TO TYPE:

class Test {
int total;

public static void main(String[] args){


Test myTest = new Test(); // instantiate the class Test
myTest.demo(); // start the class
}

public void demo(){


int[] table = new int[12]; // instantiate the array table
for (int i=0; i < table.length; i++)
table[i] = 1; // populate the array table with all 1s
total = sum(table); // call the method sum and pass the
array table
System.out.println("The total is " + total);
}

public int sum(int [] array) {


total = 0;
for (int s=0; s < array.length; s++) // when the index s equals the
length, loop will stop
total = total + array[s]; // find the sum of all of t
he elements in the array
return total;
}
}

Save and Run it.

It sho uld wo rk no w, because the m ain () metho d creates an instance o f the Test class and then accesses the
variable via the reference to the new instance o f the class (myTest).

No n-static instance metho ds can access static o r no n-static stuff. Static metho ds can o nly access
T ip static stuff.

The impo rtant things to see in this new co de are:

1. So mewhere an array was instantiated:


int [] t able = ne w int [12];
2. In the metho d where the array is created--de m o ()--a metho d call is made and the array's
variable is passed as an actual parameter:
t o t al = sum (t able );
3. A metho d is defined with a fo rmal parameter o f an array:
public int sum (int [] array)

Two o ther impo rtant aspects:

1. The name o f the actual parameter do es no t need to match the name o f the fo rmal parameter.
2. The array t able did no t need to be an inst ance variable , because it co uld be seen by the o ther
metho d when passed.
This last aspect is mo re impo rtant than yo u might think. Objects (and arrays) in Java are passed by passing a
reference to the o bject (o r array); o bjects (and arrays) in Java are no t passed by passing the values o f the
elements o f the o bject (o r array). Phew! This means that:

Yo u are actually giving the memo ry lo catio n o f the variable table to the metho d sum.
If yo u change anything in the array while in the metho d sum, it changes that array co ntent
everywhere.

So me so urces say that o bjects and arrays are passed "by reference" (because yo u are passing the po inter to
a memo ry lo catio n) and no t "by value."

Oracle's Java Tuto rial uses this termino lo gy:

"Reference data type parameters, such as o bjects, are also passed into metho ds by value. This means that
when the metho d returns, the passed-in reference still references the same o bject as befo re. However, the
values o f the o bject's fields can be changed in the metho d, if they have the pro per access level."

Be aware when reading abo ut ho w o bjects are passed, that the use o f the terms "by value" and
Note "by reference" are no t always co nsistent.

Objects are arrays that pass the memo ry lo catio n and so they can be inadvertently changed.

Edit the Test.java class as sho wn:


CODE TO TYPE
class Test {
int total;

public static void main(String[] args){


Test myTest = new Test(); // instantiate the class Test
myTest.demo(); // start the class
}

public void demo(){


int[] table = new int[12]; // instantiate the array table
for (int i=0; i < table.length; i++)
{
table[i] = 1; // populate the array table with all
1's
System.out.print(table[i] + " ");
}
total = sum(table); // call the method sum and pass the
array table
System.out.println("The total is " + total);
System.out.println("After method invocation completes \n and control has
returned, values are");
for (int i=0; i < table.length; i++)
System.out.print(table[i] + " ");
}

public int sum(int [] array) {


total = 0;
for (int s=0; s < array.length; s++) // when the index s equals the l
ength, loop will stop
{
total = total + array[s]; // find the sum of all of the
elements in the array
array[s]= array[s] + 1;
}
return total;
}
}

Save and Run it.

The co py metho d is useful when yo u want to pass an array witho ut causing its elements to change.

Copying Arrays

Go to the API to the java.lang package. Go to the Syst e m class. Find the arrayco py metho d:

Try it o ut by editing the Test.java class as sho wn blo w. (Add the co de sho wn in blue , and delete the co de
sho wn in re d):
CODE TO TYPE

class Test {
int total;

public static void main(String[] args){


Test myTest = new Test(); // instantiate the class Test
myTest.demo(); // start the class
}

public void demo(){


int[] table = new int[12]; // instantiate the array table
for (int i=0; i < table.length; i++)
{
table[i] = 1; // populate the array table with all
1's
System.out.print(table[i] + " ");
}

int[] table2 = new int[12];


System.arraycopy(table, 0, table2, 0, table.length);
total = sum(table2); // call the method sum and pass the
copy of array table

total = sum(table); // call the method sum and pass the


array table
System.out.println("The total is " + total);
System.out.println("After method invocation completes \n and control has
returned, values are");
for (int i=0; i < table.length; i++)
System.out.print(table[i] + " ");
}

public int sum(int [] array) {


total = 0;
for (int s=0; s < array.length; s++) // when the index s equals the
length, loop will stop
{
total = total + array[s]; // find the sum of all of th
e elements in the array
array[s]= array[s] +1;
}
return total;
}
}

Save and Run it.

It's nice to kno w yo u can do that!

Common Mistakes

Can yo u find the erro rs in the de f ault FillGrade () metho d belo w? It gives two erro rs:
CODE TO TYPE

class Test {

public static void main(String[] args){


Test myTest = new Test();
myTest.demo();
}

public void demo(){


String [] grades = new String[4];
defaultFillGrade(grades);
for (int i=0; i < grades.length; i++) System.out.print(grades[i] + " ");
}

public void defaultFillGrade(String [] grades){


for (int studentNum = 0; studentNum <= grades.length; studentNum++)
grades(studentNum) = "A";
}
}

st ude nt Num <= grade s.le ngt h


If studentNum = grades.length, then the array element with index grades[studentNum] causes a run-t im e
array out of bounds exceptio n. Remember, the indices start at 0 , so they o nly go as far as the array's length
which is -1.
grade s(st ude nt Num )
Java wo uld think this is a call to a metho d grade s with a parameter st ude nt Num . But Java sho uld be
lo o king at indices in an array. Arrays use square brackets. So the co rrect syntax fo r putting the string value o f
"A" into the array grade s at lo catio n st ude nt Num is:
grade s[st ude nt Num ] = " A" ;
Altho ugh this is the re al pro blem, what Eclipse will tell yo u is: T he le f t -hand side o f an assignm e nt
m ust be a variable . Why? Fo r the reaso n I said abo ve--Java thinks that grade s(st ude nt Num ) is a
metho d call, and metho d calls canno t be o n the left side o f an assignment, because the left side is a
memo ry lo catio n.

Edit yo ur Test class as sho wn in blue belo w:

CODE TO TYPE

class Test {

public static void main(String[] args){


Test myTest = new Test();
myTest.demo();
}

public void demo(){


String [] grades = new String[4];
defaultFillGrade(grades);
for (int i=0; i < grades.length; i++) System.out.print(grades[i] + " ");
}

public void defaultFillGrade(String [] grades){


for (int studentNum = 0; studentNum < grades.length; studentNum++)
grades[studentNum] = "A";
}
}

Save and Run it.

When this lo o p is do ne, the array lo o ks like:


ARRAY grades: A A A A
INDICES 0 1 2 3

I like that grading scale!

Yo u've wo rked hard; go take a ride with Duke and Tux to relax befo re the next lesso n o n lo o ps.

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
The Other Loops
Lesson Objectives
When yo u co mplete this co urse, yo u will be able to :

create an applicatio n that instantiates and tests a class.


use while and do -while lo o ps.
change a while lo o p into an equivalent do -while lo o p.

Repetition: while, do-while


Enhanced For Loops
When Java added the J ava Co lle ct io ns Fram e wo rk to their De ve lo pm e nt Kit , they also added a new
enhanced for statement to be used in Ge ne ric classes. Pro grammers o ften iterate thro ugh an entire set, o r
co llectio n, o r array o f things, so Java created so me co nstructs that make do ing that easier. The Co llectio ns
Framewo rk and Generic classes will be studied in greater detail in the next co urse, but we can use the
enhanced for right no w.

Go to yo ur java2_Le sso n10 Pro ject, and edit the Be at le juice class's m ain metho d as sho wn:

CODE TO TYPE:

class Beatlejuice {
public static void main(String[] args) {
String[] beatles;
beatles = new String[5];

beatles[0] = "John Lennon";


beatles[1] = "Paul McCartney";
beatles[2] = "George Harrison";
beatles[3] = "Ringo Starr";
beatles[4] = "George Martin";

for(String item : beatles)


System.out.println("Element is : " + item);

System.out.println("\nSize of the beatles array is " + beatles.length);


}
}

Save and Run it.

We changed this co de:

OBSERVE:
for (int i=0; i <= beatles.length; i++)
System.out.println("Element is : " + beatles[i]);

into this co de:

OBSERVE:

for (String item : beatles)


System.out.println("Element is : " + item);
be at le s co uld have been any array name.

There is no need to specify that the co de sho uld start at the beginning o f the array and go thro ugh each index
until the end (as in the standard "fo r" lo o p), the e nhance d f o r allo ws yo u to do so mething to each it e m in
the array.

We o nly have to specify the array name and the type o f elements in the array. it e m is o ur cho sen variable
name that tempo rarily ho lds each value o f the array fo r each step o f the e nhance d f o r lo o p. Let's wo rk
tho rugh an example o f o ne no w.

In the temp pro ject, edit the T e st .java class as sho wn:

CODE TO TYPE:

class Test {
public static void main(String[] args){
int [] arrayValues = {5,6,6,44,6,7,34,4,9,89};
int sum = 0;
for (int e : arrayValues) // e is short for element
sum += e;
System.out.println("Sum of the array is " + sum);
}
}

Save and Run it.

If we just want to iterate thro ugh an array, we can use this sho rtcut. Java reco mmends using this fo rm o f the
f o r st at e m e nt instead o f the general fo rm whenever po ssible.

while
It's true that f o r lo o ps make it easy to manipulate arrays, but no t all pro gramming lo o ps use arrays. The two
o ther types o f lo o p co nstructs, while and do -while , pro vide mo re flexibility.

The grammatical structure fo r a while lo o p is:

OBSERVE
while(condition) {
statement1;
statement2;
...
}

The while statement co ntinues testing the co nditio n expressio n and executing its blo ck until the co nditio n
evaluates to false.

The three lo o p co mpo nents are no t part o f the while co nstruct itself. Only the sto p co nditio n is present within
the parentheses. The initializatio n pro cess and increment pro cesses o ccur o utside o f them. YOU, the
pro grammer, must remember to make and place the initialize and increment statements:

1. The while lo o p variable sho uld be init ialize d o ut side o f the lo o p.


2. The while lo o p variable sho uld be incre m e nt e d inside o f the lo o p.

Let's create an example o f the while lo o p by editing o ur Slinky.java.

Open the Slinky.java class in java2_Lesso n10 , and edit it as sho wn belo w:
CODE TO TYPE:
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class Slinky extends Applet implements ActionListener {


private TextField countInput;
private int howManyCircles = 0;

public void init() {

Label l = new Label("How many circles?");


add(l);

countInput = new TextField(3);


add(countInput);
countInput.addActionListener(this);

Button reset = new Button("Reset");


add(reset);
reset.addActionListener(this);
}

public void paint(Graphics g) {


int x = 20, y = 20;
int count=1; // declare and set loop varia
ble
while (count <= howManyCircles) { // check condition before ente
ring loop block
g.drawOval (x+count*5, y+count*5, 50, 50);
count++; // increment loop variable
}
}

public void actionPerformed(ActionEvent event) {


if (event.getSource() instanceof Button)
{
howManyCircles = 0;
countInput.setText("");
}
else if (event.getSource() instanceof TextField)
if (countInput.getText().length() == 0)
howManyCircles = 0;
else
howManyCircles = Integer.parseInt(countInput.getText());
repaint();
}
}

Save and Run it. Try testing lo ts o f different numbers (include so me big o nes). Results fo r the while
sho uld lo o k the same as tho se fro m the f o r lo o p.
The while lo o p co mpo nents

int x = 20, y = 20;


int count=1; // declare and set loop
variable
while (count <= howManyCircles) { // check condition befor
e entering loop block
g.drawOval (x+count*5, y+count*5, 50, 50);
count++; // increment loop vari
able
}

In the co de abo ve, we can determine where we:

init ialize d t he variable


incre m e nt e d it
che cke d f o r t he e nd o f lo o ping

while lo o ps are o ften used to gether with f lags. A f lag is simply a certain value fo r a variable that indicates
the end (o r to alert yo u to so me special case). Fo r example, yo u may want to set a flag in this case: "While I
do no t see po lice, I will drive o ver the speed limit":
( while (!po lice ) {spe e d = " f ast " ; wat ching = t rue ;} )

do-while
The do -while lo o p is very similar to the while lo o p. The o nly difference is that do -while lo o ps evaluate their
co nditio nal expressio ns at the bo tto m o f the lo o p instead o f the beginning. So the statements within the do -
while blo ck are always e xe cut e d at le ast o nce .

The structure o f a do -while lo o p lo o ks like this:

OBSERVE:
do {
statement1;
statement2;
...
} while(condition);

No te as in the while , the three lo o p co mpo nents are no t a part o f the do -while co nstruct. You, the
pro grammer, must remember to do the initialize and increment statements.

We will demo nstrate the do -while lo o p by editing o ur Slinky.java o ne mo re time.

Edit the class as sho wn belo w:


CODE TO TYPE:

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class Slinky extends Applet implements ActionListener {


private TextField countInput;
private int howManyCircles = 0;

public void init() {

Label l = new Label("How many circles?");


add(l);

countInput = new TextField(3);


add(countInput);
countInput.addActionListener(this);

Button reset = new Button("Reset");


add(reset);
reset.addActionListener(this);
}

public void paint(Graphics g) {


int x = 20, y = 20;
int count=1; // declare and set loop vari
able
do {
g.drawOval (x+count*5, y+count*5, 50, 50);
count++; // increment loop variable
} while (count <= howManyCircles); // check condition after runn
ing loop block
}

public void actionPerformed(ActionEvent event) {


if (event.getSource() instanceof Button)
{
howManyCircles = 0;
countInput.setText("");
}
else if (event.getSource() instanceof TextField)
if (countInput.getText().length() == 0)
howManyCircles = 0;
else
howManyCircles = Integer.parseInt(countInput.getText());
repaint();
}
}

Save and Run it. Test it with lo ts o f different numbers, and be sure to include so me big o nes.

Hey, so mething's different! Results fo r the do -while sho uld be different fro m the f o r lo o p and the while
lo o p in o ne impo rtant way: the do -while will always go thro ugh the lo o p bo dy at least o nce.

Lo o k at the co mments in the co de we can determine where we:

initialized the variable


incremented it
checked fo r the end o f lo o ping

Infinite Loops
So metimes we want lo o ps to go o n fo rever. We can make that happen with any lo o p type. But o ther times we need to
make lo o ps st o p, especially if we created o ne by mistake. The metho d yo u use to exit a Java pro gram that is stuck in
an infinite lo o p depends o n whether yo u are running an Apple t o r an applicatio n.

If yo u are running an Apple t and yo u have an infinite lo o p, just clo se the bro wser windo w.
If yo u are running an applicatio n and yo u have an infinite lo o p, use the co nso le's T e rm inat e butto n.

Let's put this co ncept to use!

Edit the T e st .java class as sho wn:

CODE TO TYPE:

class Test {
public static void main(String[] args){
while (true){
System.out.println("I am learning lots of Java");
System.out.println("This course is wonderful! \n");
}
}
}

Save and Run it.

Yo u'll see "flickering" o r, if the Co nso le windo w is o pen, yo u might see the println o utput displaying again and again.
To sto p it, click the T e rm inat e butto n.

The flicker is actually the co mputer writing to the co nso le very fast. See the scro ll bar o n the right o f the Co nso le
Windo w? It will tell yo u many times yo ur lo o p ran befo re yo u sto pped it.

Optional For Loop

Including each o f the three expressio ns o f the f o r lo o p is o ptio nal. The mo st co mmo n reaso n fo r o mitting
these expressio n is to use a f o r to create an infinite lo o p.

OBSERVE:
for ( ; ; )
{ // infinite loop
// your code goes here
}

Edit the T e st .java class as sho wn here:


CODE TO TYPE:

class Test {
public static void main(String[] args){
for( ; ; ){
System.out.println("I am learning lots of Java");
System.out.println("This course is wonderful! \n");
}
}
}

Save and Run it. Click the T e rm inat e butto n when yo u've had eno ugh.

Branching Statements
General
We've already seen branching statements in metho ds that return values. Fo r example, so metimes yo u want a
metho d to return so mething befo re the end o f the metho d is reached. In that case yo u can use the re t urn
statement. The re t urn statement exits fro m the metho d it's in, and returns co ntro l flo w to where the metho d
was invo ked. The re t urn statement has two fo rms: it can return a value o r no t.

In additio n to co ntro l changing due to metho d calls, with nested if s and nested lo o ps, there are times when a
pro grammer wants to jump o ut o f a nested lo o p witho ut go ing back into the lo o p in which it was enclo sed.
Java pro vides two additio nal branching st at e m e nt s to allo w pro grammers to do this:

break [label]
co ntinue [label]

[label] indicates these two statements can be labeled o r no t, where a label has syntax label:

We have already seen unlabeled bre aks in swit ch statements. Here is an example to illustrate the use o f
bre ak with a label.

Edit the T e st .java class as sho wn:

CODE TO TYPE:

class Test {
public static void main(String[] args){
out:
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 3; j++) {
System.out.println("i is " + i + " , j is " + j);
if ((i + j) > 4)
break out; // jumps out of both loops
}
}
System.out.println("end of loops");
}
}

Save and Run it. Output sho uld lo o k like this:


Trace the co de to fo llo w why and when the bre ak was used.

Fo r mo re, see the Java Tuto rial o n branching.

In the next lesso n, we'll really put the po wer o f lo o ps to wo rk!

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.
Tracing Code
Lesson Objectives
When yo u co mplete this co urse, yo u will be able to :

use nested while lo o ps.


design and implement the game lo gic fo r a tic tac to e game.

How Did I Get Here?


We've co me a lo ng way. So far we've co vered all o f the Java co ntro l co nstructs and quite a few Java Classes. As yo u
co ntinue to wo rk with Java, yo u'll beco me familiar with even mo re o f the Java classes and the best ways to use them
in yo ur pro grams.

The larger o ur pro grams beco me, o r fo r that matter, the mo re lo o ps we have, the harder can be to fo llo w the flo w o f
co ntro l. In this lesso n, we will practice the technique o f t racing co de. It's the mo st co mmo n way to find lo gic bugs
(Eclipse can help us with o ur syntax erro rs, but no t with po o r lo gic reaso ning), and is an invaluable to o l.

We've already seen arrays and f o r lo o ps wo rking to gether. In this lesso n, we'll strengthen o ur kno wledge o f arrays in
metho d calls and use 2-D arrays in ne st e d f o r lo o ps. In general, o ur go al is to be able to trace thro ugh co de to
figure o ut ho w it wo rks, and if the o utput do esn't seem to match up with what we t ho ught yo u pro grammed, figure o ut
why.

Arrays for Methods--Reminder


Let's review arrays:

1. In so me classes, the array itself has to be declared and instantiated.


2. Elements o f the array must be declared and instantiated.
3. The array must be filled with these elements.

No w let's try to pass the array as a parameter:

Make a new Java Pro ject and name it java2_Le sso n14 . Inside yo ur nee pro ject, create a new applicatio n Class and
name it T he Accum ulat o r, as sho wn belo w:
Type the class named T he Accum ulat o r, as sho wn belo w:
CODE TO TYPE:

class TheAccumulator {

public static void main(String[] args){


TheAccumulator myInstance = new TheAccumulator();
int myArray [] = {1,2,3,4,5,6,7,8,9,10};
int myArrayTotal = myInstance.sum(myArray);
System.out.println("Total is : " + myArrayTotal);
}

// method definition

public int sum( int [] array) {


int total = 0;
for (int s=0; s < array.length; s++)
total = total + array[s];
// find the sum of all of the elements in the array
// total here is called an accumulator - it accumulates the sum
return total;
}
}

Save and Run it.

OBSERVE: Instantiating an Array and Passing it to a Metho d


int myArray [] = {1,2,3,4,5,6,7,8,9,10};
int myArrayTotal = myInstance.sum(myArray);

Once yo u've initialized m yArray as an array o f int , Java kno ws what it is. Fro m then o n, it is a variable like any o ther.
When yo u pass it, yo u do no t need to state again that it is an array—Java kno ws. So , when yo u call the sum () metho d,
yo u do n't need the square brackets o r any o ther indicato rs; m yArray is eno ugh.

OBSERVE: Metho d Declaring an Array as a Fo rmal Parameter

public int sum( int [] array)

Yo u do , ho wever, need to specify which types the fo rmal parameters are expected to be in a metho d definitio n. If yo u
are defining a metho d and want it to be passed an array, yo u need to specify the parameter as array.

Objects in Java are passed by passing the reference to the Object (a handle o r po inter to the place in memo ry where
the Object/array is sto red). This means that when yo u pass an array as a metho d parameter, yo u are no t giving the
metho d the co ntent o f the array, but a reference to it in memo ry.

This means pro grammers co uld inadvertently change o r co rrupt the array, because they might pass it to a metho d that
alters it. Primitive data types are passed by value, so they are no t as "dangero us" to pass. In the next sectio n, we'll see
an example to help us understand why we need to be careful o f such side e f f e ct s.

Always Look Before Passing (or Hiring)


Suppo se a co mpany has hired a student to do so me pro gramming. They want a Metho d that will take an
Array o f their sales numbers to find o ut which salesperso n has the largest sale that week. The student needs
to write a Class to test their existing co de by creating the Array in a check metho d and sending the Array to the
metho d highe st (). The pro grammer needs the metho d to return the highest sale and also to print which
salesperso n made a sale in that amo unt. Let's take a lo o k at an example to see ho w the student pro ceeded.

Make a new class called T e st . Type the T e st class as sho wn:


CODE TO TYPE:

class Test {

public static Test student;

public static void main(String[] args){


student = new Test();
student.check();
}

public void check(){


int s;
int[] sales = {3400, 2233, 3433, 754, 5664, 42}; // instantiate an
d populate the array sales
int winner = student.highest(sales); // call the meth
od highest and pass the array sales;

s=0; // while loop to


find the highest person
while (sales[s] ==0)
s++;

System.out.println("The highest sale was salesperson " + (s+1)); // sa


lespeople do not like to be named 0 so add one to indices

for (s=0; s < sales.length; s++)


System.out.println("Salesperson " + (s+1) + " sold "+ sales[s]);
}

public int highest(int [] passedSales) {


int currentHigh = passedSales[0]; // instantiate the high sale to
be the first salesperson's sales initially
int highGuy = 0; // instantiate the high person

for (int s=0; s < passedSales.length; s++)


if (passedSales[s] > currentHigh) // get highest valu
e
{currentHigh=passedSales[s]; // remember curre
nt high
passedSales[highGuy] = 0; // this one isn't
highest anymore, set to 0
highGuy = s; // new highGuy
}
else passedSales[s]=0; // only keep value at
highest so can retrieve

return currentHigh;
}
}

Save and Run it.

Note This is no t go o d co de, but we're go ing to fo llo w it anyway and address the pro blems in it.

Because he co uld o nly pass back o ne thing, the pro grammer passed back the highest sale value and then
created the array to be all zero s unless it was the to p salesperso n. Then, he searched thro ugh the array to
find the value that was no t 0 to determine which salesperso n had the higest sale. (The metho d has an array o f
sales as a parameter.)

Of co urse, the array being passed back and fo rth is the info rmatio n abo ut sales, so using it this way destro ys
the o riginal data.

Yo u do no t want to use an array that ho lds such valuable info rmatio n as a metho d argument--make a co py
instead. Also , design yo ur co de so that o ther metho ds are no t reliant o n strange manipulatio ns yo u have
made. As Albert Einstein o nce said, "Everything sho uld be made as simple as po ssible, but no t simpler."

Return the index o f the highest value. If yo u have the index, yo u have the value at that index (that is,
T ip kno wing i allo ws yo u to get sale s[i]).

Nested for
In o ur last pro ject, we made heavy use o f nested f o r lo o ps. Co nsidering the amo unt o f co de we write to create them,
f o r lo o ps give us a big bang fo r o ur buck. Let's lo o k at so me examples.

Edit the T e st class as sho wn belo w:

CODE TO TYPE:

class Test {

public static void main(String[] args){


for (int i = 0; i < 4; i++)
for (int k = 0 ; k < 5; k++)
System.out.println("here I am again");
}
}

Can yo u tell ho w many times it printed and why without the help o f running it? Let's trace it.

OBSERVE:

for (int i = 0; i < 4; i++)


for (int k = 0; k < 5; k++)

The o uter lo o p starts with i = 0 , iterates while i < 4 ; and increments by o ne (i++) fo r each iteratio n. It will iterate with i =
0 , 1, 2, and 3—o r 4 times. Fo r each o ne o f these o uter lo o ps, the inner lo o p starts with k = 0 ; interates while k < 5 ; and
increments by o ne (k++) fo r each iteratio n. It will iterate with k = 0 , 1, 2, 3, and 4—o r 5 times. The inner lo o p iterates 5
times fo r each o f 4 o uter-lo o p iteratio ns; 5 * 4 = 20 .

Pro grammers o ften use Syst e m .o ut .print lns to help them trace their co de and see what it's do ing while it runs.

Edit the T e st class's m ain() metho d as sho wn belo w:

CODE TO TYPE:
class Test {

public static void main(String[] args){


int n=0;

for (int i = 0; i < 4; i++)


for (int k = 0 ; k < 5; k++)
{
System.out.print("here I am again: ");
n++;
System.out.println(n + ": i is " + i + " and k is now " + k);
}
}
}

Save and Run it.


CODE TO TYPE:
class Test {

public static void main(String[] args){


int n=0;

for (int i = 0; i < 6; i++)


for (int k = 0 ; k < 1; k++)
{
System.out.print("here I am again: ");
n++;
System.out.println(n + ": i is " + i + " and k is now " + k);
}
}
}

Save and Run it.

Edit the co de as sho wn belo w. (Befo re running, trace it to determine ho w many times it will print this time.):

CODE TO TYPE:
class Test {

public static void main(String[] args){


int n = 0;
for (int i = 0; i < 5; i++)
for (int k = i ; k < 5-i; k++)
{
n++;
System.out.println(n + ": i is " + i + " and k is " + k);
}
}
}

No tice the use o f the variable i in the inside f o r lo o p.

Save and Run it.


Why did it print nine times? Fo llo w the interactio n o f the values o f i and k.

Edit the co de again as sho wn here:

CODE TO TYPE:

class Test {

public static void main(String[] args){


int n = 0;
for (int i = 5; i < 0; i--)
for (int k = 0 ; k < 1; k++)
{
System.out.print("here I am again: ");
n++;
System.out.println(n + ": i is " + i + " and k is " + k);
}
}
}

Save and Run it.

Hey, there's no thing there! What happened? Well, there's no o utput because i is initially 5 . 5 is no t less than 0 , so the
lo o p is never entered.

T racing do-while
Let's trace so me do lo o ps (with the help o f Syst e m .o ut .print ln).

Edit the T e st class's m ain() metho d as sho wn:


CODE TO TYPE:
class Test {

public static void main(String[] args){


int x = 1;
do {
System.out.println("Looping, round " + x);
x++;
} while (x <= 4);
}
}

Save and Run it.

Ho w abo ut this o ne. Edit the T e st class's m ain() metho d as sho wn belo w:

CODE TO TYPE:
class Test {
public static void main(String[] args){
int n = 6;
int counter = 0;
do {
counter = counter + 2;
} while (counter <= n);
}
}

Save and Run it.

There's no o utput in this pro gram, so yo u'll need to think!

T race : Fo llo w the assignment o f the co unt e r variable as the lo o ping o ccurs. It's initialized as 0 . In the first iteratio n o f
the do lo o p, co unter = co unter + 2 makes it 2; 2 <= n (which is 6 ), so lo o ping co ntinues. In the seco nd iteratio n,
co unter beco mes 4 (still <=6 ). In the third iteratio n co unter beo mes 6 (still <=6 ). In the fo urth iteratio n, it beco mes 8 ,
which is NOT <=6 ), so lo o ping sto ps.

Ho w can we be sure? Edit the T e st class's m ain( ) metho d as sho wn:

CODE TO TYPE:
class Test {
public static void main(String[] args){
int n = 6;
int counter = 0;
do {
counter = counter + 2;
System.out.println("counter is: " + counter);
} while (counter <= n);
}
}

Save and Run it. System.o ut.println can, indeed, be handy!


Using a f o r lo o p, write co de to generate the fo llo wing o utput:

Try it first yo urself. Yo ur answer sho uld lo o k so mething like this:

OBSERVE:
public class testMe {

public static void main (String args[]){

for(int c = -1000; c <= 1000; c=c+4)


System.out.println(c);
}
}

T racing Decisions
Here's an if questio n to trace. Try to determine the exact range o f values o f the variable x that causes the co de belo w
to print the letter B:

CODE TO CONSIDER:
if (x <= 200)
if (x < 100)
if (x <= 0)
System.out.println("A");
else
System.out.println("B");
else
System.out.println("C");
else
System.out.println("D");

When yo u trace if statements, try an example o f every po ssible case (remember that each e lse co rrespo nds to the
nearest if ).

When yo u try all o f these values o f x:

no t less than 20 0
equal to 20 0
less than 20 0
less than 20 0 but no t less than 10 0
less than 20 0 and less than 10 0
less than 10 0
less than 10 0 but no t less than 0
less than 10 0 and less than 0

Yo u'll see that:


Yo u'll see that:

fo r {x | x <= 0 }, "A" will print


fo r {x | 0 < x < 10 0 }, "B" will print
fo r {x | 10 0 <= x <= 20 0 }, "C" will print
fo r {x | x > 20 0 }, "D" will print

Therefo re, "B" will print fo r values o f x in the range 1 thro ugh 9 9 .

So , co uld yo u use the abo ve fo rms in co de rather than the nested if s? No . Yo u need to use well-fo rmed lo gic
statements, such as (10 0 <= x && x <= 20 0 ).

Here's ano ther lo o p (with a switch) to trace:

CODE TO CONSIDER:
int count;
for (count = 1; count <= 12; count++)
{
switch (count % 3)
{ // mod 3
case 0:
g.setColor(Color.red);
break;
case 1:
g.setColor(Color.blue);
break;
case 2:
g.setColor(Color.green);
break;
}
g.drawLine(10, count * 10 , 80, count * 10);
}

In the java2_Lesso n14 pro ject, create a new class named Line s, with the Superclass java.apple t .Apple t . Type the
Line s as sho wn belo w:

CODE TO TYPE

import java.awt.*;
import java.applet.*;

public class Lines extends Applet {

public void paint(Graphics g){


int count;
for (count = 1; count <= 12; count++) {
switch (count % 3) { // mod 3
case 0:
g.setColor(Color.red);
break;
case 1:
g.setColor(Color.blue);
break;
case 2:
g.setColor(Color.green);
break;
}
g.drawLine(10, count * 10 , 80, count * 10);
}
}
}
Save and Run it. Co mpare the o utput with a trace o f the co de. Pay patricular attentio n to the drawLine parameters
to see ho w co unt was used to mo ve the lines.

More About Flow Control


Yo u can do wnlo ad a Java applicatio n here that will help yo u visualize the flo w o f co ntro l thro ugh metho ds. It will
auto matically install itself into yo ur learning enviro nment. Place the java2_Flo wCo nt ro l pro ject in yo ur
java2_Le sso ns wo rking set. Run the J avaFlo wCo nt ro lExam ple class as a Java Applicatio n.

We've seen that all algo rithms are made up o f the fo llo wing co nt ro l co nstructs that direct the flo w o f the pro gram:

Sequences (assignment statements, IO calls)


Decisio ns and selectio ns (if/then, switch)
Repetitio ns and lo o ps (while, fo r, do -while)
Metho d invo catio n

Summary of Control Constructs


Branching

if/else>

(Co nditio n must result in bo o lean: no t 0 o r 1.)

OBSERVE:
if (Boolean)
{
statements;
}
else
{
statements;
}

if (a instanceof b) ...

swit ch

Expressio ns must be co nstants: int, byte, sho rt, o r char (co nvertible via casting to int (auto matic pro mo tio n) ).

OBSERVE:
switch (expr1)
{
case expr2:
statements;
break;
case expr3:
statements;
break;
default:
statements;
break;
}

Co nsider fo r so me graphics metho d specify Class Variables:


OBSERVE:
static int SQUARE = 1;
static int CIRCLE = 2;
...

int currShape = 0;
...
switch (currShape)
{
case (SQUARE): statements; break;
case (CIRCLE): statements; break;
}
...

Alternatively, so metimes co nst ant variables are set:

public st at ic f inal int YES = 0 , NO = 1, CANCEL = 2;

These variables are co nstant because the f inal keywo rd specifies that they can't be changed. If there are no
bre aks in a case, co ntro l dro ps thro ugh, which means that o nce there's a match, all co de that fo llo ws is
executed.

Repetition/Loops
(while, do and fo r--same as in C, C++)

while loops

OBSERVE:
while (boolean)
{
statements;
}

do-while loops

OBSERVE:
do
{
statements;
} while (boolean);

for loops

OBSERVE:
for (init expr; test expr2; increment expr3)
{ statements; }

for ( i=1 ; i < 10 ; i++)


(start, stop, increment)

Fo r reinfo rcement o f the materials co vered in this co urse, see the Java Tuto rial o n Language Basics. When yo u finish
with this first Java series, yo u will be hands-o n f am iliar with all o f the to pics in the Java Tuto rial o n Learning the Java
Language.

Copyright © 1998-2014 O'Reilly Media, Inc.

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
See http://creativecommons.org/licenses/by-sa/3.0/legalcode for more information.

You might also like