This document provides an overview of the key components of a Java program, including classes, methods, and variables. It explains that all Java code must be written within a class, with the main method serving as the program entry point. When the main method is called by the Java interpreter, the statements within it will execute. The document also describes the primitive data types in Java like int, float, boolean, and string, explaining how they are represented in memory and what values they can hold.
Download as DOC, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
89 views
Java Manual
This document provides an overview of the key components of a Java program, including classes, methods, and variables. It explains that all Java code must be written within a class, with the main method serving as the program entry point. When the main method is called by the Java interpreter, the statements within it will execute. The document also describes the primitive data types in Java like int, float, boolean, and string, explaining how they are represented in memory and what values they can hold.
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 38
Everything else in the program is required by the rules of Java syntax.
All programming in Java is done
inside "classes." The first line in the above program says that this is a class named HelloWorld. "HelloWorld" the name of the class also serves as the name of the program. !ot every class is a program. "n order to define a program a class must include a subroutine called main #ith a definition that ta$es the form% public static void main(String[] args) { statements } When you tell the Java interpreter to run the program the interpreter calls the main() subroutine and the statements that it contains are executed. These statements ma$e up the script that tells the computer exactly #hat to do #hen the program is executed. The main() routine can call subroutines that are defined in the same class or even in other classes but it is the main() routine that determines ho# and in #hat order the other subroutines are used. The #ord "public" in the first line of main() means that this routine can be called from outside the program. This is essential because the main() routine is called by the Java interpreter. The remainder of the first line of the routine is harder to explain at the moment& for no# 'ust thin$ of it as part of the required syntax. The definition of the subroutine (( that is the instructions that say #hat it does (( consists of the sequence of "statements" enclosed bet#een braces ) and *. Here "+ve used statements as a placeholder for the actual statements that ma$e up the program. Throughout this textboo$ " #ill al#ays use a similar format% anything that you see in this style of text ,#hich is green if your bro#ser supports colored text- is a placeholder that describes something you need to type #hen you #rite an actual program. As noted above a subroutine can+t exist by itself. "t has to be part of a "class". A program is defined by a public class that ta$es the form% public class program-name {
optional-variable-declarations-and-subroutines
public static void main(String[] args) { statements }
optional-variable-declarations-and-subroutines
} The name on the first line is the name of the program as #ell as the name of the class. "f the name of the class is HelloWorld then the class should be saved in a file called HelloWorld.java. When this file is compiled another file named HelloWorld.class #ill be produced. This class file HelloWorld.class contains the Java bytecode that is executed by a Java interpreter. HelloWorld.java is called the source code for the program. To execute the program you only need the compiled class file not the source code. Also note that according to the above syntax specification a program can contain other subroutines besides main() as #ell as things called "variable declarations." .ou+ll learn more about these later ,starting #ith variables in the next section-. There are eight so(called primitive types built into Java. The primitive types are named byte short int long loat double char! and boolean. The first four types hold integers ,#hole numbers such as /0 (12300 and 4-. The four integer types are distinguished by the ranges of integers they can hold. / The loat and double types hold real numbers ,such as 1.5 and (/36.77-. Again the t#o real types are distinguished by their range and accuracy. A variable of type char holds a single character from the 8nicode character set. And a variable of type boolean holds one of the t#o logical values true or alse. Any data value stored in the computer+s memory must be represented as a binary number that is as a string of 9eros and ones. A single 9ero or one is called a bit. A string of eight bits is called a byte. :emory is usually measured in terms of bytes. !ot surprisingly the byte data type refers to a single byte of memory. A variable of type byte holds a string of eight bits #hich can represent any of the integers bet#een (/;2 and /;0 inclusive. ,There are ;65 integers in that range& eight bits can represent ;65 (( t#o raised to the po#er eight (( different values.- As for the other integer types short corresponds to t#o bytes ,/5 bits-. <ariables of type short have values in the range (1;052 to 1;050. int corresponds to four bytes ,1; bits-. <ariables of type int have values in the range (;/30321532 to ;/30321530. long corresponds to eight bytes ,53 bits-. <ariables of type long have values in the range (7;;110;415263006242 to 7;;110;415263006240. .ou don+t have to remember these numbers but they do give you some idea of the si9e of integers that you can #or$ #ith. 8sually you should 'ust stic$ to the int data type #hich is good enough for most purposes. The loat data type is represented in four bytes of memory using a standard method for encoding real numbers. The maximum value for a loat is about /4 raised to the po#er 12. A loat can have about 0 significant digits. ,=o that 1;.1727;1//13 and 1;.1727;13177 #ould both have to be rounded off to about 1;.1727;1 in order to be stored in a variable of type loat.- A double ta$es up 2 bytes can range up to about /4 to the po#er 142 and has about /6 significant digits. >rdinarily you should stic$ to the double type for real values. A variable of type char occupies t#o bytes in memory. The value of a char variable is a single character such as A ? x or a space character. The value can also be a special character such a tab or a carriage return or one of the many 8nicode characters that come from different languages. When a character is typed into a program it must be surrounded by single quotes& for example% +A+ +?+ or +x+. Without the quotes A #ould be an identifier and ? #ould be a multiplication operator. The quotes are not part of the value and are not stored in the variable& they are 'ust a convention for naming a particular character constant in a program. A name for a constant value is called a literal. A literal is #hat you have to type in a program to represent a value. +A+ and +?+ are literals of type char representing the character values A and ?. @ertain special characters have special literals that use a bac$slash A as an "escape character". "n particular a tab is represented as "#t" a carriage return as "#r" a linefeed as "#n" the single quote character as "#"" and the bac$slash itself as "##". !ote that even though you type t#o characters bet#een the quotes in "#t" the value represented by this literal is a single tab character. !umeric literals are a little more complicated than you might expect. >f course there are the obvious literals such as 1/0 and /0.3;. But there are other possibilities for expressing numbers in a Java program. Cirst of all real numbers can be represented in an exponential form such as /.1e/; or /;.1010e(/42. The "e/;" and "e(/42" represent po#ers of /4 so that /.1e/; means /.1 times /4 /; and /;.1010e(/42 means /;.1010 times /4 (/42 . This format is used for very large and very small numbers. Any numerical literal that contains a decimal point or exponential is a literal of type double. To ma$e a literal of type loat you have to append an "C" or "f" to the end of the number. Cor example "/.;C" ; stands for /.; considered as a value of type loat. ,>ccasionally you need to $no# this because the rules of Java say that you can+t assign a value of type double to a variable of type loat so you might be confronted #ith a ridiculous(seeming error message if you try to do something li$e "loat $ % &.'(". .ou have to say "loat $ % &.')(*. This is one reason #hy " advise stic$ing to type double for real numbers.- Even for integer literals there are some complications. >rdinary integers such as /00000 and (1; are literals of type byte short or int depending on their si9e. .ou can ma$e a literal of type long by adding "D" as a suffix. Cor example% /0D or 0;2305203152D. As another complication Java allo#s octal ,base(2- and hexadecimal ,base(/5- literals. ," don+t #ant to cover base(2 and base(/5 in these notes but in case you run into them in other people+s programs it+s #orth $no#ing that a 9ero at the beginning of an integer ma$es it an octal literal as in 436 or 400. A hexadecimal literal begins #ith 4x or 4E as in 4x36 or 4xCC0A. By the #ay the octal literal 436 represents the number 10 not the number 36.- Cor the type boolean there are precisely t#o literals% true and alse. These literals are typed 'ust as "+ve #ritten them here #ithout quotes but they represent values not variables. Boolean values occur most often as the values of conditional expressions. Cor example rate + ,.,- is a boolean(valued expression that evaluates to true if the value of the variable rate is greater than 4.46 and to alse if the value of rate is not greater than 4.46. As you+ll see in @hapter 1 boolean( valued expressions are used extensively in control structures. >f course boolean values can also be assigned to variables of type boolean. Java has other types in addition to the primitive types but all the other types represent ob'ects rather than "primitive" data values. Cor the most part #e are not concerned #ith ob'ects for the time being. Ho#ever there is one predefined ob'ect type that is very important% the type String. A String is a sequence of characters. .ou+ve already seen a string literal% "Hello WorldF". The double quotes are part of the literal& they have to be typed in the program. Ho#ever they are not part of the actual string value #hich consists of 'ust the characters bet#een the quotes. Within a string special characters can be represented using the bac$slash notation. Within this context the double quote is itself a special character. Cor example to represent the string value " said "Are you listeningF" #ith a linefeed at the end you #ould have to type the literal% "" said A"Are you listeningFA"An" Because strings are ob'ects their behavior in programs is peculiar in some respects ,to someone #ho is not used to ob'ects-. "+ll have more to say about them in the next section. A variable can be used in a program only if it has first been declared. A variable declaration statement is used to declare one or more variables and to give them names. When the computer executes a variable declaration it sets aside memory for the variable and associates the variable+s name #ith that memory. A simple variable declaration ta$es the form% type-name variable-name-or-names& The variable-name-or-names can be a single variable name or a list of variable names separated by commas. ,We+ll see later that variable declaration statements can actually be some#hat more complicated than this.- Good programming style is to declare only one variable in a declaration statement unless the variables are closely related in some #ay. Cor example% 1 int number.Students( String name( double $! y( boolean is)inished( char irst/nitial! middle/nitial! last/nitial( "n this chapter #e #ill only use variables declared inside the main() subroutine of a program. <ariables declared inside a subroutine are called local variables for that subroutine. They exist only inside the subroutine #hile it is running and are completely inaccessible from outside. <ariable declarations can occur any#here inside the subroutine as long as each variable is declared before it is used in any expression. =ome people li$e to declare all the variables at the beginning of the subroutine. >thers li$e to #ait to declare a variable until it is needed. :y preference% Heclare important variables at the beginning of the subroutine and use a comment to explain the purpose of each variable. Heclare "utility variables" #hich are not important to the overall logic of the subroutine at the point in the subroutine #here they are first used. Here is a simple program using some variables and assignment statements% public class /nterest { 01 2his class implements a simple program that 3ill compute the amount o interest that is earned on 4&5!,,, invested at an interest rate o ,.,5 or one year. 2he interest and the value o the investment ater one year are printed to standard output. 10
public static void main(String[] args) {
01 6eclare the variables. 10
double principal( 00 2he value o the investment. double rate( 00 2he annual interest rate. double interest( 00 /nterest earned in one year.
01 6o the computations. 10
principal % &5,,,( rate % ,.,5( interest % principal 1 rate( 00 7ompute the interest.
principal % principal 8 interest( 00 7ompute value o investment ater one year! 3ith interest. 00 (9ote: 2he ne3 value replaces the old value o principal.)
01 .utput the results. 10
System.out.print(*2he interest earned is 4*)( System.out.println(interest)( System.out.print(*2he value o the investment ater one year is 4*)( System.out.println(principal)(
} 00 end o main()
} 00 end o class /nterest This program uses several subroutine call statements to display information to the user of the program. T#o different subroutines are used% System.out.print and System.out.println. The difference bet#een these is that System.out.println adds a carriage return after the end of the information that it 3 displays #hile System.out.print does not. Thus the value of interest #hich is displayed by the subroutine call "System.out.println(interest)(" follo#s on the same line after the string displayed by the previous statement. !ote that the value to be displayed by System.out.print or System.out.println is provided in parentheses after the subroutine name. This value is called a parameter to the subroutine. A parameter provides a subroutine #ith information it needs to perform its tas$. "n a subroutine call statement any parameters are listed in parentheses after the subroutine name. !ot all subroutines have parameters. "f there are no parameters in a subroutine call statement the subroutine name must be follo#ed by an empty pair of parentheses. Strings, Objects, and Subroutines THE IJE<">8= =E@T">! introduced the eight primitive data types and the type String. There is a fundamental difference bet#een the primitive types and the String type% <alues of type String are ob'ects. While #e #ill not study ob'ects in detail until @hapter 6 it #ill be useful for you to $no# a little about them and about a closely related topic% classes. This is not 'ust because strings are useful but because ob'ects and classes are essential to understanding another important programming concept subroutines. Jecall that a subroutine is a set of program instructions that have been chun$ed together and given a name. "n @hapter 3 you+ll learn ho# to #rite your o#n subroutines but you can get a lot done in a program 'ust by calling subroutines that have already been #ritten for you. "n Java every subroutine is contained in a class or in an ob'ect. =ome classes that are standard parts of the Java language contain predefined subroutines that you can use. A value of type String #hich is an ob'ect contains subroutines that can be used to manipulate that string. .ou can call all these subroutines #ithout understanding ho# they #ere #ritten or ho# they #or$. "ndeed that+s the #hole point of subroutines% A subroutine is a "blac$ box" #hich can be used #ithout $no#ing #hat goes on inside. @lasses in Java have t#o very different functions. Cirst of all a class can group together variables and subroutines that are contained in that class. These variables and subroutines are called static members of the class. .ou+ve seen one example% "n a class that defines a program the main() routine is a static member of the class. The parts of a class definition that define static members are mar$ed #ith the reserved #ord "static" 'ust li$e the main() routine of a program. Ho#ever classes have a second function. They are used to describe ob'ects. "n this role the class of an ob'ect specifies #hat subroutines and variables are contained in that ob'ect. The class is a type (( in the technical sense of a specification of a certain type of data value (( and the ob'ect is a value of that type. Cor example String is actually the name of a class that is included as a standard part of the Java language. "t is also a type and actual strings such as *Hello World* are values of type String. =o every subroutine is contained either in a class or in an ob'ect. @lasses contain subroutines called static member subroutines. @lasses also describe ob'ects and the subroutines that are contained in those ob'ects. This dual use can be confusing and in practice most classes are designed to perform primarily or exclusively in only one of the t#o possible roles. Cor example although the String class does contain a fe# rarely(used static member subroutines it exists mainly to specify a large number of subroutines that are contained in ob'ects of type String. Another standard class named ;ath exists entirely to group together a number of static member subroutines that compute various common mathematical functions. To begin to get a handle on all of this complexity let+s loo$ at the subroutine System.out.print as an example. As you have seen earlier in this chapter this subroutine is used to display information to the user. Cor example System.out.print(*Hello World*) displays the message Hello World. 6 System is one of Java+s standard classes. >ne of the static member variables in this class is named out. =ince this variable is contained in the class System its full name (( #hich you have to use to refer to it in your programs (( is System.out. The variable System.out refers to an ob'ect and that ob'ect in turn contains a subroutine named print. The compound identifier System.out.print refers to the subroutine print in the ob'ect out in the class System. ,As an aside " #ill note that the ob'ect referred to by System.out is an ob'ect of the class <rintStream. <rintStream is another class that is a standard part of Java. Any ob'ect of type <rintStream is a destination to #hich information can be printed& any ob'ect of type <rintStream has a print subroutine that can be used to send information to that destination. The ob'ect System.out is 'ust one possible destination and System.out.print is the subroutine that sends information to that destination. >ther ob'ects of type <rintStream might send information to other destinations such as files or across a net#or$ to other computers. This is ob'ect(oriented programming% :any different things #hich have something in common (( they can all be used as destinations for information (( can all be used in the same #ay (( through a print subroutine. The <rintStream class expresses the commonalities among all these ob'ects.- =ince class names and variable names are used in similar #ays it might be hard to tell #hich is #hich. All the built(in predefined names in Java follo# the rule that class names begin #ith an upper case letter #hile variable names begin #ith a lo#er case letter. While this is not a formal syntax rule " recommend that you follo# it in your o#n programming. =ubroutine names should also begin #ith lo#er case letters. There is no possibility of confusing a variable #ith a subroutine since a subroutine name in a program is al#ays follo#ed by a left parenthesis. @lasses can contain static member subroutines as #ell as static member variables. Cor example the System class contains a subroutine named e$it. "n a program of course this subroutine must be referred to as System.e$it. @alling this subroutine #ill terminate the program. .ou could use it if you had some reason to terminate the program before the end of the main routine. ,Cor historical reasons this subroutine ta$es an integer as a parameter so the subroutine call statement might loo$ li$e "System.e$it(,)(" or "System.e$it(&)(". The parameter tells the computer #hy the program is being terminated. A parameter value of 4 indicates that the program is ending normally. Any other value indicates that the program is being terminated because an error has been detected.- Every subroutine performs some specific tas$. Cor some subroutines that tas$ is to compute or retrieve some data value. =ubroutines of this type are called functions. We say that a function returns a value. The returned value must then be used someho# in the program. .ou are familiar #ith the mathematical function that computes the square root of a number. Java has a corresponding function called ;ath.s=rt. This function is a static member subroutine of the class named ;ath. "f $ is any numerical value then ;ath.s=rt($) computes and returns the square root of that value. =ince ;ath.s=rt($) represents a value it doesn+t ma$e sense to put it on a line by itself in a subroutine call statement such as ;ath.s=rt($)( 00 This doesn't make sense! What after all #ould the computer do #ith the value computed by the function in this caseK .ou have to tell the computer to do something #ith the value. .ou might tell the computer to display it% System.out.print( ;ath.s=rt($) )( 00 6isplay the s=uare root o $. or you might use an assignment statement to tell the computer to store that value in a variable% length.Side % ;ath.s=rt($)( The function call ;ath.s=rt($) represents a value of type double and it can be used anyplace #here a numerical value of type double could be used. 5 The ;ath class contains many static member functions. Here is a list of some of the more important of them% ;ath.abs($) #hich computes the absolute value of $. The usual trigonometric functions ;ath.sin($) ;ath.cos($) and ;ath.tan($). ,Cor all the trigonometric functions angles are measured in radians not degrees.- The inverse trigonometric functions arcsin arccos and arctan #hich are #ritten as% ;ath.asin($) ;ath.acos($) and ;ath.atan($). The exponential function ;ath.e$p($) for computing the number e raised to the po#er $ and the natural logarithm function ;ath.log($) for computing the logarithm of $ in the base e. ;ath.po3($!y) for computing $ raised to the po#er y. ;ath.loor($) #hich rounds $ do#n to the nearest integer value that is less than or equal to $. ,Cor example ;ath.loor(>.5?) is 1.4.- ;ath.random() #hich returns a randomly chosen double in the range ,., @% ;ath.random() @ &.,. ,The computer actually calculates so(called "pseudorandom" numbers #hich are not truly random but are random enough for most purposes.- Cor these functions the type of the parameter (( the value inside parentheses (( can be of any numeric type. Cor most of the functions the value returned by the function is of type double no matter #hat the type of the parameter. Ho#ever for ;ath.abs($) the value returned #ill be the same type as $. "f $ is of type int then so is ;ath.abs($). ,=o for example #hile ;ath.s=rt(A) is the double value 1.4 ;ath.abs(A) is the int value 7.- !ote that ;ath.random() does not have any parameter. .ou still need the parentheses even though there+s nothing bet#een them. The parentheses let the computer $no# that this is a subroutine rather than a variable. Another example of a subroutine that has no parameters is the function System.current2ime;illis() from the System class. When this function is executed it retrieves the current time expressed as the number of milliseconds that have passed since a standardi9ed base time ,the start of the year /704 in Green#ich :ean Time if you care-. >ne millisecond is one thousandth second. The value of System.current2ime;illis() is of type long. This function can be used to measure the time that it ta$es the computer to perform a tas$. Just record the time at #hich the tas$ is begun and the time at #hich it is finished and ta$e the difference. Here is a sample program that performs a fe# mathematical tas$s and reports the time that it ta$es for the program to run. >n some computers the time reported might be 9ero because it is too small to measure in milliseconds. Even if it+s not 9ero you can be sure that most of the time reported by the computer #as spent doing output or #or$ing on tas$s other than the program since the calculations performed in this program occupy only a tiny fraction of a second of a computer+s time. public class 2imed7omputation {
01 2his program perorms some mathematical computations and displays the results. /t then reports the number o seconds that the computer spent on this tasB. 10
public static void main(String[] args) {
long start2ime( 00 Starting time o program! in milliseconds. 0 long end2ime( 00 2ime 3hen computations are done! in milliseconds. double time( 00 2ime dierence! in seconds.
start2ime % System.current2ime;illis()(
double 3idth! height! hypotenuse( 00 sides o a triangle 3idth % C'.,( height % &5.,( hypotenuse % ;ath.s=rt( 3idth13idth 8 height1height )( System.out.print(*D triangle 3ith sides C' and &5 has hypotenuse *)( System.out.println(hypotenuse)(
System.out.println(*#n;athematically! sin($)1sin($) 8 * 8 *cos($)1cos($) E & should be ,.*)( System.out.println(*Fet"s checB this or $ % &:*)( System.out.print(* sin(&)1sin(&) 8 cos(&)1cos(&) E & is *)( System.out.println( ;ath.sin(&)1;ath.sin(&) 8 ;ath.cos(&)1;ath.cos(&) E & )( System.out.println(*(2here can be roundEo errors 3hen * 8 * computing 3ith real numbersG)*)(
System.out.print(*#nHere is a random number: *)( System.out.println( ;ath.random() )(
end2ime % System.current2ime;illis()( time % (end2ime E start2ime) 0 &,,,.,(
System.out.print(*#nHun time in seconds 3as: *)( System.out.println(time)(
} 00 end main()
} 00 end class 2imed7omputation A value of type String is an ob'ect. That ob'ect contains data namely the sequence of characters that ma$e up the string. "t also contains subroutines. All of these subroutines are in fact functions. Cor example length is a subroutine that computes the length of a string. =uppose that str is a variable that refers to a String. Cor example str might have been declared and assigned a value as follo#s% String str( str % *SeiIe the dayG*( Then str.length() is a function call that represents the number of characters in the string. The value of str.length() is an int. !ote that this function has no parameter& the string #hose length is being computed is str. The length subroutine is defined by the class String and it can be used #ith any value of type String. "t can even be used #ith String literals #hich are after all 'ust constant values of type String. Cor example you could have a program count the characters in "Hello World" for you by saying System.out.print(*2he number o characters in *)( System.out.println(*the string #*Hello World#* is *)( System.out.println( *Hello World*.length() )( The String class defines a lot of functions. Here are some that you might find useful. Assume that s& and s' refer to values of type String% s&.e=uals(s') is a function that returns a boolean value. "t returns true if s& consists of exactly the same sequence of characters as s' and returns alse other#ise. s&.e=uals/gnore7ase(s') is another boolean(valued function that chec$s #hether s& is the same string as s' but this function considers upper and lo#er case letters to be 2 equivalent. Thus if s& is "cat" then s&.e=uals(*7at*) is alse #hile s&.e=uals/gnore7ase(*7at*) is true. s&.length() as mentioned above is an integer(valued function that gives the number of characters in s&. s&.charDt(9) #here 9 is an integer returns a value of type char. "t returns the 9(th character in the string. Iositions are numbered starting #ith 4 so s&.charDt(,) is the actually the first character s&.charDt(&) is the second and so on. The final position is s&.length() E &. Cor example the value of *cat*.charDt(&) is +a+. An error occurs if the value of the parameter is less than 9ero or greater than s&.length() E &. s&.substring(9!;) #here 9 and ; are integers returns a value of type String. The returned value consists of the characters in s& in positions 9 98&... ;E&. !ote that the character in position ; is not included. The returned value is called a substring of s&. s&.inde$.(s') returns an integer. "f s' occurs as a substring of s& then the returned value is the starting position of that substring. >ther#ise the returned value is (/. .ou can also use s&.inde$.(ch) to search for a particular character ch in s&. To find the first occurrence of $ at or after position 9 you can use s&.inde$.($!9). s&.compare2o(s') is an integer(valued function that compares the t#o strings. "f the strings are equal the value returned is 9ero. "f s& is less than s' the value returned is a number less than 9ero and if s& is greater than s' the value returned is some number greater than 9ero. ,"f both of the strings consist entirely of lo#ercase letters then "less than" and "greater than" refer to alphabetical order. >ther#ise the ordering is more complicated.- s&.toJpper7ase() is a String(valued function that returns a ne# string that is equal to s& except that any lo#er case letters in s& have been converted to upper case. Cor example "@at".to8pper@ase,- is the string "@AT". There is also a method s&.toFo3er7ase(). s&.trim() is a String(valued function that returns a ne# string that is equal to s& except that any non(printing characters such as spaces and tabs have been trimmed from the beginning and from the end of the string. Thus if s& has the value "fred " then s&.trim() is the string "fred". Cor the methods s&.toJpper7ase() s&.toFo3er7ase() and s&.trim() note that the value of s& is not changed. "nstead a ne# string is created and returned as the value of the function. The returned value could be used for example in an assignment statement such as "s' % s&.toFo3er7ase()(". Here is another extremely useful fact about strings% .ou can use the plus operator L to concatenate t#o strings. The concatenation of t#o strings is a ne# string consisting of all the characters of the first string follo#ed by all the characters of the second string. Cor example "Hello" L "World" evaluates to "HelloWorld". ,Gotta #atch those spaces of course.- Det+s suppose that name is a variable of type String and that it already refers to the name of the person using the program. Then the program could greet the user by executing the statement% System.out.println(*Hello! * 8 name 8 *. <leased to meet youG*)( Even more surprising is that you can concatenate values belonging to one of the primitive types onto a String using the L operator. The value of primitive type is converted to a string 'ust as it #ould be if you printed it to the standard output and then it is concatenated onto the string. Cor example the expression "!umber" L 3; evaluates to the string "!umber3;". And the statements 7 System.out.print(*Dter *)( System.out.print(years)( System.out.print(* years! the value is *)( System.out.print(principal)( can be replaced by the single statement% System.out.print(*Dter * 8 years 8 * years! the value is * 8 principal)( "!M>8T Text"> The 2e$t/. class is a little more versatile at doing output than is System.out. Ho#ever it+s input for #hich #e really need it. With 2e$t/. input is done using functions. Cor example 2e$t/..get/nt() #hich #as discussed above ma$es the user type in a value of type int and returns that input value so that you can use it in your program. 2e$t/. includes several functions for reading different types of input values. Here are examples of using each of them% b % 2e$t/..getKyte()( 00 value read is a byte i % 2e$t/..getShort()( 00 value read is a short j % 2e$t/..get/nt()( 00 value read is an int B % 2e$t/..getFong()( 00 value read is a long $ % 2e$t/..get)loat()( 00 value read is a loat y % 2e$t/..get6ouble()( 00 value read is a double a % 2e$t/..getKoolean()( 00 value read is a boolean c % 2e$t/..get7har()( 00 value read is a char 3 % 2e$t/..getWord()( 00 value read is a String s % 2e$t/..getln()( 00 value read is a String Cor these statements to be legal the variables on the left side of each assignment statement must be of the same type as that returned by the function on the right side. When you call one of these functions you are guaranteed that it #ill return a legal value of the correct type. "f the user types in an illegal value as input (( for example if you as$ for a byte and the user types in a number that is outside the legal range of (/;2 to /;0 (( then the computer #ill as$ the user to re( enter the value and your program never sees the first illegal value that the user entered. .ou+ll notice that there are t#o input functions that return =trings. The first getWord() returns a string consisting of non(blan$ characters only. When it is called it s$ips over any spaces and carriage returns typed in by the user. Then it reads non(blan$ characters until it gets to the next space or carriage return. "t returns a String consisting of all the non(blan$ characters that it has read. The second input function getln() simply returns a string consisting of all the characters typed in by the user including spaces up to the next carriage return. "t gets an entire line of input text. The carriage return itself is not returned as part of the input string but it is read and discarded by the computer. !ote that the =tring returned by this function might be the empty string ** #hich contains no characters at all. All the other input functions listed (( getKyte() getShort() get/nt() getFong() get)loat() get6ouble() getKoolean() and get7har() (( behave li$e getWord(). That is they #ill s$ip past any blan$s and carriage returns in the input before reading a value. Ho#ever they #ill not s$ip past other characters. "f you try to read t#o ints and the user types ";1" the computer #ill read the first number correctly but #hen it tries to read the second number it #ill see the comma. "t #ill regard this as an error and #ill force the user to retype the number. "f you #ant to input several numbers from one line you should ma$e sure that the user $no#s to separate them #ith spaces not commas. Alternatively /4 if you #ant to require a comma bet#een the numbers use get7har() to read the comma before reading the second number. There is another character input function 2e$t/..getDny7har() #hich does not s$ip past blan$s or carriage returns. "t simply reads and returns the next character typed by the user. This could be any character including a space or a carriage return. "f the user typed a carriage return then the char returned by get7har() is the special linefeed character +An+. There is also a function 2e$t/..peeB() that let+s you loo$ ahead at the next character in the input #ithout actually reading it. After you "pee$" at the next character it #ill still be there #hen you read the next item from input. This allo#s you to loo$ ahead and see #hat+s coming up in the input so that you can ta$e different actions depending on #hat+s there. The semantics of input is much more complicated than the semantics of output. The first time the program tries to read input from the user the computer #ill #ait #hile the user types in an entire line of input. 2e$t/. stores that line in a chun$ of internal memory called the input buffer. "nput is actually read from the buffer not directly from the user+s typing. The user only gets to type #hen the buffer is empty. This lets you read several numbers from one line of input. Ho#ever if you only #ant to read in one number and the user types in extra stuff on the line then you could be in trouble. The extra stuff #ill still be there the next time you try to read something from input. ,The symptom of this trouble is that the computer doesn+t pause #here you thin$ it should to let the user type something in. The computer had stuff left over in the input buffer from the previous line that the user typed.- To help you avoid this there are versions of the 2e$t/. input functions that read a data value and then discard any leftover stuff on the same line% b % 2e$t/..getlnKyte()( 00 value read is a byte i % 2e$t/..getlnShort()( 00 value read is a short j % 2e$t/..getln/nt()( 00 value read is an int B % 2e$t/..getlnFong()( 00 value read is a long $ % 2e$t/..getln)loat()( 00 value read is a loat y % 2e$t/..getln6ouble()( 00 value read is a double a % 2e$t/..getlnKoolean()( 00 value read is a boolean c % 2e$t/..getln7har()( 00 value read is a char 3 % 2e$t/..getlnWord()( 00 value read is a String !ote that calling getln6ouble() for example is equivalent to first calling get6ouble() and then calling getln() to read any remaining data on the same line including the end(of(line character itself. " strongly advise you to use the "getln" versions of the input routines rather than the "get" versions unless you really #ant to read several items from the same line of input. .ou might be #ondering #hy there are only t#o output routines put and putln #hich can output data values of any type #hile there is a separate input routine for each data type. As noted above in reality there are many put and putln routines. The computer can tell them apart based on the type of the parameter that you provide. Ho#ever the input routines don+t have parameters so the different input routines can only be distinguished by having different names. 8sing 2e$t/. for input and output #e can no# improve the program from =ection ; for computing the value of an investment. We can have the user type in the initial value of the investment and the interest rate. The result is a much more useful program (( for one thing it ma$es sense to run more than onceF public class /nterest' {
01 2his class implements a simple program that 3ill compute the amount o interest that is earned on an investment over a period o one year. 2he initial amount o the investment and the interest rate are input by the user. // 2he value o the investment at the end o the year is output. 2he rate must be input as a decimal! not a percentage (or e$ample! ,.,-! rather than -). 10
public static void main(String[] args) {
double principal( 00 the value o the investment double rate( 00 the annual interest rate double interest( 00 the interest earned during the year
2e$t/..put(*Lnter the initial investment: *)( principal % 2e$t/..getln6ouble()(
2e$t/..put(*Lnter the annual interest rate: *)( rate % 2e$t/..getln6ouble()(
interest % principal 1 rate( 00 compute this year"s interest principal % principal 8 interest( 00 add it to principal
2e$t/..put(*2he value o the investment ater one year is 4*)( 2e$t/..putln(principal)(
} 00 end o main()
} 00 end o class /nterest'
Details of Expressions TH"= =E@T">! TANE= A @D>=EJ D>>N at expressions. Jecall that an expression is a piece of program code that represents or computes a value. An expression can be a literal a variable a function call or several of these things combined #ith operators such as 8 and +. The value of an expression can be assigned to a variable used as the output value in an output routine or combined #ith other values into a more complicated expression. ,The value can even in some cases be ignored if that+s #hat you #ant to do& this is more common than you might thin$.- Expressions are an essential part of programming. =o far these notes have dealt only informally #ith expressions. This section tells you the more(or(less complete story. The basic building bloc$s of expressions are literals ,such as ?5C >.&C true and "M"- variables and function calls. Jecall that a function is a subroutine that returns a value. .ou+ve already seen some examples of functions% the input routines from the 2e$t/. class and the mathematical functions from the ;ath class. Diterals variables and function calls are simple expressions. :ore complex expressions can be built up by using operators to combine simpler expressions. >perators include 8 for adding t#o numbers + for comparing t#o values and so on. When several operators appear in an expression there is a question of precedence #hich determines ho# the operators are grouped for evaluation. Cor example in the expression "D 8 K 1 7" K17 is computed first and then the result is added to D. We say that multiplication ,1- has higher precedence than addition ,8-. "f the default precedence is not #hat you #ant you can use parentheses to explicitly specify the grouping you #ant. Cor example you could use "(D 8 K) 1 7" if you #ant to add D to K first and then multiply the result by 7. /; The rest of this section gives details of operators in Java. The number of operators in Java is quite large and " #ill not cover them all here. :ost of the important ones are here& a fe# #ill be covered in later chapters as they become relevant. Arithmetic Operators Arithmetic operators include addition subtraction multiplication and division. They are indicated by 8 E 1 and 0. These operations can be used on values of any numeric type% byte short int long loat or double. When the computer actually calculates one of these operations the t#o values that it combines must be of the same type. "f your program tells the computer to combine t#o values of different types the computer #ill convert one of the values from one type to another. Cor example to compute 10.3 L /4 the computer #ill convert the integer /4 to a real number /4.4 and #ill then compute 10.3 L /4.4. ,The computer+s internal representations for /4 and /4.4 are very different even though people thin$ of them as representing the same number.- >rdinarily you don+t have to #orry about type conversion because the computer does it automatically. When t#o numerical values are combined ,after doing type conversion on one of them if necessary- the ans#er #ill be of the same type. "f you multiply t#o ints you get an int& if you multiply t#o doubles you get a double. This is #hat you #ould expect but you have to be very careful #hen you use the division operator 0. When you divide t#o integers the ans#er #ill al#ays be an integer& if the quotient has a fractional part it is discarded. Cor example the value of 50' is > not >.-. "f 9 is an integer variable then 90&,, is an integer and &09 is equal to 9ero for any 9 greater than oneF This fact is a common source of programming errors. .ou can force the computer to compute a real number as the ans#er by ma$ing one of the operands real% Cor example #hen the computer evaluates &.,09 it first converts 9 to a real number in order to match the type of &., so you get a real number as the ans#er. Java also has an operator for computing the remainder #hen one integer is divided by another. This operator is indicated by N. "f D and K are integers then D N K represents the remainder #hen D is divided by K. Cor example 5 N ' is & #hile >C-55 N &,, is 55 and -, N O is '. A common use of N is to test #hether a given integer is even or odd. 9 is even if 9 N ' is 9ero and it is odd if 9 N ' is &. :ore generally you can chec$ #hether an integer 9 is evenly divisible by an integer ; by chec$ing #hether 9 N ; is 9ero. Cinally you might need the unary minus operator #hich ta$es the negative of a number. Cor example EM has the same value as (E&)1M. Cor completeness Java also has a unary plus operator as in 8M even though it doesn+t really do anything. Increment and Decrement .ou+ll find that adding & to a variable is an extremely common operation in programming. =ubtracting & from a variable is also pretty common. .ou might perform the operation of adding & to a variable #ith assignment statements such as% counter % counter 8 &( goalsScored % goalsScored 8 &( The effect of the assignment statement $ % $ 8 & is to ta$e the old value of the variable $ compute the result of adding & to that value and store the ans#er as the ne# value of $. The same operation can be accomplished by #riting $88 ,or if you prefer 88$-. This actually changes the value of $ so that it has the same effect as #riting "$ % $ 8 &". The t#o statements above could be #ritten counter88( goalsScored88( /1 =imilarly you could #rite $EE ,or EE$- to subtract & from $. That is $EE performs the same computation as $ % $ E &. Adding & to a variable is called incrementing that variable and subtracting & is called decrementing. The operators 88 and EE are called the increment operator and the decrement operator respectively. These operators can be used on variables belonging to any of the numerical types and also on variables of type char. 8sually the operators 88 or EE are used in statements li$e "$88&" or "$EE&". These statements are commands to change the value of $. Ho#ever it is also legal to use $88 88$ $EE or EE$ as expressions or as parts of larger expressions. That is you can #rite things li$e% y % $88( y % 88$( 2e$t/..putln(EE$)( I % (88$) 1 (yEE)( The statement "y % $88&" has the effects of adding & to the value of $ and in addition assigning some value to y. The value assigned to y is the value of the expression $88 #hich is defined to be the old value of $ before the & is added. Thus if the value of $ is ? the statement "y % $88&" #ill change the value of $ to 5 but it #ill change the value of y to ? since the value assigned to y is the old value of $. >n the other hand the value of 88$ is defined to be the ne value of $ after the & is added. =o if $ is ? then the statement "y % 88$&" changes the values of both $ and y to 5. The decrement operator EE #or$s in a similar #ay. This can be confusing. :y advice is% Hon+t be confused. 8se 88 and EE only in stand(alone statements not in expressions. " #ill follo# this advice in all the examples in these notes. !elational Operators Java has boolean variables and boolean(valued expressions that can be used to express conditions that can be either true or alse. >ne #ay to form a boolean(valued expression is to compare t#o values using a relational operator. Jelational operators are used to test #hether t#o values are equal #hether one value is greater than another and so forth. The relation operators in Java are% %% G% @ + @% and +%. The meanings of these operators are% D %% K /s D *e=ual to* KP D G% K /s D *not e=ual to* KP D @ K /s D *less than* KP D + K /s D *greater than* KP D @% K /s D *less than or e=ual to* KP D +% K /s D *greater than or e=ual to* KP These operators can be used to compare values of any of the numeric types. They can also be used to compare values of type char. Cor characters @ and + are defined according the numeric 8nicode values of the characters. ,This might not al#ays be #hat you #ant. "t is not the same as alphabetical order because all the upper case letters come before all the lo#er case letters.- When using boolean expressions you should remember that as far as the computer is concerned there is nothing special about boolean values. "n the next chapter you #ill see ho# to use them in loop and branch statements. But you can also assign boolean(valued expressions to boolean variables 'ust as you can assign numeric values to numeric variables. By the #ay the operators OO and FO can be used to compare boolean values. This is occasionally useful. Cor example can you figure out #hat this does% boolean sameSign( sameSign % (($ + ,) %% (y + ,))( >ne thing that you cannot do #ith the relational operators @ + @% and @% is to use them to compare values of type String. .ou can legally use %% and G% to compare Strings but because of peculiarities /3 in the #ay ob'ects behave they might not give the results you #ant. ,The %% operator chec$s #hether t#o ob'ects are stored in the same memory location rather than #hether they contain the same value. >ccasionally for some ob'ects you do #ant to ma$e such a chec$ (( but rarely for strings. "+ll get bac$ to this in a later chapter.- "nstead you should use the subroutines e=uals() e=uals/gnore7ase() and compare2o() #hich #ere described in =ection 1 to compare t#o Strings. "oolean Operators "n English complicated conditions can be formed using the #ords "and" "or" and "not." Cor example ""f there is a test and you did not study for it...". "And" "or" and "not" are boolean operators and they exist in Java as #ell as in English. "n Java the boolean operator "and" is represented by QQ. The QQ operator is used to combine t#o boolean values. The result is also a boolean value. The result is true if both of the combined values are true and the result is alse if either of the combined values is alse. Cor example "($ %% ,) QQ (y %% ,)" is true if and only if both $ is equal to 4 and y is equal to 4. The boolean operator "or" is represented by RR. ,That+s supposed to be t#o of the vertical line characters R.- The expression "D RR K" is true if either D is true or K is true or if both are true. "D RR K" is alse only if both D and K are false. The operators QQ and RR are said to be short(circuited versions of the boolean operators. This means that the second operand of QQ or RR is not necessarily evaluated. @onsider the test ($ G% ,) QQ (y0$ + &) =uppose that the value of $ is in fact 9ero. "n that case the division y0$ is illegal since division by 9ero is not allo#ed. Ho#ever the computer #ill never perform the division since #hen the computer evaluates ($ G% ,) it finds that the result is alse and so it $no#s that ,($ G% ,) QQ anything- has to be false. Therefore it doesn+t bother to evaluate the second operand (y0$ + &). The evaluation has been short(circuited and the division by 9ero is avoided. Without the short(circuiting there #ould have been a division(by(9ero error. ,This may seem li$e a technicality and it is. But at times it #ill ma$e your programming life a little easier. To be even more technical% There are actually non(short(circuited versions of QQ and RR #hich are #ritten as Q and R. Hon+t use them unless you have a particular reason to do so.- The boolean operator "not" is a unary operator. "n Java it is indicated by G and is #ritten in front of its single operand. Cor example if test is a boolean variable then test % G test( #ill reverse the value of test changing it from true to alse or from alse to true. #onditional Operator Any good programming language has some nifty little features that aren+t really necessary but that let you feel cool #hen you use them. Java has the conditional operator. "t+s a ternary operator (( that is it has three operands (( and it comes in t#o pieces K and % that have to be used together. "t ta$es the form boolean-expression K expression-$ % expression-% The computer tests the value of boolean-expression. "f the value is true it evaluates expression-$& other#ise it evaluates expression-%. Cor example% ne$t % (9 N ' %% ,) P (90') : (>198&)( /6 #ill assign the value 90' to ne$t if 9 is even ,that is if 9 N ' %% , is true- and it #ill assign the value (>198&) to ne$t if 9 is odd. Assignment Operators and &ype-#asts .ou are already familiar #ith the assignment statement #hich uses the symbol "O" to assign the value of an expression to a variable. "n fact O is really an operator in the sense that an assignment can itself be used as an expression or as part of a more complex expression. The value of an assignment such as D%K is the same as the value that is assigned to D. =o if you #ant to assign the value of K to D and test at the same time #hether that value is 9ero you could say% i ( (D%K) %% , ) 8sually " #ould say don't do things li(e thatF "n general the type of the expression on the right(hand side of an assignment statement must be the same as the type of the variable on the left(hand side. Ho#ever in some cases the computer #ill automatically convert the value computed by the expression to match the type of the variable. @onsider the list of numeric types% byte short int long loat double. A value of a type that occurs earlier in this list can be converted automatically to a value that occurs later. Cor example% int D( double M( short K( D % &5( M % D( 00 .S( D is converted to a double K % D( 00 illegal( no automatic conversion 00 rom int to short The idea is that conversion should only be done automatically #hen it can be done #ithout changing the semantics of the value. Any int can be converted to a double #ith the same numeric value. Ho#ever there are int values that lie outside the legal range of shorts. There is simply no #ay to represent the int /44444 as a short for example since the largest value of type short is 1;050. "n some cases you might #ant to force a conversion that #ouldn+t be done automatically. Cor this you can use #hat is called a type cast. A type cast is indicated by putting a type name in parentheses in front of the value you #ant to convert. Cor example int D( short K( D % &5( K % (short)D( 00 .S( D is e$plicitly type cast 00 to a value o type short .ou can do type casts from any numeric type to any other numeric type. Ho#ever you should note that you might change the numeric value of a number by type(casting it. Cor example (short)&,,,,, is 13353. ,The 13353 is obtained by ta$ing the 3(byte int /44444 and thro#ing a#ay t#o of those bytes to obtain a short (( you+ve lost the real information that #as in those t#o bytes.- As another example of type casts consider the problem of getting a random integer bet#een / and 5. The function ;ath.random() gives a real number bet#een 4.4 and 4.7777... and so ?1;ath.random() is bet#een 4.4 and 6.777.... The type(cast operator (int) can be used to convert this to an integer% (int)(?1;ath.random()). A real number is cast to an integer by discarding the fractional part. Thus (int)(?1;ath.random()) is one of the integers 4 / ; 1 3 and 6. To get a number bet#een / and 5 #e can add /% "(int)(?1;ath.random()) 8 &". .ou can also type(cast bet#een the type char and the numeric types. The numeric value of a char is its 8nicode code number. Cor example (char)A5 is "a" and (int)"8" is C>. /5 Java has several variations on the assignment operator #hich exist to save typing. Cor example "D 8% K" is defined to be the same as "D % D 8 K". Every operator in Java that applies to t#o operands gives rise to a similar assignment operator. Cor example% $ E% y( 00 same as: $ % $ E y( $ 1% y( 00 same as: $ % $ 1 y( $ 0% y( 00 same as: $ % $ 0 y( $ N% y( 00 same as: $ % $ N y( (or integers $ and y) = QQ% p( 00 same as: = % = QQ p( (or booleans = and p) The combined assignment operator 8% even #or$s #ith strings. .ou #ill recall from =ection 1 that #hen the 8 operator is used #ith a string as the first operand it represents concatenation. =ince str 8% $ is equivalent to str % str 8 $ #hen 8% is used #ith a string on the left(hand side it appends the value on the right(hand side onto the string. Cor example if str has the value "tire" then the statement str 8% "d"( changes the value of str to "tired". )recedence !ules "f you use several operators in one expression and if you don+t use parentheses to explicitly indicate the order of evaluation then you have to #orry about the precedence rules that determine the order of evaluation. ,Advice% don+t confuse yourself or the reader of your program& use parentheses liberally.- Here is a listing of the operators discussed in this section listed in order from highest precedence ,evaluated first- to lo#est precedence ,evaluated last-% Jnary operators: 88! EE! G! unary E and 8! typeEcast ;ultiplication and division: 1! 0! N Dddition and subtraction: 8! E Helational operators: @! +! @%! +% L=uality and ine=uality: %%! G% Koolean and: QQ Koolean or: RR 7onditional operator: P: Dssignment operators: %! 8%! E%! 1%! 0%! N% >perators on the same line have the same precedence. When they occur together unary operators and assignment operators are evaluated right(to(left and the remaining operators are evaluated left(to(right. Cor example D1K07 means (D1K)07 #hile D%K%7 means D%(K%7). ,@an you see ho# the expression D%K%7 might be useful given that the value of K%7 as an expression is the same as the value that is assigned to KK- &he if Statement THE C"J=T >C THE TW> BJA!@H"!G =TATE:E!T= in Java is the i statement #hich you have already seen in =ection /. "t ta$es the form i (boolean-expression) statement-1 else statement-2 As usual the statements inside an i statements can be bloc$s. The i statement represents a t#o(#ay branch. The else part of an i statement (( consisting of the #ord "else" and the statement that follo#s it (( can be omitted. !o# an i statement is in particular a statement. This means that either statement-$ or statement-% in the above i statement can itself be an i statement. A problem arises ho#ever if statement-$ is an /0 i statement that has no else part. This special case is effectively forbidden by the syntax of Java. =uppose for example that you type i ( $ + , ) i (y + ,) System.out.println(*)irst case*)( else System.out.println(*Second case*)( !o# remember that the #ay you+ve indented this doesn+t mean anything at all to the computer. .ou might thin$ that the else part is the second half of your "i ($ + ,)" statement but the rule that the computer follo#s attaches the else to "i (y + ,)" #hich is closer. That is the computer reads your statement as if it #ere formatted% i ( $ + , ) i (y + ,) System.out.println(*)irst case*)( else System.out.println(*Second case*)( .ou can force the computer to use the other interpretation by enclosing the nested i in a bloc$% i ( $ + , ) { i (y + ,) System.out.println(*)irst case*)( } else System.out.println(*Second case*)( These t#o statements have different meanings% "f $ @% , the first statement doesn+t print anything but the second statement prints "=econd case.". :uch more interesting than this technicality is the case #here statement-% the else part of the i statement is itself an i statement. The statement #ould loo$ li$e this ,perhaps #ithout the final else part-% i (boolean-expression-1) statement-1 else i (boolean-expression-2) statement-2 else statement-3 Ho#ever since the computer doesn+t care ho# a program is laid out on the page this is almost al#ays #ritten in the format% i (boolean-expression-1) statement-1 else i (boolean-expression-2) statement-2 else statement-3 .ou should thin$ of this as a single statement representing a three(#ay branch. When the computer executes this one and only one of the three statements (( statement-$ statement-% or statement-* (( #ill be executed. The computer starts by evaluating boolean-expression-$. "f it is true the computer executes statement-$ and then 'umps all the #ay to the end of the outer if statement s$ipping the other t#o statements. "f boolean-expression-$ is alse the computer s$ips statement-$ and executes the second nested if statement. To do this it tests the value of boolean-expression-% and uses it to decide bet#een statement-% and statement-*. /2 Here is an example that #ill print out one of three different messages depending on the value of a variable named temperature% i (temperature @ -,) System.out.println(*/t"s cold.*)( else i (temperature @ O,) System.out.println(*/t"s nice.*)( else System.out.println(*/t"s hot.*)( "f temperature is say 3; the first test is true. The computer prints out the message ""t+s cold" and s$ips the rest (( #ithout even evaluating the second condition. Cor a temperature of 06 the first test is alse so the computer goes on to the second test. This test is true so the computer prints ""t+s nice" and s$ips the rest. "f the temperature is /01 both of the tests evaluate to alse so the computer says ""t+s hot" ,unless its circuits have been fried by the heat that is-. .ou can go on stringing together "else(if+s" to ma$e multi(#ay branches #ith any number of cases% i (boolean-expression-1) statement-1 else i (boolean-expression-2) statement-2 else i (boolean-expression-3) statement-3 . . 00 (more cases) . else i (boolean-expression-N) statement-N else statement-(N1! The computer evaluates boolean expressions one after the other until it comes to one that is true. "t executes the associated statement and s$ips the rest. "f none of the boolean expressions evaluate to true then the statement in the else part is executed. This statement is called a multi(#ay branch because only one of the statements #ill be executed. The final else part can be omitted. "n that case if all the boolean expressions are false none of the statements is executed. >f course each of the statements can be a bloc$ consisting of a number of statements enclosed bet#een ) and *. ,Admittedly there is lot of syntax here& as you study and practice you+ll become comfortable #ith it.- As an example of using i statements lets suppose that $ y and I are variables of type int and that each variable has already been assigned a value. @onsider the problem of printing out the values of the three variables in increasing order. Cor examples if the values are 3; /0 and ;4 then the output should be in the order /0 ;4 3;. >ne #ay to approach this is to as$ #here does $ belong in the listK "t comes first if it+s less than both y and I. "t comes last if it+s greater than both y and I. >ther#ise it comes in the middle. We can express this #ith a 1(#ay i statement but #e still have to #orry about the order in #hich y and I should be printed. "n pseudocode i ($ @ y QQ $ @ I) { output $! ollo3ed by y and I in their correct order } else i ($ + y QQ $ + I) { output y and I in their correct order! ollo3ed by $ } else { output $ in bet3een y and I in their correct order } Hetermining the relative order of y and I requires another i statement so this becomes /7 i ($ @ y QQ $ @ I) { 00 $ comes irst i (y @ I) System.out.println( $ 8 * * 8 y 8 * * 8 I )( else System.out.println( $ 8 * * 8 I 8 * * 8 y )( } else i ($ + y QQ $ + I) { 00 $ comes last i (y @ I) System.out.println( y 8 * * 8 I 8 * * 8 $ )( else System.out.println( I 8 * * 8 y 8 * * 8 $ )( } else { 00 $ in the middle i (y @ I) System.out.println( y 8 * * 8 $ 8 * * 8 I)( else System.out.println( I 8 * * 8 $ 8 * * 8 y)( } .ou might chec$ that this code #ill #or$ correctly even if some of the values are the same. "f the values of t#o variables are the same it doesn+t matter #hich order you print them in. !ote by the #ay that even though you can say in English "if x is less than y and 9" you can+t say in Java "i ($ @ y QQ I)". The QQ operator can only be used bet#een boolean values so you have to ma$e separate tests $@y and $@I and then combine the t#o tests #ith QQ. There is an alternative approach to this problem that begins by as$ing "#hich order should $ and y be printed inK" >nce that+s $no#n you only have to decide #here to stic$ in I. This line of thought leads to different Java code% i ( $ @ y ) { 00 $ comes beore y i ( I @ $ ) System.out.println( I 8 * * 8 $ 8 * * 8 y)( else i ( I + y ) System.out.println( $ 8 * * 8 y 8 * * 8 I)( else System.out.println( $ 8 * * 8 I 8 * * 8 y)( } else { 00 y comes beore $ i ( I @ y ) System.out.println( I 8 * * 8 y 8 * * 8 $)( else i ( I + $ ) System.out.println( y 8 * * 8 $ 8 * * 8 I)( else System.out.println( y 8 * * 8 I 8 * * 8 $)( } >nce again #e see ho# the same problem can be solved in many different #ays. The t#o approaches to this problem have not exhausted all the possibilities. Cor example you might start by testing #hether $ is greater than y. "f so you could s#ap their values. >nce you+ve done that you $no# that $ should be printed before y. Cinally let+s #rite a complete program that uses an i statement in an interesting #ay. " #ant a program that #ill convert measurements of length from one unit of measurement to another such as miles to yards or inches to feet. =o far the problem is extremely under(specified. Det+s say that the program #ill only deal #ith measurements in inches feet yards and miles. "t #ould be easy to extend it later to deal #ith other units. The user #ill type in a measurement in one of these units such as "/0 feet" or ";.01 miles". The output #ill sho# the length in terms of each of the four units of measure. ,This is easier than as$ing the user #hich units to use in the output.- An outline of the process is Head the user"s input measurement and units o measure ;4 L$press the measurement in inches! eet! yards! and miles 6isplay the our results The program can read both parts of the user+s input from the same line by using 2e$t/..get6ouble() to read the numerical measurement and 2e$t/..getlnWord() to read the units of measure. The conversion into different units of measure can be simplified by first converting the user+s input into inches. Crom there it can be converted into feet yards and miles. We still have to test the input to determine #hich unit of measure the user has specified% Fet measurement % 2e$t/..get6ouble() Fet units % 2e$t/..getlnWord() i the units are inches Fet inches % measurement else i the units are eet Fet inches % measurement 1 &' 00 &' inches per oot else i the units are yards Fet inches % measurement 1 >? 00 >? inches per yard else i the units are miles Fet inches % measurement 1 &' 1 -'O, 00 -'O, eet per mile else 2he units are illegalG <rint an error message and stop processing Fet eet % inches 0 &'., Fet yards % inches 0 >?., Fet miles % inches 0 (&'., 1 -'O,.,) 6isplay the results =ince units is a String #e can use units.e=uals(*inches*) to chec$ #hether the specified unit of measure is "inches". Ho#ever it #ould be nice to allo# the units to be specified as "inch" or abbreviated to "in". To allo# these three possibilities #e can chec$ i (units.e=uals(*inches*) RR units.e=uals(*inch*) RR units.e=uals(*in*)). "t #ould also be nice to allo# upper case letters as in ""nches" or ""!". We can do this by converting units to lo#er case before testing it or by substituting the function units.e=uals/gnore7ase for units.e=uals. "n my final program " decided to ma$e things more interesting by allo#ing the user to enter a #hole sequence of measurements. The program #ill end only #hen the user inputs 4. To do this " 'ust have to #rap the above algorithm inside a 3hile loop and ma$e sure that the loop ends #hen the user inputs a 4. Here+s the complete program follo#ed by an applet that simulates it. public class Fength7onverter {
01 2his program 3ill convert measurements e$pressed in inches! eet! yards! or miles into each o the possible units o measure. 2he measurement is input by the user! ollo3ed by the unit o measure. )or e$ample: *&5 eet*! *& inch*! *'.5> mi*. Dbbreviations in! t! yd! and mi are accepted. 2he program 3ill continue to read and convert measurements until the user enters an input o ,. 10
public static void main(String[] args) {
double measurement( 00 9umerical measurement! input by user. String units( 00 2he unit o measure or the input! also 00 speciied by the user.
double inches! eet! yards! miles( 00 ;easurement e$pressed in 00 each possible unit o 00 measure.
2e$t/..putln(*Lnter measurements in inches! eet! yards! or miles.*)( ;/ 2e$t/..putln(*)or e$ample: & inch &5 eet '.5> miles*)( 2e$t/..putln(*Tou can use abbreviations: in t yd mi*)( 2e$t/..putln(*/ 3ill convert your input into the other units*)( 2e$t/..putln(*o measure.*)( 2e$t/..putln()(
3hile (true) {
01 Uet the user"s input! and convert units to lo3er case. 10
2e$t/..put(*Lnter your measurement! or , to end: *)( measurement % 2e$t/..get6ouble()( i (measurement %% ,) breaB( 00 terminate the 3hile loop units % 2e$t/..getlnWord()( units % units.toFo3er7ase()(
01 7onvert the input measurement to inches. 10
i (units.e=uals(*inch*) RR units.e=uals(*inches*) RR units.e=uals(*in*)) { inches % measurement( } else i (units.e=uals(*oot*) RR units.e=uals(*eet*) RR units.e=uals(*t*)) { inches % measurement 1 &'( } else i (units.e=uals(*yard*) RR units.e=uals(*yards*) RR units.e=uals(*yd*)) { inches % measurement 1 >?( } else i (units.e=uals(*mile*) RR units.e=uals(*miles*) RR units.e=uals(*mi*)) { inches % measurement 1 &' 1 -'O,( } else { 2e$t/..putln(*Sorry! but / don"t understand #** 8 units 8 *#*.*)( continue( 00 bacB to start o 3hile loop }
01 7onvert measurement in inches to eet! yards! and miles. 10
;; 2e$t/..putln()( 2e$t/..putln(*.SG Kye or no3.*)(
} 00 end main()
} 00 end class Fength7onverter &he for Statement WE T8J! "! TH"= =E@T">! to another type of loop the or statement. Any or loop is equivalent to some 3hile loop so the language doesn+t get any additional po#er by having or statements. But for a certain type of problem a or loop can be easier to construct and easier to read than the corresponding 3hile loop. "t+s quite possible that in real programs or loops actually outnumber 3hile loops. The or statement ma$es a common type of #hile loop easier to #rite. :any #hile loops have the general form% initiali"ation 3hile ( continuation-condition ) { statements update } Cor example consider this example copied from an example in =ection ;% years % ,( 00 initiali"e the variable years 3hile ( years @ - ) { 00 condition or continuing loop
interest % principal 1 rate( 00 principal 8% interest( 00 do three statements System.out.println(principal)( 00
years88( 00 update the value o the variable! years } This loop can be #ritten as the follo#ing equivalent or statement% or ( years % ,( years @ -( years88 ) { interest % principal 1 rate( principal 8% interest( System.out.println(principal)( } The initiali9ation continuation condition and updating have all been combined in the first line of the or loop. This $eeps everything involved in the "control" of the loop in one place #hich helps ma$es the loop easier to read and understand. The or loop is executed in exactly the same #ay as the original code% The initiali9ation part is executed once before the loop begins. The continuation condition is executed before each execution of the loop and the loop ends #hen this condition is alse. The update part is executed at the end of each execution of the loop 'ust before 'umping bac$ to chec$ the condition. The formal syntax of the or statement is as follo#s% or ( initiali"ation( continuation-condition( update ) statement or using a bloc$ statement% or ( initiali"ation( continuation-condition( update ) { statements } The continuation-condition must be a boolean(valued expression. The initiali+ation can be any expression as can the update. Any of the three can be empty. "f the continuation condition is empty it ;1 is treated as if it #ere "true" so the loop #ill be repeated forever or until it ends for some other reason such as a breaB statement. ,=ome people li$e to begin an infinite loop #ith "or ((()" instead of "3hile (true)".- 8sually the initiali9ation part of a or statement assigns a value to some variable and the update changes the value of that variable #ith an assignment statement or #ith an increment or decrement operation. The value of the variable is tested in the continuation condition and the loop ends #hen this condition evaluates to alse. A variable used in this #ay is called a loop control variable. "n the or statement given above the loop control variable is years. @ertainly the most common type of or loop is the counting loop #here a loop control variable ta$es on all integer values bet#een some minimum and some maximum value. A counting loop has the form or ( variable % min( variable @% max( variable88 ) { statements } #here min and max are integer(valued expressions ,usually constants-. The variable ta$es on the values min minL/ minL; ...max. The value of the loop control variable is often used in the body of the loop. The or loop at the beginning of this section is a counting loop in #hich the loop control variable years ta$es on the values / ; 1 3 6. Here is an even simpler example in #hich the numbers / ; ... /4 are displayed on standard output% or ( 9 % & ( 9 @% &, ( 988 ) System.out.println( 9 )( Cor various reasons Java programmers li$e to start counting at 4 instead of / and they tend to use a "@" in the condition rather than a "@%". The follo#ing variation of the above loop prints out the ten numbers 4 / ; ... 7% or ( 9 % , ( 9 @ &, ( 988 ) System.out.println( 9 )( 8sing @ instead of @% in the test or vice versa is a common source of off(by(one errors in programs. .ou should al#ays stop and thin$ do " #ant the final value to be processed or notK "t+s easy to count do#n from /4 to / instead of counting up. Just start #ith /4 decrement the loop control variable instead of incrementing it and continue as long as the variable is greater than or equal to one. or ( 9 % &, ( 9 +% & ( 9EE ) System.out.println( 9 )( !o# in fact the official syntax of a or statemenent actually allo#s both the initiali9ation part and the update part to consist of several expressions separated by commas. =o #e can even count up from / to /4 and count do#n from /4 to / at the same timeF or ( i%&! j%&,( i @% &,( i88! jEE ) { 2e$t/..put(i!-)( 00 .utput i in a -Echaracter 3ide column. 2e$t/..putln(j!-)( 00 .utput j in a -Echaracter column 00 and end the line. } As a final example let+s say that #e #ant to use a or loop that prints out 'ust the even numbers bet#een ; and ;4 that is% ; 3 5 2 /4 /; /3 /5 /2 ;4. There are several #ays to do this. Just to sho# ho# even a very simple problem can be solved in many #ays here are four different solutions ,three of #hich #ould get full credit-% (&) 00 2here are &, numbers to print. 00 Jse a or loop to count &! '! 00 ...! &,. 2he numbers 3e 3ant 00 to print are '1&! '1'! ... '1&,.
(>) 00 7ount o all the numbers 00 '! >! C! ...! &A! ',! but 00 only print out the numbers 00 that are even.
or (9 % '( 9 @% ',( 988) { i ( 9 N ' %% , ) 00 is 9 evenP System.out.println( 9 )( }
(C) 00 /rritate the proessor 3ith 00 a solution that ollo3s the 00 letter o this silly assignment 00 3hile maBing un o it.
or (9 % &( 9 @% &( 988) { System.out.print(*' C ? O &, &' *)( System.out.println(*&C &? &O ',*)( } Ierhaps it is #orth stressing one more time that a or statement li$e any statement never occurs on its o#n in a real program. A statement must be inside the main routine of a program or inside some other subroutine. And that subroutine must be defined inside a class. " should also remind you that every variable must be declared before it can be used and that includes the loop control variable in a or statement. "n all the examples that you have seen so far in this section the loop control variables should be declared to be of type int. "t is not required that a loop control variable be an integer. Here for example is a or loop in #hich the variable ch is of type char% 00 <rint out the alphabet on one line o output. char ch( 00 2he loop control variable( 00 one o the letters to be printed. or ( char ch % "D"( ch @% "V"( ch88 ) System.out.print(ch)( System.out.println()( Det+s loo$ at a less trivial problem that can be solved #ith a or loop. "f 9 and 6 are positive integers #e say that 6 is a divisor of 9 if the remainder #hen 6 is divided into 9 is 9ero. ,Equivalently #e could say that 9 is an even multiple of 6.- "n terms of Java programming 6 is a divisor of 9 if 9 N 6 is 9ero. Det+s #rite a program that inputs a positive integer 9 from the user and computes ho# many different divisors 9 has. The numbers that could possibly be divisors of 9 are / ; ...9. To compute the number of divisors of 9 #e can 'ust test each possible divisor of 9 and count the ones that actually do divide 9 evenly. "n pseudocode the algorithm ta$es the form Uet a positive integer! 9! rom the user ;6 Fet divisor7ount % , or each number! test6ivisor! in the range rom & to 9: i test6ivisor is a divisor o 9: 7ount it by adding & to divisor7ount .utput the count This algorithm displays a common programming pattern that is used #hen some but not all of a sequence of items are to be processed. The general pattern is or each item in the se=uence: i the item passes the test: process it The or loop in our divisor(counting algorithm can be translated into Java code as or (test6ivisor % &( test6ivisor @% 9( test6ivisor88) { i ( 9 N test6ivisor %% , ) divisor7ount88( } >n a modern computer this loop can be executed very quic$ly. "t is not impossible to run it even for the largest legal int value ;/30321530. ,"f you #anted to run it for even larger values you could use variables of type long rather than int.- Ho#ever it does ta$e a noticeable amount of time for very large numbers. =o #hen " implemented this algorithm " decided to output a period every time the computer has tested one million possible divisors. "n the improved version of the program there are t#o types of counting going on. We have to count the number of divisors and #e also have to count the number of possible divisors that have been tested. =o the program needs t#o counters. When the second counter reaches /444444 #e output a +.+ and reset the counter to 9ero so that #e can start counting the next group of one million. Jeverting to pseudocode the algorithm no# loo$s li$e Uet a positive integer! 9! rom the user Fet divisor7ount % , 00 9umber o divisors ound. Fet number2ested % , 00 9umber o possible divisors tested 00 since the last period 3as output. or each number! test6ivisor! in the range rom & to 9: i test6ivisor is a divisor o 9: 7ount it by adding & to divisor7ount Ddd & to number2ested i number2ested is &,,,,,,: print out a "." Fet number2ested % , .utput the count Cinally #e can translate the algorithm into a complete Java program. Here it is follo#ed by an applet that simulates it% public class 7ount6ivisors {
01 2his program reads a positive integer rom the user. /t counts ho3 many divisors that number has! and then it prints the result. 10
public static void main(String[] args) {
int 9( 00 D positive integer entered by the user. 00 6ivisors o this number 3ill be counted.
int test6ivisor( 00 D number bet3een & and 9 that is a 00 possible divisor o 9.
int divisor7ount( 00 9umber o divisors o 9 that have been ound.
int number2ested( 00 Jsed to count ho3 many possible divisors ;5 00 o 9 have been tested. When the number 00 reaches &,,,,,,! a period is output and 00 the value o number2ested is reset to Iero.
01 Uet a positive integer rom the user. 10 3hile (true) { 2e$t/..put(*Lnter a positive integer: *)( 9 % 2e$t/..getln/nt()( i (9 + ,) breaB( 2e$t/..putln(*2hat number is not positive. <lease try again.*)( }
01 7ount the divisors! printing a *.* ater every &,,,,,, tests. 10 divisor7ount % ,( number2ested % ,(
or (test6ivisor % &( test6ivisor @% 9( test6ivisor88) { i ( 9 N test6ivisor %% , ) divisor7ount88( number2ested88( i (number2ested %% &,,,,,,) { 2e$t/..put(".")( number2ested % ,( } }
01 6isplay the result. 10
2e$t/..putln()( 2e$t/..putln(*2he number o divisors o * 8 9 8 * is * 8 divisor7ount)(
} 00 end main()
} 00 end class 7ount6ivisors
,ested -oops @ontrol structures in Java are statements that contain statements. "n particular control structures can contain control structures. .ou+ve already seen several examples of i statements inside loops but any combination of one control structure inside another is possible. We say that one structure is nested inside another. .ou can even have multiple levels of nesting such as a 3hile loop inside an i statement inside another 3hile loop. The syntax of Java does not set a limit on the number of levels of nesting. As a practical matter though it+s difficult to understand a program that has more than a fe# levels of nesting. !ested or loops arise naturally in many algorithms and it is important to understand ho# they #or$. Det+s loo$ at a couple of examples. Cirst consider the problem of printing out a multiplication table li$e this one% & ' > C - ? 5 O A &, && &' ' C ? O &, &' &C &? &O ', '' 'C > ? A &' &- &O '& 'C '5 >, >> >? C O &' &? ', 'C 'O >' >? C, CC CO - &, &- ', '- >, >- C, C- -, -- ?, ? &' &O 'C >, >? C' CO -C ?, ?? 5' 5 &C '& 'O >- C' CA -? ?> 5, 55 OC O &? 'C >' C, CO -? ?C 5' O, OO A? ;0 A &O '5 >? C- -C ?> 5' O& A, AA &,O &, ', >, C, -, ?, 5, O, A, &,, &&, &', && '' >> CC -- ?? 55 OO AA &&, &'& &>' &' 'C >? CO ?, 5' OC A? &,O &', &>' &CC The data in the table are arranged into /; ro#s and /; columns. The process of printing them out can be expressed in a pseudocode algorithm as or each ro39umber % &! '! >! ...! &': <rint the irst t3elve multiples o ro39umber on one line .utput a carriage return The first step in the or loop can itself be expressed as a or loop% or 9 % &! '! >! ...! &': <rint 9 1 ro39umber so a refined algorithm for printing the table has one or loop nested inside another% or each ro39umber % &! '! >! ...! &': or 9 % &! '! >! ...! &': <rint 9 1 ro39umber .utput a carriage return Assuming that ro39umber and 9 have been declared to be variables of type int this can be expressed in Java as or ( ro39umber % &( ro39umber @% &'( ro39umber88 ) { or ( 9 % &( 9 @% &'( 988 ) { 00 print in CEcharacter columns 2e$t/..put( 9 1 ro39umber! C )( } 2e$t/..putln()( } This section has been #eighed do#n #ith lots of examples of numerical processing. Cor our final example let+s do some text processing. @onsider the problem of finding #hich of the ;5 letters of the alphabet occur in a given string. Cor example the letters that occur in "Hello World" are H E H D > J and W. :ore specifically #e #ill #rite a program that #ill list all the letters contained in a string and #ill also count the number of different letters. The string #ill be input by the user. Det+s start #ith a pseudocode algorithm for the program. DsB the user to input a string Head the response into a variable! str Fet count % , (or counting the number o dierent letters) or each letter o the alphabet: i the letter occurs in str: <rint the letter Ddd & to count .utput the count =ince #e #ant to process the entire line of text that is entered by the user #e+ll use 2e$t/..getln() to read it. The line of the algorithm that reads "for each letter of the alphabet" can be expressed as "or (letter%"D"( letter@%"V"( letter88)". But the body of this or loop needs more thought. Ho# do #e chec$ #hether the given letter letter occurs in strK >ne idea is to loo$ at each letter in the string in turn and chec$ #hether that letter is equal to letter. We can get the iEth character of str #ith the function call str.charDt(i) #here i ranges from 4 to str.length() E &. >ne more difficulty% A letter such as +A+ can occur in str in either upper or lo#er case +A+ or +a+. We have to chec$ for both of these. But #e can avoid this difficulty by converting str to upper case before processing it. Then #e only have to chec$ for the upper case letter. We can no# flesh out the algorithm fully. !ote the use of breaB in the nested or loop. "t is required to avoid printing or counting a given letter more than once. The breaB statement brea$s out of the inner or loop but not the outer or loop. 8pon executing the breaB the computer continues the outer loop #ith the next value of letter. ;2 DsB the user to input a string Head the response into a variable! str 7onvert str to upper case Fet count % , or letter % "D"! "K"! ...! "V": or i % ,! &! ...! str.length()E&: i letter %% str.charDt(i): <rint letter Ddd & to count breaB 00 jump out o the loop .utput the count Here is the complete program and an applet to simulate it% public class FistFetters {
01 2his program reads a line o te$t entered by the user. /t prints a list o the letters that occur in the te$t! and it reports ho3 many dierent letters 3ere ound. 10
public static void main(String[] args) {
String str( 00 Fine o te$t entered by the user. int count( 00 9umber o dierent letters ound in str. char letter( 00 D letter o the alphabet.
2e$t/..putln(*<lease type in a line o te$t.*)( str % 2e$t/..getln()(
str % str.toJpper7ase()(
count % ,( 2e$t/..putln(*Tour input contains the ollo3ing letters:*)( 2e$t/..putln()( 2e$t/..put(* *)( or ( letter % "D"( letter @% "V"( letter88 ) { int i( 00 <osition o a character in str. or ( i % ,( i @ str.length()( i88 ) { i ( letter %% str.charDt(i) ) { 2e$t/..put(letter)( 2e$t/..put(" ")( count88( breaB( } } }
} 00 end class FistFetters "n fact there is an easier #ay to determine #hether a given letter occurs in a string str. The built(in function str.inde$.(letter) #ill return E& if letter does not occur in the string. "t returns a number greater than or equal to 9ero if it does occur. =o #e could chec$ #hether letter occurs in str simply by chec$ing "i (str.inde$.(letter) +% ,)". "f #e used this technique in the above ;7 program #e #ouldn+t need a nested or loop. This gives you previe# of ho# subroutines can be used to deal #ith complexity. &he #hile and do$$#hile Statements =TATE:E!T= "! JA<A @A! BE either simple statements or compound statements. =imple statements such as assignments statements and subroutine call statements are the basic building bloc$s of a program. @ompound statements such as 3hile loops and i statements are used to organi9e simple statements into complex structures #hich are called control structures because they control the order in #hich the statements are executed. The next four sections explore the details of all the control structures that are available in Java starting #ith the 3hile statement and the do..3hile statement in this section. At the same time #e+ll loo$ at examples of programming #ith each control structure and apply the techniques for designing algorithms that #ere introduced in the previous section. &he #hile Statement The 3hile statement #as already introduced in =ection /. A 3hile loop has the form 3hile ( boolean-expression ) statement The statement can of course be a bloc$ statement consisting of several statements grouped together bet#een a pair of braces. This statement is called the body of the loop. The body of the loop is repeated as long as the boolean-expression is true. This boolean expression is called the continuation condition or more simply the test of the loop. There are a fe# points that might need some clarification. What happens if the condition is false in the first place before the body of the loop is executed even onceK "n that case the body of the loop is never executed at all. The body of a #hile loop can be executed any number of times including 9ero. What happens if the condition is true but it becomes false some#here in the middle of the loop bodyK Hoes the loop end as soon as this happensK "t does not because the computer continues executing the body of the loop until it gets to the end. >nly then does it 'ump bac$ to the beginning of the loop and test the condition and only then can the loop end. Det+s loo$ at a typical problem that can be solved using a 3hile loop% finding the average of a set of positive integers entered by the user. The average is the sum of the integers divided by the number of integers. The program #ill as$ the user to enter one integer at a time. "t #ill $eep count of the number of integers entered and it #ill $eep a running total of all the numbers it has read so far. Here is a pseudocode algorithm for the program% Fet sum % , Fet count % , 3hile there are more integers to process: Head an integer Ddd it to the sum 7ount it 6ivide sum by count to get the average <rint out the average But ho# can #e test #hether there are more integers to processK A typical solution is to tell the user to type in 9ero after all the data have been entered. This #ill #or$ because #e are assuming that all the data are positive numbers so 9ero is not a legal data value. The 9ero is not itself part of the data to be averaged. "t+s 'ust there to mar$ the end of the real data. A data value used in this #ay is sometimes called a sentinel value. =o no# the test in the #hile loop becomes "#hile the input integer is not 9ero". But there is another problemF The first time the test is evaluated before the body of the loop has ever been executed no integer has yet been read. There is no "input integer" yet so testing #hether the input integer is 9ero doesn+t ma$e sense. =o #e have to do something before the #hile loop to ma$e sure that 14 the test ma$es sense. =etting things up so that the test in a 3hile loop ma$es sense the first time it is executed is called priming the loop. "n this case #e can simply read the first integer before the beginning of the loop. Here is a revised algorithm% Fet sum % , Fet count % , Head an integer 3hile the integer is not Iero: Ddd the integer to the sum 7ount it Head an integer 6ivide sum by count to get the average <rint out the average !otice that "+ve rearranged the body of the loop. =ince an integer is read before the loop the loop has to begin by processing that integer. At the end of the loop the computer reads a ne# integer. The computer then 'umps bac$ to the beginning of the loop and tests the integer that it has 'ust read. !ote that #hen the computer finally reads the sentinel value the loop ends before the sentinel value is processed. "t is not added to the sum and it is not counted. This is the #ay it+s supposed to #or$. The sentinel is not part of the data. The original algorithm even if it could have been made to #or$ #ithout priming #as incorrect since it #ould have summed and counted all the integers including the sentinel. ,=ince the sentinel is 9ero the sum #ould still be correct but the count #ould be off by one. =uch so(called off(by( one errors are very common. @ounting turns out to be harder than it loo$sF- We can easily turn the algorithm into a complete program. !ote that the program cannot use the statement "average % sum0count&" to compute the average. =ince sum and count are both variables of type int the value of sum0count is an integer. The average should be a real number. We+ve seen this problem before% #e have to convert one of the int values to a double to force the computer to compute the quotient as a real number. This can be done by type(casting one of the variables to type double. The type cast ",double-sum" converts the value of sum to a real number so in the program the average is computed as "average % ((double)sum) 0 count&". Another solution in this case #ould have been to declare sum to be a variable of type double in the first place. >ne other issue is addressed by the program% "f the user enters 9ero as the first input value there are no data to process. We can test for this case by chec$ing #hether count is still equal to 9ero after the 3hile loop. This might seem li$e a minor point but a careful programmer should cover all the bases. Here is the program and an applet that simulates it% public class 7omputeDverage {
01 2his program reads a se=uence o positive integers input by the user! and it 3ill print out the average o those integers. 2he user is prompted to enter one integer at a time. 2he user must enter a , to marB the end o the data. (2he Iero is not counted as part o the data to be averaged.) 2he program does not checB 3hether the user"s input is positive! so it 3ill actually 3orB or both positive and negative input values. 10
public static void main(String[] args) {
int input9umber( 00 .ne o the integers input by the user. int sum( 00 2he sum o the positive integers. int count( 00 2he number o positive integers. double average( 00 2he average o the positive integers.
01 /nitialiIe the summation and counting variables. 10 1/
sum % ,( count % ,(
01 Head and process the user"s input. 10
2e$t/..put(*Lnter your irst positive integer: *)( input9umber % 2e$t/..getln/nt()(
3hile (input9umber G% ,) { sum 8% input9umber( 00 Ddd input9umber to running sum. count88( 00 7ount the input by adding & to count. 2e$t/..put(*Lnter your ne$t positive integer! or , to end: *)( input9umber % 2e$t/..getln/nt()( }
01 6isplay the result. 10
i (count %% ,) { 2e$t/..putln(*Tou didn"t enter any dataG*)( } else { average % ((double)sum) 0 count( 2e$t/..putln()( 2e$t/..putln(*Tou entered * 8 count 8 * positive integers.*)( 2e$t/..putln(*2heir average is * 8 average 8 *.*)( } } 00 end main()
} 00 end class 7omputeDverage
&he do$$#hile Statement =ometimes it is more convenient to test the continuation condition at the end of a loop instead of at the beginning as is done in the 3hile loop. The do..3hile statement is very similar to the 3hile statement except that the #ord "#hile" along #ith the condition that it tests has been moved to the end. The #ord "do" is added to mar$ the beginning of the loop. A do..3hile statement has the form do statement 3hile ( boolean-expression )( or since as usual the statement can be a bloc$ do { statements } 3hile ( boolean-expression )( !ote the semicolon +&+ at the end. This semicolon is part of the statement 'ust as the semicolon at the end of an assignment statement or declaration is part of the statement. >mitting it is a syntax error. ,:ore generally every statement in Java ends either #ith a semicolon or a right brace +*+.- To execute a do loop the computer first executes the body of the loop (( that is the statement or statements inside the loop (( and then it evaluates the boolean expression. "f the value of the expression is true the computer returns to the beginning of the do loop and repeats the process& if the value is alse it ends the loop and continues #ith the next part of the program. =ince the condition is not tested until the end of the loop the body of a do loop is executed at least once. 1; Cor example consider the follo#ing pseudocode for a game(playing program. The do loop ma$es sense here instead of a 3hile loop because #ith the do loop you $no# there #ill be at least one game. Also the test that is used at the end of the loop #ouldn+t even ma$e sense at the beginning% do { <lay a Uame DsB user i he 3ants to play another game Head the user"s response } 3hile ( the user"s response is yes )( Det+s convert this into proper Java code. =ince " don+t #ant to tal$ about game playing at the moment let+s say that #e have a class named 7hecBers and that the 7hecBers class contains a static member subroutine named playUame() that plays one game of chec$ers against the user. Then the pseudocode "Ilay a game" can be expressed as the subroutine call statement "7hecBers.playUame()(". We need a variable to store the user+s response. The 2e$t/. class ma$es it convenient to use a boolean variable to store the ans#er to a yesMno question. The input function 2e$t/..getlnKoolean() allo#s the user to enter the value as "yes" or "no". ".es" is considered to be true and "no" is considered to be alse. =o the algorithm can be coded as boolean 3ants2o7ontinue( 00 2rue i user 3ants to play again. do { 7hecBers.playUame()( 2e$t/..put(*6o you 3ant to play againP *)( 3ants2o7ontinue % 2e$t/..getlnKoolean()( } 3hile (3ants2o7ontinue %% true)( When the value of the boolean variable is set to true it is a signal that the loop should end. When a boolean variable is used in this #ay (( as a signal that is set in one part of the program and tested in another part (( it is sometimes called a flag or flag variable ,in the sense of a signal flag-. By the #ay a more(than(usually(pedantic programmer #ould sneer at the test "3hile (3ants2o7ontinue %% true)". This test is exactly equivalent to "3hile (3ants2o7ontinue)". Testing #hether "3ants2o7ontinue %% true" is true amounts to the same thing as testing #hether "3ants2o7ontinue" is true. A little less offensive is an expression of the form "lag %% alse" #here lag is a boolean variable. The value of "lag %% alse" is exactly the same as the value of "G lag" #here G is the boolean negation operator. =o you can #rite "3hile (Glag)" instead of "3hile (lag %% alse)" and you can #rite "i (Glag)" instead of "i (lag %% alse)". Although a do..3hile statement is sometimes more convenient than a 3hile statement having t#o $inds of loops does not ma$e the language more po#erful. Any problem that can be solved using do..3hile loops can also be solved using only 3hile statements and vice versa. "n fact if doSomething represents any bloc$ of program code then do { do%omething } 3hile ( boolean-expression )( has exactly the same effect as do%omething 3hile ( boolean-expression ) { do%omething } =imilarly 3hile ( boolean-expression ) { do%omething } can be replaced by i ( boolean-expression ) { 11 do { do%omething } 3hile ( boolean-expression )( } #ithout changing the meaning of the program in any #ay. &he break and continue Statements The syntax of the 3hile and do..3hile loops allo#s you to test the continuation condition at either the beginning of a loop or at the end. =ometimes it is more natural to have the test in the middle of the loop or to have several tests at different places in the same loop. Java provides a general method for brea$ing out of the middle of any loop. "t+s called the breaB statement #hich ta$es the form breaB( When the computer executes a breaB statement in a loop it #ill immediately 'ump out of the loop. "t then continues on to #hatever follo#s the loop in the program. @onsider for example% 3hile (true) { 00 looBs liBe it 3ill run oreverG 2e$t/..put(*Lnter a positive number: *)( 9 % 2e$t/..getlnlnt()( i (9 + ,) 00 input is .S( jump out o loop breaB( 2e$t/..putln(*Tour ans3er must be + ,.*)( } 00 continue here ater breaB "f the number entered by the user is greater than 9ero the breaB statement #ill be executed and the computer #ill 'ump out of the loop. >ther#ise the computer #ill print out ".our ans#er must be P 4." and #ill 'ump bac$ to the start of the loop to read another input value. ,The first line of the loop "3hile (true)" might loo$ a bit strange but it+s perfectly legitimate. The condition in a 3hile loop can be any boolean(valued expression. The computer evaluates this expression and chec$s #hether the value is true or alse. The boolean literal "true" is 'ust a boolean expression that al#ays evaluates to true. =o "3hile (true)" can be used to #rite an infinite loop or one that can be terminated only by a breaB statement.- A breaB statement terminates the loop that immediately encloses the breaB statement. "t is possible to have nested loops #here one loop statement is contained inside another. "f you use a breaB statement inside a nested loop it #ill only brea$ out of that loop not out of the loop that contains the nested loop. There is something called a "labeled brea$" statement that allo#s you to specify #hich loop you #ant to brea$. " #on+t give the details here& you can loo$ them up if you ever need them. The continue statement is related to breaB but less commonly used. A continue statement tells the computer to s$ip the rest of the current iteration of the loop. Ho#ever instead of 'umping out of the loop altogether it 'umps bac$ to the beginning of the loop and continues #ith the next iteration ,after evaluating the loop+s continuation condition to see #hether any further iterations are required-. breaB and continue can be used in 3hile loops and do..3hile loops. They can also be used in or loops #hich are covered in the next section. "n =ection 5 #e+ll see that breaB can also be used to brea$ out of a s3itch statement. !ote that #hen a breaB occurs inside an i statement it brea$s out of the loop or s3itch statement that contains the i statement. "f the i statement is not contained inside a loop or s3itch then the i statement cannot legally contain a breaB statement. A similar consideration applies to continue statements. 13 &he s#itch Statement THE =E@>!H BJA!@H"!G =TATE:E!T in Java is the s3itch statement #hich is introduced in this section. The s3itch is used far less often than the i statement but it is sometimes useful for expressing a certain type of multi(#ay branch. =ince this section #raps up coverage of all of Java+s control statements "+ve included a complete list of Java+s statement types at the end of the section. A s#itch statement allo#s you to test the value of an expression and depending on that value to 'ump to some location #ithin the s#itch statement. The expression must be either integer(valued or character( valued. "t cannot be a String or a real number. The positions that you can 'ump to are mar$ed #ith "case labels" that ta$e the form% "case constant%". This mar$s the position the computer 'umps to #hen the expression evaluates to the given constant. As the final case in a s#itch statement you can optionally use the label "default%" #hich provides a default 'ump point that is used #hen the value of the expression is not listed in any case label. A s3itch statement has the form% s3itch (expression) { case constant-1: statements-1 breaB( case constant-2: statements-2 breaB( . . 00 (more cases) . case constant-N: statements-N breaB( deault: 00 optional deault case statements-(N1! } 00 end o s3itch statement The breaB statements are technically optional. The effect of a breaB is to ma$e the computer 'ump to the end of the s#itch statement. "f you leave out the brea$ statement the computer #ill 'ust forge ahead after completing one case and #ill execute the statements associated #ith the next case label. This is rarely #hat you #ant but it is legal. ," #ill note here (( although you #on+t understand it until you get to the next chapter (( that inside a subroutine the breaB statement is sometimes replaced by a return statement.- !ote that you can leave out one of the groups of statements entirely ,including the breaB-. .ou then have t#o case labels in a ro# containing t#o different constants. This 'ust means that the computer #ill 'ump to the same place and perform the same action for each of the t#o constants. Here is an example of a s#itch statement. This is not a useful example but it should be easy for you to follo#. !ote by the #ay that the constants in the case labels don+t have to be in any particular order as long as they are all different% s3itch (9) { 00 assume 9 is an integer variable case &: System.out.println(*2he number is &.*)( breaB( case ': case C: case O: System.out.println(*2he number is '! C! or O.*)( System.out.println(*(2hat"s a po3er o 'G)*)( breaB( 16 case >: case ?: case A: System.out.println(*2he number is >! ?! or A.*)( System.out.println(*(2hat"s a multiple o >G)*)( breaB( case -: System.out.println(*2he number is -.*)( breaB( deault: System.out.println(*2he number is 5!*)( System.out.println(* or is outside the range & to A.*)( } The s#itch statement is pretty primitive as control structures go and it+s easy to ma$e mista$es #hen you use it. Java ta$es all its control structures directly from the older programming languages @ and @L L. The s#itch statement is certainly one place #here the designers of Java should have introduced some improvements. >ne application of s3itch statements is in processing menus. A menu is a list of options. The user selects one of the options. The computer has to respond to each possible choice in a different #ay. "f the options are numbered / ; ... then the number of the chosen option can be used in a s3itch statement to select the proper response. "n a 2e$t/.(based program the menu can be presented as a numbered list of options and the user can choose an option by typing in its number. Here is an example that could be used in a variation of the Fength7onverter example from the previous section% int option9umber( 00 .ption number rom menu! selected by user. double measurement( 00 D numerical measurement! input by the user. 00 2he unit o measurement depends on 3hich 00 option the user has selected. double inches( 00 2he same measurement! converted into inches.
01 6isplay menu and get user"s selected option number. 10
2e$t/..putln(*What unit o measurement does your input useP*)( 2e$t/..putln()( 2e$t/..putln(* &. inches*)( 2e$t/..putln(* '. eet*)( 2e$t/..putln(* >. yards*)( 2e$t/..putln(* C. miles*)( 2e$t/..putln()( 2e$t/..putln(*Lnter the number o your choice: *)( option9umber % 2e$t/..getln/nt()(
01 Head user"s measurement and convert to inches. 10
s3itch ( option9umber ) { case &: 2e$t/..putln(*Lnter the number o inches: )( measurement % 2e$t/..getln6ouble()( inches % measurement( breaB( case ': 2e$t/..putln(*Lnter the number o eet: )( measurement % 2e$t/..getln6ouble()( inches % measurement 1 &'( breaB( case >: 2e$t/..putln(*Lnter the number o yards: )( measurement % 2e$t/..getln6ouble()( 15 inches % measurement 1 >?( breaB( case C: 2e$t/..putln(*Lnter the number o miles: )( measurement % 2e$t/..getln6ouble()( inches % measurement 1 &' 1 -'O,( breaB( deault: 2e$t/..putln(*LrrorG /llegal option numberG / =uitG*)( System.e$it(&)( } 00 end s3itch
01 9o3 go on to convert inches to eet! yards! and miles... 10 &he Empty Statement As a final note in this section " #ill mention one more type of statement in Java% the empty statement. This is a statement that consists simply of a semicolon. The existence of the empty statement ma$es the follo#ing legal even though you #ould not ordinarily see a semicolon after a *. i ($ @ ,) { $ % E$( }( The semicolon is legal after the * but the computer considers it to be an empty statement not part of the i statement. >ccasionally you might find yourself using the empty statement #hen #hat you mean is in fact "do nothing". " prefer though to use an empty bloc$ consisting of ) and * #ith nothing bet#een for such cases. >ccasionally stray empty statements can cause annoying hard(to(find errors in a program. Cor example the follo#ing program segment prints out "Hello" 'ust once not ten times% or (int i % ,( i @ &,( i88)( System.out.println(*Hello*)( WhyK Because the "&" at the end of the first line is a statement and it is this statement that is executed ten times. The System.out.println statement is not really inside the or statement at all so it is executed 'ust once after the or loop has completed. A -ist of .ava Statement &ypes " mention the empty statement here mainly for completeness. .ou+ve no# seen 'ust about every type of Java statement. A complete list is given belo# for reference. The only ne# items in the list are the try..catch thro3 and synchroniIed statements #hich are related to advanced aspects of Java $no#n as exception(handling and multi(threading and the return statement #hich is used in subroutines. These #ill be covered in later sections. Another possible surprise is #hat "+ve listed as "other expression statement" #hich reflects the fact that any expression follo#ed by a semicolon can be used as a statement. To execute such a statement the computer simply evaluates the expression and then ignores the value. >f course this only ma$es sense #hen the evaluation has a side effect that ma$es some change in the state of the computer. An example of this is the expression statement "xLL&" #hich has the side effect of adding / to the value of x. =imilarly the function call "2e$t/..getln()" #hich reads a line of input can be used as a stand(alone statement if you #ant to read a line of input and discard it. !ote that technically assignment statements and subroutine call statements are also considered to be expression statements. Java statement types% declaration statement ,for declaring variables- 10 assignment statement subroutine call statement ,including inputMoutput routines- other expression statement ,such as "xLL&"- empty statement bloc$ statement 3hile statement do..3hile statement i statement or statement s3itch statement breaB statement ,found in loops and s3itch statements only- continue statement ,found in loops only- return statement ,found in subroutine definitions only- try..catch statement thro3 statement synchroniIed statement 12