You are on page 1of 90

Comments

Computer programs are read by both computes and humans. You write Java instructions to
tell the computer what to do. You must also write comments to explain to humans what the
program does. Of course, Java can't understand them because they are written in English, or
Spanish, or hai, or ... .
Java ignores all comments. here is, however, a program called !avadoc which reads certain
"inds of comments and produces #$% documentation &see below'.
Spaces and blank lines
One of the most effective ways to ma"e a program readable is to put spaces in at "ey points. here
are several styles for doing this. Even more important is to put blan" lines in your program. hese
should separate sections of code. here should be a blan" line between each (paragraph( of code.
)y paragraph, * mean a group of statements that belong together logically+ there is no Java concept
of paragraph.
Java comments
// comments -- one line
,fter the two // characters, Java ignores everything to the end of the line. his is the most
common type of comment.
//--- local variables ---
int nquest; // number of questions.
int score; // count of number correct minus number
wrong.

/* ... */ comments -- multiple lines
,fter the /* characters, Java will ignore everything until it finds a */. his "ind of comment
can cross many lines, and is commonly used to (comment out( sections of code -- ma"ing
Java code into a comment while debugging a program. .or example,
/* Use comments to describe variables or sections of the
program.
They are very helpful to everyone who reads your programs:
your teacher your boss but especially yourself!
*/
javadoc comments
/omments that start with /** are used by the "avadoc program to produce #$%
documentation for the program. he Java documentation from Sun $icrosystems is
produced using !avadoc. *t is essential to use this "ind of comment for large programs.
Best Practices
0on't write comments to document obvious statements. ,ssume the reader "nows Java.
Every comment has the potential to create an inconsistency between what the comment
says, and what the code does. One cause of (software rot( is that code is changed over
time, but comments are not updated. o avoid this, "eep comments next to the code that is
documented so that they may be more easily synchoni1ed.
nteresting comments
Write Sweet-Smelling Comments by $i"e /lar".
Ota"u, /edric's weblog
Identifier Names
2etting the names of things right is extremely important. *t ma"es a huge difference in readability.
$any *0Es support refactoring, and specifically renaming. * will sometimes rename classes several
times before * hit on exactly the obvious name. *t's worth the effort.
!egal Characters
Every name is made from the following characters, starting with a letter3
%etters3 a-1, ,-4, and other alphabetic characters from other languages.
0igits3 5-6
Special3 7 &underscore'
8o names can be the same as a Java "eyword &eg, import, if, ...'.
"#amples
apple
his is a legal name. %owercase implies it's a variable or method.
#pple
his is a different legal name. 9ppercase implies it's a class or interface.
#$$%&
Yet a different legal name. ,ll uppercase implies it's a constant.
topleft
%egal, but multiple words should be camelcase.
top'left
)etter, but camelcase is preferred to 7 in Java.
top%eft
2ood Java style
top left
*%%E2,% - no blan"s in a name
import
*%%E2,% - same as the Java "eyword
$sing $ppercase% !o&ercase% and 'Camelcase' !etters
he conventions for the use of upper- and lowercase is not enforced by compilers, but it is so widely
observed, that it should have been. Camelcase is the practice of capitali1ing the first letter of
successive words in multi-word identifiers. /amelcase is much preferred in the Java community over
the use of underscores to separate words, or even worse, no distinction made at word boundaries.
Class and inter(ace names - Start &ith uppercase
/lass and interface names start with an uppercase letter, and continue in lowercase. .or
multiple words, use camelcase. Eg, 0irection, %ogical%ayout, 0ebug2apSpacer.
)ariable and method names - !o&ercase
%owercase is used for variable and method names. *f a name has multiple words, use
camelcase. Eg, top, width, top%eft, room:idth, income,fteraxes.
Constants - *ll uppercase% use + to separate &ords
he names of constants &typically declared static final' should be in all uppercase. .or
example, (order%ayout.)*+T,. :hen constant names are made from multiple words,
use an underscore to separate words, eg, -.rame.&/0T'*)'1%*2&
,eadable names are more important than most comments
Java doesn't care if your names are readable, but it's really important to ma"e your names readable
to humans.
* once wor"ed on a pro!ect where we had to distribute the source code so that it could be compiled
on another machine, but we didn't want to reveal our algorithms. :e deleted all comments and
indentation, and wrote a small program to change all variable names to combinations of (*(, (;(,
(O(, and (5(, figuring that it would be too much effort for them to decode it. .or example, the semi-
readable
%ogical3ap0nfo top(order 4
m'logical%ayout.get3ap0nfo5%ogical%ayout.#/02'6 78;
/ould be translated into
0779* 07707 4 *9779.*07795*9**0.0*797 78;
Packages and Import
Package - directory. Java classes can be grouped together in packages. , pac"age name is the
same as the directory &folder' name which contains the .!ava files. You declare pac"ages when you
define your Java program, and you name the pac"ages you want to use from other libraries in an
import statement.
Package declaration
he first statement, other than comments, in a Java source file, must be the pac"age declaration.
.ollowing the optional package declaration, you can have import statements, which allow you to
specify classes from other pac"ages that can be referenced without <ualifying them with their
pac"age.
.e(ault package. ,ltho all Java classes are in a directory, it's possible to omit the pac"age
declaration. .or small programs it's common to omit it, in which case Java creates what it calls a
default pac"age. Sun recommends that you do not use default pac"ages.
Package declaration synta#
he statement order is as follows. /omments can go anywhere.
;. =ac"age statment &optional'.
>. *mports &optional'.
?. /lass or interface definitions.
// This source file must be :rawing."ava in the illustration
directory.
package illustration;
import "ava.awt.*;
public class :rawing ;
. . .
<
mports/ three options
he JOptionPane class is in the swing pac"age, which is located in the javax pac"age. he wildcard
character &@' is used to specify that all classes with that pac"age are available to your program.
his is the most common programming style.
import javax.swing.*; // =a>e all classes visible altho only one is
used.
class 0mportTest ;
public static void main52tring?@ args8 ;
-*ption$ane.show=essage:ialog5null A,iA8;
2ystem.eBit578;
<
<
/lasses can be specified explicitly on import instead of using the wildcard character.
import javax.swing.JOptionPane; // =a>e a single class visible.
class 0mportTest ;
public static void main52tring?@ args8 ;
-*ption$ane.show=essage:ialog5null A,iA8;
2ystem.eBit578;
<
<
,lternately we can the fully <ualified class name without an import.
class 0mportTest ;
public static void main52tring?@ args8 ;
javax.swing.-*ption$ane.show=essage:ialog5null A,iA8;
2ystem.eBit578;
<
<
Common imports
here are ;AA pac"ages containing ?>B6 classes and interfaces in Java C. #owever, only a few
pac"ages are used in most programming. 29* programs typically use at least the first three
imports.
import "ava.awt.*;
/ommon 29* elements.
import "ava.awt.event.*;
he most common 29* event listeners.
import "avaB.swing.*;
$ore common 29* elements. 8ote (!avax(.
import "ava.util.*;
0ata structures &/ollections', time, Scanner, etc classes.
import "ava.io.*;
*nput-output classes.
import "ava.teBt.*;
Some formatting classes.
import "ava.util.regeB.*;
Degular expression classes.
import 0*1
;. 1/ .oes importing all classes in a package make my object (ile 2.class or .jar3
larger4
,3 8o, import only tells the compiler where to loo" for symbols.
>. 1/ s it less e((icient to import all classes than only the classes need4
,3 8o. he search for names is very efficient so there is no effective difference.
?. 1/ .oesn5t it provide better documentation to import each class e#plicitly4
,3 his shows good intentions, but ...
o *t's hard to remember to remove classes when they are no longer used, so the
import list is surprisingly often wrong. *t can seriously slow down reading because
unusual or unexpected class imports ma"e me loo" for that class, only to discover
that it must have been used in an earlier version.
o Explicit class imports permit accidentally defining classes with names that conflict
with the standard library names. his is very bad. 9sing (@( to import all classes
prevents this dangerous naming accident.
o *t's annoying to always update this list, altho if you use 8et)eans, fixing the list is
only a clic" away &see below'.
E. 1/ 5ve imported java.awt.*% &hy do also need java.awt.event.*4
,3 he wildcard (@( only ma"es the classes in this pac"age visible, not any of the
subpac"ages.
C. 1/ 6hy don5t need an import to use String% System% etc4
,3 ,ll classes in the java.lang pac"age are visible without an import.
A. 1/ s the order o( the imports important4
,3 8o. 2roup them for readability.
7etBeans creates packages by de(ault
he project name is used as the default pac"age name, but you can change it.
, directory F folder is created with this pro!ect name. his directory name is the name of
your pac"age.
, package declaration is automatically inserted into each new source file it creates.
:hen you build a main pro!ect, the double-clic"able .!ar file uses this
pro!ectFpac"ageFdirectory name.
7etBeans &ill create your imports
*f you forgot to write import statements, or don't remember which pac"age a class is in, no
problem. Just right clic" on the source file and choose ix !mports. *t will add all necessary import
statements.
Static imports in Java 8
Java C added an import static option that allows static variables &typically constants' to be
referenced without <ualifying them with a class name. .or example, after
import static "ava.awt.1olor;
*t would then be possible to write
1olor bac>ground 4 +&:;
instead of
1olor bac>ground 4 1olor.+&:;
,dding this (feature( wasn't the best idea because it leads to name pollution and confusion about
which class constants come from. Even Sun &see Deferences below' basically advises not to use itG
The Many Meanings of final
The final modifier can be applied to four Java constructs:
1. variables: a final variable can be set once and only once.
2. fields: a final field can also be set only once, by the constructor of the class which
defines it.
3. methods: a final method cannot be overridden nor hidden.
4. classes: a final class cannot be extended.
otice how usin! final is an entirely ne!ative act. The final "eyword wor"s by
subtractin!, limitin! default lan!ua!e mechanisms: the ability to override a method, to set
a variable or a field. The motivations behind usin! final fall into three broad cate!ories:
correctness, robustness, and finally performance.
Final Variables
# final variable can be set only once, allowin! you to declare local constants. $uch a
variable can be left un%assi!ned at the point of declaration, creatin! blank finals. &ut all
final variables must be assi!ned exactly once. 'inal variables come in handy in mostly
two situations: to prevent accidental chan!es to method parameters, and with variables
accessed by anonymous classes.
Final Parameters
The followin! sample declares final parameters:
public void do2omething5final int i final int "8
;
// ...
<
final is used here to ensure the two indexes i and " won(t accidentally be reset by the
method. )t(s a handy way to protect a!ainst an insidious bu! that erroneously chan!es the
value of your parameters. *enerally spea"in!, short methods are a better way to protect
from this class of errors, but final parameters can be a useful addition to your codin!
style.
ote that final parameters are not considered part of the method si!nature, and are
i!nored by the compiler when resolvin! method calls. +arameters can be declared final
,or not- with no influence on how the method is overriden.
Anonymous Local Classes
The second situation involvin! final variables is actually mandated by lan!ua!e
semantics. )n that situation, the Java compiler won(t let you use a variable unless it is
declared final. This situation arises with closures, also "nown as anonymous local
classes. .ocal classes can only reference local variables and parameters that are declared
final.
public void do2omething5int i int "8
;
final int n 4 i C "; // must be declared final
1omparator comp 4 new 1omparator58
;
public int compare5*b"ect left *b"ect right8
;
return n; // return copy of a local variable
<
<;
<
The reason for this restriction becomes apparent if we shed some li!ht on how local
classes are implemented. #n anonymous local class can use local variables because the
compiler automatically !ives the class a private instance field to hold a copy of each local
variable the class uses. The compiler also adds hidden parameters to each constructor to
initiali/e these automatically created private fields. Thus, a local class does not actually
access local variables, but merely its own private copies of them. The only way this can
wor" correctly is if the local variables are declared final, so that they are !uaranteed not
to chan!e. 0ith this !uarantee in place, the local class is assured that its internal copies of
the variables accurately reflect the actual local variables.
Final Fields
# final field can be assi!ned once and only once, and must be initiali/ed by every
constructor of the class that declares it. )t is also possible to assi!n the field directly, in
the same statement where it is defined. This simply reflects the fact that such shortcut
assi!nments are compiled into a synthetic constructor. 1.!. both the followin! code
samples are correct and strictly e2uivalent3 the first is preferred for bein! shorter.
public class =y1lass
;
private final int i 4 D;
<
public class =y1lass
;
private final int i;
public =y1lass58
;
i 4 D;
<
<
Declare Constants
4oupled with static, final is used to fla! constants. This usa!e is well%"nown to all
Java pro!rammers, so ) won(t expand much on it. )t is useful to "now that the value of a
field declared constant in that manner will be computed statically if possible, at compile%
time.
private static final int &++*+'1*:& 4 9 C E * F / D;
public static final 2tring &++*+'=&22#3& 4 A#n error occurred with
code4A C &++*+'1*:&;
The compiler will compute the value for &++*+'1*:&, concatenate the strin! e2uivalent
of the result, and assi!n the resultin! 2tring to &++*+'=&22#3&.
Aggregation vs. Acquaintance
)n the words of *amma et al.(s Design Patterns:
#!!re!ation implies that one ob5ect owns or is responsible for another ob5ect. *enerally
we spea" of an ob5ect having or bein! part of another ob5ect. #!!re!ation implies that an
a!!re!ate ob5ect and its owner have identical lifetimes.
#c2uaintance implies that an ob5ect merely knows of another ob5ect. $ometimes
ac2uaintance is called 6association6 or the 6usin!6 relationship. #c2uainted ob5ects may
re2uest operations of each other, but they aren(t responsible for each other. #c2uaintance
is a wea"er relationship than a!!re!ation and su!!ests much looser couplin! between
ob5ects.
)t(s easy to confuse a!!re!ation and ac2uaintance, because they are often implemented in
the same way. 7ltimately, ac2uaintance and a!!re!ation are determined more by intent
than by explicit lan!ua!e mechanisms. #!!re!ation relationships tend to be fewer and
more permanent than ac2uaintance. #c2uaintance, in contrast, are made and remade more
fre2uently, sometimes existin! only for the duration of an operation. #c2uaintances are
more dynamic as well, ma"in! them more difficult to discern in the source code.
#s it turns out, the Java lan!ua!e does offer an explicit mechanism to differentiate
a!!re!ation relationships from mere ac2uaitances: the ob5ect of this article, the "eyword
final. 7se it to fla! and ma"e explicit a!!re!ations. &ut why should this be important to
you8 The short answer is: to improve code quality.
Enforce Atomicity of Object Creation
9nce a field is determined to be an a!!re!ation of another ob5ect, and it is declared final,
an interestin! property emer!es. The a!!re!atin! ob5ect is !uaranteed to be created in
full, or it won(t be created at all3 either all final fields are initiali/ed successfully, or an
exception terminates the constructor.
$ay an ob5ect 4ar a!!re!ates another ob5ect 1n!ine, and therefore is defined as
absolutely re2uirin! an 1n!ine instance to function. :eclarin! the reference to the 1n!ine
as final ensures any 4ar instance is correctly initiali/ed in full ; or the constructor was
terminated abruptly by a thrown exception. The 4ar class doesn(t even compile without
the 1n!ine reference bein! initiali/ed.
public class 1ar
;
private final &ngine engine; // always has an engine
public 1ar58
;
engine 4 new &ngine58;
<
<
$imply by ta!!in! a field with final, we have 5ust created a very stron! condition on all
4ar instances: namely, they must have an 1n!ine to exist. This simple property can
dramatically raise the 2uality of your code, by enforcin! correct a!!re!ation relationships
between ob5ects. The ob5ect thus defined, and all its a!!re!ated dependents, always exists
in a stable state.
Declare Invariants
:esi!n by 4ontract is an effective pro!rammin! methodolo!y for desi!nin! robust
software components: by declarin! ,and verifyin!- conditions specific to a !iven
component, its behavior can be asserted correct, even at runtime. final is a !reat tool to
enforce field invariance: since final fields can only be set once, any attempt to reset their
value ,accidental or not- is detected by the compiler. This idiom is also of !reat help
durin! refactorin!: it catches refactorin! mista"es by actin! as a safe!uard a!ainst the re%
initiali/ation of a field.
# caveat applies here: if a final variable holds a reference to an ob5ect, the ob5ect may be
modified, in spite of it bein! final. This is because final only applies to the reference
holdin! the ob5ect, not the ob5ect itself. The final variable will always refer to the same
ob5ect, but the ob5ect itself may chan!e throu!h its methods.
This applies also to arrays and collections, because they are both ob5ects. )f a final
variable holds a reference to an array, then the components of the array may be chan!ed
by operations on the array, althou!h the variable will always refer to the same array. The
same restriction applies to collections as well. 1.!. a list may be declared final and thus
always exist as far as the a!!re!atin! ob5ect is concerned, its content is undetermined,
and can be chan!ed at will. 1lements can be added<removed from the collection, even
thou!h it is declared final.
For Performance
The revised memory model proposed by J$= 133 includes special provisions for final
fields, provisions that are absent from the existin! specification. ewer >?s already
implement this specification, and treat final fields accordin!ly. &ecause final fields are
assi!ned exactly once, a!!ressive optimi/ations in a multithreaded context become
possible. $pecifically, a field doesn(t need to be ever reloaded, since its value is
!uaranteed never to chan!e.
Conclusion on Final Fields
1xtensive use of final fields leads to a new and interestin! pro!rammin! idiom. &y
statically enforcin! field initiali/ation at construction time, ob5ects can be desi!ned to be
correct, fully initiali/ed, once their construction is complete. :oin! so is a simple yet
powerful way to increase both the correctness and robustness of a !iven ob5ect: since it
cannot fail to be correctly initiali/ed, subse2uent methods are free to deal with their own
processin!, and use whatever fields they need to do said processin!, without concern for
the correct initiali/ation se2uence of the ob5ect.
This idiom stron!ly relates to eager initialization: all fields are initiali/ed as soon as
possible, at construction, and never chan!ed once the initiali/ation phase is over. )n my
experience, developers shun ea!er initiali/ation because it is perceived as more expensive
than la/y initiali/ation. 6) don(t need this field until later, so let(s not bother with it now,6
their thin"in! !oes. 7nfortunately, this line of thin"in! leads to more complex code that
simply initiali/in! all fields ri!ht away. 1very usa!e of the field has to chec" whether the
field has been initiali/ed, and initiali/e it if it hasn(t. )t(s a"in to premature optimi/ation,
which, as we all "now, is the root of all evil.
4ompare the two followin! examples. 0hile it may loo" li"e a trivial transformation, in a
real class with potentially do/ens of fields, ea!er initiali/ation will clear up a lot of code
by removin! extraneous tests. &y declarin! all fields final, initiali/ation is !athered in
one place ,the constructor-, yieldin! simpler, more maintainable, code.
public class %aGy1ar
;
private &ngine engine; // laGily initialiGed
public void drive58
;
if 5engine 44 null8
;
engine 4 new &ngine58;
<
// ...
<
<
public class (etter1ar
;
private final &ngine engine 4 new &ngine58; // using final
public void drive58
;
// the engine is always present
// ...
<
<
Final Methods
# final method is implemented exactly once, in the declarin! class. $uch a method cannot
be overridden: subclasses cannot substitute a new definition for the method. ote that
either modifier private or static also implies final, which is therefore redundant,
when applied to methods. Private and static methods are always implicitely final, since
they cannot be overridden.
Enforce Invariant Code
The Template Method pattern declares an abstract method solely for the purpose of
overridin! it in a subclass. This allows the base class to dele!ate parts of an al!orithm to
subclasses. 'inal methods cannot be overridden, therefore they create an almost exact
anti%6template method6 pattern. &ut in fact, they are best used in con5unction with
template methods. &y specifyin! explicitely which parts of the al!orithm can vary ,usin!
abstract methods- and which cannot ,usin! final methods-, the class(s author conveys a
precise picture of the wor" expected by subclasses. 'inal methods are used with template
methods to declare the invariant parts of an al!orithm.
public abstract class #bstract(ase
;
public final void perform*peration58 // cannot be overridden
;
prepare.or*peration58;
do$erform*peration58;
<

protected abstract void do$erform*peration58; // must override
<
&e aware that final methods impose a very strict restriction on subclass implementors. )n
a framewor" context, thin" lon! and hard before declarin! methods final, as it will
severely limit the extensibility of the framewor", and the possibilities of adaptin! the
framewor" to situations unforeseen by the ori!inal developers.
For ecurity
)n Java all methods are by default overridable. 0hile this !ives maximum flexibility to us
pro!rammers, this liberal attitude can sometimes lead to conflictin! situations. .et(s loo"
at the *b"ect class for example. )t declares methods that certainly must be overridable:
*b"ect.equals and *b"ect.to2tring are two well%"nown examples. &ut *b"ect also
includes methods such as *b"ect.wait and *b"ect.notify ; system%level methods
which implement core lan!ua!e capabilities. )t simply cannot be allowed for
*b"ect.wait to be substituted by a different implementation. )t would alter the
semantics of the lan!ua!e itself.
'inal methods come to the rescue a!ain in this case: *b"ect.wait is declared final, and
therefore it cannot be chan!ed, accidentally or not. This reasonin! also applies to entire
J:@ classes, as discussed below.
For Performance!
$ince a final method is only implemented in the declarin! class, there is no need to
dynamically dispatch a call to a final method, and static invocation can be used instead.
The compiler can emit a direct call to the method, bypassin! entirely the usual virtual
method invocation procedure. &ecause of this, final methods are also candidates for
inlinin! by a Just%)n%Time compiler or a similar optimi/ation tool. ,=emember,
private<static methods are already final, therefore always considered for this
optimi/ation.-
$tatic invocation is faster than dynamic method loo"up, leadin! to the widespread use of
final methods as an optimi/ation techni2ue. &ut this 6optimi/ation6 is next to useless in
recent virtual machines: they are able to detect if a non%final method is overridden, and if
not, use static invocation. Therefore, final should be used first and foremost for sofware
en!ineerin! reasons, as discussed in the rest of this article.
Final Classes
# final class cannot be subclassed, or extended, in any way. 'inal classes can be re!arded
as a !enerali/ation of final methods: a final class has all its method declared final. 9n the
other hand, fields of a final class do not have any special property.
Enforce Com"osition over In#eritance
$ince final classes cannot be extended, the only way to reuse them is by composin! them
with other ob5ects. #nd encoura!in! that practice in your own code mi!ht prove very
healthy3 inheritance, while a powerful techni2ue that should not be dismissed, has it own
share of issues. )t introduces a very ti!ht couplin! between classes, sometimes leadin! to
the infamous Fragile Base lass problem . )t is also more complex, forcin! users to
bounce up and down a class hierarchy in order to understand what a !iven class does.
#nd finally, it can brea" encapsulation by allowin! less restrictive access to methods.
Thus final classes are used to enforce composition. This is particularly important with
core classes, classes that define the base functionality of a framewor". 0e loo" at this
case next.
For ecurity
9ne of the very best feature of the Java environment is its ability to dynamically load
classes. ecessarily, this flexibility comes at a price, includin! a more complex security
model. )f classes can be loaded dynamically, at any time, the virtual machine must be
able to enforce security policies on the runnin! code. 'inal classes are used in this context
to prevent malicious code from alterin! the semantics of classes essential to the
framewor".
The best "nown example of a final class is certainly "ava.lang.2tring. This class is so
vital to the operation of the Java compiler and interpreter that it must be !uaranteed that
whenever code uses a strin!, it !ets exactly a "ava.lang.2tring and not an instance of
some other class. &ecause "ava.lang.2tring is final, it cannot be subclassed, none of
its methods can be overriden, and therefore any 2tring instance is !uaranteed to always
behave the way it is intended.
Immutable Objects
) would li"e to conclude this article with a section about immutable ob5ects and what a
useful pattern they form.
#n immutable ob5ect is an ob5ect which state is !uaranteed to stay identical over its entire
lifetime. 0hile it is perfectly possible to implement immutability without final, its use
ma"es that purpose explicit, to the human ,the software developer- and the machine ,the
compiler-.
)mmutable ob5ects carry some very desirable characteristics:
they are simple to understand and easy to use
they are inherently thread%safe: they re2uire no synchroni/ation
they ma"e !reat buildin! bloc"s for other ob5ects
4learly final is !oin! to help us define immutable ob5ects. 'irst in labellin! our ob5ect
as immutable, which ma"es it simple to use and understand by other pro!rammers.
$econd in !uaranteein! that the ob5ect(s state never chan!es, which enable the thread%safe
property: thread concurrency issues are relevant when one thread can chan!e data while
another thread is readin! the same data. &ecause an immutable ob5ect never chan!es its
data, synchroni/in! access to it is not needed.
4reate an immutable class by meetin! all of the followin! conditions:
1. :eclare all fields private final.
2. $et all fields in the constructor.
3. :on(t provide any methods that modify the state of the ob5ect3 provide only !etter
methods ,no setters-.
4. :eclare the class final, so that no methods may be overridden.
A. 1nsure exclusive access to any mutable components, e.!. by returnin! copies.
Conclusion
) hope you have en5oyed this scrutiny of a sometimes for!otten feature of the Java
lan!ua!e. ?y references section lists additional resources useful to the reader ea!er to
"eep on learnin! about final and its uses.
if Statement - Overview
Purpose
he purpose of the if statement is to ma"e decisions, and execute different parts of your program
depending on a boolean trueFfalse value. ,bout 66H of the flow decisions are made with if. Ihe
other ;H of the decisions use the switch statement.J
9eneral 0orms
he if statement has this form, where condition is true or false.
... // Do these statements before.
if 5condition8 ;
... // Do this clause if the condition is true.
<
... // Do these statements after.
or
... // Do these statements before.
if 5condition8 ;
... // Do this clause if the condition is true
< else ;
... // Do this clause if the condition is false
<
... // Do these statements after.
"#ample - "valuateScore.java
his displays one of two messages, depending on an input value.
9
D
E
F
// :escription: &valuate a test score. 0llustrates if statement.
// .ile : if/&val2core."ava
// #uthor: .red 2wartG - D77H-7F-7I - $laced in public domain.
import "avaB.swing.*;
J
K
H
L
I
97
99
9D
9E
9F
9J
9K
9H
9L
9I
D7
D9
DD
DE
public class &val2core ;
public static void main52tring?@ args8 ;//... 0nput a score.
2tring score2tr 4 -*ption$ane.show0nput:ialog5null A&nter
your scoreMA8;
int score 4 0nteger.parse0nt5score2tr8;

//... 1reate a message.
2tring comment; // =essage to the user.
if 5score N4 K78 ;
comment 4 A)ot so badA;
< else ;
comment 4 AThis is terribleA;
<

//... *utput the message.
-*ption$ane.show=essage:ialog5null comment8;
<
<
0lo&chart representation o( if statement
he flow of execution in a program is sometimes represented by a flowc"art. .lowcharts are
sometimes a good way to outline the flow in a method, especially if it gets complex. hey may be
useful in user documentation, but most flowcharting is done in <uic" s"etches, which are thrown
away once the program is written.
.ecisions &if statements' are written in diamonds, and computational processes are written in
boxes. here are several styles, and here is one of the most common.
*lternate &ays to &rite the above if statement
here are lots of ways to write the above if statement. #ere are some.
;. Deverse the condition. :hich to put firstK here are two practices3 Either put the normal
case first, or the case that ma"es the boolean condition easiest to read.
D. 2tring comment; // =essage to the user.
E. if 5score O K78 ;
F. comment 4 AThis is terribleA;
J. < else ;
K. comment 4 A)ot so badA;
<
B. *nitiali1e the variable to a default value, and only change it if necessary. his is often used
when the condition is only rarely true.
L. 2tring comment 4 A)ot so bad; // =essage to the user.
I. if 5score O K78 ;
97. comment 4 AThis is terribleA;
<
;;. ),03 wo ifs. his is almost always a bad way to write an if-else. *t's confusing to read,
border values can slip through, and both conditions must be evaluated &inefficiency'.
9D. // (#: (#: (#: (#: (#: (#: (#: (#: (#:
9E. 2tring comment; // =essage to the user.
9F. if 5score O K78 ;
9J. comment 4 AThis is terribleA;
9K. <
9H. if 5score N4 K78 ;
9L. comment 4 A)ot so badA;
<
Brace style
*l&ays &rite braces. *t is good programming style to always write the curly braces, ;<, altho
they are not needed if the clause contains only a single statement. here are two reasons this is
good.
,eliability. :hen code is modified, the indentation is such a strong indicator of structure
that the programmer may not notice that the addition of a statement at the (correct(
indentation level really isn't included in the scope of the if statement. his is a suprisingly
common error.
,eadability. *t is faster to read code with the braces because the reader doesn't have to
"eep in mind whether they are dealing with an un-braced single statement or a braced
bloc".
#istor$. )races have been used in most language that have descended from ,lgol, including /, /L
L, Java, /M etc because language designers want to ma"e it easy for programmers in earlier
languages to ma"e the transition. )races are an annoying and error prone, and numerous
languages, eg, Nisual )asic and =ython, have tried to choose better notation.
'else' Not Required
5else5 is not re:uired
*t is not necessary to have the else part of an if statement. $aybe only C5H of the time there is
an else part.
0orm
he if statement without an else has this form3
if (condition) {
do this if the condition is true

"#ample
#ere is a paint1omponent58 method with an if statement without an else clause.
public void paint1omponent53raphics g8 ;
super.paint1omponent5g8; // draw bac>ground etc.
if 5mar>s O J78 ;
g.set1olor51olor.red8;
<
g.draw2tring5A2core 4 A C mar>s 97 J78;
<
:hen the paint1omponent58 method begins, the 2raphics context g uses /olor.blac" by default.
herefore there is no need to set the color to blac".
Braces are our friend
Braces { not re:uired (or one statement 2but are al&ays good3
*f the true or false clause of an if statement has only one statement, you do not need to use
braces &also called (curly brac"ets('. his braceless style is dangerous, and most style guides
recommend always using them.
Braceless (orm
he if statement doesn't need braces if there is only one statement in a part. #ere both the true
and false parts have only one statement3
// %egal but dangerous.
if 5condition8
Exactly one statement to execute if condition is true
else
Exactly one statement to execute if condition is false
"#amples sho&ing &hat can go &rong
* sample &ritten &ith braces.
//... 3ood style - 0ndented with braces.
2tring comment 4 A)ot so bad.A;
if 5mar>s O K78 ;
comment 4 AThis is terrible.A;
<
2ystem.out.println5comment8;
6ithout braces it5s still correct% but not as sa(e.
//... %ess good style - 0ndented but without braces.
2tring comment 4 A)ot so bad.A;
if 5mar>s O K78
comment 4 AThis is terrible.A;
2ystem.out.println5comment8;
:hat can go wrongK
1;/ 6hat does this 'legal' version print4
//... Phat does this printM
2tring comment 4 A)ot so bad.A;
if 5mar>s O K78;
comment 4 AThis is terrible.A;
2ystem.out.println5comment8;
,3 it always prints (his is terrible( because of that semicolo after the if clause. he semicolon
indicates an empty statement, which satisfies the compiler, but is surely not what you intended.
=utting a beginning brace after the if condition prevents programmers from also adding a semicolon
and creating this "ind of error.
1</ 6hat5s &rong &ith this4
So your program is wor"ing OO without the braces and you decide to add a grade. he compiler is
very happy with this, but you won't be. :hyK
//... Phat does this printM
2tring comment 4 A)ot so bad.A;
2tring grade 4 A#A;
if 5mar>s O K78
comment 4 AThis is terrible.A;
grade 4 A.A;
2ystem.out.println5AQour grade is A Cgrade8;
2ystem.out.println5comment8;
,3 ,lthough the comment will be appropriate to the score, the grade will always be (.(. ,lthough
the second grade assignment is indented, it isn't inside the if because the unbraced clause only
includes one statementG his appearance of being included is a ma!or source of programming
errors.
=ther Java constructions use braces
here are many "inds of Java statements that use braces to group things. You've already seen class
and met"od &eg, main' declarations, which enclose their contents in braces. *n addition to ifs, you'll
learn about loops &for, w"ile, and do', tr$...catc", and switc" statements which use braces to
enclose other statements.
'if' Statement - Indentation
ndent to make programs readable
here are several meathods to ma"e programs readable. #ow can you easily ma"e the reader see
which statements are inside the true part and false part of an if statement.
he best way to show this is to indent the statements that are inside. o do this you move the
statements to the right by a few spaces. =eople commonly use two, three, or four spaces. /hoose
one number &eg, * use > or ?', and use it for all programs.
Java doesn't care about your indentation -- it is for humans &including yourselfG'.
"#ample ; - 7o indentation - B*. B*. B*.
#ere is the paint1omponent58 method from a previous page without indentation. his is small,
so it's easy to see which statements are in the true and false parts. *f the if statement is much
larger, it will be unreadable without indentation.
public void paint1omponent53raphics g8 ;
super.paint1omponent5g8;
if 5mar>s O J78
g.set1olor51olor.red8;
else
g.set1olor51olor.blac>8;
g.draw2tring5A2core 4 A C mar>s 97 J78;
<
"#ample < - 7o indentation and no line breaks
Even a very short method is almost unreadable when you take out the line breaks and
spaces. Here is the same method:
public void paintComponent(Graphics g) {super.paintComponent(g);if
(marks<50) g.setColor(Color.red);else
g.setColor(Color.black);g.dra!tring("!core # " $ marks%&0%50);'
'if' Statement - if inside if
i( inside i(
You can put an if statement inside another if statement.
7earest 5else5
*f you use braces, there is no problem with deciding which else goes with which if .or example,
if 5age O DF8 ;
if 5height N D778 ;
c 4 1olor.+&:;
<
< else ;
c 4 1olor.(%U&;
<
)ecause the true and false parts are both single statements, you might be tempted to omit braces
and write3
if 5age O DF8
if 5height N D778
c 4 1olor.+&:;
else // :#)3&+: which RifR goes with this RelseR
c 4 1olor.(%U&;
)ut this is :DO82, because 'else' always goes with the nearest 'if' when there are no braces. his
code is the same as3
if 5age O DF8 ;
if 5height N D778
c 4 1olor.+&:;
else
c 4 1olor.(%U&;
<
*dvice/ *l&ays use braces on if statements
hese "inds of errors are very hard to find. his is another good reason to alwa$s use braces.
6atch out (or semicolons on your i( statements
:hy does the following code always say it thin"s the user is lyingK
2tring age2tr 4 -*ption$ane.show0nput:ialog5null A,ow old are youMA8;
int age 4 0nteger.parse0nt5age2tr8;
if 5age N 9D7 SS age O 78;
2ystem.out.println5A0 thin> youRre lying about your age!A8;
*t's the semicolonG if you put a semicolon directly after the condition in an if statement, Java
thin"s it's finished with the body of the statement. he indentation of the next line, which is so
important to human readers, is ignored by Java.
his is another error that's harder to ma"e if you always follow the condition by an opening brace.
'if' Statement - 'else if' stle
Series o( tests
*t is common to ma"e a series of tests on a value, where the else part contains only another if
statement. *f you use indentation for the else part, it isn't easy to see that these are really a series
of tests which are similar. *t is better to write them at the same indentation level by writing the if
on the same line as the else.
"#ample -- series o( tests - cascading i(s
his code is correctly indented, but ugly and hard to read. *t also can go very far to the right if there
are many tests.
if 5score O EJ8 ;
g.set1olor51olor.=#3&)T#8;
< else ;
if 5score O J78 ;
g.set1olor51olor.+&:8;
< else ;
if 5score O K78 ;
g.set1olor51olor.*+#)3&8;
< else ;
if 5score O L78 ;
g.set1olor51olor.Q&%%*P8;
< else ;
g.set1olor51olor.3+&&)8;
<
<
<
<
"#ample -- using 5else i(5 style (or (ormatting
#ere is the same example, using a style of writing the if immediately after the else. his is a
common exception to the indenting rules, because it results in more readable programs. 8ote that it
ma"es use of the rule that a single statement in one of the Java clauses doesn't need braces.
if 5score O EJ8 ;
g.set1olor51olor.=#3&)T#8;
< else if 5score O J78 ;
g.set1olor51olor.+&:8;
< else if 5score O K78 ;
g.set1olor51olor.*+#)3&8;
< else if 5score O L78 ;
g.set1olor51olor.Q&%%*P8;
< else ;
g.set1olor51olor.3+&&)8;
<
=ther languages
Some programming languages recogni1e this common construction with a special elseif "eyword.
,lthough it is hardly necessary, this "ind of small touch can ma"e a language a little nicer to use.
he Java language designers are very conservative about adding "eywords to the language, so
don't expect it.
switc! Statement - Overview
Purpose o( s&itch/ select one o( many possible statements to e#ecute
he if statement allows you to select one of two sections of code to execute based on a boolean
value &only two possible values'. he switch statement allows you to choose from many
statements based on an integer &including char' or enum value.
Synta# e#ample
Synta#
switc! 5expr8 ;
case c9:
statements // do these if eBpr 44 c9
"reak;
case cD:
statements // do these if eBpr 44 cD
"reak;
case cD:
case cE:
case cF: // 1ases can simply fall thru.
statements // do these if eBpr 44 any of cRs
"reak;
. . .
#efault:
statements // do these if eBpr !4 any above
<
S&itch key&ords
s&itch
he switch "eyword is followed by a parenthesi1ed integer expression, which is followed
by the cases, all enclosed in braces.. he switch statement executes the case corresponding
to the value of the expression. 8ormally the code in a case clause ends with a brea>
statement, which exits the switch statement and continues with the statement following the
switch. *f there is no corresponding case value, the default clause is executed. *f no case
matched and there is no default clause, execution continues after the end of the switch
statement.
case
he case "eyword is followed by an integer constant and a colon. his begins the
statements that are executed when the switch expression has that case value.
de(ault
*f no case value matches the switch expression value, execution continues at the default
clause. his is the e<uivalent of the (else( for the switch statement. *t is written after the
last case be convention, and typically isn't followed by brea> because execution !ust
continues out the bottom of switch if this is the last clause.
break
he brea> statement causes execution to exit to the statement after the end of the switch.
*f there is no brea", execution flows thru into the next case. .lowing directly into the next
case is almost always an error.
"#ample - ,andom comment
2tring comment; // The generated insult.
int which 4 5int85=ath.random58 * E8; // +esult is 7 9 or D.
switch 5which8 ;
case 7: comment 4 AQou loo> so much better than usual.A;
brea>;
case 9: comment 4 AQour wor> is up to its usual standards.A;
brea>;
case D: comment 4 AQouRre quite competent for so little
eBperience.A;
brea>;
default: comment 4 A*ops -- something is wrong with this code.A;
<
":uivalent i( statement
, switch statement can often be rewritten as an if statement in a straightforward manner. .or
example, the preceding switch statement could be written as follows. :hen one of a number of
bloc"s of code is selected based on a single value, the switch statement is generally easier to
read. he choice of if or switch should be based on which is more readable.
2tring comment; // The generated insult.
int which 4 5int85=ath.random58 * E8; // +esult is 7 9 or D.
if 5which 44 78 ;
comment 4 AQou loo> so much better than usual.A;
< else if 5which 44 98 ;
comment 4 AQour wor> is up to its usual standards.A;
< else if 5which 44 D8 ;
comment 4 AQouRre quite competent for so little eBperience.A;
< else ;
comment 4 A*ops -- something is wrong with this code.A;
<
.e(ensive programming
,lways include a default clause in your switch statement as a general policy of defensive
programming - assume there will be bugs in your code and ma"e sure they are caught.
6here to use s&itch4
he ability of switch to choose between many sections of code seems to ma"e it more powerful
than if. #owever, selecting sections of code depending on specific integer values turns out not to be
very common. *f you are handling specific coded values &eg, the number of the button that was
clic"ed in a JOption=ane', or processing characters &whose codes are treated li"e numbers', you
may find it useful.
"((iciency4 Some compilers can produce more efficient code for certain switch statements than
for e<uivalent if statements. * haven't bothered to test the Java compiler because, if there is a
speed difference, it would be extremely small and the choice between switch and if should be
based on readability.
Comments on s&itch
Java's switch statement, which was ta"en directly from /LL to increase its attractiveness to /LL
programmers, is not well loved.
7o ranges. *t doesn't allow ranges, eg case I7-977:. $any other languages do.
ntegers only. *t re<uires integers and doesn't allow useful types li"e String. $any other
languages do.
"rror-prone. *t is error-prone and a common source of bugs - forgetting brea> or
default silently ignores errors. Some languages have eliminated these dangerous
situations.
switc! "#ample - Random Insults
he following class could be
useful for generating
random insults in response
to erroneous user input.
Source code (ormatting.
Some of the cases are
formatted on a single line.
his is a common style when
they do similar short
actions. *t ma"es the switch
statements much easier to
read.
Separate model 2logic3 (rom user inter(ace. his program is separated into two classes3 one
contains the logic &or (model( as it's more often called' for generating an insult as a string. *t "nows
nothing about the user interface, and could e<ually well be used in a dialog program &as in the test
program below', console *FO, a 29* program, or a web-based application.
,andom nsult >odel
his is the logic of the program, and does no *FO so it would be e<ually suitable as the logic behind
a console program, 29* program, or web server program.
9
// .ile : flow-switch/insult/0nsult3enerator9."ava
D
E
F
J
K
H
L
I
97
99
9D
9E
9F
9J
9K
9H
9L
9I
D7
D9
DD
DE
DF
DJ
DK
DH
DL
DI
E7
E9
ED
EE
EF
EJ
// $urpose: 3enerates random insults.
// #uthor : .red 2wartG D77K #ug DE $laced in public domain
// 1omments: This switch statements were written in the
// most conservative style -- a default clause
// and no returns in them.
//
// The structure of the random generation is
// entirely in eBecutable code
// # much better way to write this is as a
// data-:riven program where this information is
// represented by data structures with a
// simple program to process the data.
//
// The data-driven style allows the data to be
// read in from user-editable files for eBample
// so the program need not be recompiled for changes.
public class 0nsult3enerator9 ;
//44444444444444444444444444444444444444444444 bad0nput0nsult
public static 2tring bad0nput0nsult58 ;
2tring insult;
switch 5rand5D88 ;
case 7: insult 4 APhat >ind of A
C info#d"ective58 C A A
C info)oun58
C A is this you A
C person#d"ective58 C A A
C person58
C AMA;
brea>;
case 9: insult 4 A)ever enter this >ind of A
C info#d"ective58 C A A
C info)oun58
C A again!!!!A;
brea>;

default:insult 4 A*ops -- bad switch statementA;
<
return insult;
<
//4444444444444444444444444444444444444444444444444444 person
private static 2tring person58 ;
2tring name;
switch 5rand5E88 ;
case 7 : name 4 AidiotA ; brea>;
case 9 : name 4 AimbecileA; brea>;
case D : name 4 AmoronA ; brea>;
default: name 4 Abad value from personMMMA;
<
return name;
EK
EH
EL
EI
F7
F9
FD
FE
FF
FJ
FK
FH
FL
FI
J7
J9
JD
JE
JF
JJ
JK
JH
JL
JI
K7
K9
KD
KE
KF
KJ
KK
KH
KL
KI
H7
<
//4444444444444444444444444444444444444444444 person#d"ective
private static 2tring person#d"ective58 ;
2tring ad";
switch 5rand5F88 ;
case 7 : ad" 4 AcluelessA; brea>;
case 9 : ad" 4 AwitlessA ; brea>;
case D : ad" 4 AstupidA ; brea>;
case E: ad" 4 AhopelessA; brea>;
default: ad" 4 Abad value from info#d"ectiveMMMA;
<
return ad";
<
//444444444444444444444444444444444444444444444 info#d"ective
private static 2tring info#d"ective58 ;
2tring ad";
switch 5rand5J88 ;
case 7: ad" 4 ArevoltingA ; brea>;
case 9: ad" 4 AinsultingA ; brea>;
case D: ad" 4 AmeaninglessA; brea>;
case E: ad" 4 AuselessA ; brea>;
case F: ad" 4 AidioticA ; brea>;
default:ad" 4 Abad value from info#d"ectiveMMMA;
<
return ad";
<
//44444444444444444444444444444444444444444444444444 info)oun
private static 2tring info)oun58 ;
2tring noun;
switch 5rand5F88 ;
case 7: noun 4 AnonsenseA; brea>;
case 9: noun 4 AcrapA ; brea>;
case D: noun 4 AswillA ; brea>;
case E: noun 4 AgarbageA ; brea>;
default:noun 4 Abad value from info)ounMMMA;
<
return noun;
<
//44444444444444444444444444444444444444444444444444444 rand
// Utility method to generate random numbers in range 7..bound-
9.
// 2tarting the range at Gero was simply to match the typical
// -ava ranges 5eg switch subscripts8 that start at Gero.
// +eturns random int in range 7...bound-9
private static int rand5int bound8 ;
return 5int8 5=ath.random58 * bound8;
<
<
H9
HD
HE
HF
HJ
HK
HH
HL
HI
L7
L9
LD
LE
LF
LJ
LK
LH
LL
LI
I7
I9
ID
IE
IF
IJ
IK
IH
IL
II
977
979
97D
97E
97F
97J
>ain program

9

D

E

F

J

K

H

L

I

97

99

9D

9E

9F

9J

9K

9H
// .ile : flow-switch/insult/TestTeBt3enerator9."ava
// $urpose: 2how some random insults.
// #uthor : .red 2wartG
// %icense: public domain
// :ate : D77K =ay E
import "avaB.swing.*;
public class TestTeBt3enerator9 ;
public static void main52tring?@ args8 ;
2tring display;
do ;
display 4 0nsult3enerator9.bad0nput0nsult58
C ATnTnPould you li>e another opinionMA;
< while 5-*ption$ane.show1onfirm:ialog5null display8 44
-*ption$ane.Q&2'*$T0*)8;
<
<
.ata-driven programming
,eplace methods &ith data structure4 his version is written with executable Java code. *t is
usually very desirable to replace executable code with some "ind of data structure. here are
several reasons for this.
0ata can be stored in user-editable files, which allows modifying the functioning of the
program without recompiling, or even having access to the source code.
Every line of code is a liabilityG Oeeping code small is a very good goal. *t loo"s li"e nothing
can go wrong here, but surely it will sometime when the program is updated.
Programming problems
;. =roblem &using arrays'3 2et rid of the methods, and replace them with arrays of strings.
You'll find it useful to define a method to choose a random element from an array of
Strings. o "eep this problem simple don't read the data in from files. *t might loo" li"e
D. private static 2tring choose+andom52tring?@ words8

?. =roblem &using $ap and .ile *FO'3 ,nother way to thin" about this problem is to have a
special syntax to denote something that should be replaced -- *'ll use (angle brac"ets( to
surround terms that should be replaced by a something that is dynamically generated. .or
example, the starting element could be the string (PinsultQ(.
he program would then loo" up the definition of (insult( in something li"e
,ash=apO2tring #rray%istO2tringNN and randomly choose one of the strings
from the array list. .or example, it might replace (PinsultQ( with (8ever enter this "ind of
Pinfo,d!Q Pinfo8ounQ againGGGG(
he program would then find each thing surrounded by angle brac"ets and replace it with a
randomly chosen values from its associated arrays. his process is repeated until all angle
brac"etted symbols have been replaced.
Dead data in from a file. One plausible format would be to have the the (meta-symbols(
start in column ;, and all possible definitions follow on lines that start with a blan". .or
example,
OinsultN
)ever enter this >ind of Oinfo#d"N Oinfo)ounN again!!!!
Phat >ind of Oinfo#d"N Oinfo)ounN is this you Operson#d"N
OpersonNM

Oinfo#d"N
revolting
insulting
meaningless
useless
idiotic
. . .
$oops - Introduction
he purpose of loop statements is to repeat Java statements many times. here are several "inds of
loop statements in Java.
&hile statement - ?est at beginning
he w"ile statement is used to repeat a bloc" of statements while some condition is true. he
condition must become false somewhere in the loop, otherwise it will never terminate.
//... Phile loop to build table of squares.
2tring result 4 AA; // 2tring(uilder would be more efficient.
int i 4 9;
while 5i O4 D78 ;
result 4 result C i C A squared is A C 5i * i8 C ATnA;
iCC;
<
-*ption$ane.show=essage:ialog5null ATables of squaresTnA C result8;
he following example has an assignment inside the condition. 8ote that (R( is assignment, not
comparison &(RR('. his is a common coding idiom when reading input.
//... #dd a series of numbers.
-*ption$ane.show=essage:ialog5null A&nter ints. 1ancel to endA8;
2tring val2tr;
int sum 4 7;
while 55val2tr 4 -*ption$ane.show0nput:ialog5null A)umberMA88 !4
null8 ;
sum C4 0nteger.parse0nt5val2tr.trim588;
<
-*ption$ane.show=essage:ialog5null A2um is A C sum8;
(or statement - Combines three parts
$any loops consist of three operations surrounding the body3 &;' initiali1ation of a variable, &>'
testing a condition, and &?' updating a value before the next iteration. he for loop groups these
three common parts together into one statement, ma"ing it more readable and less error-prone
than the e<uivalent w"ile loop. .or repeating code a "nown number of times, the for loop is the
right choice.
//... .or loop to build table of squares.
2tring result 4 AA; // 2tring(uilder would be more efficient.
for 5int i 4 9; i O4 D7; iCC8 ;
result C4 i C A squared is A C 5i * i8 C ATnA;
<
-*ption$ane.show=essage:ialog5null ATables of squaresTnA C result8;
do..&hile statement - ?est at end
:hen you want to test at the end to see whether something should be repeated, the do..w"ile
statement is the natural choice.
2tring ans;
do ;
. . .
ans 4 -*ption$ane.show0nput:ialog5null A:o it again 5Q/)8MA8;
< while 5ans.equals0gnore1ase5AQA88;
'(oreach' statement - Java 8 data structure iterator
Java C introduced what is sometimes called a (for each( statement that accesses each successive
element of an array, %ist, or Set without the boo""eeping associated with iterators or indexing.
//... 6ariable declarations.
-TeBt#rea nameTeBt#rea 4 new -TeBt#rea597 D78;
2tring?@ names 4 ;A=ichael =ausA A=ini =ausA<;
//... :isplay array of names in a -TeBt#rea.
for 52tring s : names8 ;
nameTeBt#rea.append5s8;
nameTeBt#rea.append5ATnA8;
<
Similar to the 5i(5 statement
here are three general ideas that you will see in many parts of Java.
Braces ;< to enclose multiple statements in the bod$.
ndentation to show the extent of the body clearly.
Boolean &trueFfalse' conditions to control whether the body is executed.
Scope o( loop indicated &ith braces @A
*f the body of a loop has more than one statement, you must put the statements inside braces. *f
there is only one statement, it is not necessary to use braces ;<. #owever, many programmers
thin" it is a good idea to al&ays use braces to indicate the scope of statements. ,lways using
braces allows the reader to relax and not worry about the special single statement case.
ndentation. ,ll statements inside a loop should be indented one level &eg, E spaces', the same as
an if statement.
'w!ile' Statement
Purpose - to repeat statements
he purpose of the while statement is to repeat a group of Java statements many times. *t's
written !ust li"e an if statement, except that it uses the while "eyword.
9eneral 0orm
he while statement has this form3
w!ile 5condition8 ;
statements to repeat while the condition is true
<
Condition is true or false
he value of condition must be true or false &ie, a boolean value'. *t is often a comparison
&see example below'.
"#ample/ !oop continues &hile the condition is true
public void paint1omponent53raphics g8 ;
super.paint1omponent5g8;
int count 4 7;
while 5count O J78 ;
g.draw%ine5D7 count*J L7 count*J8;
count 4 count C 9;
<
g.draw2tring5A%oop is finished. count4ACcount 97 E778;
<
his repeats the draw%ine&' call C5 times. he first time the while condition is tested, it is true
because the value of count is 5, which is less than C5. ,fter the statements in the body are done,
the while loop comes bac" to the top of the loop and ma"es the test again. Each time the value of
count is larger. .inally, count is C5, and the value of the condition will be false.
:hen the loop stops, the program continues with the statement after the end of the loop &the
draw%ine&' call'. his will display the string (%oop is finished. count4J7(.
"#ample &ith (lo&chart
he following shows some code and the e<uivalent flowchart.
int n 4 7;
int i 4 9;
while 5i O F8 ;
nCC;
iCC;
<
. . .
Bere is another e#ample o( code and an e:uivalent (lo&chart
int n 4 7;
int i 4 9;
while 5i O F8 ;
int " 4 9;
while 5"O4i8 ;
n C4 9;
"CC;
<
i 4 i C 9;
<
'for' $oop
Purpose
he for statement is similar to the w"ile statement, but it is often easier to use if you are counting
or indexing because it combines three elements of many loops3 initiali1ation, testing, and
incrementing.
9eneral 0orm
he for and e<uivalent w"ile statements have these forms.
for 5init-stmt; condition; next-
stmt8 ;
init-stmt;
while 5condition8 ;
body
<
body
next-stmt;
<
here are three clauses in the for statement.
;. he init-stmt statement is done before the loop is started, usually to initiali1e an iteration
variable.
2. he condition expression is tested before each time the loop is done. he loop isn't
executed if the boolean expression is false &the same as the while loop'.
?. he next-stmt statement is done after the body is executed. *t typically increments an
iteration variable.
"#ample - Printing a table o( s:uares
#ere is a loop written as both a w"ile loop and a for loop. .irst using w"ile3
int number 4 9;
while 5number O4 9D8 ;
2ystem.out.println5number C A squared is A C 5number * number88;
numberCC;
<
,nd here is the same loop using for.
for 5int number 4 9; number O4 9D; numberCC8 ;
2ystem.out.println5number C A squared is A C 5number * number88;
<
"#ample - Counting doubled characters
his code will loo" at each character in a string, sentence, and count the number of times any
character occurs doubled.
2tring sentence 4 ...;
int double1ount 4 7; // )umber of doubled characters.
// 2tart at second char 5indeB 98.
for 5int pos 4 9; pos O sentence.length58; posCC8 5
// 1ompare each character to the previous character.
if 5sentence.char#t5pos8 44 sentence.char#t5pos-988 ;
double1ountCC;
<
<
Summary
he for loop is shorter, and combining the intiali1ation, test, and increment in one statement ma"es
it easier to read and verify that it's doing what you expect. he for loop is better when you are
counting something. *f you are doing something an indefinite number of times, while loop may be
the better choice.
%or-eac! $oop
Purpose
he basic for loop was extended in Java C to ma"e iteration over arrays and other collections more
convenient. his newer for statement is called the en"anced for or for-eac" &because it is called this
in other programming languages'. *'ve also heard it called the for-in loop.
$se it in preference to the standard for loop if applicable &see last section below' because it's much
more readable.
Series o( values. he for-eac" loop is used to access each successive value in a collection of
values.
*rrays and Collections. *t's commonly used to iterate over an array or a /ollections class &eg,
,rray%ist'.
IterableE!. *t can also iterate over anything that implements the !terable%&' interface &must
define iterator58 method'. $any of the /ollections classes &eg, #rray%ist' implement
!terable%&', which ma"es the for-eac" loop very useful. You can also implement !terable%&' for
your own data structures.
9eneral 0orm
he for-eac" and e<uivalent for statements have these forms. he two basic e<uivalent forms are
given, depending one whether it is an array or an !terable that is being traversed. *n both cases an
extra variable is re<uired, an index for the array and an iterator for the collection.
0or-each loop ":uivalent (or loop
for 5type var : arr8 ;
body-of-loop
<
for 5int i 4 7; i O arr.length; iC
C8 ;
type var 4 arr?i@;
body-of-loop
<
for 5type var : coll8 ;
body-of-loop
<
for 50teratorOtypeN iter 4
coll.iterator58; iter.has)eBt58; 8
;
type var 4 iter.neBt58;
body-of-loop
<
"#ample - *dding all elements o( an array
#ere is a loop written as both a for-eac" loop and a basic for loop.
double?@ ar 4 ;9.D E.7 7.L<;
int sum 4 7;
for 5double d : ar8 ; // d gets successively each value in ar.
sum C4 d;
<
,nd here is the same loop using the basic for. *t re<uires an extra iteration variable.
double?@ ar 4 ;9.D E.7 7.L<;
int sum 4 7;
for 5int i 4 7; i O ar.length; iCC8 ; // i indeBes each element
successively.
sum C4 ar?i@;
<
6here the for"each is appropriate
,ltho the enhanced for loop can ma"e code much clearer, it can't be used in some common
situations.
=nly access. Elements can not be assigned to, eg, not to increment each element in a
collection.
=nly single structure. *t's not possible to traverse two structures at once, eg, to compare
two arrays.
=nly single element. 9se only for single element access, eg, not to compare successive
elements.
=nly (or&ard. *t's possible to iterate only forward by single steps.
*t least Java 8. 0on't use it if you need compatibility with versions before Java C.
"#ample& String reverse
he following program reverses a string in a very straightforward, but rather inefficient way. :hen
you learn about 2tring(uilder &or the e<uivalent 2tring(uffer', you can do this more
efficiently. )ut the purpose of this is to see how looping over a string wor"s.
7ested loops. here are two nested loops in the is program, the outer while loop reads more
input. he inner for loop gets every character from the input string starting at character 5.
9
D
E
F
J
K
H
// .ile : loops/reverse/+everse."ava
// $urpose: +everse a string using a loop.
// #uthor : .red 2wartG
// :ate : *ct DE D77J
// 1omments: (uilding a 2tring one character at a time
// is very inefficient because it requires
// creating a new ob"ect for each concatenation.
// 2tring(uilder is better and it already
// has a reverse58 method!
import "avaB.swing.*;
L
I
97
99
9D
9E
9F
9J
9K
9H
9L
9I
D7
D9
DD
DE
DF
DJ
DK
DH
DL
DI
E7
E9
public class +everse ;
public static void main52tring?@ args8 ;
2tring input; // Used for the input string.
2tring reversed; // +eversed form or the input string.
while 5true8 ;
input 4 -*ption$ane.show0nput:ialog5null A&nter a
stringA8;
if 5input 44 null8 brea>;
reversed 4 AA;
for 5int i47; iOinput.length58; iCC8 ;
reversed 4 input.substring5i iC98 C reversed;
<
-*ption$ane.show=essage:ialog5null A+eversed:TnA C
reversed8;
<
<
<
6hile loop vs 0or loop
Counting. , for loop is preferred to a while loop when counting through a series of numbers --
in this case all character positions in a string.
":uivalent. , for loop has the same condition as the e<uivalent while loop, but also
incorporates an initiali(ation, which would be before the while statement, and the increment,
which would be at the end of the while body. You can write the loop either way, but putting the
initiali1ation, condition, and increment in one statement increases the readability.
0or loop 6hile loop
for 5int i$%; iOinput.length58; i&
&8 ;
reversed 4 input.substring5i
iC98 C reversed;
int i $ %;
while 5iOinput.length588 ;
reversed 4 input.substring5i
iC98 C reversed;
< i&&;
<
* single character - String or char4
his program uses substring5...8 to get a single character. *t would be more efficient to use
char#t5...8, which returns a single primitive char value.
for 5int i$%; iOinput.length58; i&&8 ;
reversed 4 input.c!ar't(i) C reversed;
<
'ssertions
*ssertions are used to stop e#ecution &hen 'impossible' situations are
detected
mpossible conditions. =rogram debugging is filled with (impossible( problems &()ut that
parameter can't possibly be null('. *f you're luc"y, the problem is detected immediately in some way
you can easily diagnose. *f not, the error may propagate thru the program, finally crashing, but so
far from the original bug that diagnosis is difficult. Even worse, the bug may not produce visible
symptoms until after it has altered permanent data. ,ssert statements provide an easy means to
chec" for impossible conditions, with little or no runtime cost.
Programmer% not user problems. he purpose or asserts is to detect programming errors, and
they should not be used in the case of erroneous user input or actions.
Crash as :uickly as possible. 0iscovering bugs as early as possible is good. Every program starts
with bugs, and the debugging process is faster and simpler when the bugs are detected early. *t's
better to discover a problem at compile time than at run time, and it's better to discover a run-time
bug as early as possible. Often a run-time bug doesn't cause an immediate, visible, disaster.
*nstead, the conse<uences of the bug distort the following execution, and the bad effects may not
become visible for a long time. he crippled program may corrupt files or have other bad
conse<uences. racing symptoms bac" to the original cause can be a long, tedious process. he
goal is to detect bugs as early as possible. ,ssertions provide a relatively painless way to stop many
bugs before they go too far.
?&o (orms o( the assert statement.
$sual (orm
,n assert statement has two parts separated by a colon. he boolean condition must be
true for execution to continue. *f it is false, an #ssertion&rror is thrown, which
terminates execution and display the message string. Some examples.
assert "obUueue.siGe58 44 7 : Aprocess(: queue should have been
empty.A;
assert connector !4 null : Amerge: 1onnector null for A C rel;
:hen asserts are enabled &more on that below', the assert statement chec"s the condition
&<ueue empty, connector is not null, etc' which must be true for the program to function
correctly.. *f it's true, execution continues. *f it's null, an exception containing the message
is thrown. his message is for the programmer, so it doesn't have to be user friendly. *
typically include the name of the method and sometimes other information that will help
ma"e sense of the error.
*bbreviated (orm
he simplest form the assert statement specifies only a boolean expression that must be
true. his is OO when there's not much to say, or the li"elihood of failing seems so remote
it isn't worth the extra typing.
assert n N 7;
Bo& to (igure out i( assertions are turned on
ry this program to see if assertions are turned on.
9
D
E
F
J
K
H
L
I
97
99
9D
9E
9F
9J
9K
9H
9L
9I
D7
/** flow-assertion/#ssertTest."ava - test assertions.
* Vauthor .red 2wartG
* Vversion 9.79 D77J-97-7E
* 1ompile: "avac #ssertTest."ava
* +un : "ava -ea #ssertTest
*/
class #ssertTest ;
//44444444444444444444444444444444444444444444444444444444444
main
public static void main52tring?@ args8 ;
// The following assert statement will stop eBecution
// with a message if assertions are turned on.
assert false ( )'ssertions are turne# on.);
// The following statement will only be printed if
// assertions are turned off because assertions
// were not allowed at run time by the -ea parameter.
2ystem.out.println5A#ssertions are not active.A8;
<
<
?est (or consistency
One path to early bug detection is to test variables to see if they have expected values. *f
something is wrong, the program can stop and indicate that an unexpected inconsistency was
discovered. %ater, when the program is released, this chec"ing may either be disabled to increase
speed, or left in if a (crash( is better than uncontrolled bug propagation &usually the case'. *f the
chec"ing code is removed or disabled, it should be reinserted or activated during testing all future
updates. :riting chec"ing code can be a ma!or headache, so it isn't done in many cases. he
assert statement ma"es testing conditions relatively easy, and allows easy activation or
deactivation of some or all of the chec"ing code.
Check (or 'impossible' conditions% not bad input
assert shouldn't be used for chec"ing for bad input. *nput should be chec"ed by code that gives
the user a meaningful response and perhaps a chance to correct the input.
,ssertions are used to chec" for things that can't possibly be wrongG his is what bugs are -- things
that shouldn't happen do happen because there is something wrong with the code. ,ssertions are
often used in the following cases.
/hec" situations which must be true, but aren't obviously so. .or example, the result of a
complicated calculation must be in a certain range.
,ll switch statements should have default clauses. *f this path is impossible, use an
assert that will always fail.
default:
assert false: AQou shouldnRt be here!A
,dd an assert where control should never flow, eg, when loo"ing up and returning an entry
that (must( be in an array, the code after the loop should never be executed. =ut an
assert false: Asome messageA there.
here is less of a need to chec" conditions which produce immediate execution errors. .or
example, there is no need to chec" if an array reference is null when the array is used
immediately after that, because a 8ull=ointerException would stop execution. ,n assert
would allow a better error message, and you must decide if the extra code is worth the
better error diagnostic. *n many cases the answer is (no(.
"nabling assertions &hen running in 7etBeans or ?e#tPad
,ssertion chec"ing defaults to off at runtime, unfortunately. You should always turn them on.
See 8et)eans E.; *0E for how to enable assertions. his also applies to the 8et)eans C beta
version.
See the ext=ad Editor description for how to enable assertions.
Shouldn5t runtime assertion checking de(ault on4
;. Some argue that a production program should not have the overhead of evaluating asserts.
,sserts are not slow, but there is some cost. *f they are not turned on at at execution time,
the class loader actually strips out all the assertion code so they really don't ta"e up any
time or memory. )ut this small amount of time is surely unnoticeable in all but the most
critical tas"s.
>. he user may be presented with an unfamiliar error message. his seems li"e an especially
bad argument. 0oes the user really prefer bad results to a strange error messageK
:hy don't the same people that want assertion chec"ing to default off also want subscript chec"ing
to default offK
Be(ore Java 8
he assert statement was added to Java in version ;.E, but it didn't default on for the compiler
until version C. You have to explicitly turn it on in Java ;.E by specifying the (-source ;.E( option to
the compiler.
"#ceptions
Exceptions S Exception 9sage S Exceptions - $ore
Java thro&s an e#ception
:hen your program causes an error, Java thro&s an e#ception. Java then t"rows this exception
to a part of the program that will catch it. You shouldn't try to catch most exceptions, but you
should catch all exceptions that are caused by events which you have no control over - exceptions
caused by bad user input or *FO problems.
Processing an e#ception
:hen an exception is thrown, execution of that statement stops immediately and Java loo"s for
someone to catch the exception.
1. *t loo"s to see if the code that caused the exception is inside a try statement that can
handle the exception. *f the try statement has a catch clause that can handle this type of
exception, then it goes to that code. ,fter catch clause is executed, execution resumes after
the end of the entire try statement. *t's not possible to return to the point at which the
exception was thrown.
2. *f there is no try statement around the code that threw the exception, Java goes up the
call stac" and loo"s at the statement that called this method, and chec"s for a try
statement surrounding the call. *f it finds an enclosing try statement that has a catch clause
for this "ind of exception, the catch clause is executed and then execution continues after
that try statement. Java continues moving up the call stac" until it finds an enclosing try
statement.
?. *f no enclosing try statement and catch clause is found, the exception is caught by the
initial Java system method that called main initially. *t prints an error message and
terminates the program.
tr*...catc! statement catches e#ceptions
=ut a try...catch statement around any section of code that might generate a user generated
exception &eg, converting text field input to numbers'. he simplest form is3
try ;
. . . // )ormal statements that might cause a problem
< catch 5exception-name parameter-name8 ;
. . . // 2tatements to eBecute if exception-name occurred.
<
"#ample
*f the user types an illegal value into a Jext.ield that expects an integer &eg, (;>?TEC(',
attempting to convert with 0nteger.parse0nt will throw a )umber.ormat&Bception.
tBt 4 aTeBt.ield.getTeBt58;
try ;
. . . // other code
i 4 0nteger.parse0nt5tBt8;
. . . // process the input
catch 5)umber.ormat&Bception nfe8 ;
aTeBt.ield.setTeBt5A&nter an integerA8;
<
"#ception (sage
Exceptions Exception 9sage S Exceptions - $ore
Common "#ceptions ?o Catch
he most common exceptions to catch are number conversion exceptions and *FO exceptions. #ere
are some common exceptions to catch3
&xception Cause
)umber.ormat&Bception
You tried to convert a number from an illegal String form.
0nput=ismatch&Bception
, Scanner method, eg neBt:ouble58 will throw this exception
when the next input text is not the right type, eg double.
0*&Bception
/atch an *OException to get either of its subclasses below.
.ile)ot.ound&Bception
he specified file didn't exist.
&*.&Bception
ried to read past end of file.
=alformedU+%&Bception
his can be generated if you are using the !ava.net pac"age.
Suggestions (or catching e#ceptions
( you catch an e#ception% do something. .on5t silence e#ceptions.
Some programs catch exceptions, then do nothing with them. his is almost always a
mista"e, and the underlying error should be fixed.
here are a few cases where you might want to silently ignore an exception. .or example,
changing the %oo" and .eel of the 29* may cause an exception. here's nothing to be done
about it, so you don't want to stop execution. .or example, * sometimes use the %i<uid loo"
and feel, and have this code.
try ;
U0=anager.set%oo>#nd.eel5new
net.sourceforge.nap>inlaf.)ap>in%oo>#nd.eel588;
< catch 5&Bception e8 ;
// 2ilently ignore -- thereRs nothing to be done.
<
,nother example where exceptions are typically ignored is in calls to sleep.
try ;
Thread.sleep5:&%#Q8;
< catch 50nterrupted&Bception ignored&Bception8 ;
// 2ilently ignore. This thread can never cause an
eBception.
<
*f you do silently ignore exceptions, enclose onl$ one call in the try clause+ do not use
larger bloc"s of code as suggested below. Dather than silently ignoring exceptions, consider
logging them to a file.
Put larger blocks o( code in a tr* clause
,ltho an exception is generated by a single statement, an entire bloc" of code is usually
affected. *t is often better to put the try around the bloc", not !ust single statements.
.on5t catch e#ceptions that you can5t really do anything &ith
*f you can't do anything useful, don't catch an exception. %et someone higher up catch it.
"#ception handling is usually slo&
*t is generally not a good idea to use exception handling mechanism instead of simple if
tests because throwing and catching exceptions is typically much slower.
Catch and rethro& e#ceptions to clean up
*f your code has to clean up something &eg, close files, put a data structure into a
consistent state, ...', it can catch exceptions, do the cleanup, and then rethrow the
exception.
Printing the call stack
.or debugging purposes you can print a trace of the current call stac".
e.print2tac>Trace58;
"#ceptions - )ore
=rev3 Exception 9sage 8ext3 hrowing Exceptions
Cinds o( "#ceptions
here are many exceptions, but they can be put into two groups3 chec"ed exceptions and
unchec"ed exceptions. here is some controversy about which type you should use. , discussion of
some of the issues can be found at Java theory and practice3 he exceptions debate.
$nchecked "#ceptions -- hese exceptions are usually something that should have been
prevented by more careful programming. .or example, you should never get
)ull$ointer&Bception or #rray0ndeB*ut*f(ounds&Bception. *f you do, there
is something wrong with your program, and you need to fix it. Dou usually don5t catch
unchecked e#ceptions. *nstead, fix your program so it can't produce one of these.
#owever, )umber.ormat&Bception is the one exception of this type that is usually
caught.
Checked "#ceptions -- hese are usually errors in the input data. he programmer has no
control over the input the user gives you, eg, file names, .... *f the user gives you a bad
value, it may cause an exception when you use it. Dou need to check (or bad input
using a tr* statement.
$se e#ceptions (or e#ceptional conditions% 7=? normal control (lo&
=robably most of your student programming has been (#appy rails( style, where you didn't have to
worry much about handling errors. )ut error handling is really a big deal in most real programs, and
exceptions play a central role in dealing with errors.
,ll experienced programmers agree that using exceptions for normal processing flow is wrong.
Exceptions should only be used only for errors or unusual conditions, and the e<uivalent if tests
should be used for normal processing. here are good reasons for this.
Slo&. Exceptions are ver$ slow. :hen an exception occurs, the Java runtime system wor"s
its way up the call stac" &you might be surprised at how deep this can get', identifying each
source statement at which a call was made, and building a string that reports this. his
string is then used in creating the exception ob!ect that is t"rown. his is not fast.
,eadability. Experienced programmers expect exceptions to have something to do with
errors, so it is very uncomfortable to read code where it is used for normal flow. ,
programmer has to stop and examine the code in the try clause to see what might have
caused the exception.
#ere are examples where beginning programmers used exceptions, but should 8O have. hese are
all done to either speed execution &which they do not' or simplify code &which they arguably do
not'.
"#ample/ ?est (or end o( array inde# range
9ood B*.
int?@ a 4 new int?9777@;
for 5int i47; i O a.length; iC
C8 ;
a?i@ 4 i;
<
You might wonder how inefficient this is
because the loop must compare the index with
the array si1e ;555 times, but only the final
test is important. )ecause Java always chec"s
the subscript range anyway, why not ma"e
use of its chec"K
int?@ a 4 new int?9777@;
try ;
for 5int i47; ; iCC8 ; // )o
range chec>.
a?i@ 4 i;
<
< catch
5#rray0ndeB*ut*f(ounds&Bception e8 ;
<
Exceptions are so slow that this won't be faster
unless the array is extremely large &much, much
larger than ;555'.
*voiding edges in looking (or adjacent array cells.
Problem3 You must invert the values in a cell in a rectangular grid and its non-diagonally ad!acent
cells. he difficulty is in dealing with the edge cases, where you must avoid referencing non-existent
ad!acent cells.
?&o alternate de(initions of a method are given, one uses exceptions and the other uses if to
handle the boundary violation cases. he exception solution is very inefficient and might be very
hard to interpret by the reader. he difficulty is increased because the writer chose to use the
&xception class instead of )rra$!ndexOutOf*ounds&xception. he use of &xception suggests that it
is designed to catch other exceptions too. if the body of the tr$ had been larger, it might have been
very difficult decide exactly which exception is being caught. 0o you see which other exception
could be thrown by the code, at least in principleK
private boolean?@?@ cell 4 new boolean?20W&@?20W&@;
. . .
// (#:
public void flip#5int row int col8 ;
cell?col @?row @ 4 !cell?col@?row@;
try ; cell?colC9@?row @ 4 !cell?colC9@?row @;< catch5&Bception e8
;<
try ; cell?col-9@?row @ 4 !cell?col-9@?row @;< catch5&Bception e8
;<
try ; cell?col @?rowC9@ 4 !cell?col @?rowC9@;< catch5&Bception e8
;<
try ; cell?col @?row-9@ 4 !cell?col @?row-9@;< catch5&Bception e8
;<
<
// =uch better 5faster and less worrisome to the normal reader8
public void flip(5int row int col8 ;
cell?col @?row @ 4 !cell?col @?row @;
if 5col O 20W&-98 cell?colC9@?row @ 4 !cell?colC9@?row @;
if 5col N 7 8 cell?col-9@?row @ 4 !cell?col-9@?row @;
if 5row O 20W&-98 cell?col @?rowC9@ 4 !cell?col @?rowC9@;
if 5row N 7 8 cell?col @?row-9@ 4 !cell?col @?row-9@;
<
*nother solution to avoid edge cases is to define extra rows and columns of boundary cells, and
translate the subscripts, thereby replacing the if tests with two additions. his re<uires translating
subscript references in all methods. *f the class is properly encapsulated, users of the class will not
"now about it.
private boolean?@?@ cell 4 new boolean?20W&&+@?20W&&+@;
. . .
public void flip15int r int c8 ;
int row 4 r & ,;
int col 4 c & ,;
cell?col @?row @ 4 !cell?col @?row @;
cell?colC9@?row @ 4 !cell?colC9@?row @;
cell?col-9@?row @ 4 !cell?col-9@?row @;
cell?col @?rowC9@ 4 !cell?col @?rowC9@;
cell?col @?row-9@ 4 !cell?col @?row-9@;
<
=ther e#amples
here are numerous cases in addition to subscription where the use of exceptions is entirely
inappropriate.
.anger (rom the intermediate layers - finall*
Exceptions provide a good infrastructure for error processing. he simplicity of throwing an
exception at a deep level and catching it at a high level may generate problems at the intermediate,
s"ipped, levels. 0id any of these methods leave any part of a data structure or resource in an
inconsistent stateK Each place that this may be true of needs to enclose critical code in a
try...finally bloc".
,e(erences
&xception-#andling )ntipatterns by im $c/une,
today.!ava.netFpubFaFtodayF>55AF5EF5AFexception-handling-antipatterns.htm, is a good
article if you're ready for some advanced exception usage.
+"ree ,ules for &ffective &xception #andling by Jim /ushing,
http3FFtoday.!ava.netFpubFaFtodayF>55?F;>F5EFexceptions.html, has some useful (rules(,
but even more useful is the list of lin"s what was posted in response to this article.
*!rowing "#ceptions
=rev3 Exceptions
?hro&ing prede(ined e#ceptions
*t's common to test parameters of methods or constructors for legality. )ut if the value is illegal,
what should you doK *f your class is designed to be called by other, you should define your own
exceptions, so you can document the errors for them more easily.
)ut if your methods are only being called by your own code, you can either use an assert or throw
an exception. * often use something li"e the following, supplying a comment with the class, method,
and meaningful comment.
if 5age O 78 ;
throw new
-llegal'rgument.xception5A$hysical&Bam.scale(lood$ressure: age is
negativeA8;
<
8ote that this shouldn't be used for illegal user input -- that should have been chec"ed in the
interface. his should only be thrown if there is a programming error. Only the programmer should
see this exception.
.e(ining your o&n e#ceptions
You can also create your own exceptions. I8ot yet writtenJ
.e(ine library e#ceptions to tell programmer they should (i# their code
*f you write a library that is used by others, throw your own exceptions if your code is called with
illegal values, eg, something isn't initiali1ed. Your exceptions are a way to tell the applications
programmer that they should fix their code.
)et!ods + - Introduction to
met!ods
Purpose o( this lesson3
)asic purpose of methods.
erm3 call R Execution proceeds to the code in a method.
erm3 return R Execution of a method finishes and then continues after point of call,
possibly using a value form the method.
erm3 static met"od R $ethod re<uiring no extra ob!ect.
erm3 instance met"od R $ethod that operates on the ob!ect before the dot.
7e& Java language (eatures
Static call syntax3 class(ame.methodName5 arguments 8
*nstance call syntax3 ob)ect.methodName5 arguments 8
Basic idea - * named group o( statements - )erbs
)y now you have used a lot of the predefined library methods, and written many main methods.
his chapter explains methods in more detail.
Java statements are grouped together in met"ods. Each method must be inside a class. Every
method has a name, which starts with a lowercase character and typically is a verb because it does
something.
=ther terms3 he idea of met"od is in every programming language, but different terms are used
in many languages. You might have seen terms li"e function, procedure, or subroutine. :e'll use
met"od consistently here, but you will hear programmers using these e<uivalent terms occasionally.
Business analogy - services provided by an organiEation
You could thin" of classes as corresponding to departments in an organi1ation, and methods as
being the services they provide. %et's ta"e an example of calling the telephone information service
to get someone's phone number. :hen you ma"e the call, you pass information, the name of the
person whose number you want, to the method &information service'. his called (method( then
does something, and returns a value to you &the desired phone number'. Just as you don't have to
"now how the information service performs its !ob, you typically don't need to "now exactly how a
method does its wor", unless of course, you are writing it.
Bierarchical organiEation. /omputer programs are structured in many ways li"e an organi1ation
-- higher levels rely on others to do much of the wor". hey (call( on lower levels to do the wor",
passing them all necessary (arguments(. *n a similar way, the top level of a computer program,
main, often consists largely of method calls, and those methods may in turn call on yet other
methods.
?erms/ call and return
Call. :hen a method call is encountered in a program, the program remembers where it was and
execution goes to the method &calls the method'. ,fter a small amount of initiali1ation, the
statements in the method are executed starting at the beginning.
,eturn. :hen the end of the method is reached or a return statement is executed, the method
returns to the where it was called from, and execution continues in the calling method from that
point. , method may return a value &eg, parse:ouble' or not &show=essage:ialog'. he call-
return terminology is almost universal.
Static 2class3 methods
Static. his starts with static &also called class' methods because all applications start with the
static method main, and many of the early library methods that you use are static methods. Static
methods are different than instance methods because they don't have an extra ob!ect passed to
them.
nstance methods are associated with an ob!ect &an (instance( of a class'.
denti(ying methods
Parentheses (ollo& name. You can identify a method name because it is always followed by left
and right parentheses, which may enclose arguments &parameters'. *f you see a left parenthesis
with a name preceding it, it will be a method call or definition, or a constructor &constructors are
very similar to methods'. *n the following example each method name is highlighted.
:hen calling methods outside of the current class, eg, in the Java library, static methods are
preceded by the class name &followed by a dot', and instance methods are preceded by an ob!ect.
:hen a static method is defined, the "eyword (static( will preceded it. he example below has only
static methods.

9

D

E

F

J

K

H

L

I

97

99

9D

9E

9F
// .ile : methods/XmTo=iles."ava
// $urpose: 1onvert >ilometers to miles. Use -*ption$ane for input /
output.
// #uthor : .red 2wartG
// :ate : DD #pr D77K
import "avaB.swing.*;
public class XmTo=iles ;
//444444444444444444444444444444444444444444444444444444444444
constants
private static final double =0%&2'$&+'X0%*=&T&+ 4 7.KD9;

//44444444444444444444444444444444444444444444444444444444444444444
main
public static void main52tring?@ args8
; //)ote 9
//... %ocal variables
2tring >m2tr; // 2tring >m before conversion to double.
double >m; // )umber of >ilometers.
double mi; // )umber of miles.
//... 0nput
>m2tr 4 -*ption$ane.s!ow-nput/ialog5null A&nter
>ilometers.A8;
>m 4 :ouble.parse/ou"le5>m2tr8;
//... 1omputation
mi 4 >m * =0%&2'$&+'X0%*=&T&+;
//... *utput
-*ption$ane.s!ow0essage/ialog5null >m C A >ilometers is A
C mi C A miles.A8;
<

9J

9K

9H

9L

9I

D7

D9

DD

DE

DF

DJ

DK

DH

DL

DI

E7
<
7otes
;. his defines a method called (main(. Everything between the (U( on the end of this line to
the matching (V( second from the end is the (body( of the method.
he above code defines the static main method, which someone &eg, the operating system' will call
with XmTo=iles.main5. . .8.
o do its wor", main calls on other methods3 show0nput:ialog, which is defined in the
-*ption$ane class, parse:ouble, which is defined in the :ouble class, and
show=essage:ialog, which is also in the -*ption$ane class.
:henever you call a static method in a different class, precede it with the name of the class
containing its definition, followed by a dot. *f you don't specify the class name, it assumes the
method is defined in the current class.
denti(ying instance methods
=bject precedes. *nstance method calls are identified in the following program. 8ote that they are
all preceded by an ob!ect reference. his ob!ect is used by the methods to do their wor". *n this
case, the ob!ects are strings.
*n addition to supplying the ob!ect's data to the method, the class of the ob!ect, eg String, is where
the method is defined.
9
D
E
F
J
K
H
L
I
97
99
9D
9E
9F
9J
9K
9H
9L
9I
D7
D9
DD
// .ile : dialog/capitaliGe/1apitaliGeD."ava
// $urpose: 1apitaliGe first letter of each name. :eclare with first
use.
// #uthor : .red 2wartG - placed in public domain.
// :ate : E7 =ar D77K
import "avaB.swing.*;
public class 1apitaliGeD ;
public static void main52tring?@ args8 ;
//.. 0nput a word
2tring inputPord 4 -*ption$ane.show0nput:ialog5null A&nter a
wordA8;
//.. $rocess - 2eparate word into parts change case put
together.
2tring first%etter 4 inputPord.su"string5798; // 3et first
letter
2tring remainder 4 inputPord.su"string598; // 3et
remainder of word.
2tring capitaliGed 4 first%etter.to1pper2ase58 C
remainder.to3ower2ase58;
//.. *utput the result.
-*ption$ane.show=essage:ialog5null capitaliGed8;
<
<
6hat5s be(ore the dot tells &hether it5s a class or
instance method
6hat5s be(ore the dot4 *f it's a class name, then it's a static &class' method+ if it's an ob!ect, it's
an instance method.
7othing at (ront &hen calling methods in same class. :hen calling your own methods, you
don't have to write anything before the method name. he compiler assumes the same class or
ob!ect.
)et!ods , - 'ctual arguments
-parameters.
Purpose o( this lesson3
%eft-to-right argument evaluation
erm3 actual argument R value which is passed in a method call.
erm3 void method R method that doesn't return a value.
erm3 value-returning method R method that does return a value.
?erms/ actual argument% argument% actual parameter%
parameter
he values that are passed to a method are called actual arguments in the Java specification.
#owever, it is very common for them to be called !ust arguments, actual parameters, or !ust plain
parameters. hese terms are so used interchangeably so often that even the Java specification isn't
entirely consistent. .or a value which is passed in a call *'ll try to stic" to actual argument or !ust
argument, which are generally regarded as the (best( terms.
denti(ying method arguments
:hen you call a method, you can pass information for it to use. hese actual arguments are inside
parentheses following the method name. 9se commas to separate arguments if there is more than
one. he previous program is shown below, but this time the arguments in the calls are highlighted.
9
D
E
F
J
K
H
L
I
97
99
9D
9E
// .ile : methods/XmTo=iles#rgs."ava
// $urpose: 1onvert >ilometers to miles. Use -*ption$ane for
input / output.
// #uthor : .red 2wartG
// :ate : DD #pr D77K
import "avaB.swing.*;
public class XmTo=iles#rgs ;
//444444444444444444444444444444444444444444444444444444444444
constants
private static final double =0%&2'$&+'X0%*=&T&+ 4 7.KD9;

//44444444444444444444444444444444444444444444444444444444444444444
main
public static void main52tring?@ args8 ;
//... %ocal variables
2tring >m2tr; // 2tring >m before conversion to double.
double >m; // )umber of >ilometers.
double mi; // )umber of miles.
9F
9J
9K
9H
9L
9I
D7
D9
DD
,/ )et!ods / - 0efining a static
met!od
Purpose o( this lesson3
Show how to define a method.
Explain parts of method header.
erm3 formal parameter R variable in method which gets the argument value.
7e& Java language (eatures
Syntax of method header
>ethod header synta#
, method header is the part of the method definition that occurs at the beginning. he following
definition leaves out a few obscure features, but gives the syntax of ordinary method headers.
See Syntax 8otation to understand how to read the following.
met"od#eader R
Ivisibilit$J I(static(J return+$pe met"od-ame (&( Iparameter.istJ ('( .
visibilit$ R
(public( S (private( S (protected( .
parameter.ist R parameter/eclaration U(,( parameter.istV .
parameter/eclaration R t$pe Parameter-ame .
return+$pe R (void( S t$pe
Bo& to de(ine your o&n method
he previous program is rewritten below to define a method to convert from "ilometers to miles.
he method call, and the first line &header' of the method definition are highlighted.

9

D
// .ile : methods/XmTo=iles=ethod."ava
// $urpose: 1onvert >ilometers to miles using a method.
-*ption$ane 0*.
// ,ighlight call and method definition header.
// #uthor : .red 2wartG
//... 0nput
>m2tr 4 -*ption$ane.show0nput:ialog5
kilometers.)8;
>m 4 :ouble.parse:ouble5
//... 1omputation
mi 4 >m * =0%&2'$&+'X0%*=&T&+;
//... *utput
-*ption$ane.show=essage:ialog5

<
<

E

F

J

K

H

L

I

97

99

9D

9E

9F

9J

9K

9H

9L

9I

D7

D9

DD

DE
// :ate : DD #pr D77K
import "avaB.swing.*;
public class XmTo=iles=ethod ;
//444444444444444444444444444444444444444444444444444444444444
constants
private static final double =0%&2'$&+'X0%*=&T&+ 4 7.KD9;

//44444444444444444444444444444444444444444444444444444444444444444
main
public static void main52tring?@ args8 ;
//... %ocal variables
2tring >m2tr; // 2tring >m before conversion to double.
double >m; // )umber of >ilometers.
double mi; // )umber of miles.
//... 0nput
>m2tr 4 -*ption$ane.show0nput:ialog5null A&nter
>ilometers.A8;
>m 4 :ouble.parse:ouble5>m2tr8;
//... 1omputation
mi 4 convert4m5o0i(km);
//)ote 9
//... *utput
-*ption$ane.show=essage:ialog5null >m C A >ilometers is A
C mi C A miles.A8;
<
//444444444444444444444444444444444444444444444444444444444
convertXmTo=i
private static #ou"le convert4m5o0i(#ou"le kilometers) ;
//)ote D
double miles 4 >ilometers * =0%&2'$&+'X0%*=&T&+;
return miles;
<
<

DF

DJ

DK

DH

DL

DI

E7

E9

ED

EE

EF

EJ

EK

EH
7otes
;. /all our own method below to do the conversion. :e could have <ualified the name with
our class name, Omo$iles$ethod.convertOmo$i&"m', but this is unnecessary when
calling a static method in the same class.
>. ,ltho this method is trivial, !ust a multiplication, it is good practice to separate the
(model(, or (logic(, from the user interface. ,s programs become larger, this separation
becomes essential.
*natomy o( the convert4m5o0i method header
:e'll ta"e a loo" at each of the parts of the method header in order.
)isibility - pu"lic% private% or package
private static double convertXmTo=i5double >ilometers8 ;
double miles 4 >ilometers * =0%&2'$&+'X0%*=&T&+;
return miles;
<
.or greatest reliability and flexibility in your programs, you should always give methods
the lowest visibility to others that you can.
:hen you define a method, you should thin" about who can use it. 2enerally you want to
choose the lowest level of visibility that ma"es your program usable, either private or
the default &package'. #ere are the four options, from least visible to most visible.
private - *f you don't want any other class to use it, declare it private. his is a
good choice.
-one &pac"age' - *f you don't specify anything, the default visibility allows only
classes in the same pac"age &directory' to see it. his is a common choice. *t's
common to use public visibility when package visibility is more appropriate -- *
do it myself. he lac" of a "eyword for pac"age visibility ma"es it a little harder
to read.
protected - 0on't use this protected, except in certain cases to let a child
class see it. Even then, its use is controversial.
public - %et's anyone see it. /hoose this if you've defined a method that will be
used by others outside of your pro!ect. 8ote that main must be declared
public so the run-time system can call it.
Class 2static3 or instance method
private static double convertXmTo=i5double >ilometers8 ;
double miles 4 >ilometers * =0%&2'$&+'X0%*=&T&+;
return miles;
<
, method should be declared static if it doesn't user instance variables or methods. ,
static method must use only only parameters, local variables, and static constants, and
other static methods in the same class. *f the static "eyword is omitted, the method
will be an instance method. his example uses static, but soon you will learn about
instance methods too.
,eturn type
private static #ou"le convertXmTo=i5double >ilometers8 ;
double miles 4 >ilometers * =0%&2'$&+'X0%*=&T&+;
return miles;
<
>ethod name
private static double convert4m5o0i5double >ilometers8 ;
double miles 4 >ilometers * =0%&2'$&+'X0%*=&T&+;
return miles;
<
$ethod names should begin with a lowercase letter. $ethod names are typically verbs,
whereas variable names are usually nouns.
Parameter2s3
private static double convertXmTo=i5#ou"le kilometers8 ;
double miles 4 >ilometers * =0%&2'$&+'X0%*=&T&+;
return miles;
<
=arameters are enclosed in parentheses following the method name. hey are also called
formal parameters'. here is only one parameter in this example - >ilometers, but if
there are more, they must be separated by commas. he t$pe of each parameter is
specified before the name &eg, double'. =arameters are local variables that only exist
inside the method. hey are assigned initial values from the arguments when the method
is called.
>ethod body
private static double convertXmTo=i5double >ilometers8 ;
#ou"le miles $ kilometers * 0-3.67P.874-3O0.5.8;
return miles;
<
he bod$ of a method is the statements which are executed when the method is called
are enclosed in braces following the the method header. ,dditional local variables may be
defined &eg, miles'.
,eturn statement
private static double convertXmTo=i5double >ilometers8 ;
double miles 4 >ilometers * =0%&2'$&+'X0%*=&T&+;
return miles;
<
, method returns to the caller after it has done what it wants. *f the method returns a
value &not a void method', it must contain a return statement that specifies a value to
return. :hen execution reaches the return statement, control transfers bac" to the
calling method, passing a return value to it.
,eturning an e#pression
he above example returns the value in the local variable miles. he return statement can
be followed by any expression of the appropriate type, not !ust a single value. .or
example, this method body could have been written as a single return statement.
private static double convertXmTo=i5double >ilometers8 ;
return kilometers * 0-3.67P.874-3O0.5.8;
<
=rder o( method de(initions doesn5t matter
*f you define multiple methods in a class, you don't have to worry about the order of the
definitions, unli"e some other languages.
DF
DJ
DK
DH
DL
DI
E7
*rgument evaluation
)efore a method is called, the arguments are evaluated left-to-right. *n the example above most
arguments are simple values, except the second argument in the call to show=essage:ialog.
)efore the call can be made, this argument expression must be evaluated by performing the
conversions to string and the concatenations.
)oid and value-returning methods
, method may return a value. *n the example above, show0nput:ialog returns a String and
parse:ouble returns a double value. hese method calls can be used anywhere in an expression
where a String or double value is re<uired. #ere they simply provide the value for the right side of
an assignment.
voi#. *f a method has a (side effect(, but doesn't produce a value, it is called a void method. he
show=essage:ialog method shows something to the user, but doesn't return a value, and is a
void method.
:hen a method is defined, you need to specify the "eyword void if it doesn't return a value. You
can see this on line ;? where the main method definition starts.
)et!ods 1 - $ocal varia2les
Purpose o( this lesson3
%ocal variables are declared within a method.
%ocal variable lifetime is from method entry to method return.
%ocal variable visibility is only within the method.
%ocal variables have no initial value.
=arameter variables are local variables initiali1ed from the argument values.
7e& Java language (eatures
final modifier to prevent assignment to parameters.
Principles / Style
0on't assign to parameter variables.
!ocal variables
8ow that we've written two methods, main and convertXmTo=i, you should "now a little more
about the variables in them.
Nariables that are declared in a method are called local variables. hey are called local because they
can only be referenced and used locally in the method in which they are declared. *n the method
below miles is a local variable.
private static double convertXmTo=i5double >ilometers8 ;
double miles 4 >ilometers * =0%&2'$&+'X0%*=&T&+;
return miles;
<
)isibility/ =nly in de(ining method
8o code outside a method can see the local variables inside another method. here is no need, or
even possibility, of declaring a local variable with a visibility modifier -- local variables are
automatically "nown only in the method itself.
!i(etime/ 0rom method call to method return
%ocal variables are created on the call stac" when the method is entered, and destroyed when the
method is exited. You can't save values in local variables between calls. .or that you have to use
instance variables, which you'll learn about a little later.
nitial value/ 7one
%ocal variables don't have initial values by default -- you can't try to use their value until you assign
a value. *t's therefore common to assignment a value to them when they're declared.
Compiler error. *f you try to use a local variable before it's been assigned a value, the compiler
will notice it and give an error message. )ut the compiler doesn't really "now the exact order of
execution in a program, so it ma"es some conservative assumptions. hese assumptions can
sometimes be too conservative, and there are cases where you must initiali1e a local variable even
though you "now it will have a value before it's referenced.
// (#: (#: (#: (#: (#: (#: (#: (#: (#: (#: (#: (#: (#: (#: (#:
private static double convertXmTo=i5double >ilometers8 ;
double miles;
return miles; // PonRt compile because nothing was assigned to
miles.
<
Parameters are preinitialiEed local variables
$ethod parameters are basically implemented as local variables. hey have the same visibility
&none outside the method' and lifetime &created on method call, destroyed on method return'.
PreinitialiEed. he difference is that parameters are initiali1ed from the corresponding argument
values.
// (oth kilometers and miles are implemented as local variables.
private static double convertXmTo=i5double kilometers8 ;
double miles 4 >ilometers * =0%&2'$&+'X0%*=&T&+;
return miles;
<
Style/ .on5t assign to a parameter
You can assign to a parameter variable, !ust as you would to a local variable, but this is often
considered bad style because it can deceive the casual reader in two ways3
$ne#pected meaning change.. =rogrammers assume parameter variables represent
actual argument values. ,ssigning to parameters brea"s that assumption.
.oesn5t change actual argument. )ecause formal parameter variables are really local
variables, assigning new values to them doesn't have any effect on the actual parameters.
#owever, in some programming languages assignment to a parameter can assign to the
corresponding actual parameter &eg, /LL reference parameters'. herefore if you write an
assignment to a formal parameter variable, it may mislead the careless programmer with a
/LL bac"ground. Or the reader may pause and try to decide if you thought you were
assigning to the actual argument. *n either case it reduces the readability.
"#ample. he example below shows how a parameter could be reused. he overhead of declaring
an extra variable is !ust about 1ero, so this really isn't more efficient, and even this small example is
astoundingly misleading.
// (#: (#: (#: (#: (#: (#: (#: (#: (#: (#: (#: (#: (#: (#: (#:
private static double convertXmTo=i5double >ilometers8 ;
>ilometers 4 =0%&2'$&+'X0%*=&T&+ * >ilometers; // (#: - :onRt do
this altho it wor>s.
return >ilometers;
<
Style/ final key&ord prevents assignment
Some programmers recommend using the final "eyword for each parameter. his prevents
assignment to the parameter. .ew programmers do this because it adds extra clutter, which in a
different way reduces the readability. he use of self-restraint in assigning to parameters is usually
suffcient, but specifying final isn't a bad idea.
private static double convertXmTo=i5final double >ilometers8 ;
double miles 4 >ilometers * =0%&2'$&+'X0%*=&T&+;
return miles;
<
)et!ods 3 - 4ow call works
Purpose o( this lesson3
Examine the method callFreturn process in more detail.
erm3 call stack R $emory that is used to save return address and local variables.
erm3 stack frame R he storage on the call stac" that is used by one method.
7e& Java language (eatures
8one.
he table below shows how the call stac" changes as calls and returns in the Omo$iles$ethods
program are made. his shows the first W changes to the call stac" after main is entered.
.ynamic changes in the call stack memory allocation
he table below shows how the call stac" changes as calls and returns in the Omo$iles$ethods
program are made. his shows the first W changes to the call stac" after main is entered.
here is actually something before main on the call stac", and the library methods that are called
call many methods of their own, which isn't shown here because we don't need to "now what they
call.
Stack (rame. Each box represents the information that's stored on the call stac" for each method.
his bloc" of information is often called a stack frame. here is internal information associated with
the method, for example, it saves the place to resume execution in the calling method. Each stac"
frame is labelled with the method name and a list of parameters and local variables that are
allocated on the stac". (KKK( is written when we don't "now &or care' what the local variables are
that are used by a library method.
; < F G 8 H I J
main
args
"ms
miles
main
args
"ms
miles
get#ouble
prompt
str
main
args
"ms
miles
get#ouble
prompt
str
showInput#ialog
KKK
main
args
"ms
miles
get#ouble
prompt
str
main
args
"ms
miles
get#ouble
prompt
str
parse#ouble
KKK
main
args
"ms
miles
get#ouble
prompt
str
main
args
"ms
miles
main
args
"ms
miles
convert$m%o&i
"ilometers
miles
?ypical call se:uence
;. "valuate arguments le(t-to-right. *f an argument is a simple variable or a literal value,
there is no need to evaluate it. :hen an expression is used, the expression must be
evaluated before the call can be made.
>. Push a ne& stack frame on the call stack. :hen a method is called, memory is
re<uired to store the following information.
o Parameter and local variable storage. he storage that is needed for each of
the parameters and local variables is reserved in the stac" frame.
o :here to continue execution when the called method returns. You don't have to
worry about this+ it's automatically saved for you.
o Other wor"ing storage needed by the method may be re<uired. You don't have to
do anything about this because it's handled automatically.
?. nitialiEe the parameters. :hen the arguments are evaluated, they are assigned to the
local parameters in the called method.
E. "#ecute the method. ,fter the stac" frame for this method has been initiali1ed, execution
starts with the first statement and continues as normal. Execution may call on other
methods, which will push and pop their own stac" frames on the call stac".
C. ,eturn (rom the method. :hen a return statement is encountered, or the end of a void
method is reached, the method returns. .or non-void methods, the return value is passed
bac" to the calling method. he stac" frame storage for the called method is popped off the
call stac". =opping something off the stac" is really efficient - a pointer is simply moved to
previous stac" frame. his means that the current stac" frame can be reused by other
methods. Execution is continued in the called method immediately after where the call too"
place.
)et!ods 5 - "#ample wit! t!ree
met!ods
Purpose o( this lesson3
Show definition of multiple methods.
Programming ideas
,ll code is in methods.
Style3 he main method often consists largely of method calls.
Style3 $ethods should generally be no larger than one page.
#ere is another variation of the program, this time using three methods. ,ltho there is no real need
for these methods in such a small program, large programs are in fact composed of many small
methods. *t is the essential way that all code is structured.
Each of the user-defined method names, both in the call and the definition, is hilited.
One method is void, which means it doesn't return a value.
hree methods call other methods.
he main program consists mostly of calls to other methods.
Source code

9

D

E

F

J
// .ile : methods/XmTo=iles=ethods."ava
// $urpose: 1onverts >ilometers to miles using two methods.
// #uthor : .red 2wartG - placed in public domain
// :ate : DD #pr D77K
import "avaB.swing.*;
public class XmTo=iles=ethods ;
//444444444444444444444444444444444444444444444444444444444
constants
private static final double =0%&2'$&+'X0%*=&T&+ 4 7.KD9;

K

H

L

I

97

99

9D

9E

9F

9J

9K

9H

9L

9I

D7

D9

DD

DE

DF

DJ

DK
//44444444444444444444444444444444444444444444444444444444444444
main
public static void main52tring?@ args8 ;
double >ms 4 get/ou"le5A&nter number of >ilometers.A8;
double miles 4 convert4m5o0i5>ms8;
#ispla*6tring5>ms C A >ilometers is A C miles C A miles.A8;
<
//44444444444444444444444444444444444444444444444444444
convertXmTo=i
// 1onversion method - >ilometers to miles.
private static double convert4m5o0i5double >ilometers8 ;
double miles 4 >ilometers * =0%&2'$&+'X0%*=&T&+;
return miles;
<
//444444444444444444444444444444444444444444444444444444444
get:ouble
// 0/* convenience method to read a double value.
private static double get/ou"le52tring prompt8 ;
2tring temp2tr;
temp2tr 4 -*ption$ane.show0nput:ialog5null prompt8;
return :ouble.parse:ouble5temp2tr8;
<
//44444444444444444444444444444444444444444444444444444
display2tring
// 0/* convenience method to display a string in dialog boB.
private static void #ispla*6tring52tring output8 ;
-*ption$ane.show=essage:ialog5null output8;
<
<

DH

DL

DI

E7

E9

ED

EE

EF

EJ

EK

EH

EL

EI
)et!ods 6 - Overloading
Purpose o( this lesson3
Explain overloading R multiple methods with the same name.
Programming ideas
he method name is important to the human programmer as the "ey to describing an
action to be performed.
*t's often useful to do the (same( action, but with different "inds of parameters.
he compiler can distinguish methods that have the same name only if they have a
different number and F or t$pe of parameters.
#ere is a small program which simply computes the average of three numbers. *t uses three
overloaded methods to read the numbers. .or such a small program you would not use three
different methods, of course, but this shows how overloaded methods are defined and used. *t's
very common for one overloaded method to call another. another variation of the program, this
time using three methods. ,ltho there is no real need for these methods in such a small program,
large programs are in fact composed of many small methods. *t is the essential way that all code is
structured.
Each of the user-defined method names, both in the call and the definition, is hilited.
One method is void, which means it doesn't return a value.
hree methods call other methods.
he main program consists mostly of calls to other methods.
9ood practices
Coherence. *t's important that all the methods do the (same( thing, so that the program is
human comprehensible. ,ll methods sharing the same name should return the same value,
have the same side effects, and all be either static or instance methods. he language
doesn't re<uire this, but doing otherwise is as"ing for trouble.
Call each other. )ecause all overridden methods should be doing the same thing, it is very
common for there to be calls from one to another, supplying extra default parameter values
as re<uired.
.e(ault parameter values. Some programming languages allow you to specify default
values for parameters, and if a the parameter is not supplied, the default value is used.
Java doesn't have default parameters, but you can easily implement them using overloaded
methods.
"#ample o( overloading - averaging three values

9

D

E

F

J

K

H

L

I

97

99
// .ile : methods/avgE/#vgThree*verloaded."ava
// :escription: #verages three numbers -- meaningless but
// $urpose: 2how an overloaded method get:ouble with three
definitions
// differing in the number of parameters.
// 0ssues : 0nput isnRt chec>ed for legality 5non-null number8
because
// the point is to show overloading.
// #uthor : .red 2wartG - D77H-79-99 - placed in public domain
import "avaB.swing.*;
public class #vgThree*verloaded ;
//44444444444444444444444444444444444444444444444444444444444444
main
public static void main52tring?@ args8 ;
//... +ead three numbers using the three different methods.
// Using three different methods is only to show
overloading.
double n9 4 get/ou"le();
double nD 4 get/ou"le().nter t!e secon# num"er.));
double nE 4 get/ou"le().nter last num"er.)9 %.%9 ,%%.%);
double average 4 5n9 C nD C nE8 / E.7;
display2tring5A#verage is A C average8;
<
//444444444444444444444444444444444444444444444444444444444

9D

9E

9F

9J

9K

9H

9L

9I

D7

D9

DD

DE

DF

DJ

DK

DH

DL

DI

E7

E9

ED
get:ouble
// 0/* convenience method to read a double value.
// This version of the get:ouble method simply calls on
another
// version passing it a generic input message.
private static double get/ou"le() ;
return get:ouble5A&nter a numberA8;
<
//444444444444444444444444444444444444444444444444444444444
get:ouble
// 0/* convenience method to read a double value given a prompt.
// This version of get:ouble displays the user supplied
prompt.
private static double get/ou"le(6tring prompt) ;
2tring temp2tr;
temp2tr 4 -*ption$ane.show0nput:ialog5null prompt8;
return :ouble.parse:ouble5temp2tr8;
<
//444444444444444444444444444444444444444444444444444444444
get:ouble
// 0/* convenience method to read a double value in a range.
// 0t builds a new prompt and calls another version to get
// the value looping until a value in the range is found.
private static double get/ou"le(6tring prompt9 #ou"le low9 #ou"le
!ig!) ;
double result;
2tring range$rompt 4 prompt C A 6alue must be in range A
C low C A to A C high;

//... +ead and loop bac> if the number is not in the right
range.
do ;
result 4 get:ouble5range$rompt8;
< while 5result O low SS result N high8;

return result;
<
//44444444444444444444444444444444444444444444444444444
display2tring
// 0/* convenience method to display a string in dialog boB.
private static void #ispla*6tring52tring output8 ;
-*ption$ane.show=essage:ialog5null output8;
<
<

EE

EF

EJ

EK

EH

EL

EI

F7

F9

FD

FE

FF

FJ

FK

FH

FL

FI

J7

J9

JD

JE

JF

JJ

JK

JH

JL

JI

K7

K9

KD

KE
.on5t con(use overloading and overriding
his two terms are easily confused because they both have to do with multiple definitions of
methods. )etter terms would have been nice, but these are what we have. Overloading is ma"ing
multiple method definitions which differ in the number or types of parameters, as described here.
Overriding is redefining a method in a super class, using exactly the same number and types of
parameters.
OOP +7 Introduction to Classes
and O28ects
Purpose o( this lesson3
Overview
o /lasses combine data and methods.
o , class defines a data t$pe.
o ,dvantage3 /lasses correspond to concepts in the problem domain.
o ,dvantage3 /lasses reduce complexit$ by increasing co"erence and reducing
coupling.
*ntroduce classes to store data in value objects.
?erminology
!nstance variable R Nariable declared in class outside a method. ypically private.
ield R Synonym for instance variable, attribute. /ommon informal term.
)ttribute R Synonym for instance variable, field. Often used in the design phase.
Propert$ R Synonym for instance variable, field. /ommon term if field is "nown publicly.
7e& Java language (eatures
0eclaring fields &instance variables'.
=bject-=riented Programming 2==P3 concepts
Class - data K methods. Everything &data and methods' in Java is contained in classes. So far
you've been using classes to hold met"ods &main and perhaps a few other static methods'. hese
methods use local variables, which are completely private to the method, and which disappear when
the method returns.
Bistorical development. /lasses can also be used to store data. #istorically, programming
languages had something similar to classes for grouping data, usually called structs or records.
hese were used for storing only data, not methods. Eventually, advantages of combining both data
and the methods to wor" on that data were recogni1ed.
Classes model problem. One advantage of encapsulating data and methods in a class is to ma"e
programming ob!ects that reflect (ob!ects( in the problem domain. *f your problem deals with orders
and products, then you'll very li"ely have classes called Order and Product.
Classes reduce comple#ity. ,nother advantage of classes is reducing complexit$. /omplexity
limits the si1e and reliability of programs. /omplexity is reduced by increasing co"esion &putting
things together that belong together' and reducing coupling &interconnections'. he proper use of
classes can ma"e large improvements in both of these.
Class% object% ==P. he name class was almost universally adopted for programming language
structure which combines data and methods, object is used for each instance of a class that is
created, and the practices that developed around these ideas is called Object-Oriented
Programming &OO='.
)alue objects - .ata-(irst approach. :e'll start with classes that represent data, and then add
constructors and methods. 9ltimately you will be more concerned with methods than data, and
you'll see how &and why' methods are used to completely hide the data implementation.
* class stores the attributes 2data3 o( something
9roup values. /lasses are used to group a number of related, named, data values associated with
an entity. )y entit$ we mean something that is typically a noun when you are tal"ing about a
problem you are solving. .or example, in a university computing system, you might have a class to
represent a student, an instructor, a classroom, a department, a course, a section of a course, ....
Student e#ample. he information you would store about students, would be their name, id, etc.
:e'll "eep this example simple and !ust save name and id information.
.eclare each (ield. , class contains declarations of the fields &instance variables, attributes' that
hold the data associated with a student. hese declarations are li"e declaring a local variable in a
method, except that you will also specify the visibilit$. :e'll start by using the visibility modifier
public, which lets anyone see them. .or example, the following 2tudent9 class can be used to
represent a student. ,s you go through these notes, we'll ma"e improvements to this class.
public class 2tudent9 ;
public 2tring first)ame;
public 2tring last)ame;
public int id;
<
* class is a type
7oun. /lasses are usually given the name of a noun, and the fields &variables' in it are attributes
associated with that noun. =redefined Java classes that you have already used are 2tring, which
contains the characters in the string and the length, -*ption$ane, which contains information
necessary to produce a dialog box on the screen, etc. hese predefined Java classes are used for
the programming infrastructure that you need. $any common infrastructure classes are available in
the ?555L predefined Java library classes. )ut, of course, these don't address your problems.
Business objects. $ost classes you define will concern your problem domain, where they
represent business objects &Student, imeOf0ay, Order, ...'.
.eclaring business object variables is li"e declaring any other variable. 9se the class name as a
type, !ust as you've used 2tring, int, etc. .or example, the following declares two 2tudent9
variables.
6tu#ent, best0n1lass; // This variable references a 2tudent9 ob"ect.
6tu#ent, t; // #nd here is another
hese don't have values yet, but we'll do that in the next section.
.oes your problem re:uire classes or simple variables4
*f the data you are wor"ing with, for example a temperature, can be expressed as a simple value
and the operations on it are all defined by operators, then !ust use a simple variable for it &int,
double, 2tring, ...'. Often the data associated with an entity in your problem is not a simple
value, but has multiple attributes.
"#amples showing classes as groups of attriutes.
*nstead of wor"ing with simple temperature numbers, you might have
+emperature0easurement ob!ects, which have several attributes3 the temperature, the
time, and the location.
, Student class would represent information about a student3 name, id, address, ... Each
ob!ect of this class would have a data about a specific student.
, Classroom class would have information about a classroom's building, room number,
capacity, whether it has a pro!ector, etc.
=bject-=riented .esign involves deciding which classes you need to represent the things
&entities' in your problem. .or simple programs, you often use only simple variables, but as
programs get larger, you will define more and classes to represent the things you are wor"ing with.
Similarity to database table
*f your are familiar with databases, a class is very similar to a table definition. *f you're not familiar
with databases, don't worry because these lessons don't assume you are.
OOP ,7 0ata - Student Class
Purpose o( this lesson3
/lasses versus ob!ects.
#ow to create ob!ects and assign values to the instance variables &fields'.
2ood practice3 One class per file is the standard.
7e& Java language (eatures
9sing new to create an ob!ect.
Deferencing fields using dot notation.
=ne class per (ile is standard practice
#ere is the class again that represents information about a student. ypically there is one class
definition per file, so this would be stored in 2tudent9."ava.
// .ile : oop/dataclass/2tudent9."ava
// $urpose: 0nformation about a student.
public class 2tudent9 ;
public 2tring first)ame; // .irst name
public 2tring last)ame; // %ast name
public int id; // 2tudent id
<
Class versus object
, class is a template that defines what attributes an object can have. You ma"e one class definition,
then create ob!ects of that class using the new "eyword. Some analogies might ma"e this clearer.
*nalogy/ Cookie cutter and cookies. , coo"ie cutter is li"e a class definition. *t isn't a coo"ie,
but can be used to create a coo"ie. Each coo"ie can will have the same attributes &shape', but each
coo"ie can have different values for the attributes &type of dough, thic"ness, ...'.
*nalogy/ .og and 0ido. he concept of 0og is li"e a class, but there are many possible instances
of this class, eg, my dog .ido, or your dog Dover.
*nalogy/ 0orm stamp and (illed out (orms. here are rubber in"pad stamps that are used to
stamp out a small form. hese have been used in several places in my passport, where passport
control stamped my passport, then filled out the fields with the date, how long * could stay, etc. he
rubber stamp is li"e a class, defining the fields. he filled out form in each passport are the ob!ects,
with specific values for each field.
$se new to create a ne& object
, class defines what fields an object will have when it's created. :hen a new Student; ob!ect is
created, a bloc" of memory is allocated, which is big enough to hold these three fields -- as well as
some extra overhead that all ob!ects have.
2tudent9 tatiana;
tatiana 4 new 6tu#ent,(); // 1reate 2tudent9 ob"ect with new.
'ne&' and parentheses
o create a new ob!ect, write new followed by the name of the class &eg, 2tudent9', followed by
parentheses. %ater we'll see that we can specify arguments in the parentheses when creating a new
ob!ects.
.e(ault (ield values - null% Eero% (alse
9nli"e local variables in a method, fields do have default values &li"e the default values in arrays'.
Ob!ect references are null, numbers are 1ero, and booleans are false.
*ccess public (ields &ith dot notation
he fields &first)ame, last)ame, id' name data which is stored in each ob!ect. ,nother term
for field is instance variable. ,ll public fields can be referenced using dot notation &later we'll see
better ways to access and set fields'. o reference a field, write the ob!ect name, then a dot, then
the field name.
2tudent9 tatiana; // :eclare a variable to hold a
2tudent9 ob"ect.
//... 1reate a new 2tudent9 ob"ect for Tatiana.
tatiana 4 new 2tudent958; // 1reate a new 2tudent9 ob"ect
with default values.
tatiana.first:ame 4 ATatianaA; // 2et values of the fields.
tatiana.last:ame 4 A-ohnsonA;
tatiana.i# 4 IIJ7LFD;
-*ption$ane.show=essage:ialog5null A*ne student is named: A
C tatiana.last:ame C A A C tatiana.first:ame8;
)wkward1 his simple example with one student is somewhat aw"ward, but we'll get to examples
that show real advantages soon.
* class de(inition is a template (or creating objects
, class defines which fields an ob!ect has in it. You need to use new to create a new ob!ect from the
class by allocating memory and assigning a default value to each field. , little later you will learn
how to write a constructor to control the initiali1ation.
*t's not very interesting to create only one ob!ect of class, so the following example creates a couple
of them.

9

D
// .ile : oop/dataclass/Test2tudent9."ava
import "avaB.swing.*;
public class Test2tudent9 ;

E

F

J

K

H

L

I

97

99

9D

9E

9F

9J

9K

9H

9L

9I

D7

D9

DD

DE
public static void main52tring?@ args8 ;
2tudent9 tatiana;
2tudent9 pupil;
//... 1reate new 2tudent9 ob"ect with new.
tatiana 4 new 6tu#ent,();
tatiana.first)ame 4 ATatianaA;
tatiana.last)ame 4 A-ohnsonA;
tatiana.id 4 IIJ7LFD;
//... 1reate another 2tudent9 ob"ect.
pupil 4 new 6tu#ent,();
pupil.first)ame 4 -*ption$ane.show0nput:ialog5null A.irst
nameA8;
pupil.last)ame 4 -*ption$ane.show0nput:ialog5null A%ast
nameA8;
pupil.id 4
0nteger.parse0nt5-*ption$ane.show0nput:ialog5null A0:A88;
-*ption$ane.show=essage:ialog5null A*ne student is named: A
C tatiana.last)ame C A A C tatiana.first)ame
C ATn and another is named: A
C pupil.last)ame C A A C pupil.first)ame8;
<
<

DF

DJ

DK

DH
OOP /7 Constructor - Student
Class
Purpose o( this lesson3
o introduce the concept of constructors.
=urpose of constructors is both guaranteed initiali1ation and convenience.
7e& Java language (eatures
/onstructor syntax - li"e a method but with class name and implicit typeFvalue.
*dd a constructor (or better initialiEation
*void bad initialiEations. One problem with the Student; class is that the user has to explicitly
initiali1e all fields. his re<uires extra typing, but more importantly, it is error-prone. *f we forget to
initiali1e a field, the default value could have bad conse<uences.
Convenience. 0efining a constructor ma"es creation of an ob!ect easier to write.
Constructor Synta#
Similar to method. , constructor is similar to a method -- it's called li"e a method, has
parameters li"e a method, and it returns. )ut it must have the same name as the class for which it
is a constructor. ,lso, the type and return value are implicit.
Student< e#ample &ith a constructor
#ere is the Student; class with a constructor which simply initiali1es the fields &instance variables'
from its parameters. Often constructors do more wor" in initiali1ation, including chec"ing for legal
values, but for now we'll !ust simply copy the parameter values.
// .ile : oop/dataclass/2tudentD."ava
// $urpose: 0nformation about a student. :efines constructor.
public class 2tudentD ;
public 2tring first)ame; // .irst name
public 2tring last)ame; // %ast name
public int id; // 2tudent id

//4444444444444444444444444444444444444444 constructor
pu"lic 6tu#ent+(6tring fn9 6tring ln9 int i#num) ;
first)ame 4 fn;
last)ame 4 ln;
id 4 idnum;
<
<
8ote that a constructor has no return type and the name is the same as the class name.
$sing the constructor
#ere is the first program rewritten to use the above class definition with a constructor.

9

D

E

F

J

K

H

L

I

97

99

9D

// .ile : oop/dataclass/Test2tudentD."ava
// $urpose: Tests 2tudentD constructor.
import "avaB.swing.*;
public class Test2tudentD ;
public static void main52tring?@ args8 ;
2tudentD tatiana;
2tudentD pupil;
//... 1reate new 2tudentD ob"ect with new.
tatiana 4 new 6tu#ent+()5atiana)9 )Jo!nson)9 ;;<%=>+);
//... 1reate another 2tudentD ob"ect.
2tring first 4 -*ption$ane.show0nput:ialog5null A.irst
nameA8;
2tring last 4 -*ption$ane.show0nput:ialog5null A%ast
nameA8;
int stud0:4
0nteger.parse0nt5-*ption$ane.show0nput:ialog5null A0:A88;
pupil 4 new 6tu#ent+(first9 last9 stu#-/);
-*ption$ane.show=essage:ialog5null A*ne student is named: A
C tatiana.last)ame C A A C tatiana.first)ame
C ATn and another is named: A
C pupil.last)ame C A A C pupil.first)ame8;
<
<
9E

9F

9J

9K

9H

9L

9I

D7

D9

DD

DE

DF

DJ
6hen you de(ine a constructor% the Java compiler doesn5t create a de(ault constructor
if you define a constructor in a class, the Java compiler no longer automatically creates a default
&parameterless' constructor. ,ll ob!ect creation therefore must use your explicitly defined
constructor. .or example,
2tudentD someone;
someone 4 new 2tudentD58; // 0%%&3#%. There is no default
constructor.
someone 4 new 2tudentD5A=ichaelA A=ausA 98; // *X. =ust specify E
values.
he constructor can chec" that all fields are defined with legal values. :e're not going to extend the
Student> class any further to test for legal values, but we will in the next example.
.or the moment we'll leave the Student class, and move to something different to show the same
ideas.
Class and nter(ace Concepts
#ere are some of the basic building bloc"s of Ob!ected-Oriented =rogramming that you will become
familiar with3
class
, collection of fields &instance and class variables' and methods.
instance variable 2aka (ield variable or member variable
,n instance variable is a variable that is defined in a class, but outside of a method. here
is one copy of the variable for every instance &ob!ect' created from that class.
, common problem is trying to reference an instance variable from a static method. , static
method &eg, main' can only reference static variables in its own class &or its own local
variables'.
class variable 2aka static variable3
, class variable or static variable is defined in a class, but there is only one copy regardless
of how many ob!ects are created from that class. *t's common to define static final
variables &constants' that can be used by all methods, or by other classes. 1olor.blue is
an example of a static final variable.
constructor
:hen an ob!ect is created, a constructor for that class is called. *f no constructor is defined,
a default constructor is called. *t's common to have multiple constructors ta"ing different
numbers of parameters. )efore a constructor is executed, the constructor for the parent
class is called implicitly if there is no parent constructor called explicitly on the first line.
inner class
*f a class is defined within another class, it is an inner class. here are two common reasons
to do this3 to attach an anonymous listener to a control at the point where the control is
being built, and to have access to the fields and methods of the enclosing class.
override 2applies to methods3
*f a subclass redefines a method defined in a superclass, the method in the superclass is
overridden. , common use of this is in defining a subclass of J=anel that you use for
graphics. :hen you define the paint1omponent method, you are overriding the one that
is already defined in J=anel. *n paint/omponent, but not in most overriding methods, you
should call the method in the parent class with super.paint1omponent. he (super(
"eyword is how you refer to the overridden parent method. here is no way to explicitly call
the (grandparent's( method if it was overridden by the parent class.
overload 2applies to methods3
, method in a class is overloaded if there is more than one method by the same name. *f
the same name is used, the methods must different in the number andFor types of the
parameters so that there is no confusion. his really has nothing to do with classes, only
methods.
abstract class
, class which doesn't define all it's methods is called an abstract class. o be useful, there
must be a subclass which defines the missing methods. he (You must declare this class
abstract( error message from the Java compiler is rather misleading. his usually means
that you declared your class to implement an interface, but failed to write all re<uired
methods -- or more commonly that there's a spelling error in a method header.
inter(ace
,n interface is a list of methods that must be implemented. , class that implements an
interface must define all those methods. he method signatures &prototypes' are listed in
the interface. *nterfaces may also define public static final (constants(. ,n interface is
essentially the same as an completely abstract class.
=ther vie&s on ==P
OO= *s $uch )etter in heory han in =ractice at www.devx.com.
0on't .ear the OopG - , light hearted, but incomplete intro to OO=. )y the late Johannes
/laerbout.
Constructors
:hen you create a new instance &a new ob!ect' of a class using the new "eyword, a constructor for
that class is called. /onstructors are used to initiali1e the instance variables &fields' of an ob!ect.
/onstructors are similar to methods, but with some important differences.
Constructor name is class name. , constructors must have the same name as t"e class
its in.
.e(ault constructor. *f you don't define a constructor for a class, a default parameterless
constructor is automatically created by the compiler. he default constructor calls the
default parent constructor &super&'' and initiali1es all instance variables to default value
&1ero for numeric types, null for ob!ect references, and false for booleans'.
.e(ault constructor is created only i( there are no constructors. *f you define an$
constructor for your class, no default constructor is automatically created.
.i((erences bet&een methods and constructors.
o here is no return t$pe given in a constructor signature &header'. he value is this
ob!ect itself so there is no need to indicate a return value.
o here is no return statement in the body of the constructor.
o he first line of a constructor must either be a call on another constructor in the
same class &using this', or a call on the superclass constructor &using super'. *f
the first line is neither of these, the compiler automatically inserts a call to the
parameterless super class constructor.
hese differences in syntax between a constructor and method are sometimes hard to see
when loo"ing at the source. *t would have been better to have had a "eyword to clearly
mar" constructors as some languages do.
t!is(...) - Calls another constructor in same class. Often a constructor with few
parameters will call a constructor with more parameters, giving default values for the
missing parameters. 9se this to call ot"er constructors in the same class.
super(...). 9se super to call a constructor in a parent class. /alling the constructor for
the superclass must be the first statement in the body of a constructor. *f you are satisfied
with the default constructor in the superclass, there is no need to ma"e a call to it because
it will be supplied automatically.
"#ample o( e#plicit t!is constructor call
public class $oint ;
int m'B;
int m'y;
//444444444444 1onstructor
public $oint5int B int y8 ;
m'B 4 B;
m'y 4 y;
<
//444444444444 $arameterless default constructor
public $oint58 ;
t!is57 78; // 1alls other constructor.
<
. . .
<
super(...) - ?he superclass 2parent3 constructor
,n ob!ect has the fields of its own class plus all fields of its parent class, grandparent class, all the
way up to the root class *b"ect. *t's necessary to initiali1e all fields, therefore all constructors
must be calledG he Java compiler automatically inserts the necessary constructor calls in the
process of constructor c"aining, or you can do it explicitly.
he Java compiler inserts a call to the parent constructor &super' if you don't have a constructor
call as the first statement of you constructor. he following is the e<uivalent of the constuctor
above.
//444444444444 1onstructor 5same as in above eBample8
public $oint5int B int y8 ;
super(); // #utomatically done if you donRt call constructor
here.
m'B 4 B;
m'y 4 y;
<
6hy you might &ant to call super e#plicitly
8ormally, you won't need to call the constructor for your parent class because it's automatically
generated, but there are two cases where this is necessary.
1. You want to call a parent constructor which has parameters &the automatically generated
super constructor call has no parameters'.
>. here is no parameterless parent constructor because only constructors with parameters
are defined in the parent class.
Constructor Pu99le
?his class compiles &ithout a problem

/////////////////// class P0T,*UT a parameterless
constructor.//////////////////
9

D

E

F

J

K

H

L

I
class Parent ;
int 'B;
Parent(int x) ; // 1onstructor with a parameter.
'B 4 B;
<
<
But &hy &on5t this subclass compile4

9

D

E

F

J

K

H

L
////////////////// Phy wonRt this class
compileM ///////////////////////////////
class 2!il# exten#s Parent ;
int 'y;
1hild5int y8 ; // This line mysteriously generates an error!
'y 4 y;
<
<
Bint
he error message from the compiler is3
1hild."ava:J: cannot find symbol symbol : constructor $arent58
)ut you defined a constructor for $arent, and anyway, you didn't even call the =arent constructor,
so what's the problem with line CK
Constructor chaining - implicit or e#plicit constructor call as (irst statement
)efore you can initiali1e an ob!ect in a constructor, the ob!ect's parent constructor must be called
first. *f you don't write an explicit call to the super58 constructor, Java automatically inserts one in
your constructor. he compiler automatically inserts superclass constructor calls in both
constructors.
$arent5int B8 ;
super(); // 1ompiler inserts this statement to call *b"ect58.
'B 4 B;
<
his is fine because there is a parameterless constructor for Ob!ect. #owever, when the 1hild
class constructor is modified to call its superclass constructor, there's a problem.
1hild5int y8 ;
super(); // 1ompiler inserts this statement to call $arent58.
'y 4 y;
<
7o parameterless constructor
he problem is that the $arent class has no parameterless constructor. :hen any constructor is
explicitly defined &as in $arent above', the compiler no longer produces a default parameterless
constructor.
Possible solution ; - "#plicit constructor call
9sually the best solution is for the subclass constructor to explicitly call the superclass constructor
so that its fields are correctly initiali1ed.
1hild5int y8 ;
super(?@@@); // =a>e eBplicit call to superclass constructor.
'y 4 y;
<
Possible solution < - .e(ine a parameterless constructor
But no invalid values please. ,dvice you will sometimes see is to always define a parameterless
constructor, so that this problem doesn't occur. )ut an essential element of data encapsulation is
that the value of a ob!ect can be guaranteed to be a legal value. , constructor insures that the
initial value of an ob!ect is valid. $any ob!ects can't be given a valid value with a default
constructor. his peculiar semantic-free example $arent class might be changed to have a
parameterless constructor as follows &supposing that a value of -AAA ma"es sense for this class'3
9
D
E
/////////////////// class with parameterless
constructor. //////////////////////
class $arent ;
int 'B;
F
J
K
H
L
I
97
99
9D
9E
Parent() ; // $arameterless constructor
t!is(?@@@); // 1all other constructor with default value.
<
$arent5int B8 ; // 1onstructor with a parameter.
'B 4 B;
<
<
"#ample class &here a de(ault constructor &ould be a disaster
*t's common to have a class with no legal default values. .or example, what should the default
constructor do for this classK
9
D
E
F
J
K
H
L
I
97
99
9D
9E
9F
9J
9K
9H
9L
9I
D7
D9
// # parameterless constructor would be wrong here.
public class 2tudentD ;
private 2tring first)ame; // .irst name
private 2tring last)ame; // %ast name
private int id; // 2tudent id

//444444444444444444444444444444444444444444444444444444
constructor
public 2tudentD52tring fn 2tring ln int idnum8 ;
first)ame 4 fn;
last)ame 4 ln;
id 4 idnum;
<

//4444444444444444444444444444444444444444 parameterless
constructor
public 2tudentD58 ;
MMMM // )o possible legal values.
<

//4444444444444444444444444444444444444444444444444444444444
setters
public void set0:5int id8 ;
this.id 4 id;
<

. . .
<
DD
DE
DF
DJ
*f you defined a default constructor for 2tudentD, what would you assign to the fields - null for
the names and 1ero for the idK :hatever you choose it's illegal. here are setters so you hope that
the user will set the fields to legal values. Or you will chec" for the illegal initial values and throw an
exception or give some other error when there is an attempt to use them. =erhaps there are times
when this is acceptible in a small one-person pro!ect, but it's a disaster waiting to happen in
anything larger.
7ever de(ine a parameterless constructor unless it can create a valid object.
Constructor C!aining "#ercise +
8ame 7777777777777777777777777777777
?he (irst line of every constructor must be either
, this call to another constructor in the same class.
, super call to a parent constructor.
*f no constructor call is written as the first line of a constructor, the compiler automatically inserts a
call to the parameterless superclass constructor.
1uestion
:hat is printed by this programK
// .ile : 1onstructor1hain."ava
// $urpose: 0llustrate constructor chaining.
// #uthor : .red 2wartG
// :ate : J =ay D77E
class 1onstructor1hain ;
public static void main52tring?@ args8 ;
1hild c 4 new 1hild58;
<
<
class 2!il# exten#s Parent ;
1hild58 ;
2ystem.out.println5A1hild58 constructorA8;
<
<
class Parent exten#s Aran#parent ;
$arent58 ;
this5DJ8;
2ystem.out.println5A$arent58 constructorA8;
<

$arent5int B8 ;
2ystem.out.println5A$arent5A C B C A8 constructorA8;
<
<
class Aran#parent ;
3randparent58 ;
2ystem.out.println5A3randparent58 constructorA8;
<
<
You can chec" your answer with /onstructor /haining ,nswer.
Interfaces
*n interface is a list o( methods that must be de(ined by any class &hich implements that
inter(ace. *t may also define constants &public static final'.
Similar to abstract class. ,n interface is similar to a class without instance and static variables
&static final constants are allowed', and without method bodies. his is essentially what a
completely abstract class does, but abstract classes do allow static method definitions, and
interfaces don't.
Contractual obligation. :hen a class specifies that it implements an interface, it must define all
methods of that interface. , class can implement many different interfaces. *f a class doesn't define
all methods of the interfaces it agreed to define &by the implements clause', the compiler gives an
error message, which typically says something li"e (his class must be declared abstract(. ,n
abstract class is one that doesn't implement all methods it said it would. he solution to this is
almost always to implement the missing methods of the interface. , misspelled method name or
incorrect parameter list is the usual cause, not that it should have been abstractG
, very common use o( inter(aces is (or listeners. , listener is an ob!ect from a class that
implements the re<uired methods for that interface. You can create anon$mous inner listeners, or
implement the re<uired interface in any class.
*nterfaces are also used extensively in the data structures &Java /ollections' pac"age.
Classes versus nter(aces
/lasses are used to represent something that has attributes &variables, fields' and
capabilitiesFresponsibilities &methods, functions'. nter(aces are only about capabilities. .or
example, you are a human because you have the attributes of a human &class'. You are a plumber
because you have the ability of a plumber &interface'. You can also be an electrician &interface'. You
can implement many interfaces, but be only one class.
his analogy fails in one way however. /apabilities &methods' of a class are unchanging &if a class
implements an interface, it is implemented for all instances', whereas the human s"ills we're tal"ing
about are dynamic and can be learned or forgotten. he analogy is flawed, as all analogies are, but
it gives some idea of a distinction between classes and interfaces.
nter(aces replace multiple inheritance
Simpler. , /LL class can have more than one parent class. his is called multiple in"eritance.
$anaging instance variable definitions in multiple inheritance can be really messy, and leads to
more problems &eg, the (0eadly 0iamond of 0eath(' than solutions. .or this reason Java designers
chose to allow only one parent class, but allow multiple interfaces. his provides most of the useful
functionality of multiple inheritance, but without the difficulties.
mplementing an nter(ace
You may implement as many interfaces in a class as you wish+ !ust separate them with commas.
.or example,
// )ote:
// #ction%istener requires defining action$erformed5...8
// =ouse=otion%istener requires defining mouse=oved5...8 and
mouse:ragged5...8.
public class =y$anel eBtends -$anel implements 'ction3istener9
0ouse0otion3istener ;
public void action$erformed5#ction&vent e8 ;
/* =ethod body */
<
public void mouse:ragged5=ouse&vent me8 ;
/* =ethod body */
<
public void mouse=oved5=ouse&vent me8 ;
/* =ethod body */
<
// &verything else in this class.
<
*t is common for a panel that does graphics and responds to the mouse to implement its own mouse
listeners &but not action listeners' as above.
.eclaring an inter(ace
.or simple programs you are more li"ely to use an interface than define it. #ere is what the
!ava.awt.event.,ction%istener interface definition loo"s something li"e the following.
public interface #ction%istener ;
public void action$erformed5#ction&vent e8;
<
?agging nter(aces
Java defines a few interfaces that are !ust used as a boolean property of a class, but don't actually
re<uire the implemenation of any methods. hese are called tagging interfaces.
agging interfaces are an abuse of the interface principle, but Java ma"es use of ob!ect-oriented
features to solve all problems if possible, rather than invent a more appropriate feature.
Common tagging inter(aces that you might see are3
1loneable
*mplementing this interface indicates that the class has overridden Ob!ect's
clone58 method. )ut there is no chec" that this is true, and because subclasses
inherit interfaces, it will loo" li"e all subclasses have defined clone58 altho that is
not necessarily true. Yes, this is not the normal spelling of the English word. KKK
:hy needed.
2erialiGable
his tagging interface indicates that a class can seriali(ed - that an ob!ect of this
class can be written out and read bac" in using KKK. his can be useful for short-
term storage of ob!ects, but should not be used for long-term storage because any
change to the class definition ma"es that persistent copy unreadableG
"nums
Problem/ #ow to represent a set of named constant values. .irst we'll loo" at the (old( Java
solution, then see how Java C enums substantially improve the situation.
=lder% but common% solution
Just define a number of public static final int constants. .or example3
//... 1onstants to represent possible shapes.
public static final int +&1T#)3%& 4 7;
public static final int 10+1%& 4 9;
public static final int %0)& 4 D;
...
int drawing 4 +&1T#)3%&; // (ut any int could be assigned.
hese values can then be assigned to an integer variable, and can be used in switch statements.
his style is useful, but is not a great solution.
*llo&s illegal values. ,ny variable containing one of these values could also be assigned
any integer value, although there are only three legal choices. Eg,
drawing 4 II; // 0llogical value but allowed by compiler.
$pdates not re(lected in other code. *f there are additions, deletions, or reorderings,
code from other classes will not automatically be read!usted to reflect these changes. ,ll
code that uses these definitions would have to be recompiled.
7o easy /=. o convert values to and from a string form re<uires maintaining an
additional array and loo"up code.
0ragile (or loops. here is no obvious first and last value so iterating over all values is
sub!ect to errors which are not diagnosed at compile time if the values are rearranged,
deleted, or added to. here is no way to use the enhanced for loop.
7o behavior. his style is pre-OO= -- there are values, but no behavior defined for them.
.e(ining an enum type
,n enum type is a "ind of class definition. he possible enum values are listed in the curly braces,
separated by commas. )y convention the value names are in upper case.
public enum 2hape ; +&1T#)3%& 10+1%& %0)& <
.eclaring enum variables and using enum values
he enum class name can be use li"e any other class type in declarations. 9sually enum values
must be prefixed with the enum type name.
2hape drawing 4 2hape.+&1T#)3%&; // *nly a 2hape value can be
assigned.
Printing enum values
he enum class has a to2tring58 method defined that returns the un<ualified string version of
the value. his means that it's easy to print these values without any special conversion effort.
2ystem.out.println5drawing8; // $rints +&1T#)3%&
!ooping over all enum values &ith (oreach loop
he static values58 method of an enum type returns an array of the enum values. he foreac"
loop is a good way to go over all of them.
//... %oop over all values.
for 52hape shp : 2hape.values588 ;
2ystem.out.println5shp8; // $rints +&1T#)3%& 10+1%& ...
<
S&itch statement
he switch statement was enhanced to allow a convenient use of enums. 8ote that the case
values don't have to be <ualified with the enum class name, which can be determined from the
switch control value.
switch 5drawing8 ;
case +&1T#)3%&: g.draw+ect5B y width height8;
brea>;
case 10+1%& : g.draw*val5B y width height8;
brea>;
case %0)& : g.draw%ine5B y B C width y C height8;
brea>;
<
9etting an integer e:uivalent o( an enum value
Each enum value in an enum class has an associated default value, starting with 1ero for the first
value and incrementing by one for each additional value. his may be accessed with the
ordinal58 method.
2ystem.out.println5drawing.ordinal588; // $rints 7 for +&1T#)3%&.
nput
he value*f58 method can be used to convert a string value to an enum value. #ere is an
example of reading in a Shape value from a Scanner ob!ect in.
drawing 4 2hape.valueOf5in.neBt588;
.e(ining additional (ields% methods% and constants (or your enum type
$ethods can be defined for an enum class, including defining a different method body for each of
the constants. See the Sun article for examples of this. *f you are using switc" statements with
cases for each of the enum constants, consider putting the code into the enum class.
,elated data structure classes/ "numSet and "num>ap
he !ava.util.EnumSet class provides an efficient implementation of sets of enums as bit maps, or
powersets as they were called in =ascal. EnumSet can also generate an !terable for use with subsets
in the for-each statement.
!ava.util.Enum$ap provides an efficient implementation of a map for enums based on an array.
0urther reading
Enums is a good Sun overview of the Java enum features. *t's very readable with good
examples.
Example3 =aint0emo is a small paint program which represents the shape with an enum. *t
shows how to use an enum to represent simple constants, and also how to associate a
method with each constant.
/lass EnumPE extends EnumPEQQ is the ,=* documentation for the superclass of all
enums. You'll find useful methods in this class such as compareTo5...8, ordinal58,
to2tring58, and value*f5...8. he addition of generics negated the former Java
claim to simplicity, and it's this Enum definition which is often used as an example of the
incomprehensible. *t's hard to find anyone who understands this obscure declaration.
.ortunately, the use of enums doesn't re<uire that that you "now what this declaration
means.

You might also like