CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

45
CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost

Transcript of CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

Page 1: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

CSE 501NFall ’0902: Fundamental Types & Expressions

1 September 2009

Nicholas Leidenfrost

Page 2: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

2

Lecture Outline Review of Lecture 01

Fundamental Data Types Primitives Arithmetic Operators Expressions Data Conversion

The “String” Object Quiz #0

Page 3: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

3

ReviewLanguage Evolution

Binary11010111000101001101010111000001010

AssemblyADD AX BXMOV AX CX

Procedural Languages (C, etc.) Object Oriented (C++, Java) OO Languages borrow Heavily from

Procedural Languages

High-Level Languages

Page 4: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

4

Review Object-Oriented Concepts

A class is blueprint for an object which defines: the attributes (state) the methods (behavior)

Classes often model real-world concepts E.g. Person, Student, Gameboard, Gamepiece, Player, etc.

An object is an example, or instance of a class Its internal state differentiates it from other objects of the same

class

Page 5: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

5

Review: Why OO?High-Level Software Concepts – Principle Benefits of OOP

Abstraction Hiding implementation details in order to develop

software at a “high level”

Encapsulation Restricting access to inner state of program modules

in order to increase scalability and reliability

Work hand in hand to help us develop dependable, maintainable large-scale applications

Page 6: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

6

Review Basic Structure of a Java Program

public class Person {

}

/* Person.java Nick Leidenfrost Example program*/

public static void main (String[] args) {

}

// this method starts my program

// statements to be executed here...

Initially, we will focus on

statements

Then, we will focus on methods and their

interaction (procedural

programming)

Finally, we will learn about

class and object interaction.

Page 7: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

7

Statements A statement is the smallest standalone unit of

code inside of a program Statements are composed of:

Variables (& Constants) Expressions Method calls, etc.

Statements can also allow us to do things: Conditionally (Conditional Statements) Repeatedly (Loops)

Most statements are terminated by a semicolon: ‘;’

int foo;

foo = bar + baz;

Page 8: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

8

Variables A variable is a human-readable name for a location in memory that stores a

value

A variable must be declared by specifying the variable's name and the type of information that it will hold:

int total;

int count, temp, result;

Multiple variables of the same type can be created in one declaration (separated by commas)

data type variable name

Page 9: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

9

Primitive Data(Also called Fundamental Data Types / Primitives)

There are eight primitive data types in Java

Four of them represent integers (whole numbers):

byte, short, int, long

Two of them represent floating point (real) numbers:

float, double

One of them represents characters:

char

And one of them represents boolean values:

boolean

Page 10: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

10

Booleans A boolean value represents a true or false condition

The reserved words true and false are the only valid values for a boolean type

boolean done = false;

A boolean variable can also be used to represent any two states, such as a light switch being on or off

Later, we will also use booleans to direct program flow

Page 11: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

11

Discrete NumbersInteger Primitives

We learned that the storage capacity of a data type is 2^n, where n is the number of bits in the data type

So for a byte (8 bits):2^8 = 256 Discrete values

In Binary: 00000001 is 100000010 is 200000011 is 3…01111111 is 12710000000 is -12810000001 is -1…

Page 12: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

12

Numeric Primitive DataInteger vs. Floating Point Data Types

How to store fractional components of numbers? Need a data type that can store both 81,000,000,000.5

and 0.000000000009 Floating point data Types

Pros: Flexible Cons: Can only measure rational numbers Cons: (relatively) Computationally Expensive

Performance is a chief reason why we differentiate between discrete (whole) numbers and numbers with fractional components (real numbers)

Sign bit Exponent Significand

32 bits in a float

Page 13: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

13

Numeric Primitive Data The difference between the various numeric primitive types is their

size, and therefore the values they can store:

Type

byteshortintlong

floatdouble

Bytes

1 (8 bits)2 (16 bits)4 (32 bits)8 (64 bits)

4 (32 bits)8 (64 bits)

Min Value

-128-32,768-2,147,483,648< -9 x 1018

+/- 3.4 x 1038 with 7 significant digits+/- 1.7 x 10308 with 15 significant digits

Max Value

12732,7672,147,483,647> 9 x 1018D

iscr

ete

Rea

l

Page 14: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

14

Characters A char variable stores a single character

Character literals are delimited by single quotes:

'a' 'X' '7' '$' ',' '\n'

Example declarations:

char topGrade = 'A';

char terminator = ';', separator = ' ';

Note a primitive character variable holds only one character.

We will use a String object to hold multiple characters

Page 15: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

15

IdentifiersRules

An identifier is a name that we choose for a variable, a method, or a class

An identifier can be made up of any combination of letters, digits, the underscore character ‘_’, and the dollar sign ‘$’ One exception: Identifiers cannot begin with a digit

Typically, in Java, ‘$’ is not used often, so avoid it in this class*

* Unless you’re T-Pain $$$ $$$

Page 16: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

16

IdentifiersStyle Guidelines: “Just because it’s legal don’t make it right.”

Typically, methods and variables are given identifiers beginning with lowercase letters, while identifiers for class names are uppercase

Most Java Programmers use a capitalization technique called “Camel-backing” or “Camel-case” to increase code readability:

int numclasses;

- Or -

int numClasses; // more readable

Most programming languages, including Java are case sensitive

int myCount = 17;

System.out.print(MyCount); // error!

Page 17: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

17

IdentifiersStyle Guidelines Identifiers are chosen by the programmer, so they can be almost anything

we want, but…

Identifiers should be as descriptive as possible

Emphasize clarity over brevity

int ph;

int phoneNumber; // More descriptive

This is known as “Self-Commenting Code”

Special identifiers called reserved words have a predefined meaning in the language

Reserved words cannot be used as identifiers

Page 18: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

18

IdentifiersOff-Limits: Reserved Words

abstractbooleanbreakbytecasecatchcharclassconstcontinuedefaultdodouble

elseenumextendsfalsefinalfinallyfloatforgotoifimplementsimportinstanceof

intinterfacelongnativenewnullpackageprivateprotectedpublicreturnshortstatic

strictfpsuperswitchsynchronizedthisthrowthrowstransienttruetryvoidvolatilewhile

Page 19: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

19

Constant VariablesInvariable Variables

A constant variable is an identifier that is similar to a variable except that it holds the same value during its entire existence

As the name implies, it is constant, not variable

The compiler will issue an error if you try to change the value of a constant variable after assignment

In Java, we use the final modifier in front of the type to declare a constant variable final indicates that the value assigned is the final value that

variable will have during its existence

Traditionally, constant variables are named with all capital letters, with underscores as word-breaks

final int MIN_HEIGHT = 100;

Page 20: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

20

Constant VariablesInvariable Variables

Constant variables are useful for three important reasons

First, they give meaning to otherwise unclear literal values (Self-commenting code)

For example, MIN_HEIGHT means more than the literal 100

Second, they facilitate program maintenance

If a constant variable is used in multiple places, its value need only be updated in one place

Third, they formally establish that a value is not arbitrary, avoiding inadvertent errors by other programmers

Page 21: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

21

Constant Values Sometimes it is necessary to use hard-coded

values in our statements, called constants:

Constant values have types too: Whole numbers are assumed to be ints:

Numbers with decimals are assumed to be doubles We can specify explicitly that a number is a float or double by specifying ‘f’ or ‘d’ after the numeric value

double circumference = 2.0*pi*radius;

double radius = 10.0d;float length = 4.5f;

double ratio = 2/3;

Since this is part of a common formula, and is a single use, there’s

no need to define a constant variable

This presents an very subtle problem that we will look at

in a few slides.

Page 22: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

22

Expressions An expression is a combination of one or more operators and operands

(variables, Right-hand values) Arithmetic expressions compute numeric results and make use of the

arithmetic operators:

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

Page 23: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

23

Adding, Subtracting, Multiplying

The +, -, and * operators all work as you expect them to.

However, some other operators can have unintended results, depending on the types of their operands.Specifically when integer types are used

Page 24: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

24

Division and Remainder If both operands to the division operator (/) are integers, the result is

an integer (the fractional part is discarded)

The remainder operator, or modulus (%) returns the remainder after dividing the second operand into the first

14 / 3 equals

8 / 12 equals

4

0

14 % 3 equals

8 % 12 equals

2

8

Page 25: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

25

Operator Precedence Operators can be combined into complex expressions

result = total + count / max - offset;

Operators have a well-defined precedence which determines the order in which they are evaluated

Multiplication, division, and modulus (remainder) are evaluated prior to addition, subtraction, and string concatenation

Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order

Page 26: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

26

Operator Precedence

What is the order of evaluation in the following expressions?

a + b + c + d + e1 432

a + b * c - d / e3 241

a / (b + c) - d % e2 341

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

Page 27: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

27

The Assignment Operator: =

In Java, the following is not an equation:

The Assignment operator, ‘=‘ is used to store the resulting value of a Right-hand Side to the variable on the Left-hand Side

count = count + 1;Right-Hand Side(expression)

Left-Hand Side(variable)

Page 28: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

28

The Assignment Operator: = An assignment statement changes the value of a variable The assignment operator is the = sign

total = 55;

The value that was in total is overwritten

You can only assign a value to a variable that is consistent with the variable's declared type*

The expression on the right is completely evaluated and the result is stored in the variable on the left

* This is a bit of a lie, but I’ll address it later…

Page 29: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

29

Variable Initialization A variable can be given an initial value in the declaration

When a variable is referenced in a program, its most current value is used

int sum = 0;int base = 32, max = 149;

Page 30: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

30

The Assignment Operator: == Operator Precedence

The assignment operator (=) has a lower precedence than all arithmetic operators

First the expression on the right handside of the = operator is evaluated

Then the result is stored in thevariable on the left hand side

answer = sum / 4 + MAX * lowest;

14 3 2

Page 31: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

31

The Assignment Operator: =

The right and left hand sides of an assignment statement can contain the same variable

First, one is added to theoriginal value of count

Then the result is stored back into count(overwriting the original value)

count = count + 1;

Page 32: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

32

Assignment Operators Often we perform an operation on a variable, and

then store the result back into that variable

Java provides assignment operators to simplify that process and shorten the expression

For example, the statement

num += count;

is equivalent to

num = num + count;

Page 33: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

33

Assignment Operators

There are many assignment operators in Java, including the following:

Operator

+=-=*=/=%=

Example

x += yx -= yx *= yx /= yx %= y

Equivalent To

x = x + yx = x - yx = x * yx = x / yx = x % y

Page 34: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

34

Assignment Operators

The right hand side of an assignment operator can be a complex expression

The entire right-hand expression is evaluated first, then the result is combined with the original variable

Therefore

result /= (total-MIN) % num;

is equivalent to

result = result / ((total-MIN) % num);

Page 35: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

35

Unary OperatorsIncrement and Decrement

The increment and decrement operators use only one operand

The increment operator (++) adds one to its operand

The decrement operator (--) subtracts one from its operand

The statement

count++;

is functionally equivalent to

count = count + 1;

Page 36: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

36

Unary OperatorsIncrement and Decrement

The increment and decrement operators have a higher precedence than other operators can be applied in postfix form:

count++

or prefix form:

++count

When used as part of a larger expression, the two forms can have different effects. Why does this happen?

Because of their subtleties, the increment and decrement operators should be used with care

Page 37: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

38

Data Conversion Sometimes it is convenient or necessary to convert

data from one type to another

For example, in a particular situation we may want to treat an integer as a floating point value

These conversions do not change the type of a variable or the value that's stored in it – they only convert the value it stores to the new type

int count = 10;float fraction = count;

Page 38: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

39

Data Conversion Conversions must be handled carefully to avoid losing

information Widening conversions are safest because they go from a

small data type to a larger one (such as a short to an int) Narrowing conversions can lose information because they

tend to go from a large data type to a smaller one (such as an int to a short)

In Java, data conversions can occur in three ways:

assignment conversion promotion casting

Page 39: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

40

Data ConversionAssignment Conversion

Assignment conversion occurs when a value of one type is assigned to a variable of another

If money is a float variable and dollars is an int variable, the following assignment converts the value in dollars to a float

float money;

int dollars;

money = dollars

Only widening conversions can happen via assignment

Note that the value or type of dollars did not change

Page 40: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

41

Data ConversionPromotion

Promotion happens automatically when operators in expressions convert their operands

For example, if sum is a float and count is an int, the value of count is converted to a floating point value to perform the following calculation:

The resultant type of an expression is always the widest type of the operands in the expression

result = sum / count;

Page 41: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

42

Data ConversionCasting Casting is the most powerful, and dangerous, technique for conversion

A way of telling Java to trust you and convert the type of the variable Java will trust you at compile time but may throw an error at runtime

Both widening and narrowing conversions can be accomplished by explicitly casting a value

Java will not allow a narrowing assignment without a cast

To cast, the desired type is put in parentheses in front of the value being converted

For example, if variables total and count are integers, but we want a floating point result when dividing them, we can cast total:

result = (float) total / count;

Page 42: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

43

The String Object

In Java, the String object represents a series (or string) of characters

String values are encapsulated by double quotesString name = “Peter”;

Strings are Objects in JavaLots of predefined functionality

This is known as a string-literal, or a

string constant

Page 43: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

44

The String ObjectConcatenation

Strings can be “added” together like primitives with the ‘+’ and ‘+=‘ operatorsThis is referred to as concatenation

String firstName = “George”;

String lastName = “Henrichs”;

String name = firstName + “ “ + lastName;

// “George Henrichs”

// ...Or

String lastFirst = lastName;

lastFirst += “, “ + firstName; // “Henrichs, George”

Page 44: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

45

The String ObjectConcatenation

Strings can be also concatenated with primitive types:

String name = “George”;

double examGrade = 89.7;

String output = name + “ received an “ + examGrade + “% on exam 1”;

// “George received an 89.7% on exam 1”

Page 45: CSE 501N Fall ’09 02: Fundamental Types & Expressions 1 September 2009 Nicholas Leidenfrost.

46

Conclusion

Questions about what we have covered today? Lab #0 due Thursday Quiz #0 Lab Session After Class

I’ll be there to help and answer questions