Working With Base Types (or built-in types) not objects or references
Download
Report
Transcript Working With Base Types (or built-in types) not objects or references
EXPRESSIONS AND ARITHMETIC
• Working With Base Types (or built-in types)
– not objects or references: Java has special syntax
to deal with them
– easy to learn and work with!
• Arithmetic
– integers
– fractional numbers
– arithmetic operations
• Constants
Arithmetic
1 of 21
© 2006 Pearson Education
Number Crunching (chomp, chomp)
• Why do we have to learn about arithmetic?
We’ve done fine without it so far...
• Numbers are very useful
– do obvious things that involve arithmetic such as
allowing user to keep electronic checkbook or use
ATM
– keep track of what’s going on inside program
(e.g., loop counters — stay tuned)
– drive peripherals, like graphic displays and
printers
• We use integers to position and size shapes
on screen. Entire screen or any subscreen
defines bounded coordinate system that is a
Cartesian plane.
(0, 0)
(MAX_X, 0)
(0, MAX_Y)
(MAX_X, MAX_Y)
Arithmetic
2 of 21
© 2006 Pearson Education
Numbers in Java
• Before we learn about arithmetic, we need to
learn about numbers in Java
• Until now, our variables have only been
references to objects
• Now we learn to use primitive data types
predefined by Java, called base types
• There are six different numerical base types:
–
–
–
–
–
–
bytes
shorts
ints
longs
floats
doubles
Arithmetic
3 of 21
© 2006 Pearson Education
Integers
• An integer is any whole number, negative or
positive, including 0
• In Java we can have integers of different
sizes
– bytes (8 bits) can store values from -128 to 127
(-27 to 27 - 1)
– shorts (16 bits) can store values from -32,768 to
32,767 ( -215 to 215 - 1)
– ints (32 bits) can store values from 2,147,483,648 to 2,147,483,647 (-231 to 231 - 1)
– longs (64 bits) can store values -9,223,372,...808
to 9,223,372,...807 (-263 to 263 -1)
• When using integers, we usually use ints
Arithmetic
4 of 21
© 2006 Pearson Education
Declaring Base Types
• Java recognizes int and other numbers as
“base types,” but they are not objects or
references!
• Base types do not have constructors,
instance variables, or methods
– hence, we do not “new” them, we just assign
values to them!
– example on next slide
• But they are declared just like other
variables:
public class HockeyPlayer{
private int _numTeeth;
}
• all types in procedural languages are base
types
Arithmetic
5 of 21
© 2006 Pearson Education
Integer Assignment
• Integer variables can be used in arithmetic
expressions, sent as parameters, and
assigned values, just like other variables
• References to objects are assigned a default
value of null; integers are assigned a
default value of 0
• However, it is good coding style to assign a
value to everything before using it
– we write code for _numTeeth, assigning it an
initial value:
public class HockeyPlayer {
private int _numTeeth;
public HockeyPlayer() {
_numTeeth = 8;
}
public void playHockey() {
// we can reassign it!
_numTeeth = 4;
}
}
• = means “gets” just like it does when
assigning references to variables
Arithmetic
6 of 21
© 2006 Pearson Education
Arithmetic Operators
Operator
Meaning
*
multiplication
/
division
%
+
mod (remainder of integer div.)
addition
-
subtraction
• For integers, division truncates (rounds)
toward zero
• Arithmetic expressions can be constants,
numeric variables, functions, two subexpressions joined by an operator, or
expressions surrounded in parentheses
• Examples
–
–
–
–
(((10.4))) evaluates to 10.4
7 % 5 evaluates to 2
9 / 2 evaluates to 4
numOne + numOne evaluates to twice the value
of numOne (assuming numOne is a numeric
variable type)
– 2 (3 + 4) is not a valid expression — why?
Arithmetic
7 of 21
© 2006 Pearson Education
More Operators
• To change sign, use - operator on single
expression
val = -val; // negates val
• Since = represents assignment, not
statement of equality, can operate on and
assign to same variable
– e.g., a = a + 5;
• We can also do this using shorthand <op>=
a
a
a
a
a
+=
-=
*=
/=
%=
5;
5;
5;
5;
5;
a
a
a
a
a
=
=
=
=
=
a
a
a
a
a
+
*
/
%
5;
5;
5;
5;
5;
• Even more shorthand!
a++;
a--;
Arithmetic
a = a + 1;
a = a - 1;
8 of 21
© 2006 Pearson Education
Variable Increment operators
• Variable increment operators:
– i++ use i, then add 1 to it
– ++i add 1 to i, then use it
• What does order mean?
– first case, prefix: increment variable, then use
int i = 10;
int j = ++i; // j is 11, so is i
– second case, postfix: use, then increment variable
int i = 10;
int j = i++; // j is 10, i becomes 11
– same for decrement operators
Arithmetic
9 of 21
© 2006 Pearson Education
Evaluation: Follow Rules from 9th
Grade Algebra
• Three rules for evaluation
– evaluation takes place from left to right, except
that
– expressions in parentheses are evaluated first,
starting at the innermost level, and
– operators are evaluated in order of precedence
*, /, and % have precedence over + and • Sample expressions:
2
2 * 3
2 + 4 * 3 - 7
4 / 2
10 % 3
(2 + 3) * (11 / 12)
(6 + 4) * 3 + (2 - (6 / 3))
0 % 9
9 % 9
Arithmetic
10 of 21
© 2006 Pearson Education
Fractional Numbers
• What if we want to represent fractional
numbers?
• In Java we can use floats (floating point)
or doubles (double precision floating point)
– floating point refers to where the decimal point is
assumed to be – internal implementation detail
– use doubles for scientific computation because
they have larger range
• We declare and assign these in same way
r
Arithmetic
double myRadius = 2.427;
11 of 21
© 2006 Pearson Education
Mixing Integers and Fractional #s
• Can use different types of numbers together,
but be careful!
• Can go from less to more precise, not the
other way around!
– Java will not let you lose precision implicitly
public class MyMathClass {
public void reassign() {
int myInt = 4;
double myDouble = 2.64;
myInt = myDouble;
// can’t assign a double to an int
}
}
• Change above assignment to:
myDouble = myInt;
• We can force Java to convert double to int
– called casting or coercion
– loss of precision
myInt = (int) myDouble; // myInt is now 2
Arithmetic
12 of 21
© 2006 Pearson Education
Digression: static Class Variables
• Each instance of a class has different copies
of instance variables. What if we want entire
class to have same value for variable?
• Can use reserved word static to make
class variables, of which there is only one
copy for entire class.
• Each time any method of any instance
changes the value of a static variable, all
instances have access to that new value.
public class ContrivedExample {
private static int _numberOfInstances;
public ContrivedExample() {
// we want to keep a tally of all the
// ContrivedExamples that we create
_numberOfInstances++;
}
// now every instance of ContrivedExample
// can access _numberOfInstances to see how
// many contrived examples have been
// created
}
Arithmetic
13 of 21
© 2006 Pearson Education
Constants (1 of 2)
• Constants are used to represent values which
never change in a program (like Planck’s
constant, speed of light, etc.)
– we’ve seen constants before: the red, blue,
green, etc., values of the java.awt.Color class
• They should be:
– static, so there is exactly one value for entire
class
– final, so their values can’t be changed
– and probably public, so they are widely available
public class Physics {
// Speed of Light
// (hundred-million meters per second)
public static final double LIGHT_SPEED =
2.998;
public double getDistanceTraveled(
double numSeconds) {
// distance = velocity * time
return (LIGHT_SPEED * numSeconds);
}
}
• Note: our convention is to capitalize constants
and put underscores between words
Arithmetic
14 of 21
© 2006 Pearson Education
Constants (2 of 2)
• If a new value for LIGHT_SPEED is
discovered, we can change our entire program
very easily, by changing the value of our
constant and recompiling
– extendable to different universes
• Constants never change after declaration
– <constant> = <expr> in a method won’t work
• Constants have descriptive names; literal
numbers (such as 42) don’t
– LIGHT_SPEED is called a symbolic constant
– 42 is called a literal constant
• 42 is also a literary constant
– (in Memoriam, Douglas Adams)
• Always use constants when possible — literal
numbers should never (well, hardly ever)
appear in programs. 0, 1 are common
exceptions
– makes your program easier to change
– makes your code easier to read
Arithmetic
15 of 21
© 2006 Pearson Education
Using Interfaces with Constants
• So far we have only used interfaces to
declare methods — we can also use them to
declare constants
• What if many classes use same constants?
• Can put constants in an interface and have
classes implement it!
– then public, static, and final are implicit
public interface PhysicsConstants {
// speed of light (hundred-million meters
// per second
double LIGHT_SPEED = 2.998;
// more constants, if we want . . .
}
• Now all classes that implement the
PhysicsConstants interface have access
to LIGHT_SPEED
Arithmetic
16 of 21
© 2006 Pearson Education
A Fun Example: Flying Cow (1 of 2)
• We want to model a cow that can fly, but only
if the moon is full and if the cow is under a
certain weight
• When cow grazes, its weight changes. We
need to calculate its new mass after grazing.
But how?
• First, we’ll need some constants to help us.
public interface CowConstants {
// initial weight of cow in pounds
double COW_START_WEIGHT = 587.45;
// weight of one blade of grass in pounds
double BLADE_WEIGHT = 0.0118;
// cow must be under this weight to fly
double MAX_FLYING_WEIGHT = 603.76;
}
Arithmetic
17 of 21
© 2006 Pearson Education
Flying Cow (2 of 2)
• Now we can have our cow calculate its weight
• Since cow doesn’t gain full weight of grass, we
need equation to determine how much weight
cow gains after grazing
• Let’s say cow will gain 5 times square root of
grass’ weight:
public class Cow extends FarmAnimal
implements CowConstants {
private double _weight;
/**
* This method changes the cow’s weight
* based on how many blades of grass it ate.
*/
public void eatGrass(int numBlades) {
double grassWeight = numBlades *
BLADE_WEIGHT;
// Uh-oh... how to calculate square root?
}
}
Arithmetic
18 of 21
© 2006 Pearson Education
Java Math Class
• We can use Math class which is predefined
by Java!
• Provides all kinds of cool methods
Math.sin(x);
Math.cos(x);
Math.tan(x);
Math.pow(x,y); — raises x to the power of y
Math.log(x);
Math.sqrt(x); — square root of x
... and more!
• Math also defines two symbolic constants:
E = 2.71...
PI = 3.14...
• Why can we call methods on Math without
instantiating it?
• Because its methods are static!
Arithmetic
19 of 21
© 2006 Pearson Education
static Class Methods
• static methods, or class methods, are
invoked on behalf of entire class, not on
specific instance of class – no instance
variables needed (nor are you allowed to
access any)!
• In Math class, methods are declared:
public static double sin(double a) {
...
}
• When calling static method, don’t have to
instantiate class, just send message to class
_side = Math.sin(x);
• This is just so you know, you’ll never need to
write a static method in this course, although
you will use Math in future assignments.
Arithmetic
20 of 21
© 2006 Pearson Education
eatGrass
• Now we can finish writing eatGrass
method:
public void eatGrass(int numBlades) {
double grassWeight = numBlades *
BLADE_WEIGHT;
_weight += 5 * Math.sqrt(grassWeight);
}
• But how do we know if flying conditions are
met?
Arithmetic
21 of 21
© 2006 Pearson Education