Alice in Action with Java Chapter 8 Types and Expressions.

Slides:



Advertisements
Similar presentations
Types and Arithmetic Operators
Advertisements

1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
Alice in Action with Java Chapter 9 Methods. Alice in Action with Java2 Objectives Use Math methods Use string methods Understand boolean type Build your.
©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 Chapter 3 Arithmetic Expressions. 2 Chapter 3 Topics l Overview of Java Data Types l Numeric Data Types l Declarations for Numeric Expressions l Simple.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
Data types and variables
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
JavaScript, Fourth Edition
Chapter 2 Data Types, Declarations, and Displays
JavaScript, Third Edition
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Alice in Action with Java Chapter 8 Types and Expressions.
String Escape Sequences
1 Chapter 2 JAVA FUNDAMENTALS CONT’D. 2 PRIMITIVE DATA TYPES Computer programs operate on data values. Values in Java are classified according to their.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Chapter 2 Data Types, Declarations, and Displays.
Objectives You should be able to describe: Data Types
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
1 Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
2440: 211 Interactive Web Programming Expressions & Operators.
Chapter 3: Data Types and Operators JavaScript - Introductory.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Input, Output, and Processing
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Chapter 2: Using Data.
CHAPTER 4: CONTROL STRUCTURES - SEQUENCING 10/14/2014 PROBLEM SOLVING & ALGORITHM (DCT 1123)
Knowledge Base C++ #include using std namespace; int main(){} return 0 ; cout
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
1 Operations Making Things Happen (Chap. 3) Expressions.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Chapter 2 Variables.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
COMP Primitive and Class Types Yi Hong May 14, 2015.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
OPERATORS IN C CHAPTER 3. Expressions can be built up from literals, variables and operators. The operators define how the variables and literals in the.
1Object-Oriented Program Development Using C++ Built-in Data Types Data type –Range of values –Set of operations on those values Literal: refers to acceptable.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Chapter 2 Variables.
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Multiple variables can be created in one declaration
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2: Basic Elements of Java
Chapter 2 Variables.
elementary programming
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Primitive Types and Expressions
Chapter 2 Variables.
Presentation transcript:

Alice in Action with Java Chapter 8 Types and Expressions

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 ’

Alice in Action with Java3 Java’s Primitive Types (continued)

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: e9 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 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;

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

Alice in Action with Java7 The double Type (continued)

Alice in Action with Java8 The double Type (continued)

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

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;

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

Alice in Action with Java12 The char Type (continued)

Alice in Action with Java13 The char Type (continued)

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

Alice in Action with Java15 The boolean Type (continued)

Alice in Action with Java16 The boolean Type (continued)

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

Alice in Action with Java18 The boolean Type (continued)

Alice in Action with Java19 The boolean Type (continued)

Alice in Action with Java20 Reference Types Two distinguishing features of reference types –Reference variable initialization –The encapsulation of behaviors and attributes

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

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

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

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

Alice in Action with Java25 Sending Messages (continued)

Alice in Action with Java26 Sending Messages (continued)

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

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

Alice in Action with Java29 The String Type (continued)

Alice in Action with Java30 The String Type (continued)

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

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

Alice in Action with Java33 Performing Input and Output (continued)

Alice in Action with Java34 Performing Input and Output (continued)

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

Alice in Action with Java36 Performing Input and Output (continued)

Alice in Action with Java37 Expression Details Precedence level: priority assigned to an operator –Ex: * and / have higher precedence than + and – Illustration: * 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 Java38 Expression Details (continued)

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 –Expression evaluates to 5.0

Alice in Action with Java40 Expression Details (continued)

Alice in Action with Java41 Expression Details (continued)

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)

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

Alice in Action with Java44 Designing the SoundLevel Program (continued)

Alice in Action with Java45 Designing the SoundLevel Program (continued)

Alice in Action with Java46 Designing the SoundLevel Program (continued)

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

Alice in Action with Java48 Writing the Program (continued)

Alice in Action with Java49 Writing the Program (continued)