CSE 501N
Fall ’09
02: Fundamental Types & Expressions
1 September 2009
Nicholas Leidenfrost
Lecture Outline

Review of Lecture 01

Fundamental Data Types
 Primitives
 Arithmetic Operators
 Expressions



Data Conversion
The “String” Object
Quiz #0
2
Review
Language Evolution

Binary
 11010111000101001101010111000001010

Assembly
 ADD AX
BX
 MOV AX CX
High-Level
Languages
Procedural Languages (C, etc.)
 Object Oriented (C++, Java)
 OO Languages borrow Heavily from
Procedural Languages

3
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
4
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
5
Review
Basic Structure of a Java Program
/*
Person.java
Nick Leidenfrost
Example program
*/
public class Person {
Finally, we will
learn about
class and
object
Then,
we will focus
interaction.
on methods and their
interaction
(procedural
programming)
Initially, we will
// this method starts my program
focus on
public static void main (String[] args)
{
statements
//
statements to be executed here...
}
}
6
Statements


A statement is the smallest standalone unit of
code inside of a program
Statements are composed of:
 Variables
(& Constants)
 Expressions
 Method calls, etc.

int foo;
foo = bar + baz;
Statements can also allow us to do things:
 Conditionally
(Conditional Statements)
 Repeatedly (Loops)

Most statements are terminated by a semicolon:
‘;’
7
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:
variable name
data type
int total;
int count, temp, result;
Multiple variables of the same type can be created
in one declaration (separated by commas)
8
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

char
 And

of them represents characters:
one of them represents boolean values:
boolean
9
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
10
Discrete Numbers
Integer 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 1
00000010 is 2
00000011 is 3
…
01111111 is 127
10000000 is -128
10000001 is -1
…
11
Numeric Primitive Data
Integer 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
32 bits in a float
Sign bit

Exponent
Significand
Performance is a chief reason why we differentiate
between discrete (whole) numbers and numbers with
fractional components (real numbers)
12
Numeric Primitive Data
Type
Bytes
Min Value
Max Value
Discrete
The difference between the various numeric primitive
types is their size, and therefore the values they can
store:
byte
short
int
long
1 (8 bits)
2 (16 bits)
4 (32 bits)
8 (64 bits)
-128
-32,768
-2,147,483,648
< -9 x 1018
127
32,767
2,147,483,647
> 9 x 1018
Real

float
double
4 (32 bits) +/- 3.4 x 1038 with 7 significant digits
8 (64 bits) +/- 1.7 x 10308 with 15 significant digits
13
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
14
Identifiers
Rules

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
$$$
$$$
15
Identifiers
Style 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!
16
Identifiers
Style 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
17
Identifiers
Off-Limits: Reserved Words
abstract
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
enum
extends
false
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
true
try
void
volatile
while
18
Constant Variables
Invariable 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
final int MIN_HEIGHT = 100;

Traditionally, constant variables are named with all capital letters,
19
with underscores as word-breaks
Constant Variables
Invariable Variables

Constant variables are useful for three important reasons

First, they give meaning to otherwise unclear literal
values (Self-commenting code)


Second, they facilitate program maintenance


For example, MIN_HEIGHT means more than the literal
100
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
20
Constant Values

Since this is part of a
common formula, and
is a single use, there’s
to no
use
hard-coded
need
to define a
constant variable
Sometimes it is necessary
values in our statements, called constants:
This presents an very
double circumference = 2.0*pi*radius;
subtle problem that
will look at in a
 Constant values have types we
too:
few slides.
 Whole
numbers are assumed to be ints:
double ratio = 2/3;
 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 radius = 10.0d;
float length = 4.5f;
21
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)
+
*
%
22
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
23
Division and Remainder


If both operands to the division operator (/) are
integers, the result is an integer (the fractional part is
discarded)
14 / 3
equals
4
8 / 12
equals
0
The remainder operator, or modulus (%) returns the
remainder after dividing the second operand into the
first
14 % 3
equals
2
8 % 12
equals
8
24
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
25
Operator Precedence

What is the order of evaluation in the following
expressions?
a + b + c + d + e
1
2
3
4
a + b * c - d / e
3
1
4
2
a / (b + c) - d % e
2
1
4
3
a / (b * (c + (d - e)))
4
3
2
1
26
The Assignment Operator: =

In Java, the following is not an equation:
count = count + 1;
Left-Hand Side
(variable)

Right-Hand Side
(expression)
The Assignment operator, ‘=‘ is used to
store the resulting value of a Right-hand
Side to the variable on the Left-hand Side
27
The Assignment Operator: =


An assignment statement changes the value of a
variable
The assignment operator is the = sign
total = 55;

The expression on the right is completely evaluated
and the result is stored in the variable on the left

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*
* This is a bit of a lie, but I’ll address it later…
28
Variable Initialization

A variable can be given an initial value in the
declaration
int sum = 0;
int base = 32, max = 149;

When a variable is referenced in a program,
its most current value is used
29
The Assignment Operator: =
= Operator Precedence

The assignment operator (=) has a lower
precedence than all arithmetic operators
answer
First the expression on the right hand
side of the = operator is evaluated
= sum / 4 + MAX * lowest;
4
1
3
2
Then the result is stored in the
variable on the left hand side
30
The Assignment Operator: =

The right and left hand sides of an assignment
statement can contain the same variable
First, one is added to the
original value of count
count
=
count + 1;
Then the result is stored back into count
(overwriting the original value)
31
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;
32
Assignment Operators

There are many assignment operators in
Java, including the following:
Operator
+=
-=
*=
/=
%=
Example
x
x
x
x
x
+=
-=
*=
/=
%=
y
y
y
y
y
Equivalent To
x
x
x
x
x
=
=
=
=
=
x
x
x
x
x
+
*
/
%
y
y
y
y
y
33
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);
34
Unary Operators
Increment 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;
35
Unary Operators
Increment 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
36
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
int count = 10;
float fraction = count;

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
38
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
39
Data Conversion
Assignment 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
40
Data Conversion
Promotion

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:
result = sum / count;

The resultant type of an expression is always the
widest type of the operands in the expression
41
Data Conversion
Casting

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;
42
The String Object
In Java, the String object represents a
series (or string) of characters
This is known
 String values are encapsulated
double
as aby
stringliteral, or a
quotes
string constant

 String

name = “Peter”;
Strings are Objects in Java
 Lots
of predefined functionality
43
The String Object
Concatenation

Strings can be “added” together like
primitives with the ‘+’ and ‘+=‘ operators
 This
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”
44
The String Object
Concatenation

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”
45
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
46
Descargar

CSE 501N Fall ‘06 02: Machine Overview + Fundamental …