Chapter 2: Data and Expressions

Similar documents
Chapter 2: Data and Expressions

Chapter 2: Data and Expressions

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Chapter. Let's explore some other fundamental programming concepts

ECE 122 Engineering Problem Solving with Java

A variable is a name for a location in memory A variable must be declared

Data Conversion & Scanner Class

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

2: Basics of Java Programming

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections

Full file at

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

CMPT 125: Lecture 3 Data and Expressions

We now start exploring some key elements of the Java programming language and ways of performing I/O

Primitive Data Types: Intro

Computational Expression

Chapter 2 ELEMENTARY PROGRAMMING

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Lecture 3: Variables and assignment

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Learning objectives: Objects and Primitive Data. Introduction to Objects. A Predefined Object. The print versus the println Methods

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Chapter 2. Elementary Programming

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

CS313D: ADVANCED PROGRAMMING LANGUAGE

For the course, we will be using JCreator as the IDE (Integrated Development Environment).

Basics of Java Programming

Computational Expression

AP Computer Science A

Declaration and Memory

Chapter 2 Elementary Programming

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

COMP 202 Java in one week

Program Elements -- Introduction

Chapter 6 Primitive types

CEN 414 Java Programming

Visual C# Instructor s Manual Table of Contents

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

Table of Contents Date(s) Title/Topic Page #s. Abstraction

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Lecture Set 2: Starting Java

4 Programming Fundamentals. Introduction to Programming 1 1

AP Computer Science Unit 1. Programs

Basic Computation. Chapter 2

Lecture Set 2: Starting Java

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

Full file at

COMP-202 Unit 2: Programming Basics. CONTENTS: The Java Programming Language Variables and Types Basic Input / Output Expressions Conversions

Information Science 1

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

JAVA Programming Concepts

Chapter 2 Primitive Data Types and Operations. Objectives

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Programming with Java

Variables, Constants, and Data Types

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

COMP 202. Java in one week

objectives chapter Define the difference between primitive data and objects. Declare and use variables. Perform mathematical computations.

Information Science 1

3. Java - Language Constructs I

Chapter 2: Using Data

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Basic Programming Elements

Elementary Programming

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

COMP 202 Java in one week

PRIMITIVE VARIABLES. CS302 Introduction to Programming University of Wisconsin Madison Lecture 3. By Matthew Bernstein

JAVA Programming Fundamentals

CS 302: Introduction to Programming

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

CIS 110: Introduction to Computer Programming

Introduction to Java Applications; Input/Output and Operators

More Programming Constructs -- Introduction

Chapter 2 Primitive Data Types and Operations

Program Fundamentals

Section 2: Introduction to Java. Historical note

Chapter 2: Using Data

FUNDAMENTAL DATA TYPES

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

Chapter 2: Using Data

Java Notes. 10th ICSE. Saravanan Ganesh

Chapter 3: Operators, Expressions and Type Conversion

CS111: PROGRAMMING LANGUAGE II

CS110: PROGRAMMING LANGUAGE I

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

DATA TYPES AND EXPRESSIONS

COMP Primitive and Class Types. Yi Hong May 14, 2015

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

4 WORKING WITH DATA TYPES AND OPERATIONS

Numerical Data. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Basic Computation. Chapter 2

Expressions and Casting

Transcription:

Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University April 21, 2015 Chapter 2: Data and Expressions CS 121 1 / 53

Chapter 2 Part 1: Data Types Go to part 1 Part 2: Expressions and Scanner Go to part 2

Part 1: Data Types Character Strings Concatenation Escape Sequences Java Primitive Data Types Declaring and Using Variables Go to index. Chapter 2: Data and Expressions CS 121 3 / 53

Character Strings A sequence of characters can be represented as a string literal by putting double quotes around it. "This is a string literal." "So is this." What about the string literal? "" A character string is an object in Java, defined by the String class. Every string literal represents a String object. See javadoc for String here: http://docs.oracle.com/ javase/8/docs/api/java/lang/string.html. Chapter 2: Data and Expressions CS 121 4 / 53

Printing Strings The System.out object represents a destination (the monitor) to which we can send output. We can invoke the println and print methods of the System.out object to print a character string. println prints a new line character ( \n ) after the string. print does NOT print a new line character ( \n ) after the string. Example: Countdown.java Chapter 2: Data and Expressions CS 121 5 / 53

String Concatenation (1) The string concatenation operator (+) appends one string to the end of another. "Peanut butter " + "and jelly" Allows strings to be broken across multiple lines. "If this was a long string, we may want it on " + "two lines so we can see it more easily" Also used to append numbers to a string. "We will have " + 8 + " quizzes this semester." Chapter 2: Data and Expressions CS 121 6 / 53

String Concatenation (2) The + operator is also used for addition. The function it performs depends on the context. String concatenation Both operands are strings. One operand is a string and one is a number. Addition Both operands are numeric. Example: Addition.java Precedence: evaluated left to right, but can use parenthesis to force order (more about this later). Chapter 2: Data and Expressions CS 121 7 / 53

Escape Sequences What if we wanted to actually print the character?? Let s try it. System.out.println("I said "Hello" to you"); Our compiler is confused! Do you know why? We can fix it with an escape sequence a series of characters that represents a special character. Begins with a backslash character (\). System.out.println("I said \"Hello\" to you"); Chapter 2: Data and Expressions CS 121 8 / 53

Some Java Escape Sequences Escape Sequence Meaning \b backspace \t tab \n newline \r carriage return \ double quote \ single quote \\ backslash Chapter 2: Data and Expressions CS 121 9 / 53

Using Java Escape Sequences Example: BlankOrDark.java Example: CarriageReturnDemo.java (must run from command-line) Chapter 2: Data and Expressions CS 121 10 / 53

Primitive Data Types There are 8 primitive data types in Java (varies in other languages) Integers byte, short, int, long Floating point types float, double Characters char Boolean values (true/false) boolean Chapter 2: Data and Expressions CS 121 11 / 53

Numeric Types Type Space (#bits) Minimum value Maximum Value byte 8-128 127 short 16-32768 32767 int 32-2147483648 2147483647 long 64-9223372036854775808 9223372036854775807 float 32 1.4E-45 3.4028235E38 double 64 4.9E-324 1.7976931348623157E308 float has 6-9 significant digits double has 15-17 significant digits Chapter 2: Data and Expressions CS 121 12 / 53

Initializing Numeric variable A decimal literal value is an int by default. To write a long literal value, we have to use the L suffix. int answer = 42; long neuronsinbrain = 100000000000L; A floating point literal value is double by default. To write a float literal value, we have to use the F suffix. double delta = 453.234343443; float ratio = 0.2363F; Chapter 2: Data and Expressions CS 121 13 / 53

Characters A char stores a single character delimited by single quotes. char topgrade = A ; char comma =, ; char tab = \t ; A char variable in Java can store any character from the Unicode character set. Each character corresponds to a unique 16-bit number. We typically use characters from the ASCII character set. Older and smaller subset of Unicode (only 8-bits). See Apendix C on page 951 of your textbook. http://en.wikipedia.org/wiki/unicode http://en.wikipedia.org/wiki/ascii Chapter 2: Data and Expressions CS 121 14 / 53

Booleans Only two valid values for the boolean type: true or false. Reserved words true and false. boolean done = false; Commonly used to represent two states (e.g. on/off) Chapter 2: Data and Expressions CS 121 15 / 53

Java Identifiers Identifiers are words a programmer uses in a program. Consists of a combination of A-Z, a-z, 0-9, _, and $ Can t begin with digit. Case sensitive. Total, total, and TOTAL are different Good practice to use different case style for different types of identifiers. title case for class names Lincoln, HelloClass camel case for variables count, nextcount upper case for constants MAXIMUM, MINIMUM Chapter 2: Data and Expressions CS 121 16 / 53

Reserved Words Reserved words are special identifiers that have pre-defined meaning. They can t be used in any other way. Some examples public, static, void, class See page 7 (Chapter 1) in textbook for full list of reserved words. Chapter 2: Data and Expressions CS 121 17 / 53

Variables A variable is just a name for a location in memory. Variable names are identifiers. They must be unique. Variables must be declared by specifying a name and the type of information it will hold. String name; int radius, area, circumference; When a variable is used in a program, the current value is used. Chapter 2: Data and Expressions CS 121 18 / 53

Assignment An assignment statement changes the value of a variable. The assignment operator is the equals sign (=). int radius; radius = 10; The value on the right-hand side is stored in the variable on the left. The previous value in radius is overwritten. Variables can also be initialized when they are declared. int count = 0; The type of the right-hand side must be compatible with the type of the variable. Chapter 2: Data and Expressions CS 121 19 / 53

Assignment The right-hand side can be an expression. The expression will be evaluated first and then stored in the variable. radius = 10; radius = radius * 2; // double the radius What is the new value of radius? 20 Chapter 2: Data and Expressions CS 121 20 / 53

Constants A constant is an identifier (similar to a variable) that holds the same value during its entire existence. It is constant, not variable. The compiler will issue an error if you try to change the value of a constant. In Java, we use the final modifier to declare a constant. We typically use all caps to name constants. final int MAX_RADIUS = 1000; Chapter 2: Data and Expressions CS 121 21 / 53

Why do we need constants? Readability give meaning to arbitrary literals. Program maintenance only need to change value once. Program protection establishes that a value should not change; less chance for error. Chapter 2: Data and Expressions CS 121 22 / 53

In-class Exercises EX 2.2. What output is produced by the following code fragment? Explain. System.out.print("Here we go!"); System.out.println("12345"); System.out.print("Another."); System.out.println(""); System.out.println("All done."); EX 2.4. What output is produced by the following statement? Explain. System.out.println("50 plus 25 is " + 50 + 25); PP 2.1. Create a revised version of the Lincoln application from Chapter 1 such that quotes appear around the quotation. Chapter 2: Data and Expressions CS 121 23 / 53

Part 2: Expressions and Scanner Expressions Data conversions The Scanner class for interactive programs Go to index. Chapter 2: Data and Expressions CS 121 24 / 53

In-class Exercises Which data type would you use to represent each of the following items? The name of a restaurant. The maximum number of occupants a restaurant can hold. The current number of occupants. The price of a meal. Whether or not the restaurant is open. Write a variable declaration for each of the above items. Make sure to give your variables descriptive names. Chapter 2: Data and Expressions CS 121 25 / 53

Expressions An expression is a combination of one or more operators and operands. We focus on arithmetic expressions that produce numeric results. Chapter 2: Data and Expressions CS 121 26 / 53

Arithmetic Expressions Arithmetic expressions use the arithmetic operators. Addition + Subtraction - Multiplication * Division / Remainder (modulo) % Chapter 2: Data and Expressions CS 121 27 / 53

Arithmetic Expressions and Data Types If any one of the operands used by an arithmetic operator is floating point (float or double), then the result will be a floating point. For example: int radius = 10; final double PI = 3.14159265358979323; double area = PI * radius * radius; If both operands used by an arithmetic operator are floating point, then the result will be a floating point If both operands used by an arithmetic operator are integer, then the result will be an integer. Be careful!! Chapter 2: Data and Expressions CS 121 28 / 53

Division and Data Types If both operands of the division operator are integers, then the result will be an integer. This means we lose the fractional part of the result. For example, let s assume we want to divide a wall into equal sections. int length = 15; int sections = 2; double newlength = length / sections; Let s try this. How can we fix it? Data conversion we ll get to this soon. Chapter 2: Data and Expressions CS 121 29 / 53

Remainder Operator (modulo) Given two positive numbers, a (the dividend) and b (the divisor), a % n (a mod n) is the remainder of the Euclidean division of a by n. 14 / 3 == 4 14 % 3 == 2 8 / 12 == 0 8 % 12 == 8 10 / 2 == 5 10 % 2 == 0 7 / 6 == 1 7 % 6 == 1 9 / 0 == error 9 % 0 == error Chapter 2: Data and Expressions CS 121 30 / 53

Remainder Operator (modulo) Typically used to determine if a number is odd or even. How? Chapter 2: Data and Expressions CS 121 31 / 53

Operator Precedence (Order of Operations) Just like in Mathematics, operators can be combined into complex expressions. result = total + count / max - offset; Operators have well-defined precedence to determine order of evaluation. result = total + count / max - offset; 4 2 1 3 Expressions are evaluated from left to right in order of operator precedence. Chapter 2: Data and Expressions CS 121 32 / 53

Operator Precedence Precedence Operator Operation Association 0 () parenthesis 1 + unary plus R to L - unary minus 2 * multiplication L to R / division % modulo (remainder) 3 + addition L to R - subtraction + string concatenation 4 = assignment R to L See the full precedence table in Figure D.1 on page 956 of your textbook. Chapter 2: Data and Expressions CS 121 33 / 53

In-Class Exercise Determine the order of evaluation in the following expressions. 1) a + b + c + d + e 2) a + b * c - d / e 3) a / (b + c) - d % e 4) a / (b * (c + (d - e))) Chapter 2: Data and Expressions CS 121 34 / 53

In-Class Exercise Determine the order of evaluation in the following expressions. 1) a + b + c + d + e 1 2 3 4 2) a + b * c - d / e 3 1 4 2 3) a / (b + c) - d % e 2 1 4 3 4) a / (b * (c + (d - e))) 4 3 2 1 Chapter 2: Data and Expressions CS 121 35 / 53

Order of Evaluations and Integer Division Expressions are evaluated from left to right in order of operator precedence. This order can change the results of an expression, especially where possible integer division is involved, which can easily lead to bugs in code. final double PI = 3.14159; double radiuscubed = 1.0; double volume1 = 4 / 3 * PI * radiuscubed; double volume2 = PI * radiuscubed * 4 / 3; Does volume1 equal volume2? Example: Volume.java Chapter 2: Data and Expressions CS 121 36 / 53

Expression Trees Evaluation order of an expression can also be shown using an expression tree. The operators lower in the tree have higher precedence for that expression. a + (b - c) / d + a / - d b c Chapter 2: Data and Expressions CS 121 37 / 53

Assignment Operator The assignment operator has the lowest operator precedence. The entire right-hand side expression is evaluated first, then the result is stored in the original variable. It is common for the right hand side and left hand sides of an assignment statement to contain the same variable. count = count + 1; Chapter 2: Data and Expressions CS 121 38 / 53

Increment and Decrement Operators The increment operator (++) adds one to its operand. The following statements produce the same result. count++; count = count + 1; The decrement operator (--) subtracts one from its operand. The following statements produce the same result. count--; count = count - 1; The increment ++ and decrement operators have the same level of precedence as the unary + and unary - operators. Chapter 2: Data and Expressions CS 121 39 / 53

Postfix vs. Prefix The increment and decrement operators can be applied in postfix form count++; count--; or prefix form ++count; --count; When used as part of a larger expression, the two can have different effects. Use with care!! Chapter 2: Data and Expressions CS 121 40 / 53

Assignment Operators Java provides assignment operators to simplify expressions where we perform an operation on an expression then store the result back into that variable. Consider the following expression. num = num + count; We can simplify this using the addition assignment operator. num += count; Java provides the following assignment operators. += (string concatenation or addition), -=, *=, /=, %= Chapter 2: Data and Expressions CS 121 41 / 53

Data Conversion Sometimes we need to convert from one data type to another (e.g. double to int). These conversions do not change the type of a variable, they just convert it temporarily as part of a computation. Widening conversions. Safest. Go from small data type to large one. e.g. short to int, int to double Narrowing conversions. Not so safe. Go from large data type to smaller one. Must be used carefully as we can lose information! e.g. int to short, double to int By default, Java will not allow narrowing conversions unless we force it (shown later) int count = 3.14 ; //won t compile! Chapter 2: Data and Expressions CS 121 42 / 53

Data Conversions Assignment conversion. Promotion. Casting. Chapter 2: Data and Expressions CS 121 43 / 53

Assignment Conversion Assignment conversion occurs when one type is assigned to a variable of another. Only widening conversions can happen via assignment. For example: double totalcost; int dollars; totalcost = dollars; The value stored in dollars is converted to a double before it is assigned to the totalcost variable. The dollars variable and the value stored in it are still int after the assignment. Chapter 2: Data and Expressions CS 121 44 / 53

Promotion Promotion happens automatically when operators in expressions convert their operands. For example: double sum; int count; double result = sum / count; The value of count is converted to a double before the division occurs. Note that a widening conversion also occurs when the result is assigned to result. Chapter 2: Data and Expressions CS 121 45 / 53

Casting Casting is the most powerful and potentially dangerous conversion technique. Explicitly perform narrowing and widening conversions. Recall our example from earlier: int length = 15, sections = 2; double newlength = length / sections; Recall: If both operands of the division operator are integers, then the result will be an integer. If either or both operands used by an arithmetic operator are floating point, then the result will be a floating point. By casting one of the operands (length in this case), we get the desired result double newlength = ((double) length) / sections; Chapter 2: Data and Expressions CS 121 46 / 53

In-Class Exercise Will the following program produce an accurate conversion (why or why not)? /** * Computes the Fahrenheit equivalent of a specific * Celsius value using the formula : * F = (9/5) * C + 32. */ public class TempConverter { public static void main ( String [] args ) { final int BASE = 32; double fahrenheittemp ; int celsiustemp = 24; // value to convert fahrenheittemp = celsiustemp * 9 / 5 + BASE ; 1. Yes. 2. Sometimes. 3. Nope. 4. I have no idea. } System. out. println (" Celsius Temperature : " + celsiustemp ); System. out. println (" Fahrenheit Equivalent : " + fahrenheittemp ); } Chapter 2: Data and Expressions CS 121 47 / 53

The Scanner class Typically, we want our programs to interact with our users. The Scanner class is part of the java.util class library. It must be imported. import java.util.scanner; It provides methods for reading input values of various types. A Scanner object can read input from various sources (e.g. keyboard, file) See Java 8 API docs: http://docs.oracle.com/javase/8/ docs/api/java/util/scanner.html Chapter 2: Data and Expressions CS 121 48 / 53

Using the Scanner Create a new Scanner object that reads from the keyboard. Scanner scan = new Scanner(System.in); The new operator creates a new Scanner object. The System.in object represents keyboard input. After the object is created, we can invoke various input methods it provides. Chapter 2: Data and Expressions CS 121 49 / 53

Example Example: Convert TempConverter.java to interactive program. Example: Echo.java Chapter 2: Data and Expressions CS 121 50 / 53

Input Tokens By default, white space is used to separate input elements (called tokens). White space includes Space characters ( ) Tab characters ( \t ) New line characters ( \n and \r ) The next, nextint, nextdouble, etc. methods of the Scanner class read and return the next input tokens. See Scanner documentation for more details. Chapter 2: Data and Expressions CS 121 51 / 53

Example Example: GasMileage.java Chapter 2: Data and Expressions CS 121 52 / 53

Exercises Recommended Homework: Exercises: EX 2.5, 2.7, 2.8, 2.9, 2.10 (a, b, c, d), 2.11 (e, f, g, i, j). Projects: PP 2.3, 2.4, 2.8. Browse Chapter 3 of textbook. Chapter 2: Data and Expressions CS 121 53 / 53