Week 2Data andExpressions
© 2004 Pearson Addison-Wesley. All rights reserved 2-2Data and Expressions• Lets explore some other fundamentalprogramming...
© 2004 Pearson Addison-Wesley. All rights reserved 2-3Copyright WarningCOMMONWEALTH OF AUSTRALIACopyright Regulations 1969...
© 2004 Pearson Addison-Wesley. All rights reserved 2-4Character Strings• A string of characters can be represented as astr...
© 2004 Pearson Addison-Wesley. All rights reserved 2-5The println Method• In the Lincoln program from Chapter 1, weinvoked...
© 2004 Pearson Addison-Wesley. All rights reserved 2-6The print() Method• The System.out object provides another serviceas...
© 2004 Pearson Addison-Wesley. All rights reserved 2-7String Concatenation• The string concatenation operator (+) is used ...
© 2004 Pearson Addison-Wesley. All rights reserved 2-8String Concatenation• The + operator is also used for arithmetic add...
© 2004 Pearson Addison-Wesley. All rights reserved 2-9Escape Sequences• What if we wanted to print the quote character?• T...
© 2004 Pearson Addison-Wesley. All rights reserved 2-10Escape Sequences• Some Java escape sequences:• See Roses.java (page...
© 2004 Pearson Addison-Wesley. All rights reserved 2-11OutlineCharacter StringsVariables and AssignmentPrimitive Data Type...
© 2004 Pearson Addison-Wesley. All rights reserved 2-12Variables• A variable is a name for a location in memory• A variabl...
© 2004 Pearson Addison-Wesley. All rights reserved 2-13Variable Initialization• A variable can be given an initial value i...
© 2004 Pearson Addison-Wesley. All rights reserved 2-14Assignment• An assignment statement changes the value of avariable•...
© 2004 Pearson Addison-Wesley. All rights reserved 2-15Constants• A constant is an identifier that is similar to avariable...
© 2004 Pearson Addison-Wesley. All rights reserved 2-16Constants• Constants are useful for three important reasons• First,...
© 2004 Pearson Addison-Wesley. All rights reserved 2-17OutlineCharacter StringsVariables and AssignmentPrimitive Data Type...
© 2004 Pearson Addison-Wesley. All rights reserved 2-18Primitive Data• There are eight primitive data types in Java• Four ...
© 2004 Pearson Addison-Wesley. All rights reserved 2-19Numeric Primitive Data• The difference between the various numericp...
© 2004 Pearson Addison-Wesley. All rights reserved 2-20Characters• A char variable stores a single character• Character li...
© 2004 Pearson Addison-Wesley. All rights reserved 2-21Character Sets• A character set is an ordered list of characters,wi...
© 2004 Pearson Addison-Wesley. All rights reserved 2-22Boolean• A boolean value represents a true or falsecondition• The r...
© 2004 Pearson Addison-Wesley. All rights reserved 2-23OutlineCharacter StringsVariables and AssignmentPrimitive Data Type...
© 2004 Pearson Addison-Wesley. All rights reserved 2-24Expressions• An expression is a combination of one or moreoperators...
© 2004 Pearson Addison-Wesley. All rights reserved 2-25Division and Remainder• If both operands to the division operator (...
© 2004 Pearson Addison-Wesley. All rights reserved 2-26Operator Precedence• Operators can be combined into complexexpressi...
© 2004 Pearson Addison-Wesley. All rights reserved 2-27Operator Precedence• What is the order of evaluation in the followi...
© 2004 Pearson Addison-Wesley. All rights reserved 2-28Assignment Revisited• The assignment operator has a lower precedenc...
© 2004 Pearson Addison-Wesley. All rights reserved 2-29Assignment Revisited• The right and left hand sides of an assignmen...
© 2004 Pearson Addison-Wesley. All rights reserved 2-30Increment and Decrement• The increment and decrement operators use ...
© 2004 Pearson Addison-Wesley. All rights reserved 2-31Assignment Operators• Often we perform an operation on a variable, ...
© 2004 Pearson Addison-Wesley. All rights reserved 2-32Assignment Operators• There are many assignment operators in Java,i...
© 2004 Pearson Addison-Wesley. All rights reserved 2-33OutlineCharacter StringsVariables and AssignmentPrimitive Data Type...
© 2004 Pearson Addison-Wesley. All rights reserved 2-34Data Conversion• Sometimes it is convenient to convert data fromone...
© 2004 Pearson Addison-Wesley. All rights reserved 2-35Data Conversion• Conversions must be handled carefully to avoidlosi...
© 2004 Pearson Addison-Wesley. All rights reserved 2-36Assignment Conversion• Assignment conversion occurs when a value of...
© 2004 Pearson Addison-Wesley. All rights reserved 2-37Data Promotion• Promotion happens automatically when operatorsin ex...
© 2004 Pearson Addison-Wesley. All rights reserved 2-38Casting• Casting is the most powerful, and dangerous,technique for ...
© 2004 Pearson Addison-Wesley. All rights reserved 2-39Summary• Week 2 focused on: character strings primitive data the...
Upcoming SlideShare
Loading in …5
×

Week02

439 views
391 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
439
On SlideShare
0
From Embeds
0
Number of Embeds
273
Actions
Shares
0
Downloads
6
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Week02

  1. 1. Week 2Data andExpressions
  2. 2. © 2004 Pearson Addison-Wesley. All rights reserved 2-2Data and Expressions• Lets explore some other fundamentalprogramming concepts• Chapter 2 focuses on: character strings primitive data the declaration and use of variables expressions and operator precedence data conversions accepting input from the user
  3. 3. © 2004 Pearson Addison-Wesley. All rights reserved 2-3Copyright WarningCOMMONWEALTH OF AUSTRALIACopyright Regulations 1969WARNINGThis material has been copied and communicated to you by oron behalf of Bond University pursuant to Part VB of theCopyright Act 1968 (the Act).The material in this communication may be subject to copyrightunder the Act. Any further copying or communication of thismaterial by you may be the subject of copyright protectionunder the Act.Do not remove this notice.
  4. 4. © 2004 Pearson Addison-Wesley. All rights reserved 2-4Character Strings• A string of characters can be represented as astring literal by putting double quotes around thetext:• Examples:"This is a string literal.""123 Main Street""X"• Every character string is an object in Java, definedby the String class• Every string literal represents a String object
  5. 5. © 2004 Pearson Addison-Wesley. All rights reserved 2-5The println Method• In the Lincoln program from Chapter 1, weinvoked the println method to print a characterstring• The System.out object represents a destination(the monitor screen) to which we can send outputSystem.out.println ("Whatever you are, be a good one.");objectmethodname information provided to themethod(parameters)
  6. 6. © 2004 Pearson Addison-Wesley. All rights reserved 2-6The print() Method• The System.out object provides another serviceas well• The print method is similar to the printlnmethod, except that it does not advance to thenext line• Therefore anything printed after a printstatement will appear on the same line• See Countdown.java (page 63)
  7. 7. © 2004 Pearson Addison-Wesley. All rights reserved 2-7String Concatenation• The string concatenation operator (+) is used toappend one string to the end of another"Peanut butter " + "and jelly"• It can also be used to append a number to a string• A string literal cannot be broken across two linesin a program• See Facts.java (page 65)
  8. 8. © 2004 Pearson Addison-Wesley. All rights reserved 2-8String Concatenation• The + operator is also used for arithmetic addition• The function that it performs depends on the typeof the information on which it operates• If both operands are strings, or if one is a stringand one is a number, it performs stringconcatenation• If both operands are numeric, it adds them• The + operator is evaluated left to right, butparentheses can be used to force the order• See Addition.java (page 67)
  9. 9. © 2004 Pearson Addison-Wesley. All rights reserved 2-9Escape Sequences• What if we wanted to print the quote character?• The following line would confuse the compilerbecause it would interpret the second quote as theend of the stringSystem.out.println ("I said "Hello" to you.");• An escape sequence is a series of characters thatrepresents a special character• An escape sequence begins with a backslashcharacter ()System.out.println ("I said "Hello" to you.");
  10. 10. © 2004 Pearson Addison-Wesley. All rights reserved 2-10Escape Sequences• Some Java escape sequences:• See Roses.java (page 68)Escape Sequencebtnr"Meaningbackspacetabnewlinecarriage returndouble quotesingle quotebackslash
  11. 11. © 2004 Pearson Addison-Wesley. All rights reserved 2-11OutlineCharacter StringsVariables and AssignmentPrimitive Data TypesExpressionsData ConversionInteractive ProgramsGraphicsAppletsDrawing Shapes
  12. 12. © 2004 Pearson Addison-Wesley. All rights reserved 2-12Variables• A variable is a name for a location in memory• A variable must be declared by specifying thevariables name and the type of information that itwill holdint total;int count, temp, result;Multiple variables can be created in one declarationdata type variable name
  13. 13. © 2004 Pearson Addison-Wesley. All rights reserved 2-13Variable Initialization• A variable can be given an initial value in thedeclaration• When a variable is referenced in a program, itscurrent value is used• See PianoKeys.java (page 70)int sum = 0;int base = 32, max = 149;
  14. 14. © 2004 Pearson Addison-Wesley. All rights reserved 2-14Assignment• An assignment statement changes the value of avariable• The assignment operator is the = signtotal = 55;• The value that was in total is overwritten• You can only assign a value to a variable that isconsistent with the variables declared type• See Geometry.java (page 71)• The expression on the right is evaluated and theresult is stored in the variable on the left
  15. 15. © 2004 Pearson Addison-Wesley. All rights reserved 2-15Constants• A constant is an identifier that is similar to avariable except that it holds the same value duringits entire existence• As the name implies, it is constant, not variable• The compiler will issue an error if you try tochange the value of a constant• In Java, we use the final modifier to declare aconstantfinal int MIN_HEIGHT = 69;
  16. 16. © 2004 Pearson Addison-Wesley. All rights reserved 2-16Constants• Constants are useful for three important reasons• First, they give meaning to otherwise unclearliteral values For example, MAX_LOAD means more than the literal 250• Second, they facilitate program maintenance If a constant is used in multiple places, its value needonly be updated in one place• Third, they formally establish that a value shouldnot change, avoiding inadvertent errors by otherprogrammers
  17. 17. © 2004 Pearson Addison-Wesley. All rights reserved 2-17OutlineCharacter StringsVariables and AssignmentPrimitive Data TypesExpressionsData ConversionInteractive ProgramsGraphicsAppletsDrawing Shapes
  18. 18. © 2004 Pearson Addison-Wesley. All rights reserved 2-18Primitive Data• There are eight primitive data types in Java• Four of them represent integers: byte, short, int, long• Two of them represent floating point numbers: float, double• One of them represents characters: char• And one of them represents boolean values: boolean
  19. 19. © 2004 Pearson Addison-Wesley. All rights reserved 2-19Numeric Primitive Data• The difference between the various numericprimitive types is their size, and therefore thevalues they can store:• We will tend to use int and doubleTypebyteshortintlongfloatdoubleStorage8 bits16 bits32 bits64 bits32 bits64 bitsMin Value-128-32,768-2,147,483,648< -9 x 1018+/- 3.4 x 1038with 7 significant digit+/- 1.7 x 10308with 15 significant digMax Value12732,7672,147,483,647> 9 x 1018
  20. 20. © 2004 Pearson Addison-Wesley. All rights reserved 2-20Characters• A char variable stores a single character• Character literals are delimited by single quotes:a X 7 $ , n• Example declarations:char topGrade = A;char terminator = ;, separator = ;• Note the distinction between a primitive character variable,which holds only one character, and a String object, whichcan hold multiple characters
  21. 21. © 2004 Pearson Addison-Wesley. All rights reserved 2-21Character Sets• A character set is an ordered list of characters,with each character corresponding to a uniquenumber• A char variable in Java can store any characterfrom the Unicode character set• The Unicode character set uses sixteen bits percharacter, allowing for 65,536 unique characters• It is an international character set, containingsymbols and characters from many worldlanguages
  22. 22. © 2004 Pearson Addison-Wesley. All rights reserved 2-22Boolean• A boolean value represents a true or falsecondition• The reserved words true and false are theonly valid values for a boolean typeboolean done = false;• A boolean variable can also be used to representany two states, such as a light bulb being on or off
  23. 23. © 2004 Pearson Addison-Wesley. All rights reserved 2-23OutlineCharacter StringsVariables and AssignmentPrimitive Data TypesExpressionsData ConversionInteractive ProgramsGraphicsAppletsDrawing Shapes
  24. 24. © 2004 Pearson Addison-Wesley. All rights reserved 2-24Expressions• An expression is a combination of one or moreoperators and operands which produces a result• Arithmetic expressions compute numeric resultsand make use of the arithmetic operators:• If either or both operands used by an arithmeticoperator are floating point, then the result is afloating pointAdditionSubtractionMultiplicationDivisionRemainder+-*/%
  25. 25. © 2004 Pearson Addison-Wesley. All rights reserved 2-25Division and Remainder• If both operands to the division operator (/) areintegers, the result is an integer (the fractional partis discarded)• The remainder operator (%) returns the remainderafter dividing the second operand into the first14 / 3 equals8 / 12 equals4014 % 3 equals8 % 12 equals28
  26. 26. © 2004 Pearson Addison-Wesley. All rights reserved 2-26Operator Precedence• Operators can be combined into complexexpressionsresult = total + count / max - offset;• Operators have a well-defined precedence whichdetermines the order in which they are evaluated• Multiplication, division, and remainder areevaluated prior to addition, subtraction, and stringconcatenation• Arithmetic operators with the same precedenceare evaluated from left to right, but parenthesescan be used to force the evaluation order
  27. 27. © 2004 Pearson Addison-Wesley. All rights reserved 2-27Operator Precedence• What is the order of evaluation in the followingexpressions?a + b + c + d + e1 432a + b * c - d / e3 241a / (b + c) - d % e2 341a / (b * (c + (d - e)))4 123
  28. 28. © 2004 Pearson Addison-Wesley. All rights reserved 2-28Assignment Revisited• The assignment operator has a lower precedencethan the arithmetic operatorsFirst the expression on the right handside of the = operator is evaluatedThen the result is stored in thevariable on the left hand sideanswer = sum / 4 + MAX * lowest;14 3 2
  29. 29. © 2004 Pearson Addison-Wesley. All rights reserved 2-29Assignment Revisited• The right and left hand sides of an assignmentstatement can contain the same variableFirst, one is added to theoriginal value of countThen the result is stored back into count(overwriting the original value)count = count + 1;
  30. 30. © 2004 Pearson Addison-Wesley. All rights reserved 2-30Increment and Decrement• The increment and decrement operators use onlyone operand• The increment operator (++) adds one to itsoperand• The decrement operator (--) subtracts one fromits operand• The statementcount++;is functionally equivalent tocount = count + 1;
  31. 31. © 2004 Pearson Addison-Wesley. All rights reserved 2-31Assignment Operators• Often we perform an operation on a variable, andthen store the result back into that variable• Java provides assignment operators to simplifythat process• For example, the statementnum += count;is equivalent tonum = num + count;
  32. 32. © 2004 Pearson Addison-Wesley. All rights reserved 2-32Assignment Operators• There are many assignment operators in Java,including the following:Operator+=-=*=/=%=Examplex += yx -= yx *= yx /= yx %= yEquivalentTox = x + yx = x - yx = x * yx = x / yx = x % y
  33. 33. © 2004 Pearson Addison-Wesley. All rights reserved 2-33OutlineCharacter StringsVariables and AssignmentPrimitive Data TypesExpressionsData ConversionInteractive ProgramsGraphicsAppletsDrawing Shapes
  34. 34. © 2004 Pearson Addison-Wesley. All rights reserved 2-34Data Conversion• Sometimes it is convenient to convert data fromone type to another• For example, in a particular situation we may wantto treat an integer as a floating point value• These conversions do not change the type of avariable or the value thats stored in it – they onlyconvert a value as part of a computation
  35. 35. © 2004 Pearson Addison-Wesley. All rights reserved 2-35Data Conversion• Conversions must be handled carefully to avoidlosing information• Widening conversions are safest because theytend to go from a small data type to a larger one(such as a short to an int)• Narrowing conversions can lose informationbecause they tend to go from a large data type to asmaller one (such as an int to a short)• In Java, data conversions can occur in three ways: assignment conversion promotion casting
  36. 36. © 2004 Pearson Addison-Wesley. All rights reserved 2-36Assignment Conversion• Assignment conversion occurs when a value ofone type is assigned to a variable of another• If money is a float variable and dollars is anint variable, the following assignment convertsthe value in dollars to a floatmoney = dollars;• Only widening conversions can happen viaassignment• Note that the value or type of dollars did notchange
  37. 37. © 2004 Pearson Addison-Wesley. All rights reserved 2-37Data Promotion• Promotion happens automatically when operatorsin expressions convert their operands• For example, if sum is a float and count is anint, the value of count is converted to a floatingpoint value to perform the following calculation:result = sum / count;
  38. 38. © 2004 Pearson Addison-Wesley. All rights reserved 2-38Casting• Casting is the most powerful, and dangerous,technique for conversion• Both widening and narrowing conversions can beaccomplished by explicitly casting a value• To cast, the type is put in parentheses in front ofthe value being converted• For example, if total and count are integers, butwe want a floating point result when dividing them,we can cast total:result = (float) total / count;
  39. 39. © 2004 Pearson Addison-Wesley. All rights reserved 2-39Summary• Week 2 focused on: character strings primitive data the declaration and use of variables expressions and operator precedence data conversions

×