Vous êtes sur la page 1sur 44

Java Notes

Primitive Data Types in Java


Java's primitive data types are very similar to those of C. They include boolean, byte, short, int, long, float, double, and char. The boolean type has been added. However the implementation of the data types has been substantially cleaned up in several ways. 1. Where C and C++ leave a number of issues to be machine and compiler dependent for instance the si!e of an int" Java specifies everything. #. Java prevents casting between arbitrary variables. $nly casts between numeric variables and between sub and superclasses of the same ob%ect are allowed. &. 'll numeric variables in Java are signed. isn't necessary in Java because all si!es are precisely defined. (or instance, an int is always ) bytes. This may not seem to be ade*uate when dealing with ob%ects that aren't base data types. However even if you did +now the si!e of a particular ob%ect, you couldn't do anything with it anyway. ,ou cannot convert an arbitrary ob%ect into bytes and bac+ again.
si!eof

Java's Primitive Data Types


boolean

-.bit. /ay ta+e on the values true and false only.


true and false are defined constants False, TRUE and FALSE, !ero and

of the language and are not the same as True and non!ero, - and 0 or any other numeric value. 1ooleans may not be cast into any other type of variable nor may any other variable be cast into a boolean.
byte

- signed byte two's complement". Covers values from .-#2 to -#3.


short

# bytes, signed two's complement", .&#,342 to &#,343


int

) bytes, signed two's complement". .#,-)3,)2&,4)2 to #,-)3,)2&,4)3. 5i+e all numeric types ints may be cast into other numeric types byte, short, long, float, double". When lossy casts are done e.g. int to byte" the conversion is done modulo the length of the smaller type.
long

2 bytes signed two's complement". 6anges from .7,##&,&3#,0&4,28),338,202 to +7,##&,&3#,0&4,28),338,203.


float

) bytes, 9::: 38). Covers a range from &.)0#2#&)44&28#2240e+&2 positive or negative".

-.)0-#72)4)&#)2-303e.)8

to

5i+e all numeric types floats may be cast into other numeric types byte, short, long, int, double". When lossy casts to integer types are done e.g. float to short" the fractional part is truncated and the conversion is done modulo the length of the smaller type.
double

2 bytes 9::: 38). Covers a range from ).7)0484)82)-#)48))e.&#)d to -.37347&-&)24#&-830e+&02d positive or negative".
char

# bytes, unsigned, ;nicode, 0 to 48,8&8 Chars are not the same as bytes, ints, shorts or <trings.

Java Operators
'n operator is a symbol that operates on one or more arguments to produce a result. The Hello World program is so simple it doesn't use any operators, but almost all other programs you write will.
Operator + += . .= > >= ? ?= @ @= ++ .. A A= B B= C C= EE GG == = H IJ instanceof G G= K K= E E= AA AA= BB BB= AAA AAA= Purpose addition of numbers, concatenation of <trings add and assign numbers, concatenate and assign <trings subtraction subtract and assign multiplication multiply and assign division divide and assign ta+e remainder ta+e remainder and assign increment by one decrement by one greater than greater than or e*ual to less than less than or e*ual to boolean D$T not e*ual to boolean 'DF boolean $6 boolean e*uals assignment bitwise D$T conditional type chec+ing bitwise $6 bitwise $6 and assign bitwise L$6 bitwise L$6 and assign bitwise 'DF bitwise 'DF and assign shift bits right with sign eMtension shift bits right with sign eMtension and assign shift bits left shift bits left and assign unsigned bit shift right unsigned bit shift right and assign

White Space

White space consists mostly of the space character that you produce by hitting the space bar on your +eyboard and that is commonly used to separate words in sentences. There are four other white space characters in Java, the hori!ontal tab, the form feed, the carriage return, and the linefeed. Fepending on your platform, when you hit the return or enter +ey, you get either a carriage return the /ac", a linefeed ;niM" or both F$<, Windows, N/<". This produces a hard line brea+ in the source code teMt. $utside of <tring literals Java treats all white space and runs of white space more than one white space character in immediate succession" the same. 9t's used to separate to+ens, and one space is as good as seven spaces, a tab and two carriage returns. :Mactly which white space characters you use is primarily a result of what's convenient for human beings reading the code. The compiler doesn't care. 9nside String and character literals the only white space permitted is the space character. Carriage returns, tabs, line feeds and form feeds must be inserted with special escape se*uences li+e \r, \t, \f, and \n. ,ou cannot brea+ a <tring across a line li+e thisJ
<tring poem = O/ary had a little lamb whose fleece was white as snow and everywhere that /ary went the lamb was sure to go.OP

9nstead you must use \n and the string concatenation operator, +, li+e thisJ
<tring poem = O/ary had a little lambQnO + Owhose fleece was white as snowQnO + Oand everywhere that /ary wentQnO + Othe lamb was sure to go.OP

Dote that you can brea+ a statement across multiple lines, you %ust can't brea+ a <tring literal. 'lso note that Qn only wor+s on ;niM. ,ou should probably use <ystem.getRroperty Oline.separatorO" instead to return the proper line separator string for the platform your program is running on. Java does not have all the escape se*uences C has. 1esides those already mentioned it has only Qb for bac+space, QQ for the bac+slash character itself. There are also Qu escapes that let you include any ;nicode character.

The proper use of white space in programs

1lan+ lines to separate bloc+s

;se spaces instead of tabs

Literals
5iterals are pieces of Java source code that mean eMactly what they say. (or instance OHello WorldCO is a <tring literal and its meaning is the words Hello WorldC The string OHello WorldCO loo+s li+e it's several thingsP but to the compiler it's %ust one thing, a <tring. This is similar to how an eMpression li+e -,723,#&) may be seven digits and two commas but is really %ust one number. The double *uote mar+s tell you this is a string literal. ' string is an ordered collection of characters letters, digits, punctuation mar+s, etc.". 'lthough the <tring may have meaning to a human being reading the code, the computer sees it as no more than a particular set of letters in a particular order. 9t has no concept of the meaning of the characters. (or instance it does not +now that OtwoO + OtwoO is Ofour.O 9n fact the computer thin+s that OtwoO + OtwoO is OtwotwoO The *uote mar+s show where the string begins and ends. However the *uote mar+s themselves are not a part of the string. The value of this string is Hello WorldC, not OHello WorldCO ,ou can change the output of the program by changing Hello World to some other line of teMt. ' string in a Java program has no concept of italics, bold face, font family or other formatting. 9t cares only about the characters that compose it. :ven if you're using an editor li+e DisusWriter that lets you format teMt files, "Hello Worl !" is identical to "Hello World!" as far as Java is concerned. literals are similar to string literals eMcept they're enclosed in single *uotes and must have eMactly one character. (or eMample 'c' is a char literal that means the letter c.
char true

and false are boolean literals that mean true and false.

Dumbers can also be literals. 34 is an int literal and it means the number thirty.four. 1 ! is a double literal. 4! ", #" 4E$ 34.) times -0 to the 2th power" and .&#.0 are also double literals. is a long literal and it means the number thirty.four. -.8( is a float literal. )8.4f, 34.):2( and .&#.0( are also float literals.
&)5

" entifiers in Java

Identifiers are the names of variables, methods, classes, pac+ages and interfaces. ;nli+e literals they are not the things themselves, %ust ways of referring to them. 9n the HelloWorld program, HelloWorld, <tring, args, main and println are identifiers. 9dentifiers must be composed of letters, numbers, the underscore S and the dollar sign T. 9dentifiers may only begin with a letter, the underscore or a dollar sign. :ach variable has a name by which it is identified in the program. 9t's a good idea to give your variables mnemonic names that are closely related to the values they hold. Nariable names can include any alphabetic character or digit and the underscore S. The main restriction on the names you can give your variables is that they cannot contain any white space. ,ou cannot begin a variable name with a number. 9t is important to note that as in C but not as in (ortran or 1asic, all variable names are case.sensitive. %y&ariable is not the same as 'y&ariable. There is no limit to the length of a Java variable name. The following are legal variable namesJ
/yNariable myvariable /,N'69'15: M i Smyvariable Tmyvariable S7pins andros UVWXYZ $6eilly ThisSisSanSinsanelySlongSvariableSnameSthatS%ustS+eepsSgoingSandSgoingSandSgoingSandSwellSyo uSgetStheSideaSTheSlineSbrea+sSarentSreallySpartSofStheSvariableSnameS9tsS%ustSthatSthisSvariableS nameSisSsoSridiculouslySlongSthatSitSwon'tSfitSonStheSpageS9ScantSimagineSwhySyouSwouldSneedSs uchSaSlongSvariableSnameSbutSifSyouSdoSyouScanShaveSit

The following are not legal variable namesJ


/y Nariable ?? Contains a space 7pins ?? 1egins with a digit a+c ?? The plus sign is not an alphanumeric character testing-.#.& ?? The hyphen is not an alphanumeric character $'6eilly ?? 'postrophe is not an alphanumeric character $6eillySES'ssociates ?? ampersand is not an alphanumeric character

Tip: How to Begin a Variable Name with a Number


9f you want to begin a variable name with a digit, prefiM the name you'd li+e to have e.g. 2ball" with an underscore, e.g. S2ball. ,ou can also use the underscore to act li+e a space in long variable names.

#eywor s

[eywords are identifiers li+e public, static and class that have a special meaning inside Java source code and outside of comments and <trings. (our +eywords are used in Hello World, public, static, void and class. [eywords are reserved for their intended use and cannot be used by the programmer for variable or method names. There are fifty reserved +eywords in Java -.-, 8- in Java -.#, 8# in Java -.), and 8) in Java 8. The forty.eight that are actually used in are listed below. Fon't worry if the purposes of the +eywords seem a little opa*ue at this point. They will all be eMplained in much greater detail later.

Keywords Used in Java 1.1


#eywor Purpose boolean declares a boolean variable or return type byte declares a byte variable or return type char declares a character variable or return type double declares a double variable or return type float declares a floating point variable or return type short declares a short integer variable or return type void declare that a method does not return a value int declares an integer variable or return type long declares a long integer variable or return type while begins a while loop for begins a for loop do begins a do while loop switch tests for the truth of various possible cases brea+ prematurely eMits a loop continue prematurely return to the beginning of a loop case one case in a switch statement default default action for a switch statement if eMecute statements if the condition is true else signals the code to be eMecuted if an if statement is not true try attempt an operation that may throw an eMception catch handle an eMception finally declares a bloc+ of code guaranteed to be eMecuted class signals the beginning of a class definition abstract declares that a class or method is abstract eMtends specifies the class which this class is a subclass of declares that a class may not be subclassed or that a field or method may not be final overridden implements declares that this class implements the given interface import permit access to a class or group of classes in a pac+age instanceof tests whether an ob%ect is an instanceof a class interface signals the beginning of an interface definition native declares that a method is implemented in native code

allocates a new ob%ect defines the pac+age in which this source code file belongs private declares a method or member variable to be private protected declares a class, method or member variable to be protected public declares a class, method or member variable to be public return returns a value from a method static declares that a field or a method belongs to a class rather than an ob%ect super a reference to the parent of the current ob%ect synchroni!ed 9ndicates that a section of code is not thread.safe this a reference to the current ob%ect throw throw an eMception throws declares the eMceptions thrown by a method transient This field should not be seriali!ed volatile Warns the compiler that a variable changes asynchronously
new pac+age

Two other +eywords, const and goto, are reserved by Java but are not actually implemented. This allows compilers to produce better error messages if these common C++ +eywords are improperly used in a Java program. Java -.# adds the strictfp +eyword to declare that a method or class must be run with eMact 9::: 38) semantics. Java -.) adds the assert +eyword to specify assertions. Java 8 adds assert and enu'. and false appear to be missing from this list. 9n fact, they are not +eywords but rather boolean literals. ,ou still can't use them as a variable name though.
true

Separators in Java
<eparators help define the structure of a program. The separators used in HelloWorld are parentheses, ()*, braces, +),, the period, , and the semicolon, -. The table lists the siM Java separators nine if you count opening and closing separators as two". Separator Purpose "

:ncloses arguments in method definitions and callingP ad%usts precedence in

\] ^_ P , . J

arithmetic eMpressionsP surrounds cast types and delimits test eMpressions in flow control statements defines bloc+s of code and automatically initiali!es arrays declares array types and dereferences array values terminates statements separates successive identifiers in variable declarationsP chains statements in the test, eMpression of a for loop <elects a field or method from an ob%ectP separates pac+age names from sub. pac+age and class names ;sed after loop labels

$
class 'dd9nts \ int i = -P int % = #P <ystem.out.println Oi is O + i"P <ystem.out.println O% is O + %"P

ition of "ntegers in Java

public static void main <tring args^_" \

int + = i + %P <ystem.out.println Oi + % is O + +"P + = i . %P <ystem.out.println Oi . % is O + +"P ] ]

Here's what happens when you run 'dd9ntsJ


T %avac 'dd9nts.%ava T %ava 'dd9nts i is % is # i + % is &

i . % is .-

$
class 'ddFoubles \

ition of ou%les in Java

Foubles are treated much the same way, but now you get to use decimal points in the numbers. This is a similar program that does addition and subtraction on doubles.

public static void main <tring args^_" \ double M = 3.8P double y = 8.)P <ystem.out.println OM is O + M"P <ystem.out.println Oy is O + y"P double ! = M + yP <ystem.out.println OM + y is O + !"P ! = M . yP <ystem.out.println OM . y is O + !"P ] ]

Here's the resultJ


@ %avac 'ddFoubles.%ava @ %ava 'ddFoubles M is 3.8 y is 8.) M + y is -#.7 M . y is #.0777777777777774

&ultiplication an

ivision in Java

$f course Java can also do multiplication and division. <ince most +eyboards don't have the times and division symbols you learned in grammar school, Java uses . to mean multiplication and / to mean division. The syntaM is straightforward as you see below.
class /ultiplyFivide \ public static void main <tring args^_" \

int i = -0P int % = #P <ystem.out.println Oi is O + i"P <ystem.out.println O% is O + %"P int + = i?%P <ystem.out.println Oi?% is O + +"P + = i > %P <ystem.out.println Oi > % is O + +"P ] ]

Here's the resultJ


@ %avac /ultiplyFivide.%ava @ %ava /ultiplyFivide i is -0 % is # i?% is 8 i > % is #0

(loats and doubles are multiplied and divided in eMactly the same way. When faced with an ineMact integer division, Java rounds the result down. (or instance dividing -0 by & produces &.

'ne(pecte )uotients
#?& = 0 &?# = -?0 = 'rithmetic:Mception 0?0 = 'rithmetic:Mception

-.0?0.0 = 9nf -.0?0 = 9nf 0.0?0.0 = DaD .-.0?0.0 = .9nf 9nf + - = 9nf 9nf + 9nf = 9nf 9nf . 9nf = DaD 9nf?9nf = DaD DaD + anything = DaD DaD . anything = DaD DaD > anything = DaD DaD ? anything = DaD DaD B DaD is false DaD A DaD is false DaD B= DaD is false DaD A= DaD is false DaD == DaD is false DaD C= DaD is true

The *emain er or &o ulus Operator in Java


Java has one important arithmetical operator you may not be familiar with, 0, also +nown as the modulus or remainder operator. The 0 operator returns the remainder of two

numbers. (or instance 11)0)3 is - because -0 divided by & leaves a remainder of -. ,ou can use 0 %ust as you might use any other more common operator li+e + or 2.
class 6emainder \ public static void main <tring args^_" \ int i = -0P int % = &P <ystem.out.println Oi is O + i"P <ystem.out.println O% is O + %"P int + = i @ %P <ystem.out.println Oi@% is O + +"P ] ]

Here's the outputJ


@ %avac 6emainder.%ava @ %ava 6emainder i is -0 % is & i@% is -

Rerhaps surprisingly the remainder operator can be used with floating point values as well. 9t's surprising because you don't normally thin+ of real number division as producing remainders. However there are rare times when it's useful to as+ eMactly how many times does -.8 go into 8.8 and what's left overI The answer is that -.8 goes into 8.8 three times with one left over, and it's that one which is the result of 8.8 @ -.8 in Java.

Operator Prece ence in Java


9t's possible to combine multiple arithmetic eMpressions in one statement. (or instance the following line adds the numbers one through fiveJ
int m = - + # + & + ) + 8P

' slightly more interesting eMampleJ the following program calculates the energy e*uivalent of an electron using :instein's famous formula : = mc#.

class mc# \ public static void main <tring args^_" \ double mass = 7.-074:.#8P double c = #.772:2P double : = mass > c > cP <ystem.out.println :"P ] ]

Here's the outputJ


T %avac mc#.%ava T %ava mc# 2.-233-e.02

This is all very obvious. However if you use different operators on the same line it's not always clear what the result will be. (or instance consider the following code fragmentJ
int n = - . # > & . ) + 8P

9s n e*ual to .#I ,ou might thin+ so if you %ust calculate from left to right. However if you compile this in a program and print out the result you'll find that Java thin+s n is e*ual to .). Java got that number because it performs all multiplications before it performs any additions or subtractions. 9f you li+e you can thin+ of the calculation Java did as beingJ
int n = - . # > &" . ) + 8P

This is an issue of order of evaluation. Within the limited number of operators you've learned so far here is how Java calculatesJ -. >, ?, @ Fo all multiplications, divisions and remainders from left to right. #. +, . Fo additions and subtractions from left to right. &. = 'ssign the right.hand side to the left.hand side

Parentheses in Java
<ometimes the default order of evaluation isn't what you want. (or instance, the formula to change a (ahrenheit temperature to a Celsius temperature is C = 8?7" ( . &#" where C is degrees Celsius and ( is degrees (ahrenheit. ,ou must subtract &# from the (ahrenheit temperature before you multiply by 8?7, not after. ,ou can use parentheses to ad%ust the order much as they are used in the above formula. The neMt program prints a table showing the conversions from (ahrenheit and Celsius between !ero and three hundred degrees (ahrenheit every twenty degrees.

?? Rrint a (ahrenheit to Celsius table class (ahrToCelsius \ public static void main <tring args^_" \ ?? lower limit of temperature table double lower = 0.0P ?? upper limit of temperature table double upper = &00.0P ?? step si!e double step = #0.0P double fahr = lowerP while fahr B= upper" \ double celsius = 8.0 ? 7.0" > fahr.&#.0"P <ystem.out.println fahr + O O + celsius"P fahr = fahr + stepP ] ] ]

Parentheses in Java
's usual here's the outputJ
@ %avac (ahrToCelsius.%ava @ %ava (ahrToCelsius 0 .-3.3332 #0 .4.44443 )0 ).))))) 40 -8.8884 20 #4.4443

-00 &3.3332 -#0 )2.2227 -)0 40 -40 3-.----20 2#.#### #00 7&.&&&& ##0 -0).))) #)0 --8.884 #40 -#4.443 #20 -&3.332 &00 -)2.227

This program is a little more involved than the previous eMamples. /ostly it's stuff you've seen before though so a line by line analysis isn't necessary. The line to be concerned with is
celsius = 8.0 ? 7.0" > fahr.&#.0"P

This is a virtual translation of the formula C = 8?7" ( . &#" with the single change that a > was added because Java does not implicitly multiply items in parentheses. The parentheses are used %ust as they are in regular algebra, to ad%ust the precedence of terms in a formula. 9n fact the precedence of operations that use the basic arithmetic operators +, ., >, ?" is eMactly the same as you learned in high school algebra. 6emember, you can always use parentheses to change the order of evaluation. :verything inside the parentheses will be calculated before anything outside of the parentheses is calculated. 9f you're in doubt it never hurts to put in eMtra parentheses to clear up the order in which terms will be evaluated.

&i(ing Data Types


's well as combining different operations, you can miM and match different numeric data types on the same line. The program below uses both ints and doubles, for eMample.
class 9nt'ndFouble \ public static void main <tring args^_" \ int i = -0P double M = #.8P double +P <ystem.out.println Oi is O + i"P <ystem.out.println OM is O + M"P + = i + MP

<ystem.out.println + = i > MP <ystem.out.println + = i . MP <ystem.out.println + = M . iP <ystem.out.println + = i ? MP <ystem.out.println + = M ? iP <ystem.out.println ] ]

Oi + M is O + +"P Oi > M is O + +"P Oi . M is O + +"P OM . i is O + +"P Oi ? M is O + +"P OM ? i is O + +"P

This program produces the following outputJ


@ %ava 9nt'ndFouble i is -0 M is #.8 i + M is -#.8 i > M is #8 i . M is 3.8 M . i is .3.8 i ? M is ) M ? i is 0.#8 @

&i(ing Data Types


$rder can ma+e a difference when data types are miMed. (or eMample, - ? # > &.8 = 0.0 &.8 > - ? # = -.38 &.8 ? # = -.38

,ou cannot assume that the usual mathematical laws of commutativity apply when miMing data types, especially integer and floating point types. -.0 ? # > &.8 = -.38 &.8 > -.0 ? # = -.38 - ? #.0 > &.8 = -.38 &.8 > -.0 ? #.0 = -.38

$rithmetic Promotion an +inary Operations


'n int divided by an int is an int, and a double divided by a double is a double, but what about an int divided by a double or a double divided by an intI When doing arithmetic on unli+e types Java tends to widen the types involved so as to avoid losing information. 'fter all & > 8).#:-2 will be a perfectly valid double but much too big for any int. The basic rule is that if either of the variables in a binary operation addition, multiplication, subtraction, addition, remainder" are doubles then Java treats both values as doubles. 9f neither value is a double but one is a float, then Java treats both values as floats. 9f neither is a float or a double but one is a long, then Java treats both values as longs. (inally if there are no doubles, floats or longs, then Java treats both values as an int, even if there aren't any ints in the e*uation. Therefore the result will be a double, float, long or int depending on the types of the arguments.

$rithmetic Promotion, $ssignments, an -asting


9n an assignment statement, i.e. if there's an e*uals sign, Java compares the type of the left hand side to the final type of the right hand side. 9t won't change the type of the left hand side, but it will chec+ to ma+e sure that the value it has double, float, int or long" on the right hand side can fit in the type on the left hand side. 'nything can fit in a double. 'nything eMcept a double can fit in a float. 'ny integral type can fit in a long, but a float or a double can't,

and ints, shorts, and bytes can fit inside ints. 9f the right hand side can fit inside the left hand side, the assignment ta+es place with no further ado. 'ssigning long values to int variables or double values to float variables can be e*ually troublesome. 9n fact it's so troublesome the compiler won't let you do it unless you tell it you really mean it with a cast. When it's necessary to force a value into a particular type, use a cast. To cast a variable or a literal or an eMpression to a different data type %ust precede it with the type in parentheses. (or instanceJ
int i = int" 7.0?).0"P

' cast lets the compiler +now that you're serious about the conversion you plan to ma+e. When a value is cast down before assignment, series of operations ta+es place to chop the right hand side down to si!e. (or a conversion between a floating point number and an int or a long, the fractional part of the floating point number is truncated rounded toward !ero". This produces an integer. 9f the integer is small enough to fit in the left hand side, the assignment is completed. $n the other hand if the number is too large, then the integer is set to the largest possible value of its type. 9f the floating point number is too small the integer is set to the smallest possible value of its type. This can be a nasty bug in your code. 9t can also be hard to find since everything may wor+ perfectly 77 times out of a hundred and only on rare occasions will the rounding become a problem. However when it does there will be no warning or error message. ,ou need to be very careful when assigning floating point values to integer types.

Java's Primitive Data Types


boolean

-.bit. /ay ta+e on the values true and false only.


true and false are defined constants False, TRUE and FALSE, !ero and

of the language and are not the same as True and non!ero, - and 0 or any other numeric value. 1ooleans may not be cast into any other type of variable nor may any other variable be cast into a boolean.
byte

- signed byte two's complement". Covers values from .-#2 to -#3.


short

# bytes, signed two's complement", .&#,342 to &#,343


int

) bytes, signed two's complement". .#,-)3,)2&,4)2 to #,-)3,)2&,4)3. 5i+e all numeric types ints may be cast into other numeric types byte, short, long, float, double". When lossy casts are done e.g. int to byte" the conversion is done modulo the length of the smaller type.
long

2 bytes signed two's complement". 6anges from .7,##&,&3#,0&4,28),338,202 to +7,##&,&3#,0&4,28),338,203.


float

) bytes, 9::: 38). Covers a range from &.)0#2#&)44&28#2240e+&2 positive or negative".

-.)0-#72)4)&#)2-303e.)8

to

5i+e all numeric types floats may be cast into other numeric types byte, short, long, int, double". When lossy casts to integer types are done e.g. float to short" the fractional part is truncated and the conversion is done modulo the length of the smaller type.
double

2 bytes 9::: 38). Covers a range from ).7)0484)82)-#)48))e.&#)d to -.37347&-&)24#&-830e+&02d positive or negative".
char

# bytes, unsigned, ;nicode, 0 to 48,8&8 Chars are not the same as bytes, ints, shorts or <trings.

-onverting Strings to .um%ers


When processing user input it is often necessary to convert a String that the user enters into an int. The syntaM is straightforward. 9t re*uires using the static 3nteger 4alue5f(String)s* and int&alue(* methods from the 6a4a lang 3nteger class. To convert the String 7887 into the int)88 you would write
int i = 9nteger.value$f O##O".intNalue "P

Foubles, floats and longs are converted similarly. To convert a <tring li+e O##O into the long value ## you would write
long l = 5ong.value$f O##O".longNalue "P

To convert 788 !7 into a float or a double you would writeJ

double M = Fouble.value$f O##.8O".doubleNalue "P float y = (loat.value$f O##.8O".floatNalue "P

The various value$f " methods are relatively intelligent and can handle plus and minus signs, eMponents, and most other common number formats. However if you pass one something completely non.numeric li+e Opretty in pin+,O it will throw a Dumber(ormat:Mception. ,ou haven't learned how to handle eMceptions yet, so try to avoid passing theses methods non.numeric data. ,ou can now rewrite the : = mc# program to accept the mass in +ilograms as user input from the command line. /any of the eMercises will be similar.
class :nergy \ public static void main <tring args^_" \ double c = #.772:2P ?? meters?second double mass = Fouble.value$f args^0_".doubleNalue "P double : = mass > c > cP <ystem.out.println : + O JoulesO"P ] ]

Here's the outputJ


T %avac :nergy.%ava T %ava :nergy 0.0)84 ).0728&e+-8 Joules

The char ata type in Java


' char is a single character, that is a letter, a digit, a punctuation mar+, a tab, a space or something similar. ' char literal is a single one character enclosed in single *uote mar+s li+e this
char myCharacter = 'g'P

<ome characters are hard to type. (or these Java provides escape se*uences. This is a bac+slash followed by an alphanumeric code. (or instance 'Qn' is the newline character. 'Qt' is the tab character. 'QQ' is the bac+slash itself. The following escape se*uences are definedJ Qb Qt Qn Qf bac+space tab linefeed formfeed

Qr QO Q' QQ

carriage return double *uote, O single *uote, ' bac+slash, Q

The double *uote escape se*uence is used mainly inside strings where it would otherwise terminate the string. (or instance
<ystem.out.println O'nd then Jim said, QOWho's at the doorIQOO"P

9t isn't necessary to escape the double *uote inside single *uotes. The following line is legal in Java
char double*uote = 'O'P

The char data type in Java


A char is a single character, that is a letter, a digit, a punctuation mark, a tab, a space or something similar. A char literal is a single one character enclosed in single quote marks like this
char)'y9haracter):)'g'-)

Some characters are hard to type. For these Java provides escape sequences. This is a backslash follo ed by an alphanumeric code. For instance '\n' is the ne line character. '\t' is the tab character. '\\' is the backslash itself. The follo ing escape sequences are defined! "b "t "n "f "r backspace tab linefeed formfeed carriage return

"# "$ ""

double quote, # single quote, $ backslash, "

The double quote escape sequence is used mainly inside strings where it would to Java Flow Control
goto if else else)if ;hile for do);hile s;itch)case brea< continue

is a reserved ord. %t is not implemented.

&e$ll talk about e'ception handling later.

her ise terminate the string. For instance


Syste' out =rintln(7And)then)>i')said?)\7@ho's)at)the)doorA\77*-

%t isn$t necessary to escape the double quote inside single quotes. The follo ing line is legal in Java
char)doubleBuote):)'7'-

The if statement in Java


All but the most trivial computer programs need to make decisions. They test a condition and operate differently based on the outcome of the test. This is quite common in real life. For instance you stick your hand out the indo to test if it$s raining. %f it is raining then you take an umbrella ith you. %f it isn$t raining then you don$t. All programming languages have some form of an if statement that tests conditions. %n the previous code you should have tested hether there actually ere command line arguments before you tried to use them.

Arrays have lengths and you can access that length by referencing the variable arrayna'e length (ou test the length of the args array as follo s.
//)This)is)the)Cello)=rogra')in)>a4a class)Cello)+ ))))=ublic)static)4oid)'ain)(String)argsDE*)+ )))) ))))))if)(args length)F)1*)+ ))))))))Syste' out =rintln(7Cello)7)+)argsD1E*)))))), )), , Syste' out =rintln(argsD1E* as rapped in a conditional test, if)(args length)F)1*)+),. The code inside the braces, Syste' out =rintln(argsD1E*, no gets e'ecuted if and only if the

length of the args array is greater than )ero. The arguments to a conditional statement like if must be a boolean value, that is something that evaluates to true or false. %ntegers are not permissible. %n Java numerical greater than and lesser than tests are done ith the F and G operators respectively. (ou can test hether a number is less than or equal to or greater than or equal to another number ith the G: and F: operators.

Testing for Equality


Testing for equality is a little trickier. (ou ould e'pect to test if t o numbers are equal by using the * sign. +o ever the * sign has already been used as an assignment operator that sets the value of a variable. Therefore a ne symbol is needed to test for equality. Java borro s ,$s double equals sign, ::, for this purpose. %t$s not uncommon for even e'perienced programmers to rite :: hen they mean : or vice versa. %n fact this is a very common cause of errors in , programs. Fortunately in Java, you are not allo ed to use :: and : in the same places. Therefore the compiler can catch your mistake and make you fi' it before you can run the program. +o ever there is one ay you can still get into trouble!

)))))boolean)b):)true))))))if)(b):)false*)+ ))))))))Syste' out =rintln(7b)is)false7*)))))),

To avoid this, some programmers get in the habit of riting condition tests like this!
)))))boolean)b):)true))))))if)(false):)b*)+ ))))))))Syste' out =rintln(7b)is)false7*)))))),

Since you can$t assign to a literal, this causes a compiler error if you misuse the : sign hen you mean to rite ::.

The else statement in Java


//)This)is)the)Cello)=rogra')in)>a4a class)Cello)+ ))))=ublic)static)4oid)'ain)(String)argsDE*)+ )))) ))))))if)(args length)F)1*)+ ))))))))Syste' out =rintln(7Cello)7)+)argsD1E*)))))), ))))))else)+ ))))))))Syste' out =rintln(7Cello);hoe4er)you)are 7*)))))), )), ,

Else If
H3f statements are not limited to t o cases. (ou can combine an else and an if to make an else)if and test a hole range of mutually e'clusive possibilities. For instance, here$s a version of the

+ello program that handles up to four names on the command line!


//)This)is)the)Cello)=rogra')in)>a4a class)Cello)+

))))=ublic)static)4oid)'ain)(String)argsDE*)+ )))) ))))))if)(args length)::)1*)+ ))))))))Syste' out =rintln(7Cello);hoe4er)you)are7*)))))), ))))))else)if)(args length)::)1*)+ ))))))))Syste' out =rintln(7Cello)7)+)argsD1E*)))))), ))))))else)if)(args length)::)8*)+ ))))))))Syste' out =rintln(7Cello)7)+)argsD1E)+)7)7)+)argsD1E*)))))),)))))) ))))))else)if)(args length)::)3*)+ ))))))))Syste' out =rintln(7Cello)7)+)argsD1E)+)7)7)+)argsD1E)+)7)7)+)argsD8E*)))))),)))))) ))))))else)if)(args length)::)4*)+ ))))))))Syste' out =rintln(7Cello)7)+)argsD1E)+ ))))))))))7)7)+)argsD1E)+)7)7)argsD8E)+)7)7)+)argsD3E*)))))),)))))) ))))))else)+ ))))))))Syste' out =rintln(7Cello)7)+)argsD1E)+)7)7)+)argsD1E)+)7)7)argsD8E) )))))))))+)7)7)+)argsD3E)+)7)and)all)the)restI7*)))))), )), ,

(ou can see that this gets mighty complicated mighty quickly. -o e'perienced Java programmer ould rite code like this. There is a better solution and you$ll e'plore it in the ne't section.

The while loop in Java


//)This)is)the)Cello)=rogra')in)>a4a ) )class)Cello)+ ) )))=ublic)static)4oid)'ain)(String)argsDE*)+ )))) )))))Syste' out =rint(7Cello)7*-)))//)Say)Cello )))))int)i):)1-))//)Jeclare)and)initialiKe)loo=)counter )))));hile)(i)G)args length*)+)//)Test)and)Loo= )))))))Syste' out =rint(argsDiE*-)) )))))))Syste' out =rint(7)7*)))))))i):)i)+)1-)))))//)3ncre'ent)Loo=)9ounter ))))), )))))Syste' out =rintln(*-))//)Finish)the)line )), )

The for loop in Java


// This is the Hello program in Java ) )class)Cello)+ ) )))=ublic)static)4oid)'ain)(String)argsDE*)+ ) )))))Syste' out =rint(7Cello)7*-)))//)Say)Cello )))))for)(int)i):)1-)i)G)args length-)i):)i)+)1*)+)//)Test)and)Loo= )))))))Syste' out =rint(argsDiE*-)) )))))))Syste' out =rint(7)7*))))), )))))Syste' out =rintln(*-))//)Finish)the)line )),) ,

ultiple !nitiali"ers and !n#rementers


Sometimes it$s necessary to initiali)e several variables before beginning a for loop. Similarly you may ant to increment more than one variable. Java lets you do this by placing a comma bet een the different initiali)ers and incrementers like this!
for)(int)i):)1?))6):)111-))i)G)111-))i):)i+1?)6):)621*))+)))) ))))Syste' out =rintln(i)+)6*-) ,

(ou can$t, ho ever, include multiple test conditions, at least not ith commas. The follo ing line is illegal and ill generate a compiler error.
for)(int)i):)1?))6):)111-))i)G:)111?)6)F)1-))i):)i21?)6):)621*)+)))) To)include)'ulti=le)tests)you)need)to)use)the)boolean)logic)o=erators)LL) and)MM);hich);ill)be)discussed)later )

The do while loop in Java


//)This)is)the)Cello)=rogra')in)>a4a ) )class)Cello)+ ) )))=ublic)static)4oid)'ain)(String)argsDE*)+ ) )))))int)i):)21)))))do)+ )))))))if)(i)::)21*)Syste' out =rint(7Cello)7*-) )))))))else)+ )))))))))Syste' out =rint(argsDiE*-)) )))))))))Syste' out =rint(7)7*))))))), )))))))i):)i)+)1))))),);hile)(i)G)args length*)))))Syste' out =rintln(*-))//)Finish)the)line

)), ) ,

Booleans
.ooleans are named after /eorge .oole, a nineteenth century logician. 0ach boolean variable has one of t o values, true or false. These are not the same as the Strings #true# and #false#. They are not the same as any numeric value like 1 or 1. They are simply true and false. .ooleans are not numbers2 they are not Strings. They are simply booleans. .oolean variables are declared 3ust like any other variable.
boolean)test1):)trueboolean)test8):)false-)

-ote that true and false are reserved ords in Java. These are called the .oolean literals. They are case sensitive. True ith a capital T is not the same as true ith a little t. The same is true of False and false.

Relational

perators

Java has si' relational operators that compare t o numbers and return a boolean value. The relational operators are G, F, G:, F:, ::, and I:. 4ess than True if ' is less than y, other ise false. /reater than True if ' is greater than y, other ise false. N)G:)y) 4ess than or equal to True if ' is less than or equal to y, other ise false. N)F:)y) /reater than or equal to True if ' is greater than or equal to y, other ise false. N)::)y) 0qual True if ' equals y, other ise false. N)I:)y) -ot 0qual True if ' is not equal to y, other ise false.
N)G)y N)F)y

+ere are some code snippets sho ing the relational operators.
boolean)test1):)1)G)8-))//)True )5ne)is)less)that)t;o boolean)test8):)1)F)8-))//)False )5ne)is)not)greater)than)t;o boolean)test3):)3 !)I:)1-))//)True )5ne)does)not)eBual)3 ! boolean)test4):)1#.3 !)F:)"# 1)2)48-)//True )!O !)is)greater)than)! boolean)test!):)O $.!4)G:)"!4-)//)True )!8O 8)is)less)than)"!4 boolean)test"):)".4)::)3.$-)//)True )84)eBuals)84 boolean)test#):)".4)G:)3.$-)//)True )84)is)less)than)or)eBual)to)84 boolean)test$):)".4)G)3.$-)//)False )84)is)not)less)than)84

This, ho ever, is an unusual use of booleans. Almost all use of booleans in practice comes in conditional statements and loop tests. (ou$ve already seen several e'amples of this. 0arlier you sa this
if)(args length)F)1*)+ ))Syste' out =rintln(7Cello)7)+)argsD1E*,

args length)F)1)is)a)boolean)4alue )3n)other);ords)it)is)either)true)or)it)is) false )Pou)could);rite) boolean)test):)args length)F)1if)(test*)+ ))Syste' out =rintln(7Cello)7)+)argsD1E*,

instead. +o ever in simple situations like this the original approach is customary. Similarly the condition test in a ;hile loop is a boolean. &hen you rite ;hile)(i)G)args length* the i)G) args length is a boolean.

Relational

perator !recedence

&henever a ne operator is introduced you have to ask yourself here it fits in the precedence tree. %f you look back at the e'ample in the last section, you$ll notice that it as implicitly assumed that the arithmetic as done before the comparison. 5ther ise, for instance
boolean)test$):)".4)G)3.$-)//)False )84)is)not)less)than)84

6 7 8 returns false hich ould then be multiplied by si' and eight hich ould generate a compile time error because you can$t multiply booleans. 9elational operators are evaluated after arithmetic operators and before the assignment operator. ** and :* have slightly lo er precedences than 7, ;, 7* and ;*. +ere$s the revised order! 1. @. 8. 6. C. <, =, > ?o all multiplications, divisions and remainders from left to right. A, B -e't do additions and subtractions from left to right. 7, ;, ;*, 7* Then any comparisons for relative si)e. **, :* Then do any comparisons for equality and inequality * Finally assign the rightBhand side to the leftBhand side

For e'ample,
boolean)b1):)#)F)3)::)trueboolean)b8):)true)::)#)F)3b):)#)F)3-

Testing

b"ects for Equality

7, ;, 7* and ;* can only be used ith numbers and characters. They cannot be used ith Strings, booleans, arrays or other compound types since there$s no ellBdefined notion of order for these ob3ects. %s true greater than falseD %s #Ey only regret is that % have but one life to give for my country# greater than #% have a dream#D 0quality is a little easier to test ho ever. true is equal to true and true is not equal to false. Similarly #Ey only regret is that % have but one life to give for my country# is not equal to #% have a dream.# +o ever you might be surprised if you ran this program!
class)>ac<And>ill)+ ))=ublic)static)4oid)'ain(String)argsDE*)+

))))String)s1):)ne;)String(7>ac<);ent)u=)the)hill 7*))))String)s8):)ne;)String(7>ac<);ent)u=)the)hill 7*))))if)()s1)::)s8)*)+ ))))))Syste' out =rintln(7The)strings)are)the)sa'e 7*)))), ))))else)if)()s1)I:)s8)*)+ ))))))Syste' out =rintln(7The)strings)are)not)the)sa'e 7*)))), )), ,

The result is
The)strings)are)not)the)sa'e

Testing for Equality with equals#$


That$s not hat you e'pected. To compare strings or any other kind of ob3ect you need to use the eBuals(5b6ect)o* method from 6a4a lang String. .elo is a corrected version that orks as e'pected. The reasons for this odd behavior go fairly deep into Java and the nature of ob3ect data types like strings.
class)>ac<And>ill)+ ))=ublic)static)4oid)'ain(String)argsDE*)+ ))))String)s1):)ne;)String(7>ac<);ent)u=)the)hill 7*))))String)s8):)ne;)String(7>ac<);ent)u=)the)hill 7*))))if)()s1 eBuals(s8*)*)+ ))))))Syste' out =rintln(7The)strings)are)the)sa'e 7*)))), ))))else)+ ))))))Syste' out =rintln(7The)strings)are)not)the)sa'e 7*)))), )), ,

Brea%
A brea< statement e'its a loop before an entry condition fails. For e'ample, in this variation on the 9ount@heat program an error message is printed, and you break out of the for loop if 6 becomes negative.
class)9ount@heat))+ ))=ublic)static)4oid)'ain)(String)argsDE*)+ )) ))))int)total):)1-

))))for)(int)sBuare:1?)grains):)1-)sBuare)G:)"4-)sBuare++*)+ ))))))grains).:)8))))))if)(grains)G:)1*)+ ))))))))Syste' out =rintln(7ErrorQ)54erflo;7*))))))))brea<)))))), ))))))total)+:)grains))))))Syste' out =rint(total)+)7\t))7*))))))if)(sBuare)0)4)::)1*)Syste' out =rintln(*)))),) ))))Syste' out =rintln(7All)doneI7*)), ,

+ere$s the output!


0)6a4ac)9ount@heat 6a4a 0)6a4a)9ount@heat 8))))))))))))")))))))))))14))))))))))))))31 "8)))))))))))18")))))))))8!4)))))))))))))!11 1188)))))))))814"))))))))41O4))))))))))))$1O1 1"3$8))))))))38#"")))))))"!!34)))))))))))1311#1 8"8148)))))))!848$"))))))114$!#4)))))))))81O#1!1 41O4318))))))$3$$"1")))))1"###814))))))))33!!4431 "#11$$"8)))))13481##8")))8"$43!4!4)))))))!3"$#1O11 11#3#41$88)))814#4$3"4"))))))ErrorQ)54erflo; All)doneI

The most common use of brea< is in s;itch statements.

Continue
%t is sometimes necessary to e'it from the middle of a loop. Sometimes you$ll ant to start over at the top of the loop. Sometimes you$ll ant to leave the loop completely. For these purposes Java provides the brea< and continue statements. A continue statement returns to the beginning of the innermost enclosing loop ithout completing the rest of the statements in the body of the loop. %f you$re in a for loop, the counter is incremented. For e'ample this code fragment skips even elements of an array
for)(int)i):)1-)i)G)' length-)i++*)+ ))if)('DiE)0)8)::)1*)continue))//)=rocess)odd)ele'ents

The continue statement is rarely used in practice, perhaps because most of the instances here it$s useful have simpler implementations. For instance, the above fragment could equally ell have been ritten as
for)(int)i):)1-)i)G)' length-)i++*)+ ))if)('DiE)0)8)I:)1*)+ ))))//)=rocess)odd)ele'ents )), ,

There are only seven uses of continue in the entire Java 1.1.1 source code for the 3ava packages.

&abeled &oops
-ormally inside nested loops brea< and continue e'it the innermost enclosing loop. For e'ample consider the follo ing loops.
for)(int)i:1-)i)G)11-)i++*)+ ))for)(int)6:1-)6)G)4-)6++*)+ ))))if)(6)::)8*)brea<))))Syste' out =rintln(i)+)7?)7)+)6*)), , This)code)frag'ent)=rints) 1?)1 8?)1 3?)1 4?)1 !?)1 "?)1 #?)1 $?)1 O?)1

because you break out of the innermost loop hen 3 is t o. +o ever the outermost loop continues. To break out of both loops, label the outermost loop and indicate that label in the break statement like this!
iloo=Q)for)(int)i:1-)i)G)3-)i++*)+ ))for)(int)6:1-)6)G)4-)6++*)+ ))))if)(6)::)8*)brea<)iloo=))))Syste' out =rintln(i)+)7?)7)+)6*)), ,

This code fragment prints


1?)1

and then stops because 6 is t o and the outermost loop is e'ited.

The switch statement in Java


S itch statements are shorthands for a certain kind of if statement. %t is not uncommon to see a stack of if statements all relate to the same quantity like this!
if)(N)::)1*)doSo'ething1(*else)if)(N)::)1*)doSo'ething1(*else)if)(N)::)8*)doSo'ething8(*else)if)(N)::)3*)doSo'ething3(*else)if)(N)::)4*)doSo'ething4(*else)doSo'ethingElse(*-

Java has a shorthand for these types of multiple if statements, the s;itch2case statement. +ere$s ho you$d rite the above using a s;itch2case!
s;itch)(N*)+ ))case)1Q) ))))doSo'ething1(*))))brea<))case)1Q) ))))doSo'ething1(*))))brea<))case)8Q) ))))doSo'ething8(*))))brea<))case)3Q) ))))doSo'ething3(*))))brea<))case)4Q) ))))doSo'ething4(*))))brea<))defaultQ) ))))doSo'ethingElse(*,

%n this fragment N must be a variable or e'pression that can be cast to an int ithout loss of precision. This means the variable must be or the e'pression must return an int, byte, short or char. N is compared ith the value of each the case statements in succession until one matches. This fragment compares N to literals, but these too could be variables or e'pressions as long as the variable or result of the e'pression is an int, byte, short or char. %f no cases are matched, the default action is triggered. 5nce a match is found, all subsequent statements are e'ecuted until the end of the s;itch block is reached or you break out of the block. This can trigger decidedly une'pected behavior. Therefore it is common to include the brea< statement at the end of each case block. %t$s good programming practice to put a brea< after each one unless you e'plicitly ant all subsequent statements to be e'ecuted.

%t$s important to remember that the s;itch statement doesn$t end hen one case is matched and its action performed. The program then e'ecutes all statements that follo in that s;itch block until specifically told to break.

The ' ( operator in Java


The value of a variable often depends on hether a particular boolean e'pression is or is not true and on nothing else. For instance one common operation is setting the value of a variable to the ma'imum of t o quantities. %n Java you might rite
if)(a)F)b*)+ ))'aN):)a, else)+ ))'aN):)b,

Setting a single variable to one of t o states based on a single condition is such a common use of if2 else that a shortcut has been devised for it, the conditional operator, D!. Fsing the conditional operator you can re rite the above e'ample in a single line like this!
'aN):)(a)F)b*)A)a)Q)b-

is an e'pression hich returns one of t o values, a or b. The condition, (a)F)b*, is tested. %f it is true the first value, a, is returned. %f it is false, the second value, b, is returned. &hichever value is returned is dependent on the conditional test, a)F)b. The condition can be any e'pression hich returns a boolean value.
(a)F)b*)A)a)Q)b-

The ' ( operator in Java


The conditional operator only orks for assigning a value to a variable, using a value in a method invocation, or in some other ay that indicates the type of its second and third arguments. For e'ample, consider the follo ing
if)(na'e eBuals(7Ru'=lestilts<in7**)+ ))Syste' out =rintln(7Ri4e)bac<)child7*, else)+ ))Syste' out =rintln(7Laugh7*,

This may not be ritten like this!


na'e eBuals(7Ru'=lestilts<in7*) )A)Syste' out =rintln(7Ri4e)bac<)child7*) )Q)Syste' out =rintln(7Laugh7*-

First of all, both the second and third arguments are void. Secondly, no assignment is present to indicate the type that is e'pected for the second and third arguments Gthough you kno void must be rongH. The first argument to the conditional operator must have or return boolean type and the second and third arguments must return values compatible ith the value the entire e'pression can be e'pected to return. (ou can never use a 4oid method as an argument to the A)Q operator.

&ogical

perators in Java

The relational operators you$ve learned so far GG, G:, F, F:, I:, ::H are sufficient hen you only need to check one condition. +o ever hat if a particular action is to be taken only if several conditions are trueD (ou can use a sequence of if statements to test the conditions, as follo s!
if)(N)::)8*)+ ))if)(y)I:)8*)+ )))))Syste' out =rintln(7Soth)conditions)are)true 7*))), ,

This, ho ever, is hard to rite and harder to read. %t only gets orse as you add more conditions. Fortunately, Java provides an easy ay to handle multiple conditions! the logic operators. There are three logic operators, LL, MM and I. is logical and. LL combines t o boolean values and returns a boolean hich is true if and only if both of its operands are true. For instance
LL

boolean)bb):)3)F)8)LL)!)G)#-)//)b)is)true b):)8)F)3)LL)!)G)#-)//)b)is)no;)false

is logical or. MM combines t o boolean variables or e'pressions and returns a result that is true if either or both of its operands are true. For instance
MM boolean)bb):)3)F)8)MM)!)G)#-)//)b)is)true b):)8)F)3)MM)!)G)#-)//)b)is)still)true b):)8)F)3)MM)!)F)#-)//)no;)b)is)false

The last logic operator is I hich means not. %t reverses the value of a boolean e'pression. Thus if b is true Ib is false. %f b is false Ib is true.
boolean)bb):)I(3)F)8*-)//)b)is)false b):)I(8)F)3*-)//)b)is)true

These operators allo you to test multiple conditions more easily. For instance the previous e'ample can no be ritten as
if)(N)::)8)LL)y)I:)8*)+ ))Syste' out =rintln(7Soth)conditions)are)true 7*,

That$s a lot clearer.

The

rder of Evaluation of &ogic

perators

&hen Java sees a LL operator or a MM, the e'pression on the left side of the operator is evaluated first. For e'ample, consider the follo ing!
boolean)b?)c?)db):)I(3)F)8*-)//)b)is)false c):)I(8)F)3*-)//)c)is)true d):)b)LL)c-)//)d)is)false

&hen Java evaluates the e'pression d):)b)LL)c-, it first checks hether b is true. +ere b is false, so b) LL)c must be false regardless of hether c is or is not true, so Java doesn$t bother checking the value of c. 5n the other hand hen faced ith an MM Java short circuits the evaluation as soon as it encounters a true value since the resulting e'pression must be true. This short circuit evaluation is less important in Java than in , because in Java the operands of LL and MM must be booleans hich are unlikely to have side effects that depend on hether or not they are evaluated. Still it$s possible to force them. For instance consider this code. boolean)b):)(n)::)1*)MM)('/n)F)8*0ven if n is )ero this line ill never cause a division by )ero, because the left hand side is al ays evaluated first. %f n is )ero then the left hand side is true and there$s no need to evaluate the right hand side. Eathematically this makes sense because '/1 is in some sense infinite hich is greater than t o. This isn$t a perfect solution though because ' may be 1 or it may be negative. %f ' is negative and n is )ero then '/n is negative infinity hich is less than t o. And if ' is also )ero, then '/n is very undefined. The proper solution at this point depends on your problem. Since real orld quantities aren$t infinite, hen infinities start popping up in your programs, nine times out of ten it$s a sign that you$ve lost too much precision. The remaining times are generally signals that you$ve left out some small factor in your physical model that ould remove the infinity.

Therefore if there$s a real chance your program ill have a divide by )ero error think carefully about hat it means and ho you should respond to it. %f, upon reflection, you decide that hat you really ant to kno is hether '/n is finite and greater than )ero you should use a line like this
boolean)b):)(n)I:)1*)LL)('/n)F)1*-)

$voiding %hort &ir#uits


%f you ant all of your boolean e'pressions evaluated regardless of the truth value of each, then you can use L and M instead of LL and MM. +o ever make sure you use these only on boolean e'pressions. Fnlike LL and MM, L and M also have a meaning for numeric types hich is completely different from their meaning for booleans.

're#eden#e
Finally let$s add the LL, MM, L, M and A operators to the precedence table 1. <, =, > Eultiplicative operators @. A, B Additive operators 8. 7, ;, ;*, 7* 9elational operators 6. **, :* Then do any comparisons for equality and inequality C. I .it ise and J. K .it ise or L. II 4ogical and M. KK 4ogical or N. D ! ,onditional operator 11. * Assignment operator

)eclaring *rrays
4ike all other variables in Java, an array must have a specific type like byte, int, String or double. 5nly variables of the appropriate type can be stored in an array. 5ne array cannot store both ints and Strings, for instance. 4ike all other variables in Java an array must be declared. &hen you declare an array variable you suffi' the type ith DE to indicate that this variable is an array. +ere are some e'amples!
intDE)<floatDE)ytStringDE)na'es-

This says that < is an array of ints, yt is an array of floats and na'es is an array of Strings. %n other ords you declare an array like you declare any other variable e'cept that you append brackets to the end of the type. (ou also have the option to append the brackets to the variable instead of the type.
int)<DEfloat)ytDEString)na'esDE-

+o ever, unlike in ,, you cannot include the length of the array in the declaration. The follo ing is a synta' error!
int)<D3Efloat)ytD#EString)na'esD111Eint)<DEfloat)ytDEString)na'esDE-

Creating *rrays
?eclaring arrays merely says hat kind of values the array ill hold. %t does not create them. Java arrays are ob3ects, and like any other ob3ect you use the ne; key ord to create them. &hen you create an array, you must tell the compiler ho many components ill be stored in it. +ere$s ho you$d create the variables declared on the previous page!
<):)ne;)intD3Eyt):)ne;)floatD#Ena'es):)ne;)StringD!1E-

The numbers in the brackets specify the length of the array2 that is, ho many slots it has to hold values. &ith the lengths above < can hold three ints, yt can hold seven floats and na'es can hold fifty Strings. This step is sometimes called allocating the array since it sets aside the memory the array requires.

Initiali+ing *rrays
%ndividual components of an array are referenced by the array name and by an integer hich represents their position in the array. The numbers you use to identify them are called subscripts or inde'es into the array. Subscripts are consecutive integers beginning ith 1. Thus the array < above has components <D1E, <D1E, and <D8E. Since you start counting at )ero there is no <D3E, and trying to access it ill thro an

Array3ndeN5ut5fSoundsENce=tion.

(ou can use array components herever you$d use a similarly typed variable that asn$t part of an array. For e'ample this is ho you$d store values in the arrays above!
<D1E):)8<D1E):)!<D8E):)28ytD1#E):)# !fna'esD4E):)7Fred7-

This step is called initiali)ing the array or, more precisely, initiali)ing the components of the array. Sometimes the phrase #initiali)ing the array# is used to mean hen you initiali)e all the components of the array. For even medium si)ed arrays, it$s un ieldy to specify each component individually. %t is often helpful to use for loops to initiali)e the array. +ere is a loop hich fills an array ith the squares of the numbers from 1 to 111.
floatDE)sBuaressBuares):)ne;)floatD111Efor)(int)i:1-)i)G:)111-)i++*)+ )))sBuaresDiE):)i.i,

T o things you should note about this code fragment! 1. &atch the fenceposts: Since array subscripts begin at )ero you need 111 components if you ant to include the square of 111. @. Although i is an int, it is promoted to a float hen it is stored in squares, since squares is declared to be an array of floats.

,ystem-arraycopy#$
Although copying an array isn$t particularly difficult, it is an operation hich benefits from a native implementation. Therefore 6a4a lang Syste' includes a static Syste' arrayco=y(* method you can use to copy one array to another.
=ublic)static)4oid)arrayco=y(5b6ect)source?)int)sourceTosition?) )5b6ect)destination?)int)destinationTosition?)int)nu'ber5fEle'ents* Syste' arrayco=y(* copies nu'ber5fEle'ents elements from the array source, beginning element at sourceTosition, to the array destination starting at destinationTosition. The

ith the

array must already e'ist hen Syste' arrayco=y(* is called. The method does not create it. The source and destination arrays must be of the same type.
destination

For e'ample,
)intDE)unicode):)ne;)intD"!!3"E))for)(int)i):)1-)i)G)unicode length-)i++*)+ ))))unicodeDiE):)i)), ))intDE)latin1):)ne;)intD8!"E))Syste' arrayco=y(unicode?)1?)latin1?)1?)8!"*-

.ulti/)imensional *rrays
So far all these arrays have been oneBdimensional. That is, a single number could locate any value in the array. +o ever sometimes data is naturally represented by more than one number. For instance a position on the earth requires a latitude and a longitude. The most common kind of multidimensional array is the t oBdimensional array. %f you think of a oneB dimensional array as a column of values, you can think of a t oBdimensional array as a table of values like this c1 c1 c@ c8 r1 1 1 @ 8 r1 1 @ 8 6 r@ @ 8 6 C r8 8 6 C J r6 6 C J L +ere e have an array ith five ro s and four columns. %t has t enty total elements. +o ever e say it has dimension five by four, not dimension t enty. This array is not the same as a four by five array like this one! c1 c1 c@ c8 c6 r1 1 1 @ 8 6 r1 1 @ 8 6 C r@ @ 8 6 C J r8 8 6 C J L &e need to use t o numbers to identify a position in a t oBdimensional array. These are the element$s ro and column positions. For instance if the above array is called > then >D1ED1E is 1, >D1ED1E is 1, >D1ED8E is @, >D1ED3E is 8, >D1ED1E is 1, and so on. +ere$s ho the elements in a four by five array called % are referred to!

EO1PO1P EO1PO1P EO1PO@P EO1PO8P EO1PO6P EO1PO1P EO1PO1P EO1PO@P EO1PO8P EO1PO6P EO@PO1P EO@PO1P EO@PO@P EO@PO8P EO@PO6P EO8PO1P EO8PO1P EO8PO@P EO8PO8P EO8PO6P

)eclaring0 *llocating and Initiali+ing Two )imensional *rrays


T o dimensional arrays are declared, allocated and initiali)ed much like one dimensional arrays. +o ever you have to specify t o dimensions rather than one, and you typically use t o nested for loops to fill the array. This e'ample fills a t oBdimensional array ith the sum of the ro and column inde'es
class)FillArray)+ ))=ublic)static)4oid)'ain)(String)argsDE*)+ )) ))))intDEDE)'atriN))))'atriN):)ne;)intD4ED!E)) ))))for)(int)ro;:1-)ro;)G)4-)ro;++*)+ ))))))for)(int)col:1-)col)G)!-)col++*)+ ))))))))'atriNDro;EDcolE):)ro;+col)))))), )))), )))) )), )) ,

5f course the algorithm you use to fill the array depends completely on the use to hich the array is to be put. The ne't e'ample calculates the identity matri' for a given dimension. The identity matri' of dimension - is a square matri' hich contains ones along the diagonal and )eros in all other positions.
class)3J%atriN)+ ))=ublic)static)4oid)'ain)(String)argsDE*)+ )) ))))doubleDEDE)id))))id):)ne;)doubleD4ED4E)) ))))for)(int)ro;:1-)ro;)G)4-)ro;++*)+ ))))))for)(int)col:1-)col)G)4-)col++*)+ ))))))))if)(ro;)I:)col*)+ ))))))))))idDro;EDcolE:1 1)))))))), ))))))))else)+ ))))))))))idDro;EDcolE):)1 1)))))))), )))))),

)))), )))) )), )) ,

%n t oBdimensional arrays Array3ndeN5ut5fSoundsENce=tions occur henever you e'ceed the ma'imum column inde' or ro inde'. (ou can also declare, allocate, and initiali)e a a t oBdimensional array at the same time by providing a list of the initial values inside nested brackets. For instance the three by three identity matri' could be set up like this!
doubleDEDE)3J3):)+ ))+1 1?)1 1?)1 1,? ))+1 1?)1 1?)1 1,? ))+1 1?)1 1?)1 1, ,-

The spacing and the line breaks used above are purely for the programmer. The compiler doesn$t care. The follo ing orks equally ell!
doubleDEDE)3J3):)++1 1?)1 1?)1 1,?+1 1?)1 1?)1 1,?+1 1?)1 1?)1 1,,-)

Even 1igher )imensions


(ou don$t have to stop ith t o dimensional arrays. Java permits arrays of three, four or more dimensions. +o ever chances are pretty good that if you need more than three dimensions in an array, you$re probably using the rong data structure. 0ven three dimensional arrays are e'ceptionally rare outside of scientific and engineering applications. The synta' for three dimensional arrays is a direct e'tension of that for t oBdimensional arrays. The program belo declares, allocates and initiali)es a threeBdimensional array. The array is filled ith the sum of its inde'es.
class)Fill3JArray)+ ))=ublic)static)4oid)'ain)(String)argsDE*)+ )) ))))intDEDEDE)%))))%):)ne;)intD4ED!ED3E))

))))for)(int)ro;:1-)ro;)G)4-)ro;++*)+ ))))))for)(int)col:1-)col)G)!-)col++*)+ ))))))))for)(int)4er:1-)4er)G)3-)4er++*)+ ))))))))))%Dro;EDcolED4erE):)ro;+col+4er)))))))), )))))), )))), )))) )), )) ,

(ou need the additional nested for loop to handle the e'tra dimension. The synta' for still higher dimensions is similar. Just add another pair of brackets and another dimension.

Unbalan#ed $rrays
4ike , Java does not have true multidimensional arrays. Java fakes multidimensional arrays using arrays of arrays. This means that it is possible to have unbalanced arrays. An unbalanced array is a multidimensional array here the dimension isn$t the same for all ro s. %n most applications this is a horrible idea and should be avoided.

2ee% 3 E4ercises
1. Sales ta' in -e (ork ,ity is M.@C>. &rite a program that accepts a price on the command line and prints out the appropriate ta' and total purchase price. @. Eodify the sales ta' program to accept an arbitrary number of prices, total them, calculate the sales ta' and print the total amount. 8. &rite a program that reads t o numbers from the command line, the number of hours orked by an employee and their base pay rate. Then output the total pay due. 6. Eodify the previous program to meet the F.S. ?ept. of 4abor$s requirement for time and a half pay for hours over forty orked in a given eek. C. Add arning messages to the payroll program if the pay rate is less than the minimum age GQC.1C an hour as of 1NNMH or if the employee orked more than the number of hours in a eek. J. &rite a program that reads an integer n from the command line and calculates n: Gn factorialH. L. There are e'actly @.C6 centimeters to an inch. &rite a program that takes a number of inches from the command line and converts it to centimeters. M. &rite the inverse program that reads a number of centimeters from the command line and converts it to inches.

N. There are 6C6 grams in a pound and 1111 grams in a kilogram. &rite programs that convert pounds to kilograms and kilograms to pounds. 9ead the number to be converted from the command line. ,an you make this one program instead of t oD 11. The equivalent resistance of resistors connected in series is calculated by adding the resistances of the individual resistors. &rite a program that accepts a series of resistances from the command line and outputs the equivalent resistance. 11. The formula for resistors connected in parallel is a little more comple'. /iven t o resistors ith resistances 91 and 9@ connected in parallel the equivalent resistance is given by the inverse of the sum of the inverses, i.e.
18 13 14 1! 1" )))))))))))))1 ReBui4):))22222222 )))))))))))1))))1 ))))))))))22))+)22 ))))))))))R1))))R8

%f there are more than t o resistors you continue to invert the sum of their inverses2 e.g. for four resistors you have!
))))))))))))))))))1 ReBui4):))222222222222222222 )))))))))))1))))1)))))1))))1 ))))))))))22))+)22)+)22)+)22 ))))))))))R1))))R8)))R3)))R4

&rite a program that calculates the resistance of a a group of resistors arranged in parallel. The resistances ill all be passed as command line arguments.

Vous aimerez peut-être aussi