EXPRESSIONS AND ARITHMETIC

1 / 22

EXPRESSIONS AND ARITHMETIC - PowerPoint PPT Presentation

EXPRESSIONS AND ARITHMETIC. Working With Base (or Built-In) Types Arithmetic Constants. Number Crunching (crunch, crunch). Why do we have to learn about arithmetic? We’ve done fine without it so far... With numbers we can…

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

PowerPoint Slideshow about 'EXPRESSIONS AND ARITHMETIC' - lowri

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
EXPRESSIONS AND ARITHMETIC
• Working With Base (or Built-In) Types
• Arithmetic
• Constants
Number Crunching (crunch, crunch)
• Why do we have to learn about arithmetic?

We’ve done fine without it so far...

• With numbers we can…
• do obvious things that involve arithmetic such as allowing the user to keep an electronic check book or use an ATM
• keep track of what’s going on inside the program

(e.g. loop counters — stay tuned)

• drive peripherals, like graphic displays and printers
• We use integers to position and size shapes on screen. The entire screen or any subscreen defines a bounded coordinate system that is a Cartesian plane.

Imagine trying to measure something without numbers!

(0, 0)

(MAX_X, 0)

(0, MAX_Y)

(MAX_X, MAX_Y)

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:
• byte
• short
• int
• long
• float
• double
Integers
• An integer is a whole number, positive or negative, including 0
• In Java, we can have integers of different sizes
• byte (8 bits) can store values from

-128 to 127 (-27 to 27 - 1)

• short (16 bits) can store values from

-32,768 to 32,767 ( -215 to 215 - 1)

• int (32 bits) can store values from

-2,147,483,648 to 2,147,483,647

(-231 to 231 - 1)

• long (64 bits) can store values from

-9,223,372,...,808 to 9,223,372,...,807

(-263 to 263 -1)

• When using integers, we usually use int
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 non-object-oriented procedural languages are base types
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
• code using _numTeeth, declaring it and assigning it an initial value as with an instance

public class HockeyPlayer {

private int _numTeeth;

public HockeyPlayer() {

_numTeeth = 8;

}

public void playHockey() {

// we can reassign it!

_numTeeth = 4;

}

}

• = means “gets” just as it does when assigning references to variables
Arithmetic Operators

Operator Meaning

• For integers, division truncates (chops off the decimals, rounds down)
• Arithmetic expressions can be constants, numeric variables, functions (i.e., methods that return a value), two sub-expressions 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?

multiplication

division

remainder

*

/

%

+

-

subtraction

More Operators
• To change sign, use - operator on single expression

val = -val; // negates val

• Since = represents assignment, not a statement of equality, we can operate on and assign to the same variable
• e.g., a = a + 5;
• We can also do this using shorthand <op>=

a += 5; a = a + 5;

a -= 5; a = a - 5;

a *= 5; a = a * 5;

a /= 5; a = a / 5;

a %= 5; a = a % 5;

• Even more shorthand!

a++; a = a + 1; a += 1;

a--; a = a - 1; a -= 1;

Variable Increment Operators
• Variable increment operators:
• i++ usesi, then adds 1 to it (post-increment)
• ++i adds 1 to i, then uses it (pre-increment)
• What does order mean?
• first case, postfix: assign to j, then increment

variable

inti = 10;

int j = i++; // j is 10, i becomes 11

• second case, prefix: increment variable, then assign to j

inti = 10;

int j = ++i; // j is 11, so is i

• same for decrement operators
Evaluation: Follow Rules from High School 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

Fractional Numbers
• What if we want to represent fractional

numbers?

• In Java, we can use float (floating point) or double (double precision floating point)
• floating point refers to where the decimal

point is assumed to be (an internal implementation

detail you don’t have to worry about)

• use double for most computation because

they a have larger range and are more precise

• We declare and assign these the same way
• can declare and initialize in same statement

r

Mixing Integers and Fractional #s
• Can use different types of numbers together, but be careful!
• Can go from less to more precise, notthe other way around!
• Java will not let you lose precision implicitly

public class MyMathClass {

public void reassign() {

intmyInt = 4;

double myDouble = 2.64;

myInt = myDouble;

// can’t assign a double to an int

}

}

• You can change above assignment to:

myDouble = myInt;

// myDouble is now 4.0

• We can force Java to convert double to int
• called casting or coercion
• loss of precision

myInt = (int)myDouble; // myInt is now 2

Java Math Class
• 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 Math’s methods are static!
static Class Methods
• static methods, or class methods, are invoked on behalf of the entire class, not on a specific instance of the class – no instance variables needed (nor are you allowed to access any!)
• In the 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);

• You’ll never need to write a static method in CS15, although you will use Math in future assignments
static Class Variables
• Each instance of a class has different copies of instance variables. What if we want all instances of a class to have the same value for a variable?
• Use reserved word static to make all instances of a class use the same variable
• Each time any method of any instance changes the value of a static variable, all instances have access to that new value.

public class SimpleExample {

// We initialize outside of constructor

// because the variable is static

private staticint _numberOfInstances = 0;

public SimpleExample() {

// We want to keep a tally of all the

// SimpleExamples that we create

_numberOfInstances++;

}

public getNumInstances() {

return _numberOfInstances;

}

// Anyone can call getNumInstances to see

// how many SimpleExamples have been created

}

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

• Constants should be:
• static, so there is exactly one value for the 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;

// constructor elided

public double getDistanceTraveled(

double numSeconds) {

// distance = velocity * time

return (LIGHT_SPEED * numSeconds);

}

}

• Note: our convention is to capitalize constants and put underscores between words
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 compile
• this is because of the final keyword
• Constants have descriptive names; literal numbers (such as 42) don’t
• LIGHT_SPEED is called a symbolic constant
• 42is called a literal constant
• 42 is also a literary constant
• Always use constants whenpossible — literal numbersshould rarely appear in yourprograms (except 0,1)
• makes your program easier tomaintain and tweak
Using Constants in Multiple Classes
• What if many classes use the same constants?
• Can put constants in their own utility class

public abstract class PhysicsConstants {

// speed of light (hundred-million meters

// per second)

double static final LIGHT_SPEED = 2.998;

// more constants, if we want . . .

}

• To access this constant from another class just use the class name followed by the constant name. Note the use of the dot (.) , much like the use of dot in package hierarchy

public double massToEnergy(double mass) {

return mass*PhysicsConstants.LIGHT_SPEED*

PhysicsConstants.LIGHT_SPEED;

}

• Constants classes never need to be instantiated and should be declared abstract
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 a 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 abstract class CowConstants {

// initial weight of cow in pounds

double static final COW_START_WEIGHT = 587.45;

// weight of one blade of grass in pounds

double static final BLADE_WEIGHT = 0.0118;

// cow must be under this weight to fly

double static final MAX_FLYING_WEIGHT = 603.76;

} // end of CowConstants

Flying Cow (2 of 2)
• Now we can have our cow calculate its weight
• Since the cow doesn’t gain the full weight of the grass, we need an equation to determine how much weight the cow gains after grazing
• Let’s say the cow will gain 5 times the square root of the total grass’ weight:

public class Cow extends FarmAnimal {

private double _weight;

// constructor elided

/**

* This method changes the cow’s weight

* based on how many blades of grass it ate.

*/

// What can we use to calculate square

// root?

}

}

eatGrass(...)
• We can use java.lang.Math!

_weight += 5 * Math.sqrt(grassWeight);

}

• But how can we check to see if the flying conditions are met …?
Announcements
• Lab 3 (Interfaces and Polymorphism) is this week!
• TASafeHouse is due Friday at 10pm!
• Early deadline: Wednesday at 11:59pm
• Late deadline: Sunday at 11:59pm
• GFX goes out on Thursday.

Inheritance and Interfaces

22 of 29
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}