Upload
others
View
3
Download
0
Embed Size (px)
Citation preview
Week 5
COMP 111COMP 111
Introduction to Computer ScienceIntroduction to Computer Scienceand Object-Oriented Programmingand Object-Oriented Programming
Week 5
Values JudgmentValues Judgment
Week 5
Programs Manipulate ValuesPrograms Manipulate Values• Inputs them• Stores them• Calculates new values from existing ones• Outputs them
Week 5
Types of ValuesTypes of Values• In Java
Primitive types References to objects
primitive
reference
Week 5
Primitive TypesPrimitive Types• Java has eight primitive types• For each you need to know:
Possible values Defined operations How to declare Form of constants
Week 5
Integer TypesInteger Types
Type Range MemoryUnits
byte -128 . . . 127 1 byte
short -32768 . . . 32767 2 bytes
int 2,147,483,648 . . . 2,147,483,647 4 bytes
long -9,223,372,036,854,775,808 . . .-9,223,372,036,854,775,807
8 bytes
Use when in doubt!
Week 5
Integer OperationsInteger Operations• The expected: +, -, *• The unexpected: ++ and -- (later)• The unexpected: / and %
/ is integer division results in integer(remainder discarded)
% computes remainder after integer division
7 / 3 results in 27 % 3 results in 1
Week 5
Floating Point TypeFloating Point Type• Have fractional part• Two types - float and double - differ in
Min and max Significant digits
Type Range MemoryUnits
float a range of about ±1038 andabout 7 significant decimal digits f4 bytes
double a range of about ±10308 andabout 15 significant decimal digits
8 bytesUse when in doubt!
Week 5
Floating Point OperationsFloating Point Operations• The expected: +, -, *, /
Week 5
Number Number GotchasGotchas• Integer overflow
A value not “in range” for the type May not be warned Example
int n = 1000000;
System.out.println( n*n);
REMEDY: use a different type
Week 5
Number Number GotchasGotchas• Floating point rounding errors
Due to differences number systems• Decimal (the one we are used to)• Binary (used to represent numbers in a computer)
May not be warned Example
double f = 4.35;System.out.println(100 * f);
( will print 434.99999… )
REMEDY: be aware, round, use special class type
Week 5
Number Number GotchasGotchas• Conversion between types
byte -> short -> int -> long -> float ->double• value of a type can be converted to any type to its right
No loss of precision No syntax error Example
int dollars = 100;
double balance = dollars;
Week 5
Number Number GotchasGotchas• Conversion between types
byte -> short -> int -> long -> float ->double• value of a type cannot be converted to a type to its left
Potential information loss! A syntax error! Example error!
double balance = 13.75;int dollars = balance;
REMEDY: cast or round
Week 5
CastCast• Programmer agrees to possible loss of info
Use (type) before a value Only needed when otherwise a syntax error
double balance = 13.75;
int dollars = (int) balance;
In this case, 13 is assigned! Fractional part is truncated
Week 5
RoundRound• Programmer controls conversion
Use Math.round(value) round is a method of the Math class
double balance = 13.75;
int dollars = Math.round(balance);
In this case, 14 is assigned! Using normal mathematical rounding
Week 5
ConstantsConstants• Variable allow programs to be “general”
Different values input, processed, output Each time run
• Some values are the same Each time the program is run For example
Int heightInInches = 12 * feet + inches;
Week 5
Literal ConstantsLiteral Constants• Ways of writing values of a certain type
Literally within program statements Form differs by type
• Integers Sequence of digits Preceded by + or - No commas 430 0 -99833786
• Floating point numbers Sequence of digits Must be a decimal point Preceded by + or - No commas 0.0 .234 -78439.42243
Week 5
Symbolic ConstantsSymbolic Constants• Ways of writing values of a certain type
These are ‘self-documenting” Ease program maintenance Requires an initializing declaration (like a variable) Requires use of special keywords
• One form for all types In a methodfinal typename variableName = expression;
In a classstatic final typename variableName = expression;
Week 5
Symbolic ConstantsSymbolic Constants• final denotes a variable that
once given a value, cannot change value• static means the constant belongs to the class
(not part of each instance)• public is fine since value cannot be changed• Style convention: make a constant all caps
Example of a method constantfinal double QUARTER_VALUE = 0.25;
Example of a class constant:public static final double QUARTER_VALUE = 0.25;
Week 5
You TryYou TryCreate a class constant
for converting Celsius to Fahrenheit
Show how you would usethe constant in a conversion method
Week 5
Assignment OperatorAssignment Operator• Form
variable = expression; Replace the value of the variable on left Expression on right calculates the value
• Examples: ticketCount = 0;
int heightInInches = 12 * feet + inches;
wordSize = word.length():
Week 5
ExpressionsExpressions• Ways to specify a value
Directly By calculation
• Includes Literal constant - use literal value Variable of symbolic constant - use current value Call on a method - use the return value Combine the above with operators (+, -, /, *, %, etc.)
• Examples ticketCount = 0; int heightInInches = 12 * feet + inches; System.out.println( word.length() );
Week 5
Assignment OperatorAssignment Operatorvariable = expression;
• Notes on references to variables On the left
• Replace the value of the variable On the right
• Use the current value of the variable
Week 5
The Curious AssignmentThe Curious Assignment• Beware
items = items + 1;• Is legal!• Is common!• Is not equality!!
replace valueuse value
Week 5
The Increment OperatorThe Increment Operator• Another way to increment by 1
items++;• Is legal!• No assignment operator is necessary• The above is a valid statement on its own
replace valueuse value
Week 5
VariationsVariations• -- is the increment operator
++myVar; is a pre-increment myVar++; is a post-increment
• -- is the decrement operator --myVar; is a pre-decrement myVar--; is a post-decrement
Week 5
The The ++++ Side Effect! Side Effect!• Expressions with variables
Use the value of variables But do not change them
• In an expressions the ++ and -- operations Apply to single variable Provide a value to use (in an expression) Change the value of the variable
The changing of value is called a side effect
Side Effect ExampleTwo int variables
About to execute amount = 3 * cost++;
1. Start evaluation of right side 3 *
2. Get the value of cost 3 * 4
3. Increment value of cost (side effect!)
4. Evaluate right side 12
5. Assign value to left
4cost amount 12
4cost amount 12
5cost amount 12
5cost amount 12
Side Effect ExampleTwo int variables
About to execute amount = 3 * ++cost;
1. Start evaluation of right side 3 *
2. Increment value of cost (side effect!)
3. Get the value of cost 3 * 5
4. Evaluate right side 15
5. Assign value to left
4cost amount 12
4cost amount 12
5cost amount 12
5cost amount 12
5cost amount 15
Week 5
What is Output?What is Output?int myVar;
myVar = 10;System.out.println(myVar++); 10System.out.println(myVar); 11
myVar = 10;System.out.println(++myVar); 11System.out.println(myVar); 11
Week 5
What is Output?What is Output?int myVar;
myVar = 10;System.out.println(myVar--); 10System.out.println(myVar); 9
myVar = 10;System.out.println(--myVar); 9System.out.println(myVar); 9
Week 5
What is Output?What is Output?int myVar;
myVar = 10;int myNewVar = myVar--;System.out.println(myVar + “ “ + myNewVar);
Output is 9 10
Boolean TypeBoolean Type• Type specifier: boolean• Two values: true or false• Literals are: true false• What’s returned from assertEquals
Week 5
char Typechar Type• Type specifier: char• Two values: single characters• Literals are: `a` `4` `!`• Note
`a` is not the same as `A` `a` is not the same as “a”
(ones a char, ones a String)
Week 5
Week 5
Categories of VariablesCategories of Variables
• Instance fields• Local variables• Parameter variables
Notes• All hold values.• Difference is lifetime.
Week 5
Lifetime of VariablesLifetime of Variables
• Instance fieldas long as there is a reference to object itbelongs to.
• Parameter and local variables come to life when method is called die after call
Week 5
ExampleExamplepublic class BankAccount{ private double balance;
public void deposit(double amount) { double newBalance = balance + amount; balance = newBalance; } . . .
Example: harrysChecking.deposit(500);
1. Method is called2. amount is created and set to 5003. newBalance is created and set to balance + amount4. balance is set to newBalance.5. After method call, amount and newBalance dies, balance still lives.
Balance is instance fieldamount: parameter variablenewBalance: local variable
Week 5
Implicit and Explicit ParametersImplicit and Explicit Parameters
public class BankAccount{ private double balance; public void deposit(double amount) { double newBalance = this.balance + amount; this.balance = newBalance; } . . .harrysChecking.deposit(500);
• The amount parameter is an explicit parameter.• An instance field in a class method can be denoted as
this.instanceFieldName.• this.balance is equivalent for this example to “harrysChecking.balance”,• This refers to the implicit object parameter (harrysChecking object).
Week 5
Mathematical FunctionsMathematical Functions
Type Returns
Math.sqrt(x) Square root of x
Math.pow(x,y) x to the y power
Math.round(x) Closest integer to x
Math.ceil(x) Smallest integer greater than orequal to x
Math.floor(x) Largest integer less than or equalto x
Math.abs() Absolute value of x
Math.max(x,y) The larger of x and y
Math.min(x,y) The smaller of x and y
Provided by methods of the class Math
Week 5
ExamplesExamples
• 5 to the 3rd power can be expressed in Java as:int x = Math.pow(5, 3); // x equals 125
• The square root of 25 can be expressed in Java as:double x = Math.sqrt(25); // x equals 5