Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Computer Science and Object-Oriented Programming

Similar presentations


Presentation on theme: "Introduction to Computer Science and Object-Oriented Programming"— Presentation transcript:

1 Introduction to Computer Science and Object-Oriented Programming
Week 5

2 Tonight Fundamental Data Types (Ch. 4) Implementing Methods (Ch. 3)
Class Types Preparing for the Test Launching Lab 2 Week 5 2

3 Warm Up What are the classes, objects, and methods?
Client client1 = new Client("Pat",20); Client client2 = new Client(”Sal",55); System.out.println( client1.getName() + ", at your age of " + client1.getAge() + ", you E-Quotient is " + Math.round(client1.getQuotient() ); int age2 = client2.getAge(); client2.setAge(age2 + 5); Week 5 3

4 Values Judgment Week 5

5 Programs Manipulate Values
Inputs them Stores them Calculates new values from existing ones Outputs them Week 5

6 Types of Values In Java Primitive types References to objects
Week 5

7 Primitive Types Java has eight primitive types
For each you need to know: Possible values Defined operations How to declare Form of constants Week 5

8 Integer Types byte short int long Type Range -128 . . . 127
Memory Units byte 1 byte short 2 bytes int 2,147,483, ,147,483,647 4 bytes long -9,223,372,036,854,775, ,223,372,036,854,775,807 8 bytes Use when in doubt! Week 5

9 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 Week 5

10 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 ±1038 and about 7 significant decimal digits f4 bytes double a range of about ±10308 and about 15 significant decimal digits 8 bytes Use when in doubt! Week 5

11 Floating Point Operations
The expected: +, -, *, / Week 5

12 Number Gotchas Integer overflow A value not “in range” for the type
May not be warned Example int n = ; System.out.println( n*n); REMEDY: use a different type Week 5

13 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 … ) REMEDY: be aware, round, use special class type Week 5

14 byte -> short -> int -> long -> float ->double
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; Week 5

15 byte -> short -> int -> long -> float ->double
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 Week 5

16 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 Week 5

17 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 Week 5

18 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; Week 5

19 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 Floating point numbers Must be a decimal point No commas Week 5

20 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; Week 5

21 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; Week 5

22 You Try Create a class constant for converting Celsius to Fahrenheit Show how you would use the constant in a conversion method Week 5

23 Assignment Operator Form variable = expression; Examples:
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

24 Expressions Ways to specify a value Includes Examples 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 24

25 Precedence see Appenix E Big Java
Always do subexpressions within parentheses first Week 5 25

26 Resolve this Java expression Show your work - including each step
You Try It Resolve this Java expression Show your work - including each step 8 + 2 * (12 - 5) / 2 + 9 Week 5 26

27 Resolve this Java expression Show your work - including each step
You Try It Resolve this Java expression Show your work - including each step / / % 3 Week 5 27

28 Mathematical Functions
Provided by methods of the class Math 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 or equal to x Math.floor(x) Largest integer less than or equal to 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 Week 5

29 Calling Static Methods
The Math class methods are static methods A static method call uses the class name rather than an object name className.methodName(parameters) Classes like Math class are not used to create objects. think of as general purpose utility classes.

30 Examples 5 to the 3rd power can be expressed as:
int x = Math.pow(5, 3); // x equals 125 The square root of 25 can be expressed as: double x = Math.sqrt(25); // x equals 5.0 Week 5

31 variable = expression;
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 Week 5 31

32 The Curious Assignment
Beware items = items + 1; Is legal! Is common! Is not equality!! use value replace value Week 5

33 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 use value replace value Week 5

34 Variations -- is the increment operator -- is the decrement 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

35 The changing of value is called a side effect
The ++ Side Effect! Expressions with variables Use the value of variables But do not change them But in 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 Week 5

36 Side Effect Example Two int variables
About to execute amount = 3 * cost++; 4 cost amount Start evaluation of right side 3 *  Get the value of cost 3 * 4 Increment value of cost (side effect!) Evaluate right side 12 Assign value to left 4 cost amount 5 cost amount 5 cost amount 12

37 Side Effect Example Two int variables
About to execute amount = 3 * ++cost; 4 cost amount Start evaluation of right side 3 *  Increment value of cost (side effect!) Get the value of cost 3 * 5 Evaluate right side 15 Assign value to left 4 cost amount 5 cost amount 5 cost amount 5 cost amount 15

38 What is Output? int myVar; myVar = 10; System.out.println(myVar++); 10
Week 5

39 What is Output? int myVar; myVar = 10; System.out.println(myVar--); 10
Week 5 39

40 What is Output? int myVar; myVar = 10; int myNewVar = myVar--;
System.out.println(myVar + “ “ + myNewVar); Output is Week 5

41 Boolean Type Type specifier: boolean Two values: true or false
Literals are: true false What’s returned from assertEquals Week 5

42 char 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

43 String type String in not a primitive type
As a class type, it has a special status it has a form for literal values it can be initialized without a new it has a special operator The positions in a string start leftmost at 0 go to the length of the string minus 1 It has many useful methods Week 5

44 String methods Suppose word is a variable of type String
word.length() is the number of characters in word word.toUpperCase() is the word with all characters capitalized Week 5

45 Categories of Variables
Instance fields Local variables Parameter variables Notes All hold values. Difference is lifetime. Week 5

46 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 Week 5 46

47 Example public class BankAccount { private double balance;
public void deposit(double amount) double newBalance = this.balance + amount; this.balance = newBalance; } . . . Example: harrysChecking.deposit(500); Method is called amount is created and set to 500 newBalance is created and set to balance + amount balance is set to newBalance. After method call, amount and newBalance dies, balance still lives. balance is instance field amount: parameter variable newBalance: local variable Week 5

48 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) Week 5

49 Commenting the Public Interface
Use documentation comments to describe the classes and public methods Use the standard documentation notation so program called javadoc can automatically generate a set of HTML pages

50 Commenting the Public Interface
Provide documentation comments for every class every method every parameter every return value Javadoc comment are within /** and */ Best to write the method comments first, before writing code in the body

51 Example /** Withdraws money from the bank account.
@param amount the amount to withdraw */ public void withdraw(double amount) { // implementation filled in later }

52 Example /** Gets the current balance of the bank account.
@return double the current balance */ public double getBalance() { // implementation filled in later }

53 Generated by Javadoc


Download ppt "Introduction to Computer Science and Object-Oriented Programming"

Similar presentations


Ads by Google