COMP 111 Introduction to Computer Science and Object-Oriented Programming Values Judgment
Programs Manipulate Values Inputs them Stores them Calculates new values from existing ones Outputs them In Java Primitive types Types of Values References to objects reference primitive
Primitive Types Java has eight primitive types For each you need to know: Possible values Defined operations How to declare Form of constants Integer Types Type Range Memory Units byte -128... 127 1 byte short -32768... 32767 int 2,147,483,648... 2,147,483,647 2 bytes 4 bytes Use when in doubt! long -9,223,372,036,854,775,808... -9,223,372,036,854,775,807 8 bytes
Integer 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 2 7 % 3 results in 1 Floating Point Type Have fractional part Two types - float and double - differ in Min and max Significant digits Type Range Memory Units float a range of about ±10 38 and about 7 significant decimal digits 4 bytes double a range of about ±10 308 and about 15 significant decimal digits 8 bytes Use when in doubt!
Floating Point Operations The expected: +, -, *, / Number Gotchas 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
Number Gotchas 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 Number Gotchas 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;
Number Gotchas 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 Cast 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
Round 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 Constants 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;
Literal 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 Symbolic 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 method final typename variablename = expression; In a class static final typename variablename = expression;
Symbolic 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 constant final double QUARTER_VALUE = 0.25; Example of a class constant: public static final double QUARTER_VALUE = 0.25; You Try Create a class constant for converting Celsius to Fahrenheit Show how you would use the constant in a conversion method
Assignment 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(): Expressions 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() );
Assignment Operator variable = 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 Beware The Curious Assignment Is legal! Is common! Is not equality!! items = items + 1; replace value use value
The 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 value use value Variations -- is the increment operator ++myvar; myvar++; is a pre-increment is a post-increment -- is the decrement operator --myvar; myvar--; is a pre-decrement is a post-decrement
The ++ 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 Example Two int variables cost 4 amount 12 About to execute amount = 3 * cost++; 1. Start evaluation of right side 3 * cost 4 amount 12 2. Get the value of cost 3 * 4 3. Increment value of cost (side effect!) cost 5 amount 12 4. Evaluate right side 12 5. Assign value to left cost 5 amount 12
Side Effect Example Two int variables cost 4 amount 12 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 cost 4 amount 12 cost 5 amount 12 cost 5 amount 12 4. Evaluate right side 15 5. Assign value to left cost 5 amount 15 What is Output? int myvar; myvar = 10; System.out.println(myVar++); 10 System.out.println(myVar); 11 myvar = 10; System.out.println(++myVar); 11 System.out.println(myVar); 11
What is Output? int myvar; myvar = 10; System.out.println(myVar--); 10 System.out.println(myVar); 9 myvar = 10; System.out.println(--myVar); 9 System.out.println(myVar); 9 int myvar; What is Output? myvar = 10; int mynewvar = myvar--; System.out.println(myVar + + mynewvar); Output is 9 10
Boolean Type Type specifier: boolean Two values: true or false Literals are: true false What s returned from assertequals Type specifier: Two values: Literals are: Note char Type char `a` is not the same as `A` `a` is not the same as a (ones a char, ones a String) single characters `a` `4` `!`
Categories of Variables Instance fields Local variables Parameter variables Notes All hold values. Difference is lifetime. Lifetime of Variables Instance field as long as there is a reference to object it belongs to. Parameter and local variables come to life when method is called die after call
public class BankAccount { private double balance; Example public void deposit(double amount) { double newbalance = balance + amount; balance = newbalance; }... Example: harryschecking.deposit(500); 1. Method is called 2. amount is created and set to 500 3. newbalance is created and set to balance + amount 4. balance is set to newbalance. 5. After method call, amount and newbalance dies, balance still lives. Balance is instance field amount: parameter variable newbalance: local variable Implicit 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).
Mathematical Functions Provided by methods of the class Math Type Math.sqrt(x) Math.pow(x,y) Math.round(x) Math.ceil(x) Math.floor(x) Math.abs() Square root of x x to the y power Returns Closest integer to x Smallest integer greater than or equal to x Largest integer less than or equal to x Absolute value of x Math.max(x,y) Math.min(x,y) The larger of x and y The smaller of x and y Examples 5 to the 3 rd 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