alice in action with java chapter 8 types and expressions

44
Alice in Action with Java Chapter 8 Types and Expressions

Post on 22-Dec-2015

225 views

Category:

Documents


0 download

TRANSCRIPT

Alice in Action with Java

Chapter 8Types and Expressions

Alice in Action with Java 2

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

Alice in Action with Java 3

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

Alice in Action with Java 4

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 2N different bit patterns• Example: 32-bit int can represent 232 values

• Literal: raw value of a type, such as char literal ‘A’

Alice in Action with Java 5

Java’s Primitive Types

Alice in Action with Java 6

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 10C

– 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;

Alice in Action with Java 7

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;

Alice in Action with Java 8

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 radius3

– Implementation: double volume = 4.0 / 3.0 * Math.PI * Math.pow(radius, 3.0);

Alice in Action with Java 9

Math Methods

Alice in Action with Java 10

The double Type (continued)

Alice in Action with Java 11

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

Alice in Action with Java 12

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;

Alice in Action with Java 13

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

Alice in Action with Java 14

Special Characters

Literal representation Meaning

\n newline

\t tab

\" double quote (in a String)

\' single quote (in a char literal)

\\ backslash

\uhhhh unicode character hhhh

Alice in Action with Java 15

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

Alice in Action with Java 16

Relational Operators

Operator Meaning

== equal to

!= not equal to

< less than

<= less than or equal to

> greater than

>= greater than or equal to

Alice in Action with Java 17

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

Alice in Action with Java 18

Logical Operators

Alice in Action with Java 19

The boolean Type (continued)

Alice in Action with Java 20

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

Alice in Action with Java 21

Operator Precedence

Alice in Action with Java 22

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

Alice in Action with Java 23

Reference Types

• Reference types are used for objects

• Two distinguishing features of reference types– Reference variable initialization – The encapsulation of behaviors and attributes

Alice in Action with Java 24

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";

Alice in Action with Java 25

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

Alice in Action with Java 26

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

Alice in Action with Java 27

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

Alice in Action with Java 28

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

Alice in Action with Java 29

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);

Alice in Action with Java 30

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";

Alice in Action with Java 31

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

Alice in Action with Java 32

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

Alice in Action with Java 33

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

Alice in Action with Java 34

printf format codes

Alice in Action with Java 35

Example: Computing Loudness

• Problem: determine loudness of a busy highway

• Formula for loudness– SPL2 = SPL1 – 20 x log10(distance2/distance1)

– SPL1: reference “sound pressure level”

– distance2: arbitrary distance

– distance1: reference distance

• SPL is measured in decibels (usually integers)

Alice in Action with Java 36

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

Alice in Action with Java 37

Designing the SoundLevel Program (continued)

Alice in Action with Java 38

Designing the SoundLevel Program (continued)

Alice in Action with Java 39

Designing the SoundLevel Program (continued)

Alice in Action with Java 40

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

Alice in Action with Java 41

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

Alice in Action with Java 42

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

Alice in Action with Java 43

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: ++, --, +=, -=, *=, /=, %=

Alice in Action with Java 44

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