chapter 2: data and expressions - cs 121 - boise...

84
Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University January 15, 2015 Chapter 2: Data and Expressions CS 121 1/1

Upload: lycong

Post on 06-Aug-2018

222 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Chapter 2: Data and ExpressionsCS 121

Department of Computer ScienceCollege of EngineeringBoise State University

January 15, 2015

Chapter 2: Data and Expressions CS 121 1 / 1

Page 2: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Chapter 2

I Part 1: Data TypesGo to part 1

I Part 2: Expressions and ScannerGo to part 2

Page 3: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Part 1: Data Types

I Character StringsI ConcatenationI Escape Sequences

I Java Primitive TypesI Declaring and Using Variables

Go to index.

Chapter 2: Data and Expressions CS 121 3 / 1

Page 4: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Character Strings

I A sequence of characters can be represented as a string literalby putting double quotes around it.

I “This is a string literal.” “So is this.”I A character string is an object in Java, defined by the String

class.I Every string literal represents a String object.

I See http://docs.oracle.com/javase/8/docs/api/java/lang/String.html.

Chapter 2: Data and Expressions CS 121 4 / 1

Page 5: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Character Strings

I A sequence of characters can be represented as a string literalby putting double quotes around it.

I “This is a string literal.” “So is this.”I A character string is an object in Java, defined by the String

class.I Every string literal represents a String object.I See http://docs.oracle.com/javase/8/docs/api/java/

lang/String.html.

Chapter 2: Data and Expressions CS 121 4 / 1

Page 6: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Printing Strings

I The System.out object represents a destination (the monitor)to which we can send output.

I We can invoke the println and print methods of theSystem.out object to print a character string.

I println – prints a new line character (’\n’) after the string.I print – does NOT print a new line character (’\n’) after the

string.

I Example: Countdown.java

Chapter 2: Data and Expressions CS 121 5 / 1

Page 7: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Printing Strings

I The System.out object represents a destination (the monitor)to which we can send output.

I We can invoke the println and print methods of theSystem.out object to print a character string.

I println – prints a new line character (’\n’) after the string.I print – does NOT print a new line character (’\n’) after the

string.

I Example: Countdown.java

Chapter 2: Data and Expressions CS 121 5 / 1

Page 8: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

String Concatenation (1)

I The string concatenation operator (+) appends one string tothe end of another."Peanut butter " + "and jelly"

I 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 all in out editor"

I Also used to append numbers to a string."We will have " + 10 + " quizzes this semester."

Chapter 2: Data and Expressions CS 121 6 / 1

Page 9: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

String Concatenation (2)

I The + operator is also used for addition.I The function it performs depends on the context.

I String concatenationI Both operands are strings.I One operand is a string and one is a number.

I AdditionI Both operands are numeric.

I Example: Addition.java

I Precedence: evaluated left to right, but can use parenthesis toforce order (more about this later).

Chapter 2: Data and Expressions CS 121 7 / 1

Page 10: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Escape Sequences

I What if we wanted to actually print the “ character??

I Let’s try it.System.out.println("I said "Hello" to you");

I Our compiler is confused! Do you know why?I We can fix it with an escape sequence – a series of characters

that represents a special character.I Begins with a backslash character (\).

System.out.println("I said \"Hello\" to you");

Chapter 2: Data and Expressions CS 121 8 / 1

Page 11: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Escape Sequences

I What if we wanted to actually print the “ character??I Let’s try it.

System.out.println("I said "Hello" to you");

I Our compiler is confused! Do you know why?I We can fix it with an escape sequence – a series of characters

that represents a special character.I Begins with a backslash character (\).

System.out.println("I said \"Hello\" to you");

Chapter 2: Data and Expressions CS 121 8 / 1

Page 12: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Escape Sequences

I What if we wanted to actually print the “ character??I Let’s try it.

System.out.println("I said "Hello" to you");

I Our compiler is confused! Do you know why?

I We can fix it with an escape sequence – a series of charactersthat represents a special character.

I Begins with a backslash character (\).System.out.println("I said \"Hello\" to you");

Chapter 2: Data and Expressions CS 121 8 / 1

Page 13: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Escape Sequences

I What if we wanted to actually print the “ character??I Let’s try it.

System.out.println("I said "Hello" to you");

I Our compiler is confused! Do you know why?I We can fix it with an escape sequence – a series of characters

that represents a special character.

I Begins with a backslash character (\).System.out.println("I said \"Hello\" to you");

Chapter 2: Data and Expressions CS 121 8 / 1

Page 14: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Escape Sequences

I What if we wanted to actually print the “ character??I Let’s try it.

System.out.println("I said "Hello" to you");

I Our compiler is confused! Do you know why?I We can fix it with an escape sequence – a series of characters

that represents a special character.I Begins with a backslash character (\).

System.out.println("I said \"Hello\" to you");

Chapter 2: Data and Expressions CS 121 8 / 1

Page 15: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

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

Page 16: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Using Java Escape Sequences

I Example: Roses.java

I Example: CarriageReturnDemo.java (must run fromcommand-line)

Chapter 2: Data and Expressions CS 121 10 / 1

Page 17: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Using Java Escape Sequences

I Example: Roses.javaI Example: CarriageReturnDemo.java (must run from

command-line)

Chapter 2: Data and Expressions CS 121 10 / 1

Page 18: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Primitive Data Types

I There are 8 primitive data types in Java (varies in otherlanguages)

I IntegersI byte, short, int, long

I Floating points (decimals)I float, double

I CharactersI char

I Boolean values (true/false)I boolean

Chapter 2: Data and Expressions CS 121 11 / 1

Page 19: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Numeric Types

Chapter 2: Data and Expressions CS 121 12 / 1

Page 20: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Characters

I A char stores a single character delimited by single quotes.char topGrade = ‘A’;char comma = ‘,’;

I A char variable in Java can store any character from theUnicode character set.

I Each character corresponds to a unique 16-bit number.I We typically use characters from the ASCII character set.

I Older and smaller subset of Unicode (only 8-bits).

I Unicode and ASCII tables available online.

Chapter 2: Data and Expressions CS 121 13 / 1

Page 21: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Booleans

I Only two valid values for the boolean type.I Reserved words true and false.

boolean done = false;I Commonly used to represent two states (e.g. on/off)

Chapter 2: Data and Expressions CS 121 14 / 1

Page 22: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Java Identifiers

I Identifiers are words a programmer uses in a program.I A-Z, a-z, 0-9, _, and $I Can’t begin with digit.I Case sensitive.

I Total, total, and TOTAL are different

I Good practice to use different case style for different types ofidentifiers.

I title case for class names – Lincoln, HelloClassI camel case for variables – count, nextCountI upper case for constants – MAXIMUM, MINIMUM

Chapter 2: Data and Expressions CS 121 15 / 1

Page 23: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Java Identifiers

I Identifiers are words a programmer uses in a program.I A-Z, a-z, 0-9, _, and $I Can’t begin with digit.I Case sensitive.

I Total, total, and TOTAL are differentI Good practice to use different case style for different types of

identifiers.I title case for class names – Lincoln, HelloClassI camel case for variables – count, nextCountI upper case for constants – MAXIMUM, MINIMUM

Chapter 2: Data and Expressions CS 121 15 / 1

Page 24: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Reserved Words

I Reserved words are special identifiers that have pre-definedmeaning.

I They can’t be used in any other way.I Some examples – public, static, void, classI See page 7 in textbook for full list of words.

Chapter 2: Data and Expressions CS 121 16 / 1

Page 25: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Variables

I A variable is just a name for a location in memory.

I Variable names are identifiers. They must be unique.I Variables must be declared by specifying a name and the type

of information it will hold.String name;int radius, area, circumference;

I When a variable is used in a program, the current value is used.

Chapter 2: Data and Expressions CS 121 17 / 1

Page 26: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Variables

I A variable is just a name for a location in memory.I Variable names are identifiers. They must be unique.

I Variables must be declared by specifying a name and the typeof information it will hold.

String name;int radius, area, circumference;

I When a variable is used in a program, the current value is used.

Chapter 2: Data and Expressions CS 121 17 / 1

Page 27: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Variables

I A variable is just a name for a location in memory.I Variable names are identifiers. They must be unique.I Variables must be declared by specifying a name and the type

of information it will hold.

String name;int radius, area, circumference;

I When a variable is used in a program, the current value is used.

Chapter 2: Data and Expressions CS 121 17 / 1

Page 28: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Variables

I A variable is just a name for a location in memory.I Variable names are identifiers. They must be unique.I Variables must be declared by specifying a name and the type

of information it will hold.String name;int radius, area, circumference;

I When a variable is used in a program, the current value is used.

Chapter 2: Data and Expressions CS 121 17 / 1

Page 29: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Variables

I A variable is just a name for a location in memory.I Variable names are identifiers. They must be unique.I Variables must be declared by specifying a name and the type

of information it will hold.String name;int radius, area, circumference;

I When a variable is used in a program, the current value is used.

Chapter 2: Data and Expressions CS 121 17 / 1

Page 30: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Assignment

I An assignment statement changes the value of a variable.I The assignment operator is the equals sign (=).

radius = 10;I The value on the right-hand side is stored in the variable on

the left.I Variables can also be initialized when they are declared.

int count = 0;I The previous value in radius is overwritten.I The type of the right-hand side must be compatible with the

type of the variable.

Chapter 2: Data and Expressions CS 121 18 / 1

Page 31: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Assignment

I The right-hand side can be an expression.I The expression will be evaluated first and then stored in the

variable.radius = 10;radius = radius * 2; // double the radius

I What is the new value of radius? 20

Chapter 2: Data and Expressions CS 121 19 / 1

Page 32: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Assignment

I The right-hand side can be an expression.I The expression will be evaluated first and then stored in the

variable.radius = 10;radius = radius * 2; // double the radius

I What is the new value of radius?

20

Chapter 2: Data and Expressions CS 121 19 / 1

Page 33: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Assignment

I The right-hand side can be an expression.I The expression will be evaluated first and then stored in the

variable.radius = 10;radius = radius * 2; // double the radius

I What is the new value of radius? 20

Chapter 2: Data and Expressions CS 121 19 / 1

Page 34: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Constants

I A constant is an identifier (similar to a variable) that holds thesame value during its entire existence.

I It is constant, not variable.I The compiler will issue an error if you try to change the value

of a constant.I In Java, we use the final modifier to declare a constant.I We typically use all caps to name constants.

final int MAX_RADIUS = 1000;

Chapter 2: Data and Expressions CS 121 20 / 1

Page 35: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Why do we need constants?

I Readability – give meaning to arbitrary literals.I Program maintenance – only need to change value once.I Program protection – establishes that a value should not

change; less chance for error.

Chapter 2: Data and Expressions CS 121 21 / 1

Page 36: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Exercises

I EX 2.2, EX 2.4, PP 2.1

Chapter 2: Data and Expressions CS 121 22 / 1

Page 37: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Part 2: Expressions and Scanner

I ExpressionsI Data conversionsI The Scanner class for interactive programs

Go to index.

Chapter 2: Data and Expressions CS 121 23 / 1

Page 38: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Expressions

I An expression is a combination of one or more operators andoperands.

I We focus on arithmetic expressions that produce numericresults.

Chapter 2: Data and Expressions CS 121 24 / 1

Page 39: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Arithmetic Expressions

I Arithmetic expressions use the arithmetic operators.

Addition +Subtraction -Multiplication *Division /Remainder (modulo) %

Chapter 2: Data and Expressions CS 121 25 / 1

Page 40: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Arithmetic Expressions and Data Types

I If any one of the operands used by an arithmetic operator arefloating point (float or double), then the result will be afloating point.

I For example:int radius = 10;final double PI = 3.14159265358979323;double area = PI * radius * radius;

I If both operands used by an arithmetic operator are floatingpoint, then the result will be a floating point.

I 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 26 / 1

Page 41: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Division and Data Types

I If both operands of the division operator are integers, then theresult will be an integer.

I This means we lose the fractional part of the result.I For example, let’s assume we want to divide a wall into equal

sections.int length = 15;int sections = 2;float newLength = length / sections;

I Let’s try this.

I How can we fix it?I Data conversion – we’ll get to this soon.

Chapter 2: Data and Expressions CS 121 27 / 1

Page 42: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Division and Data Types

I If both operands of the division operator are integers, then theresult will be an integer.

I This means we lose the fractional part of the result.I For example, let’s assume we want to divide a wall into equal

sections.int length = 15;int sections = 2;float newLength = length / sections;

I Let’s try this.I How can we fix it?

I Data conversion – we’ll get to this soon.

Chapter 2: Data and Expressions CS 121 27 / 1

Page 43: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Division and Data Types

I If both operands of the division operator are integers, then theresult will be an integer.

I This means we lose the fractional part of the result.I For example, let’s assume we want to divide a wall into equal

sections.int length = 15;int sections = 2;float newLength = length / sections;

I Let’s try this.I How can we fix it?I Data conversion – we’ll get to this soon.

Chapter 2: Data and Expressions CS 121 27 / 1

Page 44: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Remainder Operator (modulo)

I Given two positive numbers, a (the dividend) and b (thedivisor), a % n (a mod n) is the remainder of the Euclideandivision of a by n.

14 / 3 == 4 14 % 3 == 2

8 / 12 == 0 8 % 12 == 810 / 2 == 5 10 % 2 == 07 / 6 == 1 7 % 6 == 19 / 0 == error 9 % 0 == error

Chapter 2: Data and Expressions CS 121 28 / 1

Page 45: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Remainder Operator (modulo)

I Given two positive numbers, a (the dividend) and b (thedivisor), a % n (a mod n) is the remainder of the Euclideandivision of a by n.

14 / 3 == 4 14 % 3 == 28 / 12 == 0 8 % 12 == 8

10 / 2 == 5 10 % 2 == 07 / 6 == 1 7 % 6 == 19 / 0 == error 9 % 0 == error

Chapter 2: Data and Expressions CS 121 28 / 1

Page 46: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Remainder Operator (modulo)

I Given two positive numbers, a (the dividend) and b (thedivisor), a % n (a mod n) is the remainder of the Euclideandivision of a by n.

14 / 3 == 4 14 % 3 == 28 / 12 == 0 8 % 12 == 810 / 2 ==

5 10 % 2 == 07 / 6 == 1 7 % 6 == 19 / 0 == error 9 % 0 == error

Chapter 2: Data and Expressions CS 121 28 / 1

Page 47: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Remainder Operator (modulo)

I Given two positive numbers, a (the dividend) and b (thedivisor), a % n (a mod n) is the remainder of the Euclideandivision of a by n.

14 / 3 == 4 14 % 3 == 28 / 12 == 0 8 % 12 == 810 / 2 == 5 10 % 2 ==

07 / 6 == 1 7 % 6 == 19 / 0 == error 9 % 0 == error

Chapter 2: Data and Expressions CS 121 28 / 1

Page 48: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Remainder Operator (modulo)

I Given two positive numbers, a (the dividend) and b (thedivisor), a % n (a mod n) is the remainder of the Euclideandivision of a by n.

14 / 3 == 4 14 % 3 == 28 / 12 == 0 8 % 12 == 810 / 2 == 5 10 % 2 == 07 / 6 ==

1 7 % 6 == 19 / 0 == error 9 % 0 == error

Chapter 2: Data and Expressions CS 121 28 / 1

Page 49: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Remainder Operator (modulo)

I Given two positive numbers, a (the dividend) and b (thedivisor), a % n (a mod n) is the remainder of the Euclideandivision of a by n.

14 / 3 == 4 14 % 3 == 28 / 12 == 0 8 % 12 == 810 / 2 == 5 10 % 2 == 07 / 6 == 1 7 % 6 ==

19 / 0 == error 9 % 0 == error

Chapter 2: Data and Expressions CS 121 28 / 1

Page 50: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Remainder Operator (modulo)

I Given two positive numbers, a (the dividend) and b (thedivisor), a % n (a mod n) is the remainder of the Euclideandivision of a by n.

14 / 3 == 4 14 % 3 == 28 / 12 == 0 8 % 12 == 810 / 2 == 5 10 % 2 == 07 / 6 == 1 7 % 6 == 19 / 0 ==

error 9 % 0 == error

Chapter 2: Data and Expressions CS 121 28 / 1

Page 51: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Remainder Operator (modulo)

I Given two positive numbers, a (the dividend) and b (thedivisor), a % n (a mod n) is the remainder of the Euclideandivision of a by n.

14 / 3 == 4 14 % 3 == 28 / 12 == 0 8 % 12 == 810 / 2 == 5 10 % 2 == 07 / 6 == 1 7 % 6 == 19 / 0 == error 9 % 0 ==

error

Chapter 2: Data and Expressions CS 121 28 / 1

Page 52: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Remainder Operator (modulo)

I Given two positive numbers, a (the dividend) and b (thedivisor), a % n (a mod n) is the remainder of the Euclideandivision of a by n.

14 / 3 == 4 14 % 3 == 28 / 12 == 0 8 % 12 == 810 / 2 == 5 10 % 2 == 07 / 6 == 1 7 % 6 == 19 / 0 == error 9 % 0 == error

Chapter 2: Data and Expressions CS 121 28 / 1

Page 53: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Remainder Operator (modulo)

I Typically used to determine if a number is odd or even.I How?

Chapter 2: Data and Expressions CS 121 29 / 1

Page 54: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Operator Precedence (Order of Operations)

I Just like in math, operators can be combined into complexexpressions.

result = total + count / max - offset;

I Operators have well-defined precedence to determine order ofevaluation.result = total + count / max - offset;

4 2 1 3

Chapter 2: Data and Expressions CS 121 30 / 1

Page 55: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Operator Precedence (Order of Operations)

I Just like in math, operators can be combined into complexexpressions.

result = total + count / max - offset;I Operators have well-defined precedence to determine order of

evaluation.result = total + count / max - offset;

4 2 1 3

Chapter 2: Data and Expressions CS 121 30 / 1

Page 56: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Operator Precedence

Precedence Operator Operation Association0 () parenthesis1 + unary plus R to L

- unary minus2 * multiplication L to R

/ division% modulo

3 + addition L to R- subtraction+ string concatenation

4 = assignment R to L

Chapter 2: Data and Expressions CS 121 31 / 1

Page 57: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

In-Class Exercise

I 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 32 / 1

Page 58: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

In-Class Exercise

I Determine the order of evaluation in the following expressions.

1) a + b + c + d + e

1 2 3 4

2) a + b * c - d / e3 1 4 2

3) a / (b + c) - d % e2 1 4 3

4) a / (b * (c + (d - e)))4 3 2 1

Chapter 2: Data and Expressions CS 121 33 / 1

Page 59: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

In-Class Exercise

I Determine the order of evaluation in the following expressions.

1) a + b + c + d + e1 2 3 4

2) a + b * c - d / e3 1 4 2

3) a / (b + c) - d % e2 1 4 3

4) a / (b * (c + (d - e)))4 3 2 1

Chapter 2: Data and Expressions CS 121 33 / 1

Page 60: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

In-Class Exercise

I Determine the order of evaluation in the following expressions.

1) a + b + c + d + e1 2 3 4

2) a + b * c - d / e

3 1 4 2

3) a / (b + c) - d % e2 1 4 3

4) a / (b * (c + (d - e)))4 3 2 1

Chapter 2: Data and Expressions CS 121 33 / 1

Page 61: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

In-Class Exercise

I Determine the order of evaluation in the following expressions.

1) a + b + c + d + e1 2 3 4

2) a + b * c - d / e3 1 4 2

3) a / (b + c) - d % e2 1 4 3

4) a / (b * (c + (d - e)))4 3 2 1

Chapter 2: Data and Expressions CS 121 33 / 1

Page 62: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

In-Class Exercise

I Determine the order of evaluation in the following expressions.

1) a + b + c + d + e1 2 3 4

2) a + b * c - d / e3 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 33 / 1

Page 63: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

In-Class Exercise

I Determine the order of evaluation in the following expressions.

1) a + b + c + d + e1 2 3 4

2) a + b * c - d / e3 1 4 2

3) a / (b + c) - d % e2 1 4 3

4) a / (b * (c + (d - e)))4 3 2 1

Chapter 2: Data and Expressions CS 121 33 / 1

Page 64: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

In-Class Exercise

I Determine the order of evaluation in the following expressions.

1) a + b + c + d + e1 2 3 4

2) a + b * c - d / e3 1 4 2

3) a / (b + c) - d % e2 1 4 3

4) a / (b * (c + (d - e)))

4 3 2 1

Chapter 2: Data and Expressions CS 121 33 / 1

Page 65: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

In-Class Exercise

I Determine the order of evaluation in the following expressions.

1) a + b + c + d + e1 2 3 4

2) a + b * c - d / e3 1 4 2

3) a / (b + c) - d % e2 1 4 3

4) a / (b * (c + (d - e)))4 3 2 1

Chapter 2: Data and Expressions CS 121 33 / 1

Page 66: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Expression Trees

I Evaluation order of an expression can also be shown using anexpression tree.

I The operators lower in the tree have higher precedence forthat expression.

I a + (b - c) / d +

a /

-

b c

d

Chapter 2: Data and Expressions CS 121 34 / 1

Page 67: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Assignment Operator

I The assignment operator has the lowest operator precedence.I The entire right-hand side expression is evaluated first, then

the result is stored in the original variable.I It is common for the right hand side and left hand sides of an

assignment statement to contain the same variable.I count = count + 1;

Chapter 2: Data and Expressions CS 121 35 / 1

Page 68: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Increment and Decrement Operators

I The increment operator (++) adds one to its operand.I The following statements produce the same result.count++;count = count + 1;

I The decrement operator (--) subtracts one from its operand.I The following statements produce the same result.count--;count = count - 1;

Chapter 2: Data and Expressions CS 121 36 / 1

Page 69: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Postfix vs. Prefix

I The increment and decrement operators can be applied inpostfix form

count++; count--;or prefix form

++count; --count;I When used as part of a larger expression, the two can have

different effects.I Use with care!!

Chapter 2: Data and Expressions CS 121 37 / 1

Page 70: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Assignment Operators

I Java provides assignment operators to simplify expressionswhere we perform an operation on an expression then store theresult back into that variable.

I Consider the following expression.num = num + count;

I We can simplify this using the addition assignment operator.num += count;

I Java provides the following assignment operators.I += (string concat or addition), -=, *=, /=, %=

Chapter 2: Data and Expressions CS 121 38 / 1

Page 71: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Data Conversion

I Sometimes we need to convert from one data type to another(e.g. float to int).

I These conversions do not change the type of a variable, theyjust convert it temporarily as part of a computation.

I Widening conversions. Safest. Go from small data type tolarge one.

I e.g. short to int, int to doubleI Narrowing conversions. Not so safe. Go from large data type

to smaller one. Must be used carefully.I e.g. int to short, double to int

Chapter 2: Data and Expressions CS 121 39 / 1

Page 72: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Data Conversions

I Assignment conversion.I Promotion.I Casting.

Chapter 2: Data and Expressions CS 121 40 / 1

Page 73: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Assignment Conversion

I Assignment conversion occurs when one type is assigned to avariable of another.

I Only widening conversions can happen via assignment.I For example:

float totalCost;int dollars;totalCost = dollars;

I The value stored in dollars is converted to a float before itis assigned to the totalCost variable.

I The dollars variable and the value stored in it are still intafter the assignement.

Chapter 2: Data and Expressions CS 121 41 / 1

Page 74: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Promotion

I Promotion happens automatically when operators inexpressions convert their operands.

I For example:float sum;int count;double result = sum / count;

I The value of count is converted to a float before the divisionoccurs.

I Note that a widening conversion also occurs when the result isassigned to result.

Chapter 2: Data and Expressions CS 121 42 / 1

Page 75: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Casting

I Casting is the most powerful and potentially dangerousconversion technique.

I Explictly perform narrowing and widening conversions.I Recall our example from earlier:

int length = 15, sections = 2;float newLength = length / sections;

I Recall: If both operands of the division operator are integers,then the result will be an integer. If either or both operandsused by an arithmetic operator are floating point, then theresult will be a floating point.

I By casting one of the operands (length in this case), we getthe desired result

float newLength = ((float) length) / sections;

Chapter 2: Data and Expressions CS 121 43 / 1

Page 76: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Casting

I Casting is the most powerful and potentially dangerousconversion technique.

I Explictly perform narrowing and widening conversions.I Recall our example from earlier:

int length = 15, sections = 2;float newLength = length / sections;

I Recall: If both operands of the division operator are integers,then the result will be an integer. If either or both operandsused by an arithmetic operator are floating point, then theresult will be a floating point.

I By casting one of the operands (length in this case), we getthe desired result

float newLength = ((float) length) / sections;

Chapter 2: Data and Expressions CS 121 43 / 1

Page 77: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Casting

I Casting is the most powerful and potentially dangerousconversion technique.

I Explictly perform narrowing and widening conversions.I Recall our example from earlier:

int length = 15, sections = 2;float newLength = length / sections;

I Recall: If both operands of the division operator are integers,then the result will be an integer. If either or both operandsused by an arithmetic operator are floating point, then theresult will be a floating point.

I By casting one of the operands (length in this case), we getthe desired result

float newLength = ((float) length) / sections;

Chapter 2: Data and Expressions CS 121 43 / 1

Page 78: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

In-Class ExerciseWill the following program produce an accurate conversion (why orwhy not)?

1 /**2 * Computes the Fahrenheit equivalent of a specific Celsius value using3 * the formula:4 * F = (9/5) * C + 32.5 */6 public class TempConverter7 {8 public static void main (String[] args)9 {10 final int BASE = 32;1112 double fahrenheitTemp;13 int celsiusTemp = 24; // value to convert1415 fahrenheitTemp = celsiusTemp * 9 / 5 + BASE;1617 System.out.println ("Celsius Temperature: " + celsiusTemp);18 System.out.println ("Fahrenheit Equivalent: " + fahrenheitTemp);19 }20 }

1. Yes.2. Sometimes.3. Nope.4. I have no idea.

Chapter 2: Data and Expressions CS 121 44 / 1

Page 79: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

The Scanner class

I Typically, we want our programs to interact with our users.I The Scanner class is part of the java.util class library. It

must be imported.I It provides methods for reading input values of various types.I A Scanner object can read input from various sources (e.g.

keyboard, file)I See Java 8 API docs: http://docs.oracle.com/javase/8/

docs/api/java/util/Scanner.html

Chapter 2: Data and Expressions CS 121 45 / 1

Page 80: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Using the Scanner

I Create a new Scanner object that reads from the keyboard.Scanner scan = new Scanner(System.in);

I The new operator creates a new Scanner object.I The System.in object represents keyboard input.I After the object is created, we can invoke various input

methods it provides.

Chapter 2: Data and Expressions CS 121 46 / 1

Page 81: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Example

I Example: Convert TempConverter.java to interactiveprogram.

I Example: Echo.java

Chapter 2: Data and Expressions CS 121 47 / 1

Page 82: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Input Tokens

I By default, white space is used to seprate input elemets (calledtokens).

I White space includesI Space characters (‘ ’)I Tab characters (‘\t’)I New line characters (‘\n’ and ‘\r’)

I The next, nextInt, nextDouble, etc. methods of theScanner class read and return the next input tokens.

I See Scanner documentation for more details.

Chapter 2: Data and Expressions CS 121 48 / 1

Page 83: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Example

I Example: GasMileage.java

Chapter 2: Data and Expressions CS 121 49 / 1

Page 84: Chapter 2: Data and Expressions - CS 121 - Boise …cs.boisestate.edu/.../125/handouts/02-ch2-data-and-expressions.pdf · I Booleanvalues(true/false) I boolean Chapter 2: ... 4 2

Exercises

I Read Chapter 3 of textbook.

Chapter 2: Data and Expressions CS 121 50 / 1