Download presentation
Presentation is loading. Please wait.
Published byChristina Cameron Modified over 9 years ago
1
Alice in Action with Java Chapter 8 Types and Expressions
2
Alice in Action with Java2 Java’s Primitive Types When a type is declared, memory is allocated Numeric types differ in magnitude of stored value Bit: the smallest unit of memory The bit and the base-2 (binary number) system –A single bit can represent either binary digit (1 or 0) –Combine bits to store numbers greater than 1 Example: binary 11 = decimal 3 –With N bits, there are 2 N different bit patterns Example: 32-bit int can represent 2 32 values Literal: raw value of a type, such as char literal ‘ A ’
3
Alice in Action with Java3 Java’s Primitive Types (continued)
4
Alice in Action with Java4 The double Type Represents real numbers (those with a decimal point) Example of declaring and initializing a double type –double length = 3.5 ; // 3.5 is a fixed-point literal Scientific notation number: A.B x 10 C –A, B, and C are whole number components –Java representation: A.BeC (a floating-point literal) –Two equivalent values: 0.2998e9 and 29.98e7 Constant: read-only item specified by final –Purpose: protect a value and improve readability –Ex: final double SPEED_OF_LIGHT = 2.998e8 ;
5
Alice in Action with Java5 The double Type (continued) Expression –Set of operands, operators, objects, and/or messages –The items in an expression combine to produce a value –Example: a / b * c – d + e // double variables double expression: produces a double value Arithmetic operators: +, -, *, and / Assignment statement: stores a value in a variable –Pattern: variableName = expression; –Example: runTotal = runTotal + nextValue;
6
Alice in Action with Java6 The double Type (continued) Java’s Math class: provides a set of math functions Math methods most often take double arguments Math class constants: Math.E and Math.PI Example: compute volume of a sphere given radius –Formula: volume = 4/3 x PI x radius 3 –Implementation: double volume = 4.0 / 3.0 * Math.PI * Math.pow(radius, 3.0); StrictMath class –Provides the same functionality as Math class –Difference: guarantees results across platforms
7
Alice in Action with Java7 The double Type (continued)
8
Alice in Action with Java8 The double Type (continued)
9
Alice in Action with Java9 The int Type Integers –Whole numbers that can be positive, negative, or 0 –Useful for counting indivisible items, such as eggs int type: 32-bit type used to represent an integer int literals: whole numbers like -15, 0, and 4 Ex: int monthNumber = keyboard.nextInt(); –Retrieves integer value and assigns to monthNumber Special considerations for integer division –The division operator ( / ) produces a quotient –The modulus operator ( % ) produces a remainder
10
Alice in Action with Java10 The int Type (continued) Integer assignment –Pattern: variableName = expression; –Example: int count = 0; Special considerations –You can assign an int value to a double type –You may not assign a double value to an int type Assignment shortcuts –Increment (++) and decrement (--) operators –Arithmetic and assignment: +=, -=, *=, /=, %= –Examples: count++; and count += 2;
11
Alice in Action with Java11 The char Type Declaration form: variableName = expression; –Example: char middleInitial = 'C'; char literals –A single letter, digit, or special symbol –The value is enclosed within single quotes Escape sequence –Backslash ( \ ) followed by one or more characters –Example: \r causes a carriage return Unicode: standard code for representing characters –Example: numbers 65 through 90 A through Z
12
Alice in Action with Java12 The char Type (continued)
13
Alice in Action with Java13 The char Type (continued)
14
Alice in Action with Java14 The boolean Type Holds one of two values: true (1) or false (0) boolean (logical) expressions –Control flow of execution through a program Relational operators (, =, ==, != ) –Compare two operands and return a boolean value –May also be used to build simple logical expressions Example of a simple boolean expression –boolean seniorStatus = age >= 65; –Produces true if age >= 65; otherwise false
15
Alice in Action with Java15 The boolean Type (continued)
16
Alice in Action with Java16 The boolean Type (continued)
17
Alice in Action with Java17 The boolean Type (continued) Logical operators ( &&, ||, and ! ) –Used to build compound logical expressions Example of a compound logical expression –boolean liqWater; // declare boolean variable liqWater = 0.0 < wTemp && wTemp < 100.0; –wTemp must be > 0 and < 100 to produce true Truth table –Relates combinations of operands to each operator –Shows value produced by each logical operation
18
Alice in Action with Java18 The boolean Type (continued)
19
Alice in Action with Java19 The boolean Type (continued)
20
Alice in Action with Java20 Reference Types Two distinguishing features of reference types –Reference variable initialization –The encapsulation of behaviors and attributes
21
Alice in Action with Java21 Reference Variable Initialization Usually involves use of the new operator new operation –Request memory for an object of the indicated type –Returns a reference to that object Example of a new operation –Scanner keyboard = new Scanner(System.in) ; –keyboard is a handle to a Scanner object Exception to the rule: initialization of a String object –Example: String tTwist = "Unique New York";
22
Alice in Action with Java22 Reference Variable Initialization (continued) Comparison with initialization of primitives –Reference type only stores object address (reference) –Primitives store the value indicated by the type null value: a special zero reference Reference type set to null does not refer to an object Example: String tongueTwister = null; boolean tests can be applied to objects set to null
23
Alice in Action with Java23 Sending Messages Reference types are classes containing methods Primitives are not classes and do not contain methods How to compute with reference types –Send a message to an object Pattern: referenceVariable.methodName() Ex: int monthNumber = keyboard.nextInt(); –Send nextInt() to object referenced by keyboard
24
Alice in Action with Java24 Sending Messages (continued) Two ways to identify object appropriate messages –Type the name of a handle and a period –Search the method list for the class in the Java API Java API (application programming interface) –Includes method names, parameters, return types, etc. Do not send a message to a handle with a null value –There is no object that can respond to the message NullPointerException –Error thrown if a method is sent to a handle set to null
25
Alice in Action with Java25 Sending Messages (continued)
26
Alice in Action with Java26 Sending Messages (continued)
27
Alice in Action with Java27 The String Type Used to store a sequence of characters Example: String lastName = "Cat"; Different handles may refer to one String object String literal: 0 or more characters between “ and ” –Escape sequences can also be used in String literals String handle can be set to null or empty string
28
Alice in Action with Java28 The String Type (continued) Instance method: message sent to an object Class method: message sent to a class –Indicated by the word static Java API lists a rich set of String operations Example of instance method sent to String object –char lastInit = lastName.charAt(0); Example of class method sent to String class –String PI_STR = String.valueOf(Math.PI);
29
Alice in Action with Java29 The String Type (continued)
30
Alice in Action with Java30 The String Type (continued)
31
Alice in Action with Java31 The String Type (continued) Concatenation –Joins String values using the + operator –At least one operand must be a String type An illustration of concatenation –String word = "good"; word = word + "bye"; –Second statement refers to a new object –Garbage collector disposes of the de-referenced object += : the concatenation-assignment shortcut – Example: word += "bye";
32
Alice in Action with Java32 Performing Input and Output The Scanner class –Used to read primitive types from the keyboard –Most primitives have their own Scanner methods The PrintStream class –The reference type for System.out –Includes many messages; e.g., print() and printf() Overloaded method –A method name that has multiple meanings –Compiler determines definition by inspecting parameters –Example: print() is defined for each primitive type
33
Alice in Action with Java33 Performing Input and Output (continued)
34
Alice in Action with Java34 Performing Input and Output (continued)
35
Alice in Action with Java35 Performing Input and Output (continued) printf() review –Method is used to control how values are displayed –First argument passed to printf() is a format-string –Embedded placeholders specify formatting Format-string can contain multiple placeholders –Ex: "Month #%d is %s.",monthNum,monthAbb” –Argument converts to Month #11 is Nov. General pattern for a placeholder –%[flags][width][.][precision] convCode
36
Alice in Action with Java36 Performing Input and Output (continued)
37
Alice in Action with Java37 Expression Details Precedence level: priority assigned to an operator –Ex: * and / have higher precedence than + and – Illustration: 4.0 + 2.0 * 8.0 == 20 (not 48 ) A few notes for operators ranked in Figure 8-15 –Parentheses are used to alter the order of operations –Arithmetic operators are higher than relational operators –Relational operators are higher than && and || –Assignment has the lowest precedence
38
Alice in Action with Java38 Expression Details (continued)
39
Alice in Action with Java39 Expression Details (continued) Operator associativity –Specifies order of operations for operators at same level Left-associative operator: left operation performed first –Examples: arithmetic, relational, logical AND, logical OR Right-associative operator: right operation goes first –Examples: new, logical NOT, assignment Illustration: 2.0 + 2.0 * 2.0 - 2.0 / 2.0 –Expression evaluates to 5.0
40
Alice in Action with Java40 Expression Details (continued)
41
Alice in Action with Java41 Expression Details (continued)
42
Alice in Action with Java42 Example: Computing Loudness Problem: determine loudness of a busy highway Formula for loudness –SPL 2 = SPL 1 – 20 x log 10 (distance 2 /distance 1 ) –SPL 1 : reference “sound pressure level” –distance 2 : arbitrary distance –distance 1 : reference distance SPL is measured in decibels (usually integers)
43
Alice in Action with Java43 Designing the SoundLevel Program Essentials of the user story –Query the user for the sound’s reference loudness –Read the reference loudness from the keyboard –Query the user for the reference distance –Read the reference distance from the keyboard –Query the user for the new distance –Read the new distance from the keyboard –Compute and display the new loudness Derive objects and methods from the user story Organize objects and methods into an algorithm
44
Alice in Action with Java44 Designing the SoundLevel Program (continued)
45
Alice in Action with Java45 Designing the SoundLevel Program (continued)
46
Alice in Action with Java46 Designing the SoundLevel Program (continued)
47
Alice in Action with Java47 Writing the Program Create a SoundLevel class containing main() Convert the algorithmic steps into Java statements Some program notes –Line 18 declares loudness2 to be of type long –Line 19 uses Math.round() to round a double –Math.round() returns long to long type expression
48
Alice in Action with Java48 Writing the Program (continued)
49
Alice in Action with Java49 Writing the Program (continued)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.