Java Programming 2 The Java Programming Language v1 PDF
Java Programming 2 The Java Programming Language v1 PDF
Applicatio ns
Our First Applicatio n
The System Class
A Clo ser Lo o k at main
Do cumentatio n and Co mments
Fo nts
Numbers
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
Switch Statements
What's next?
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
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
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
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 :
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.
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.
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.
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:
If the wo rking sets already exist in the Package Explo rer, they will no t be recreated, but the perspective will still
change.
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.
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:
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.
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.
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.
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.
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.
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.
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).
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.
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.
In the Hello Wo rldApp template that was created fo r yo u, remo ve the co de sho wn in blue .
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:
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.
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.
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.
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 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!
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 :
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:
import java.awt.event.*;
import java.awt.*;
public Memo() {
super("This is a Memo Title");
message = "This is the content of the Memo";
}
m = new Memo();
m.start();
}
}
public Memo() {
super("This is a Memo Title")4;
message = "This is the content of the Memo"5;
}
m = new Memo()3;
m.start()6;
}
}
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.
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 Memo() {
super("This is a Memo Title");
message = "This is the content of the Memo";
}
m = new Memo();
m.start( );
}
}
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 Memo() {
super("This is a Memo Title");
message = "This is the content of the Memo";
}
m = new Memo();
m.start( );
}
}
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 Memo() {
super("This is a Memo Title");
message = "This is the content of the Memo";
}
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.
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;
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.
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.
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:
An expression is Java co de that specifies and evaluates to a single value in the pro gram. Check o ut a few
examples:
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 :
/**
* @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:
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):
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.
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.
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 {
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.
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.
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.
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:
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.
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 {
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:
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:
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 {
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:
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:
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:
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 .
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:
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
3.14
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:
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.
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.
OR
Bo th wo rk fine.
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 {
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.
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:
\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:
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:
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.
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 .
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.
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!
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 :
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:
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:
Go to the Graphics class and find the drawSt ring() metho d. There are two instances o f the
drawSt ring() metho d here.
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:
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:
and
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.
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.*;
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:
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.
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:
import java.applet.Applet;
import java.awt.*;
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.
import java.applet.Applet;
import java.awt.*;
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.*;
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:
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:
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.*;
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:
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:
import java.applet.Applet;
import java.awt.*;
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.
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;
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;
double area;
double radius = 12;
double amountOwed = 12.00;
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!
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.
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.
Let's trace the pro gram to see exactly what's happening in the paint () metho d:
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:
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:
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.
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.
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.
are a = 6 widt h;
There's an erro r marker o n the right and red zigzags under width:
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 :
g.drawOval(10,10,radius, radius);
g.drawString("My circle's area is " + area, 10, 100);
}
}
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:
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
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.
n = n + 1;
System.out.println("After n = n + 1, n is " + n);
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.
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();
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!
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);
Be careful with these; they can get yo u in tro uble if used impro perly.
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 :
1. ( )
2. * / %
3. + -
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
6 + 3 * 4 / 2 - 9,
Let's apply precedence rules to the first expressio n belo w and fo llo w its path:
((((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.
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:
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
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.
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:
Let's test the abo ve examples. Edit the T e st class as sho wn belo w:
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;
g.drawOval(10,10,radius, radius);
g.drawString("My circle's area is " + area, 10, 100);
}
}
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:
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?:
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;
g.drawOval(10,10,diameter/2, diameter/2);
g.drawString("My circle's area is " + area, 10, 100);
}
}
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:
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.
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:
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:
import java.awt.*;
import java.applet.Applet;
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;
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.
import java.awt.*;
import java.applet.Applet;
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.
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.
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 ?
but Java first co nverts the area number into a String, then co ncatenates it.
and
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:
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.
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.
&& - 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.
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.
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:
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 .
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:
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)
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:
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
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 ).
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.*;
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:
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.*;
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.
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
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 .
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:
import java.util.Scanner;
int score;
String grade;
Scanner scan = new Scanner(System.in);
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:
import java.util.Scanner;
int score;
String grade;
Scanner scan = new Scanner(System.in);
import java.util.Scanner;
int score;
String grade;
Scanner scan = new Scanner(System.in);
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";
int year;
boolean leap;
Scanner scan = new Scanner(System.in);
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:
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:
int year;
boolean leap;
Scanner scan = new Scanner(System.in);
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:
if (year % 4 == 0)
if (year % 100 == 0)
if (year % 400 == 0)
leap = true;
else
leap = false;
else
leap = true;
else
leap = false;
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.
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:
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.
See if yo u can determine which if statement co rrespo nds to the e lse statement in the fo llo wing co de:
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 .
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:
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).
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.
CODE TO EDIT:
public class Testing {
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:
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:
}
}
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.
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 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.*;
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);
}
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.*;
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;
}
}
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
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( ).
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.
CODE TO TYPE:
import java.applet.Applet;
import java.awt.*;
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.
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);
}
}
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!
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.
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.
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:
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
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
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
What is array1[4]?
What is array1[6 ]?
What is array1[8 ]?
class ArrayDemo {
public static void main(String[] args) {
int[] array1; // declares an array of integers
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).
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.
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:
CODE TO TYPE:
class ArrayDemo {
public static void main(String[] args) {
int array1[]; // declares an array of integers
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.
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 [];
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:
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.
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.
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.
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:
class Beatlejuice {
public static void main(String[] args) {
String[] beatles;
beatles = new String[5];
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:
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:
class Beatlejuice {
public static void main(String[] args) {
String[] beatles;
beatles = new String[5];
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:
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.
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:
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:
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
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
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
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.
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.*;
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!
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:
start
The beginning o f the f o r statement initializes the lo o p co unter variable, like this:
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:
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
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:
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.
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:
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!
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.
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 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;
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:
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;
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:
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;
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.
Instance Fields:
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:
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.
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.
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.
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.
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;
Observe: Co ntainers
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.
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.
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.
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;
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:
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.
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;
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?
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 :
class Test {
public static void main(String[] args) {
int[] testArray = new int[4];
System.out.println(testArray.getClass().getSuperclass());
}
}
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.
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
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:
See ho w the declaratio n o f the type o f array matches o n the left and right side?
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:
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.
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]);
}
}
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.
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.
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:
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:
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:
or
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.
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:
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.
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;
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:
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.
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.
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[][];
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;
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.
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.
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 }
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} };
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
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:
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:
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;
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.
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."
"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.
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;
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 {
CODE TO TYPE
class Test {
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.
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 :
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];
OBSERVE:
for (int i=0; i <= beatles.length; i++)
System.out.println("Element is : " + beatles[i]);
OBSERVE:
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);
}
}
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.
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:
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.*;
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
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 .
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.
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
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.
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.
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");
}
}
}
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.
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
}
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.
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");
}
}
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 :
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.
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 {
// method definition
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.
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.
class Test {
return currentHigh;
}
}
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.
CODE TO TYPE:
class Test {
Can yo u tell ho w many times it printed and why without the help o f running it? Let's trace it.
OBSERVE:
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.
CODE TO TYPE:
class Test {
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 {
CODE TO TYPE:
class Test {
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).
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);
}
}
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.
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);
}
}
OBSERVE:
public class testMe {
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 ).
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
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 ).
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.*;
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:
if/else>
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;
}
int currShape = 0;
...
switch (currShape)
{
case (SQUARE): statements; break;
case (CIRCLE): statements; break;
}
...
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; }
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.
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.