copy of java notes( )

44
Java Notes Primitive Data T ypes in J ava 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 pr events casting between arbitrar y variables. $nly casts between numer ic variables and between sub and superclasses of the same ob%ect are allowed. &. ll numeric v aria bles in Jav a are si gned. si!eof  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.

Upload: anandreddy

Post on 09-Feb-2018

222 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 1/44

Java Notes

Primitive Data Types in JavaJava'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 theimplementation 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 dependentfor instance the si!e of an int" Java specifies everything.

#. Java prevents casting between arbitrary variables. $nly casts between numericvariables and between sub and superclasses of the same ob%ect are allowed.

&. ll numeric variables in Java are signed.

si!eof   isn't necessary in Java because all si!es are precisely defined. (or instance, an int  isalways ) bytes. This may not seem to be ade*uate when dealing with ob%ects that aren't basedata types. However even if you did now the si!e of a particular ob%ect, you couldn't doanything with it anyway. ou cannot convert an arbitrary ob%ect into bytes and bac again.

Page 2: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 2/44

Java's Primitive Data Types

boolean 

-bit. /ay tae on the values true and false only.

true and false are defined constants of the language and are not the same as True andFalse, TRUE  and FALSE, !ero 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 becast 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. 5ie all numerictypes ints may be cast into other numeric types byte, short, long, float, double". Whenlossy  casts are done e.g. int to byte" the conversion is done modulo the length of thesmaller 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-#72)4)&#)2-303e)8 to&.)0#2#&)44&28#2240e+&2 positive or negative".

5ie 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" thefractional 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.

Page 3: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 3/44

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 otherprograms you write will.

Operator 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

@ tae remainder  

@= tae remainder and assign

++ increment by one

decrement by one

A greater than

A= greater than or e*ual to

B less than

B= less than or e*ual to

boolean D$T

= not e*ual to

EE boolean DF

GG boolean $6

== boolean e*uals= assignment

bitwise D$T

I conditional

instanceof type checing

G bitwise $6

G= bitwise $6 and assign

K bitwise L$6

K= bitwise L$6 and assign

E bitwise DF

E= bitwise DF and assign

AA shift bits right with sign eMtensionAA= shift bits right with sign eMtension and assign

BB shift bits left

BB= shift bits left and assign

AAA unsigned bit shift right

AAA= unsigned bit shift right and assign

White Space

Page 4: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 4/44

White space consists mostly of the space character that you produce by hitting thespace 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, thecarriage return, and the linefeed. Fepending on your platform, when you hit the return or enterey, 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 thanone white space character in immediate succession" the same. 9t's used to separate toens,and one space is as good as seven spaces, a tab and two carriage returns. :Mactly whichwhite space characters you use is primarily a result of what's convenient for human beingsreading 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 escapese*uences lie \r, \t, \f, and \n. ou cannot brea a <tring across a line lie this

<tring poem = O/ary had a little lambwhose fleece was white as snowand everywhere that /ary wentthe lamb was sure to go.OP

9nstead you must use \n and the string concatenation operator, +, lie this

<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 wors on ;niM. ou should probably use <ystem.getRropertyOline.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 hasonly Qb for bacspace, QQ for the bacslash 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 blocs

Page 5: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 5/44

• ;se spaces instead of tabs

Literals

5iterals are pieces of Java source code that mean eMactly what they say. (or instanceOHello WorldO is a <tring literal and its meaning is the words Hello World

The string OHello WorldO  loos lie it's several thingsP but to the compiler it's %ust onething, a <tring. This is similar to how an eMpression lie -,723,#&) may be seven digits and twocommas but is really %ust one number.

The double *uote mars tell you this is a string literal. string is an ordered collectionof characters letters, digits, punctuation mars, etc.". lthough the <tring may have meaningto a human being reading the code, the computer sees it as no more than a particular set ofletters in a particular order. 9t has no concept of the meaning of the characters. (or instance itdoes not now that OtwoO + OtwoO is Ofour.O 9n fact the computer thins that OtwoO + OtwoO isOtwotwoO

The *uote mars show where the string begins and ends. However the *uote marsthemselves are not a part of the string. The value of this string is Hello World, not OHelloWorldO ou can change the output of the program by changing Hello World to some otherline of teMt.

  string in a Java program has no concept of italics, bold face, font family or otherformatting. 9t cares only about the characters that compose it. :ven if you're using an editorlie DisusWriter that lets you format teMt files, "Hello Worl!" is identical to "Hello World!"  asfar as Java is concerned.

char  literals are similar to string literals eMcept they're enclosed in single *uotes and must haveeMactly one character. (or eMample 'c' is a char literal that means the letter c.

true and false are boolean literals that mean true and false.

Dumbers can also be literals.34

 is anint

 literal and it means the number thirtyfour.1!

 is adouble literal. 4!", #"4E$ 34.) times -0 to the 2th power" and &#.0 are also double literals.

&)5 is a long literal and it means the number thirtyfour. -.8( is a float literal. )8.4f , 34.):2( and&#.0( are also float literals.

entifiers in Java

Page 6: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 6/44

Identifiers are the names of variables, methods, classes, pacages and interfaces.;nlie literals they are not the things themselves, %ust ways of referring to them. 9n theHelloWorld program, HelloWorld, <tring, args, main and println are identifiers.

9dentifiers must be composed of letters, numbers, the underscore  S  and the dollar sign. 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 giveyour variables mnemonic names that are closely related to the values they hold. Nariablenames can include any alphabetic character or digit and the underscore S. The mainrestriction on the names you can give your variables is that they cannot contain any whitespace. ou cannot begin a variable name with a number. 9t is important to note that as in Cbut not as in (ortran or 1asic, all variable names are casesensitive. %y&ariable  is not thesame as y&ariable. There is no limit to the length of a Java variable name. The following arelegal variable names

• /yNariable •

myvariable • /N6915: • M • i •  Smyvariable • myvariable •  S7pins • andros • UVXYZ • $6eilly • ThisSisSanSinsanelySlongSvariableSnameSthatS%ustSeepsSgoingSandSgoingSandSgoingSandSwellSyo

uSgetStheSideaSTheSlineSbreasSarentSreallySpartSofStheSvariableSnameS9tsS%ustSthatSthisSvariableS nameSisSsoSridiculouslySlongSthatSitSwon'tSfitSonStheSpageS9ScantSimagineSwhySyouSwouldSneedSsuchSaSlongSvariableSnameSbutSifSyouSdoSyouScanShaveSit 

The following are not legal variable names

• /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  • $6eillySESssociates ?? 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 lie to have e.g. 2ball"with an underscore, e.g. S2ball. ou can also use the underscore to act lie a space in longvariable names.

#eywors

Page 7: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 7/44

[eywords are identifiers lie public, static  and class  that have a special meaning inside Javasource 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 forvariable or method names.

There are fifty reserved eywords in Java -.-, 8- in Java -.#, 8# in Java -.), and 8) in Java8. The fortyeight that are actually used in are listed below. Fon't worry if the purposes of theeywords seem a little opa*ue at this point. They will all be eMplained in much greater detaillater.

Keywords Used in Java 1.1

#eywor Purpose

boolean declares a boolean variable or return typebyte declares a byte variable or return typechar  declares a character variable or return typedouble declares a double variable or return typefloat declares a floating point variable or return typeshort declares a short integer variable or return typevoid declare that a method does not return a valueint declares an integer variable or return typelong declares a long integer variable or return typewhile begins a while loopfor  begins a for loopdo begins a do while loopswitch tests for the truth of various possible casesbrea prematurely eMits a loopcontinue prematurely return to the beginning of a loopcase one case in a switch statementdefault default action for a switch statementif  eMecute statements if the condition is trueelse signals the code to be eMecuted if an if statement is not truetry attempt an operation that may throw an eMceptioncatch handle an eMceptionfinally declares a bloc of code guaranteed to be eMecutedclass signals the beginning of a class definitionabstract declares that a class or method is abstracteMtends specifies the class which this class is a subclass of 

finaldeclares that a class may not be subclassed or that a field or method may not beoverridden

implements declares that this class implements the given interfaceimport permit access to a class or group of classes in a pacageinstanceof  tests whether an ob%ect is an instanceof a classinterface signals the beginning of an interface definitionnative declares that a method is implemented in native code

Page 8: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 8/44

new allocates a new ob%ectpacage defines the pacage in which this source code file belongsprivate declares a method or member variable to be privateprotected declares a class, method or member variable to be protectedpublic declares a class, method or member variable to be publicreturn returns a value from a method

static declares that a field or a method belongs to a class rather than an ob%ectsuper  a reference to the parent of the current ob%ectsynchroni!ed 9ndicates that a section of code is not threadsafethis a reference to the current ob%ectthrow throw an eMceptionthrows declares the eMceptions thrown by a methodtransient This field should not be seriali!edvolatile Warns the compiler that a variable changes asynchronously

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 areimproperly used in a Java program.

Java -.# adds the strictfp eyword to declare that a method or class must be run with eMact9::: 38) semantics.

Java -.) adds the assert eyword to specify assertions.

Java 8 adds assert and enu.

true 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.

Separators in Java

<eparators help define the structure of a program. The separators used in HelloWorld areparentheses, ( *, braces, ,, the period, , and the semicolon, -. The table lists the siM Javaseparators nine if you count opening and closing separators as two".

SeparatorPurpose

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

Page 9: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 9/44

arithmetic eMpressionsP surrounds cast types and delimits test eMpressions in flocontrol statements

\ ] defines blocs of code and automatically initiali!es arrays

^ _ declares array types and dereferences array values

P terminates statements

,

separates successive identifiers in variable declarationsP chains statements in th

test, eMpression of a for loop

.<elects a field or method from an ob%ectP separates pacage names from supacage and class names

;sed after loop labels

$ition of ntegers in Java

class dd9nts \ public static void main <tring args^_" \

 int i = -P

  int % = #P 

<ystem.out.printlnOi is O + i"P  <ystem.out.printlnO% is O + %"P 

int = i + %P  <ystem.out.printlnOi + % is O + "P 

= i %P  <ystem.out.printlnOi % is O + "P ]

 ]

Here's what happens when you run dd9nts

%avac dd9nts.%ava %ava dd9ntsi is -

 % is #i + % is &

i % is -

Page 10: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 10/44

$ition of ou%les in Java

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

class ddFoubles \

  public static void main <tring args^_" \

  double M = 3.8P  double y = 8.)P

<ystem.out.printlnOM is O + M"P  <ystem.out.printlnOy is O + y"P 

double ! = M + yP  <ystem.out.printlnOM + y is O + !"P 

! = M yP

  <ystem.out.printlnOM y is O + !"P

  ]

 ]

Here's the result

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

&ultiplication an ivision in Java

$f course Java can also do multiplication and division. <ince most eyboards don't have thetimes and division symbols you learned in grammar school, Java uses .  to meanmultiplication and / to mean division. The syntaM is straightforward as you see below.

class /ultiplyFivide \

  public static void main <tring args^_" \

Page 11: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 11/44

  int i = -0P  int % = #P

  <ystem.out.printlnOi is O + i"P  <ystem.out.printlnO% is O + %"P 

int = i?%P

  <ystem.out.printlnOi?% is O + "P  = i > %P  <ystem.out.printlnOi > % is O + "P

  ]

]

Here's the result

@ %avac /ultiplyFivide.%ava@ %ava /ultiplyFividei is -0

 % is #i?% is 8i > % is #0

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

ne(pecte )uotients#?& = 0

&?# = -

-?0 = rithmetic:Mception

0?0 = rithmetic:Mception

Page 12: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 12/44

-.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 = DaD is true

The *emainer or &oulus Operator inJava

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

Page 13: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 13/44

numbers. (or instance 1 0 3 is - because -0 divided by & leaves a remainder of -. ou canuse 0 %ust as you might use any other more common operator lie + or 2.

class 6emainder \

  public static void main <tring args^_" \

  int i = -0P  int % = &P

  <ystem.out.printlnOi is O + i"P  <ystem.out.printlnO% is O + %"P 

int = i @ %P  <ystem.out.printlnOi@% is O + "P  ]

]

Here's the output

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

 % is &i@% is -

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

Operator Preceence in Java

9t's possible to combine multiple arithmetic eMpressions in one statement. (or instancethe following line adds the numbers one through five

int m = - + # + & + ) + 8P

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

Page 14: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 14/44

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 output

%avac mc#.%ava %ava mc#2.-233-e02

This is all very obvious. However if you use different operators on the same line it's notalways clear what the result will be. (or instance consider the following code fragment

int n = - # > & ) + 8P

9s n e*ual to #I ou might thin so if you %ust calculate from left to right. However if youcompile this in a program and print out the result you'll find that Java thins n is e*ual to ).Java got that number because it performs all multiplications before it performs any additionsor subtractions. 9f you lie you can thin of the calculation Java did as being

int n = - # > &" ) + 8P

This is an issue of order of evaluation. Within the limited number of operators you've learnedso far here is how Java calculates

-. >, ?, @ Fo all multiplications, divisions and remainders from left to right.#. +, Fo additions and subtractions from left to right.&. = ssign the righthand side to the lefthand 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 toad%ust the order much as they are used in the above formula. The neMt program prints a tableshowing the conversions from (ahrenheit and Celsius between !ero and three hundreddegrees (ahrenheit every twenty degrees.

Page 15: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 15/44

?? 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.printlnfahr + O O + celsius"P  fahr = fahr + stepP  ]

]

]

Parentheses in Java s usual here's the output

@ %avac (ahrToCelsius.%ava@ %ava (ahrToCelsius0 -3.3332#0 4.44443)0 ).)))))40 -8.888420 #4.4443

Page 16: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 16/44

-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 seenbefore 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 > wasadded 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 factthe precedence of operations that use the basic arithmetic operators +, , >, ?" is eMactly thesame as you learned in high school algebra.

6emember, you can always use parentheses to change the order of evaluation. :verythinginside the parentheses will be calculated before anything outside of the parentheses iscalculated. 9f you're in doubt it never hurts to put in eMtra parentheses to clear up the order inwhich terms will be evaluated.

&i(ing Data Types

 s well as combining different operations, you can miM and match different numericdata types on the same line. The program below uses both ints and doubles, for eMample.

class 9ntndFouble \

  public static void main <tring args^_" \

  int i = -0P  double M = #.8P  double P

  <ystem.out.printlnOi is O + i"P  <ystem.out.printlnOM is O + M"P 

= i + MP

Page 17: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 17/44

  <ystem.out.printlnOi + M is O + "P  = i > MP  <ystem.out.printlnOi > M is O + "P  = i MP  <ystem.out.printlnOi M is O + "P  = M iP  <ystem.out.printlnOM i is O + "P  = i ? MP

  <ystem.out.printlnOi ? M is O + "P  = M ? iP  <ystem.out.printlnOM ? i is O + "P

  ]

]

This program produces the following output

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

&i(ing Data Types

$rder can mae a difference when data types are miMed. (or eMample,

- ? # > &.8 = 0.0&.8 > - ? # = -.38&.8 ? # = -.38

Page 18: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 18/44

ou cannot assume that the usual mathematical laws of commutativity apply when miMingdata types, especially integer and floating point types.

-.0 ? # > &.8 = -.38&.8 > -.0 ? # = -.38- ? #.0 > &.8 = -.38

&.8 > -.0 ? #.0 = -.38

$rithmetic Promotion an +inaryOperations

 n int divided by an int is an int, and a double divided by a double is a double, but whatabout an int divided by a double or a double divided by an intI When doing arithmetic on unlietypes 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. 9fneither value is a double but one is a float, then Java treats both values as floats. 9f neither is afloat or a double but one is a long, then Java treats both values as longs. (inally if there are nodoubles, floats or longs, then Java treats both values as an int, even if there aren't any ints inthe e*uation. Therefore the result will be a double, float, long or int depending on the types of thearguments.

$rithmetic Promotion, $ssignments, an-asting

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

Page 19: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 19/44

and ints, shorts, and bytes can fit inside ints. 9f the right hand side can fit inside the left handside, the assignment taes place with no further ado.

 ssigning long  values to int variables or double  values to float variables can be e*uallytroublesome. 9n fact it's so troublesome the compiler won't let you do it unless you tell it youreally 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 withthe type in parentheses. (or instance

int i = int" 7.0?).0"P

  cast lets the compiler now that you're serious about the conversion you plan to mae.

When a value is cast down before assignment, series of operations taes place to chop theright hand side down to si!e. (or a conversion between a floating point number and an int ora long, the fractional part of the floating point number is truncated rounded toward !ero". Thisproduces an integer. 9f the integer is small enough to fit in the left hand side, the assignmentis completed. $n the other hand if the number is too large, then the integer is set to thelargest possible value of its type. 9f the floating point number is too small the integer is set tothe 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 worperfectly 77 times out of a hundred and only on rare occasions will the rounding become aproblem. However when it does there will be no warning or error message. ou need to bevery careful when assigning floating point values to integer types.

Java's Primitive Data Types

boolean 

-bit. /ay tae on the values true and false only.

true and false are defined constants of the language and are not the same as True andFalse, TRUE  and FALSE, !ero 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 becast into a boolean.

byte 

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

short 

Page 20: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 20/44

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

int 

) bytes, signed two's complement". #,-)3,)2&,4)2 to #,-)3,)2&,4)3. 5ie all numerictypes ints may be cast into other numeric types byte, short, long, float, double". Whenlossy  casts are done e.g. int to byte" the conversion is done modulo the length of thesmaller 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-#72)4)&#)2-303e)8 to&.)0#2#&)44&28#2240e+&2 positive or negative".

5ie 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" thefractional part is truncated and the conversion is done modulo the length of the smallertype.

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 userenters into an int. The syntaM is straightforward. 9t re*uires using the staticntegeralue5f(String s* and int&alue(* methods from the 6aalangnteger class. To

convert the String 7887 into the int 88 you would write

int i = 9nteger.value$fO##O".intNalue"P

Foubles, floats and longs are converted similarly. To convert a <tring lie O##O into the longvalue ## you would write

long l = 5ong.value$fO##O".longNalue"P

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

Page 21: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 21/44

double M = Fouble.value$fO##.8O".doubleNalue"Pfloat y = (loat.value$fO##.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 somethingcompletely nonnumeric lie Opretty in pin,O  it will throw a Dumber(ormat:Mception. ou haven'tlearned how to handle eMceptions yet, so try to avoid passing theses methods nonnumeric

data.

ou can now rewrite the : = mc# program to accept the mass in ilograms as user input fromthe 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$fargs^0_".doubleNalue"P

double : = mass > c > cP  <ystem.out.println: + O JoulesO"P

  ]]

Here's the output

%avac :nergy.%ava %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 orsomething similar. char literal is a single one character enclosed in single *uote mars liethis

char myCharacter = 'g'P

<ome characters are hard to type. (or these Java provides escape se*uences. This is abacslash followed by an alphanumeric code. (or instance 'Qn' is the newline character. 'Qt'  isthe tab character. 'QQ' is the bacslash itself. The following escape se*uences are defined

Qb bacspace

Qt tab

Qn linefeed

Qf formfeed

Page 22: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 22/44

Qr carriage return

QO double *uote, O

Q' single *uote, '

QQ bacslash, Q

The double *uote escape se*uence is used mainly inside strings where it would otherwise

terminate the string. (or instance

<ystem.out.printlnOnd 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 legalin 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 somethingsimilar. 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 backslashfolloed by an alphanumeric code. For instance '\n' is the neline character. '\t' is the tab

character. '\\' is the backslash itself. The folloing escape sequences are defined!

"b backspace

"t tab

"n linefeed

"f formfeed

"r carriage return

Page 23: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 23/44

"# double quote, #

"$ single quote, $

"" backslash, "

The double quote escape sequence is used mainly

inside strings where it would to Java FlowControl

•   if 

•   else 

•   else if 

•   ;hile 

•   for 

•   do ;hile 

•  s;itch case 

•   brea< 

•   continue 

goto is a reserved ord. %t is not implemented.

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

herise terminate the string. For instance

Systeout=rintln(7And then >i said? \7@ho's at the door\77*-

%t isn$t necessary to escape the double quote inside single quotes. The folloing 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 operatedifferently based on the outcome of the test. This is quite common in real life. For instance you stickyour hand out the indo to test if it$s raining. %f it is raining then you take an umbrella ith you. %f itisn$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 touse them.

Page 24: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 24/44

Arrays have lengths and you can access that length by referencing the variable arraynaelength 

(ou test the length of the args array as follos.

// This is the Cello =rogra in >aa

class Cello

  =ublic static oid ain (String argsD*  

if (argslength *

  Systeout=rintln(7Cello 7 + argsD*-

  ,

  ,

,

Systeout=rintln(argsD* as rapped in a conditional test, if (argslength * ,.

The code inside the braces, Systeout=rintln(argsD*, 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  and G operators respectively.

(ou can test hether a number is less than or equal to or greater than or equal to another number iththe G: and : operators.

Testing for Equality

Testing for equality is a little trickier. (ou ould e'pect to test if to numbers are equal by using the *sign. +oever the * sign has already been used as an assignment operator that sets the value of avariable. Therefore a ne symbol is needed to test for equality. Java borros $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 alloed touse :: and : in the same places. Therefore the compiler can catch your mistake and make you fi' it

 before you can run the program.

+oever there is one ay you can still get into trouble!

Page 25: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 25/44

  boolean b : true-

  if (b : false*

  Systeout=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*

  Systeout=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 >aa

class Cello

  =ublic static oid ain (String argsD*

 

if (argslength *

  Systeout=rintln(7Cello 7 + argsD*-

  ,

  else

  Systeout=rintln(7Cello ;hoeer you are7*-

  ,

  ,

,

Else If 

Hf statements are not limited to to 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 >aa

class Cello

Page 26: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 26/44

  =ublic static oid ain (String argsD*

 

if (argslength :: *

  Systeout=rintln(7Cello ;hoeer you are7*-

  ,

  else if (argslength :: 1*

  Systeout=rintln(7Cello 7 + argsD*-

  ,  else if (argslength :: 8*

  Systeout=rintln(7Cello 7 + argsD + 7 7 + argsD1*-

  ,

else if (argslength :: 3*

  Systeout=rintln(7Cello 7 + argsD + 7 7 + argsD1 + 7 7 + argsD8*-

  ,

else if (argslength :: 4*

  Systeout=rintln(7Cello 7 + argsD +

  7 7 + argsD1 + 7 7 argsD8 + 7 7 + argsD3*-

  ,

else

  Systeout=rintln(7Cello 7 + argsD + 7 7 + argsD1 + 7 7 argsD8

+ 7 7 + argsD3 + 7 and all the restI7*-

  ,

  ,

,

(ou can see that this gets mighty complicated mighty quickly. -o e'perienced Java programmer ouldrite 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 >aa

 

class Cello

 

=ublic static oid ain (String argsD*

 

Systeout=rint(7Cello 7*- // Say Cello

  int i : - // Jeclare and initialiKe loo= counter

  ;hile (i G argslength* // Test and Loo=

  Systeout=rint(argsDi*-

Systeout=rint(7 7*-

  i : i + 1- // ncreent Loo= 9ounter

  ,

  Systeout=rintln(*- // Finish the line

  ,

 

Page 27: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 27/44

,

The for loop in Java

// This is the Hello program in Java

 class Cello

 

=ublic static oid ain (String argsD*

 

Systeout=rint(7Cello 7*- // Say Cello

  for (int i : - i G argslength- i : i + 1* // Test and Loo=

  Systeout=rint(argsDi*-

Systeout=rint(7 7*-

  ,

  Systeout=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 mayant to increment more than one variable. Java lets you do this by placing a comma beteen thedifferent initiali)ers and incrementers like this!

for (int i : 1? 6 : 1- i G 1- i : i+1? 6 : 621*

Systeout=rintln(i + 6*-

,

(ou can$t, hoever, include multiple test conditions, at least not ith commas. The folloing line is

illegal and ill generate a compiler error.

for (int i : 1? 6 : 1- i G: 1? 6 - i : i21? 6 : 621*

To include ulti=le tests you need to use the boolean logic o=erators

and MM ;hich ;ill be discussed later

The do while loop in Java

// This is the Cello =rogra in >aa

 

class Cello

 

=ublic static oid ain (String argsD*

 

int i : 21-

  do

  if (i :: 21* Systeout=rint(7Cello 7*-

else

  Systeout=rint(argsDi*-

Systeout=rint(7 7*-

  ,

  i : i + 1-

  , ;hile (i G argslength*-

  Systeout=rintln(*- // Finish the line

Page 28: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 28/44

  ,

 

,

Booleans

ooleans are named after /eorge oole, a nineteenth century logician. 0ach boolean variable has oneof to values, true or false. These are not the same as the Strings #true# and #false#. They are not thesame as any numeric value like 1 or . They are simply true and false. ooleans are not numbers2 theyare not Strings. They are simply booleans.

oolean variables are declared 3ust like any other variable.

boolean test1 : true-

boolean test8 : false-

 -ote that true and false are reserved ords in Java. These are called the oolean literals. They are casesensitive. 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 to numbers and return a boolean value. The relationaloperators are G, , G:, :, ::, and I:.

N G y  4ess than True if ' is less than y, otherise false.N y  /reater than True if ' is greater than y, otherise false.N G: y

4ess than or equal to True if ' is less than or equal to y, otherise false.N : y /reater than or equal to True if ' is greater than or equal to y, otherise false.N :: y 0qual True if ' equals y, otherise false.N I: y  -ot 0qual True if ' is not equal to y, otherise false.

+ere are some code snippets shoing the relational operators.

boolean test1 : 1 G 8- // True 5ne is less that t;o

boolean test8 : 1 8- // False 5ne is not greater than t;o

boolean test3 : 3! I: 1- // True 5ne does not eBual 3!

boolean test4 : 1#.3! : "# 2 48- //True !O! is greater than !

boolean test! : O$.!4 G: "!4- // True !8O8 is less than "!4

boolean test" : ".4 :: 3.$- // True 84 eBuals 84boolean 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, hoever, is an unusual use of booleans. Almost all use of booleans in practice comes inconditional statements and loop tests. (ou$ve already seen several e'amples of this. 0arlier you sathis

if (argslength *

  Systeout=rintln(7Cello 7 + argsD*-

,

Page 29: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 29/44

argslength is a boolean alue n other ;ords it is either true or it is

false Pou could ;rite

boolean test : argslength -

if (test*

  Systeout=rintln(7Cello 7 + argsD*-

,

instead. +oever in simple situations like this the original approach is customary. Similarly thecondition test in a ;hile loop is a boolean. &hen you rite ;hile (i G argslength* the i G

argslength is a boolean.

Relational perator !recedence

&henever a ne operator is introduced you have to ask yourself here it fits in the precedence tree. %fyou look back at the e'ample in the last section, you$ll notice that it as implicitly assumed that thearithmetic as done before the comparison. 5therise, 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 compiletime error because you can$t multiply booleans. 9elational operators are evaluated after arithmeticoperators and before the assignment operator. ** and :* have slightly loer precedences than 7, ;, 7*and ;*. +ere$s the revised order!

1. <, =, > ?o all multiplications, divisions and remainders from left to right.@. , B -e't do additions and subtractions from left to right.8. 7, ;, ;*, 7* Then any comparisons for relative si)e.6. **, :* Then do any comparisons for equality and inequalityC. * Finally assign the rightBhand side to the leftBhand side

For e'ample,

boolean b1 : # 3 :: true-

boolean b8 : true :: # 3- b : # 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 hoever. 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 adream.# +oever you might be surprised if you ran this program!

class >ac<And>ill

  =ublic static oid ain(String argsD*

Page 30: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 30/44

  String s1 : ne; String(7>ac< ;ent u= the hill7*-

  String s8 : ne; String(7>ac< ;ent u= the hill7*-

  if ( s1 :: s8 *

  Systeout=rintln(7The strings are the sae7*-

  ,

  else if ( s1 I: s8 *

  Systeout=rintln(7The strings are not the sae7*-  ,

  ,

,

The result is

The strings are not the sae

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 theeBuals(5b6ect o* method from 6aalangString. 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 typeslike strings.

class >ac<And>ill

  =ublic static oid ain(String argsD*

  String s1 : ne; String(7>ac< ;ent u= the hill7*-

  String s8 : ne; String(7>ac< ;ent u= the hill7*-

  if ( s1eBuals(s8* *

  Systeout=rintln(7The strings are the sae7*-

  ,

  else

  Systeout=rintln(7The strings are not the sae7*-

  ,

  ,

,

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 oid ain (String argsD*

 

int total : -

Page 31: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 31/44

  for (int sBuare:1? grains : 1- sBuare G: "4- sBuare++*

  grains .: 8-

  if (grains G: *

  Systeout=rintln(7ErrorQ 5erflo;7*-

  brea<-

  ,

  total +: grains-

  Systeout=rint(total + 7\t 7*-

  if (sBuare 0 4 :: * Systeout=rintln(*-  ,

Systeout=rintln(7All doneI7*-

  ,

,

+ere$s the output!

0 6aac 9ount@heat6aa

0 6aa 9ount@heat

8 " 14 3

"8 18" 8!4 !1188 84" 4O4 $1O

1"3$8 38#"" "!!34 131#

8"8148 !848$" 14$!#4 8O#1!

41O438 $3$$"" 1"###814 33!!443

"#1$$"8 13481##8" 8"$43!4!4 !3"$#O1

1#3#41$88 814#4$3"4" ErrorQ 5erflo;

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 thetop 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 : - i G length- i++*

  if (Di 0 8 :: * continue-

  // =rocess odd eleents

Page 32: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 32/44

,

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 beenritten as

for (int i : - i G length- i++*

  if (Di 0 8 I: *

  // =rocess odd eleents

  ,

,

There are only seven uses of continue in the entire Java 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 folloing loops.

for (int i:1- i G 1- i++*

  for (int 6:1- 6 G 4- 6++*

  if (6 :: 8* brea<-

  Systeout=rintln(i + 7? 7 + 6*-

  ,

,

This code fragent =rints

1? 1

8? 1

3? 14? 1

!? 1

"? 1

#? 1

$? 1

O? 1

 because you break out of the innermost loop hen 3 is to. +oever the outermost loop continues.

To break out of both loops, label the outermost loop and indicate that label in the break statement likethis!

iloo=Q for (int i:1- i G 3- i++*

  for (int 6:1- 6 G 4- 6++*

  if (6 :: 8* brea< iloo=-

  Systeout=rintln(i + 7? 7 + 6*-

  ,

,

This code fragment prints

1? 1

Page 33: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 33/44

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

The switch statement in Java

Sitch 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 :: * doSoething(*-

else if (N :: 1* doSoething1(*-

else if (N :: 8* doSoething8(*-

else if (N :: 3* doSoething3(*-

else if (N :: 4* doSoething4(*-

else doSoethingElse(*-

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 Q

doSoething(*-

  brea<-

  case 1Q

doSoething1(*-

  brea<-

  case 8Q

doSoething8(*-

  brea<-

  case 3Q

doSoething3(*-

  brea<-

  case 4Q

doSoething4(*-  brea<-

  defaultQ

doSoethingElse(*-

,

%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 istriggered.

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 iscommon 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.

Page 34: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 34/44

%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 andon nothing else. For instance one common operation is setting the value of a variable to the ma'imumof to quantities. %n Java you might rite

if (a b*

  aN : a-

,

else   aN : b-

,

Setting a single variable to one of to 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!. sing the conditional operator

you can rerite the above e'ample in a single line like this!

aN : (a b* a Q b-

(a b* a Q b- is an e'pression hich returns one of to values, a or b. The condition, (a 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 b. The condition can be any

e'pression hich returns a boolean value.

The ' ( operator in Java

The conditional operator only orks for assigning a value to a variable, using a value in a methodinvocation, or in some other ay that indicates the type of its second and third arguments. For e'ample,consider the folloing

if (naeeBuals(7Ru=lestilts<in7**

  Systeout=rintln(7ie bac< child7*-

,

else

  Systeout=rintln(7Laugh7*-

,

Page 35: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 35/44

This may not be ritten like this!

naeeBuals(7Ru=lestilts<in7*

Systeout=rintln(7ie bac< child7*

Q Systeout=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 berongH.

The first argument to the conditional operator must have or return boolean type and the second andthird arguments must return values compatible ith the value the entire e'pression can be e'pected toreturn. (ou can never use a oid method as an argument to the Q operator.

&ogical perators in Java

The relational operators you$ve learned so far GG, G:, , :, I:, ::H are sufficient hen you only need tocheck one condition. +oever hat if a particular action is to be taken only if several conditions aretrueD (ou can use a sequence of if statements to test the conditions, as follos!

if (N :: 8*

  if (y I: 8*

  Systeout=rintln(7oth conditions are true7*-

  ,

,

This, hoever, 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, , MM and I.

 is logical and.  combines to boolean values and returns a boolean hich is true if and only if

 both of its operands are true. For instance

boolean b-

b : 3 8 ! G #- // b is true

b : 8 3 ! G #- // b is no; false

MM is logical or. MM combines to boolean variables or e'pressions and returns a result that is true if

either or both of its operands are true. For instance

boolean b-

b : 3 8 MM ! G #- // b is true

b : 8 3 MM ! G #- // b is still true

b : 8 3 MM ! #- // no; b is false

Page 36: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 36/44

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 b-

b : I(3 8*- // b is false

b : I(8 3*- // b is true

These operators allo you to test multiple conditions more easily. For instance the previous e'amplecan no be ritten as

if (N :: 8 y I: 8*

  Systeout=rintln(7oth conditions are true7*-

,

That$s a lot clearer.

The rder of Evaluation of &ogic perators

&hen Java sees a  operator or a MM, the e'pression on the left side of the operator is evaluated first.

For e'ample, consider the folloing!

boolean b? c? d-

b : I(3 8*- // b is false

c : I(8 3*- // c is true

d : b c- // d is false

&hen Java evaluates the e'pression d : b c-, it first checks hether b is true. +ere b is false, so b

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 inJava than in because in Java the operands of  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. Forinstance consider this code.   boolean b : (n :: * MM (/n 8*-

0ven if n is )ero this line ill never cause a division by )ero, because the left hand side is

alays 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 / is in some sense infinite hich is greater than

to.

This isn$t a perfect solution though because  may be or it may be negative. %f  is negative and n is

)ero then /n is negative infinity hich is less than to. 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 toomuch precision. The remaining times are generally signals that you$ve left out some small factor inyour physical model that ould remove the infinity.

Page 37: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 37/44

Therefore if there$s a real chance your program ill have a divide by )ero error think carefully abouthat it means and ho you should respond to it. %f, upon reflection, you decide that hat you reallyant to kno is hether /n is finite and greater than )ero you should use a line like this

boolean b : (n I: * (/n *-

 $voiding %hort &ir#uits%f you ant all of your boolean e'pressions evaluated regardless of the truth value of each, then youcan use  and M instead of  and MM. +oever make sure you use these only on boolean e'pressions.

nlike  and MM,  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 , MM, , M and  operators to the precedence table

1. <, =, > Eultiplicative operators@. , B Additive operators8. 7, ;, ;*, 7* 9elational operators6. **, :* Then do any comparisons for equality and inequalityC. I itise and. K itise orL. II 4ogical andM. KK 4ogical orN. D ! onditional operator1. * 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 bothints and Strings, for instance.

4ike all other variables in Java an array must be declared. &hen you declare an array variable yousuffi' the type ith D to indicate that this variable is an array. +ere are some e'amples!

intD <-

floatD yt-

StringD naes-

Page 38: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 38/44

This says that < is an array of ints, yt is an array of floats and naes 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 theend of the type.

(ou also have the option to append the brackets to the variable instead of the type.

int <D-

float ytD-

String naesD-

+oever, unlike in , you cannot include the length of the array in the declaration. The folloing is asynta' error!

int <D3-

float ytD#-

String naesD1-

int <D-

float ytD-

String naesD-

Creating *rrays

?eclaring arrays merely says hat kind of values the array ill hold. %t does not create them. Javaarrays are ob3ects, and like any other ob3ect you use the ne; keyord 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 createthe variables declared on the previous page!

< : ne; intD3-

yt : ne; floatD#-

naes : ne; StringD!-

The numbers in the brackets specify the length of the array2 that is, ho many slots it has to holdvalues. &ith the lengths above < can hold three ints, yt can hold seven floats and naes can hold fifty

Strings. This step is sometimes called allocating the array since it sets aside the memory the arrayrequires.

Initiali+ing *rrays

%ndividual components of an array are referenced by the array name and by an integer hich representstheir position in the array. The numbers you use to identify them are called subscripts or inde'es intothe array.

Subscripts are consecutive integers beginning ith . Thus the array < above has components <D,

<D1, and <D8. Since you start counting at )ero there is no <D3, and trying to access it ill thro an

Page 39: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 39/44

ArrayndeN5ut5foundsENce=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 arraysabove!

<D : 8-

<D1 : !-

<D8 : 28-

ytD1# : #!f-naesD4 : 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 ofthe array.

For even medium si)ed arrays, it$s unieldy to specify each component individually. %t is often helpfulto use for loops to initiali)e the array. +ere is a loop hich fills an array ith the squares of thenumbers from to 1.

floatD sBuares-

sBuares : ne; floatD11-

for (int i:- i G: 1- i++*

  sBuaresDi : i.i-

,

To things you should note about this code fragment!

1. &atch the fenceposts: Since array subscripts begin at )ero you need 11 components if youant to include the square of 1.

@. 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 nativeimplementation. Therefore 6aalangSyste includes a static Systearrayco=y(* method you can

use to copy one array to another.

=ublic static oid arrayco=y(5b6ect source? int sourceosition?

5b6ect destination? int destinationosition? int nuber5fEleents*

Systearrayco=y(* copies nuber5fEleents elements from the array source, beginning ith the

element at sourceosition, to the array destination starting at destinationosition. The

Page 40: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 40/44

destination array must already e'ist hen Systearrayco=y(* is called. The method does not

create it. The source and destination arrays must be of the same type.

For e'ample,

 intD unicode : ne; intD"!!3"-

  for (int i : - i G unicodelength- i++*

  unicodeDi : i-  ,

  intD latin1 : ne; intD8!"-

  Systearrayco=y(unicode? ? latin1? ? 8!"*-

.ulti/)imensional *rrays

So far all these arrays have been oneBdimensional. That is, a single number could locate any value inthe array. +oever 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 toBdimensional array. %f you think of a oneBdimensional array as a column of values, you can think of a toBdimensional array as a table of valueslike this

c c1 c@ c8

r 1 @ 8

r1 1 @ 8 6

r@ @ 8 6 C

r8 8 6 C

r6 6 C L

+ere e have an array ith five ros and four columns. %t has tenty total elements. +oever e sayit has dimension five by four, not dimension tenty. This array is not the same as a four by five arraylike this one!

c c1 c@ c8 c6

r 1 @ 8 6

r1 1 @ 8 6 C

r@ @ 8 6 C

r8 8 6 C L

&e need to use to numbers to identify a position in a toBdimensional array. These are the element$sro and column positions. For instance if the above array is called > then >DD is , >DD1 is 1,

>DD8 is @, >DD3 is 8, >D1D is 1, and so on.

+ere$s ho the elements in a four by five array called % are referred to!

Page 41: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 41/44

EOPOP EOPO1P EOPO@P EOPO8P EOPO6P

EO1POP EO1PO1P EO1PO@P EO1PO8P EO1PO6P

EO@POP EO@PO1P EO@PO@P EO@PO8P EO@PO6P

EO8POP EO8PO1P EO8PO@P EO8PO8P EO8PO6P

)eclaring0 *llocating and Initiali+ing Two

)imensional *rrays

To dimensional arrays are declared, allocated and initiali)ed much like one dimensional arrays.+oever you have to specify to dimensions rather than one, and you typically use to nested forloops to fill the array.

This e'ample fills a toBdimensional array ith the sum of the ro and column inde'es

class FillArray

  =ublic static oid ain (String argsD*

 

intDD atriN-

  atriN : ne; intD4D!-

 

for (int ro;:- ro; G 4- ro;++*

  for (int col:- col G !- col++*

  atriNDro;Dcol : 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' ofdimension - is a square matri' hich contains ones along the diagonal and )eros in all other positions.

class J%atriN

  =ublic static oid ain (String argsD*

 

doubleDD id-

  id : ne; doubleD4D4-

 

for (int ro;:- ro; G 4- ro;++*

  for (int col:- col G 4- col++*

  if (ro; I: col*

  idDro;Dcol:-

  ,

  else

  idDro;Dcol : 1-

  ,

  ,

Page 42: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 42/44

  ,

 

,

 

,

%n toBdimensional arrays ArrayndeN5ut5foundsENce=tions occur henever you e'ceed the

ma'imum column inde' or ro inde'.

(ou can also declare, allocate, and initiali)e a a toBdimensional array at the same time by providing alist of the initial values inside nested brackets. For instance the three by three identity matri' could beset up like this!

doubleDD J3 :

  1? ? ,?

  ? 1? ,?

  ? ? 1,

,-

The spacing and the line breaks used above are purely for the programmer. The compiler doesn$t care.The folloing orks equally ell!

doubleDD J3 : 1? ? ,?? 1? ,?? ? 1,,-

Even 1igher )imensions

(ou don$t have to stop ith to dimensional arrays. Java permits arrays of three, four or moredimensions. +oever 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 rareoutside of scientific and engineering applications.

The synta' for three dimensional arrays is a direct e'tension of that for toBdimensional arrays. The program belo declares, allocates and initiali)es a threeBdimensional array. The array is filled ith thesum of its inde'es.

class Fill3JArray

  =ublic static oid ain (String argsD*

 

intDDD %-

  % : ne; intD4D!D3-

 

Page 43: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 43/44

  for (int ro;:- ro; G 4- ro;++*

  for (int col:- col G !- col++*

  for (int er:- er G 3- er++*

  %Dro;DcolDer : ro;+col+er-

  ,

  ,

  ,

 

,

(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 usingarrays 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 ros. %n most applications this is ahorrible 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 lineand prints out the appropriate ta' and total purchase price.

@. Eodify the sales ta' program to accept an arbitrary number of prices, total them, calculate thesales ta' and print the total amount.

8. &rite a program that reads to 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 .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 ageGQC.1C an hour as of 1NNMH or if the employee orked more than the number of hours in a eek.

. &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.

Page 44: Copy of Java Notes( )

7/22/2019 Copy of Java Notes( )

http://slidepdf.com/reader/full/copy-of-java-notes- 44/44

N. There are 6C6 grams in a pound and 1 grams in a kilogram. &rite programs that convert pounds to kilograms and kilograms to pounds. 9ead the number to be converted from thecommand line. an you make this one program instead of toD

1. The equivalent resistance of resistors connected in series is calculated by adding the resistancesof the individual resistors. &rite a program that accepts a series of resistances from thecommand line and outputs the equivalent resistance.

11. The formula for resistors connected in parallel is a little more comple'. /iven to resistors ithresistances 91 and 9@ connected in parallel the equivalent resistance is given by the inverse ofthe sum of the inverses, i.e.

18 1

13 ReBui : 22222222

14 1 1

1! 22 + 22

1" R1 R8

%f there are more than to resistors you continue to invert the sum of their inverses2 e.g. for fourresistors you have!

1

ReBui : 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. Theresistances ill all be passed as command line arguments.