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

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

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

ECE 122 Engineering Problem Solving with Java

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

CMPT 125: Lecture 3 Data and Expressions

Full file at

2: Basics of Java Programming

Declaration and Memory

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

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

Lecture 3: Variables and assignment

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

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

Basics of Java Programming

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

Program Elements -- Introduction

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

Basic Operations jgrasp debugger Writing Programs & Checkstyle

Chapter 2 Elementary Programming

Information Science 1

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

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

Variables, Constants, and Data Types

Chapter 2 ELEMENTARY PROGRAMMING

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Primitive Data Types: Intro

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

3. Java - Language Constructs I

Visual C# Instructor s Manual Table of Contents

Data Conversion & Scanner Class

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

Chapter 2 Primitive Data Types and Operations. Objectives

Information Science 1

Chapter 6 Primitive types

Full file at

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

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

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

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

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

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1

Chapter 2. Elementary Programming

Chapter 2: Using Data

Java Notes. 10th ICSE. Saravanan Ganesh

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

Zheng-Liang Lu Java Programming 45 / 79

Getting started with Java

MODULE 02: BASIC COMPUTATION IN JAVA

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Chapter 1 Introduction to java

JAVA Programming Concepts

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

4 Programming Fundamentals. Introduction to Programming 1 1

DATA TYPES AND EXPRESSIONS

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

AP Computer Science A

2 rd class Department of Programming. OOP with Java Programming

CS 106 Introduction to Computer Science I

CIS 110: Introduction to Computer Programming

Chapter 3 Syntax, Errors, and Debugging. Fundamentals of Java

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

Chapter 2 Primitive Data Types and Operations

More Programming Constructs -- Introduction

B.V. Patel Institute of BMC & IT, UTU 2014

Expressions and Casting

CEN 414 Java Programming

JAVA Programming Fundamentals

FUNDAMENTAL DATA TYPES

COMP 202 Java in one week

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

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

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Program Fundamentals

Programming with Java

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

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

CS111: PROGRAMMING LANGUAGE II

These are reserved words of the C language. For example int, float, if, else, for, while etc.

QUIZ: What value is stored in a after this

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Motivations. Chapter 2: Elementary Programming 8/24/18. Introducing Programming with an Example. Trace a Program Execution. Trace a Program Execution

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

Section 2: Introduction to Java. Historical note

Chapter 2 Elementary Programming. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Operators & Expressions

Chapter 3: Operators, Expressions and Type Conversion

Expressions and Casting. Data Manipulation. Simple Program 11/5/2013

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CS Programming I: Primitives and Expressions

Chapter 2: Using Data

IT 374 C# and Applications/ IT695 C# Data Structures

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Transcription:

Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University August 21, 2017 Chapter 2: Data and Expressions CS 121 1 / 51

Chapter 1 Terminology Review algorithm program (aka. application) programming language JDK, JRE main method compiler (compiling) execution debugging syntax semantics compile-time error run-time error logical error

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

Part 1: Data Types What is a data type? Character Strings Concatenation Escape Sequences Java Primitive Data Types Declaring and Using Variables Go to index. Chapter 2: Data and Expressions CS 121 4 / 51

What is a data type? Programs represent all kinds of data. What types of data might the following programs need to represent? A calculator program. A word processor. An address book. A data type is a classification identifying various types of data, such as real, integer, Boolean, words, etc. Chapter 2: Data and Expressions CS 121 5 / 51

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 6 / 51

Printing Strings The System.out object represents a destination (the console) 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. Chapter 2: Data and Expressions CS 121 7 / 51

In-Class Exercise Example: Countdown.java Predict the output of the program before we run it. Chapter 2: Data and Expressions CS 121 8 / 51

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 9 / 51

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 10 / 51

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 11 / 51

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 12 / 51

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

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 14 / 51

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 15 / 51

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. 42 (int) 100000000000L (long) A floating point literal value is double by default. To write a float literal value, we have to use the F suffix. 453.234343443 (double) 0.2363F (float) Chapter 2: Data and Expressions CS 121 16 / 51

Characters A char stores a single character delimited by single quotes. A, \t A char variable in Java can store any character from the Unicode character set. Each character corresponds to a unique 16-bit number. The Character class supports the full Unicode Standard. English speakers typically use characters from the ASCII character set. Older and smaller subset of Unicode (only 7-bits per character). See Appendix C on page 994 of your textbook. http://en.wikipedia.org/wiki/unicode http://en.wikipedia.org/wiki/ascii To print a special character in a string, use "\u" followed by the code. System.out. println ("Are you happy? \u263a"); Here is a handy table of characters: http://unicode-table.com/en/ Chapter 2: Data and Expressions CS 121 17 / 51

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

In-Class Exercise What are the 8 primitive data types available in Java? Integers (byte, short, int, long) Floating Point (float, double) Character (char) Boolean (boolean) How do we represent a sequence of characters? Strings (the String object). Give an example of an int, double, char, boolean, and String, and when each could be used. Chapter 2: Data and Expressions CS 121 19 / 51

Declaring and Using Variables We know we can represent different types of data in our programs using the data types we just discussed, but we need a way to keep track of all of this data. Variables allow us to define and reference the data we use in our programs. Chapter 2: Data and Expressions CS 121 20 / 51

Variables A variable is just a name for a location in memory. Variables must be declared by specifying the type of information it will hold and a unique name. String name; char letter; int radius, circumference; double area; boolean done; The value of the variable should be set before it is used. Chapter 2: Data and Expressions CS 121 21 / 51

Java Identifiers Variable names are identifiers. Identifiers are words a programmer uses in a program. There are certain rules we must follow for identifiers. They must be unique. They can t be reserved words. e.g. public, void, main (see pg. 7 of book for complete list) Consist of a combination of A-Z, a-z, 0-9, _, and $ Can t begin with a digit. Examples Valid: octopus, octopus_10, and sharkbait Invalid: 10octopus, sharkbait!, and shrimp() 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, nextcounttwo upper case for constants MAXIMUM, MINIMUM Chapter 2: Data and Expressions CS 121 22 / 51

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 radius = 10; The type of the right-hand side must be compatible with the type of the variable. Chapter 2: Data and Expressions CS 121 23 / 51

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 24 / 51

In-Class Exercise 1. Declare a variable to represent the number of students in this class. What type will it be? What name will you give it? 2. Initialize the variable to the number of students in class right now. 3. Suppose one new student enrolls in this class. Write a statement that will update the value of your variable with the new number of students in this class. 4. Declare and initialize a variable that will store the name of the new student, Bugs Bunny. 5. Finally, declare a variable to represent whether or not we are having fun in this class. Chapter 2: Data and Expressions CS 121 25 / 51

Constants A constant is an identifier (similar to a variable) that holds the same value during its entire existence. It is constant, not variable. We can only assign a value one time. 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 26 / 51

Why do we need constants? Readability by giving a value a name, you help explain it s role in the program. 38 vs. MAX_ROOM_OCCUPANCY true vs. HAS_VACANCY Program maintenance if a constant is used throughout a program and its value has to be modified, then you only need to update it in one place. Program protection establishes that a value should not change; less chance for error. Chapter 2: Data and Expressions CS 121 27 / 51

Part 2: Expressions Expressions Data conversions Go to index. Chapter 2: Data and Expressions CS 121 28 / 51

In-class Exercises 1. 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. 2. Write a variable declaration for each of the above items. Make sure to give your variables descriptive names. (Don t worry about initializing your variables.) Chapter 2: Data and Expressions CS 121 29 / 51

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 30 / 51

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

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 32 / 51

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. In-Class Exercise: 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 33 / 51

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

In-Class Exercise The modulo operator is typically used to determine if a number is odd or even. How would this be accomplished? What if we want to determine if a number is a multiple 5? 10? 32? Chapter 2: Data and Expressions CS 121 35 / 51

Operator Precedence (Order of Operations) Just like in math, 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 36 / 51

Operator Precedence Precedence Operator Operation Association 0 () parenthesis L to R 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 998/999 of your textbook. Chapter 2: Data and Expressions CS 121 37 / 51

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 38 / 51

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 39 / 51

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 40 / 51

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 41 / 51

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 42 / 51

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!! int x = 10; int y = ++ x; System. out. println ("++x: " + y); // prints 11 int a = 10; int b = a ++; System. out. println ("a ++: " + b); // prints 10 Chapter 2: Data and Expressions CS 121 43 / 51

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 44 / 51

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 45 / 51

Data Conversions Assignment conversion. Promotion. Casting. Chapter 2: Data and Expressions CS 121 46 / 51

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 47 / 51

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. Chapter 2: Data and Expressions CS 121 48 / 51

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 49 / 51

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 1. Yes. 2. Sometimes. 3. Nope. 4. I have no idea. } } fahrenheittemp = celsiustemp * 9 / 5 + BASE ; System. out. println (" Celsius : " + celsiustemp ); System. out. println (" Fahrenheit : " + fahrenheittemp ); Chapter 2: Data and Expressions CS 121 50 / 51

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 51 / 51