Download presentation
Presentation is loading. Please wait.
1
Alice in Action with Java Chapter 8 Types and Expressions
2
Alice in Action with Java2 Objectives Use variables and constants Understand the difference between Java’s fundamental and class types Build complex Java expressions Better understand and use Java’s Scanner and PrintStream classes
3
Alice in Action with Java3 Types and Expressions Alice and Java allow you to send messages to objects Java uses the double type to represent real numbers Some topics to cover –Declaring variables and constants –Constructing expressions –Additional capabilities of printf() –Methods libraries provided by Java
4
Alice in Action with Java4 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 ’
5
Alice in Action with Java5 Java’s Primitive Types
6
Alice in Action with Java6 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 ;
7
Alice in Action with Java7 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;
8
Alice in Action with Java8 The Math Class 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);
9
Alice in Action with Java9 Math Methods
10
Alice in Action with Java10 The double Type (continued)
11
Alice in Action with Java11 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
12
Alice in Action with Java12 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;
13
Alice in Action with Java13 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
14
Alice in Action with Java14 Special Characters Literal representationMeaning \nnewline \ttab \"double quote (in a String) \'single quote (in a char literal) \\backslash \uhhhhunicode character hhhh
15
Alice in Action with Java15 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
16
Alice in Action with Java16 Relational Operators OperatorMeaning ==equal to !=not equal to <less than <=less than or equal to >greater than >=greater than or equal to
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 Logical Operators
19
Alice in Action with Java19 The boolean Type (continued)
20
Alice in Action with Java20 Expression Evaluation 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
21
Alice in Action with Java21 Operator Precedence
22
Alice in Action with Java22 Associativity 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
23
Alice in Action with Java23 Reference Types Reference types are used for objects Two distinguishing features of reference types –Reference variable initialization –The encapsulation of behaviors and attributes
24
Alice in Action with Java24 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";
25
Alice in Action with Java25 null Comparison with initialization of primitives –Reference type only stores object address (reference) –Primitives store the value indicated by the type null value: a special 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
26
Alice in Action with Java26 Sending Messages As in Alice, classes contain methods Primitives are not classes and do not have 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
27
Alice in Action with Java27 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 –Error thrown if a method is sent to a handle set to null NullPointerException
28
Alice in Action with Java28 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
29
Alice in Action with Java29 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);
30
Alice in Action with Java30 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";
31
Alice in Action with Java31 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
32
Alice in Action with Java32 Scanner Methods nextDouble() returns a double value read from the keyboard nextInt() returns an int value read from the keyboard next() reds up to next whitespace and returns a String nextLine() reads up to next newline and returns a String nextBoolean() reads either true or false from the keyboard and returns boolean value
33
Alice in Action with Java33 Output formatting 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
34
Alice in Action with Java34 printf format codes
35
Alice in Action with Java35 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)
36
Alice in Action with Java36 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
37
Alice in Action with Java37 Designing the SoundLevel Program (continued)
38
Alice in Action with Java38 Designing the SoundLevel Program (continued)
39
Alice in Action with Java39 Designing the SoundLevel Program (continued)
40
Alice in Action with Java40 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
41
Alice in Action with Java41 Testing the Program Use easily verifiable values –Reference loudness of 50 decibels –Reference distance of 10 meters –New distance of 100 meters Resulting loudness is 30 –20 less than reference loudness –Diminished value meets expectations
42
Alice in Action with Java42 Solving the Problem Inputs obtained from a Google search –Reference SPL of rush hour traffic is 70 db –Reference distance is 5 meters from source –Neighborhood is 200 meters away Resulting loudness is 40 db –Value is close to the real estate agent’s claim –Neighborhood is quiet
43
Alice in Action with Java43 Summary Two types used in Java: primitives and reference type Most commonly used primitive types: double, int, char, and boolean Expression: series of operands, operators, objects, and/or messages that combine to produce a value Assignment statement: instruction used to store a value in a variable Assignment shortcuts: ++, --, +=, -=, *=, /=, %=
44
Alice in Action with Java44 Summary (continued) Math class: file containing mathematical functions Reference type variable (handle): stores a reference to an object new operation: used to initialize reference types Compute with reference types by sending a message to an object String type: used to store a sequence of characters Operator precedence and operator associativity: sets of rules that specify the order of operations
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.