Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 Numeric Types.

Similar presentations


Presentation on theme: "Chapter 4 Numeric Types."— Presentation transcript:

1 Chapter 4 Numeric Types

2 Knowledge Goals Discover why different numeric types have different ranges of values Understand the differences between integral and floating-point types See how precedence rules affect the order of evaluation in an expression Understand implicit type conversion and explicit type casting

3 Knowledge Goals Be able to use additional operations associated with the String class Understand how value-return methods work with numeric types

4 Skill Goals Declare named constants and variables of types int and double Construct simple arithmetic expressions Evaluate simple arithmetic expressions Construct and evaluate expressions that include multiple arithmetic operations Read numeric values using the methods in class Scanner

5 Skill Goals Use java math methods in expressions
Format the statements in a class in a clear and readable fashion

6 Numeric Data Types

7 Numeric Data Types Integral Types
can represent whole numbers and their negatives when declared as byte, short, int, or long can represent single characters when declared as char Floating-Point Types represent real numbers with a decimal point declared as float or double

8 Numeric Data Types Sizes of Integral Types byte 8 bits short 16 bits
int bits long bits

9 Numeric Data Types Range of Integral Types byte 8 -128 127
Type Size in Bits Minimum Value to Maximum Value byte short , ,767 int ,147,483, ,147,483,647 long ,223,372,036,854,775,808 to +9,223,372,036,854,775,807

10 Numeric Data Types 1 byte = 8 bits 0 1 1 0 0 0 1 1
How many different numbers can be represented in one byte using 0’s and 1’s? Each bit can hold either a 0 or a 1. So there are just two choices for each bit, and there are 8 bits. 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 = 28 = 256

11 Numeric Data Types How many numbers can be represented in 2 bytes?
216 = If we have only one number representing the integer zero, and half of the remaining numbers positive, and half negative, we can obtain the 65,536 numbers in the range

12 Numeric Data Types 27000.0 2.7E-4 means 2.7 x 10 - 4 =
Scientific Notation 2.7E4 means x = = 2.7E-4 means x = =

13 Numeric Data Types Floating-point Types
Numbers with an integer part and a fractional part, with a decimal point in between; either the integer part or the fractional part may be missing but not both Scientific notation is also ok 1.84E E E E3

14 Numeric Data Types Floating-point size and range
Type Size in Bits Range of Values float E to E+38 double E to E+308

15 Numeric Data Types Literal numeric values in Java Literal Type 0 int
0L long int L long invalid (too long) 0.0 double 0.0f float 2.001E3 double 2.001E3F float 1.8E225F invalid (exponent too large)

16 Numeric Declarations Named constant declaration
final double PI = ; final String HOME = “Texas”; final int TEXAS_TEMP = 95; Variable declaration double taxIncreae; char initial; int dailyTemp;

17 Arithmetic Expressions
A valid arrangement of variables, constants, operators and parentheses An expression can be evaluated to compute a value of a given type The value of the expression 9.3 * is

18 Arithmetic Expressions
Arithmetic Operators + Unary plus - Unary minus + Addition - Subtraction * Multiplication / Division % Modulus Division and Modulus need more explanation

19 Arithmetic Expressions
Division (/) The result of the division operator depends on the type of its operands If one or both operands has a floating type, the result is a floating-point type (float or double); otherwise, the result is an integral type 11 / has value 2 11.0 / has value 11 / has value 11 / invalid (cannot divide by 0) 11.0 / 0 has value infinity

20 Arithmetic Expressions
Modulus (%) When used with integer type operands, the % operator returns the remainder from integer division; with floating-point operands, it returns the remainder after dividing the dividend by the divisor a whole number of times 11 % 4 has value 3 9 % 3 has value 0 3 % 5 has value 3 5 % 0 invalid (cannot divide by 0) 6.0%4.2 has value 0.12 6.0%0.0 has value not a number (NaN)

21 Arithmetic Expressions
Remember the Scanner class? Scanner in = new Scanner(System.in); String line = in.nextLine(); int nextInt() Returns next token as an int long nextLong() Returns next token as a long float nextFloat() Returns next token as a float String next() Returns next token as a string Inputs next line What happens if the next token is not a number?

22 Arithmetic Expressions
Exception An unusual condition in execution of Java code control is transferred to statements designed to handle the condition exception is thrown when the condition is detected exception is caught by the handling code

23 Arithmetic Exceptions
Checked exceptions An exception in Java that must either be caught with a catch statement or explicitly thrown to the next level Unchecked exception An exception in Java that can optionally be caught or allowed to propagate automatically to the next level InputMismatchException is unchecked More on exceptions in Chapter 6

24 Arithmetic Expressions
int number = in.nextInt(); float real = in.nextFloat(); long number2 = in.nextLong(); double real2 = in.nextDouble(); String string = in.next(); String string2 = in.next(); Data 33 12 333 44.22 End What is stored in number, real, number2, real2, string, string2 ?

25 Arithmetic Expressions
int number = in.nextInt(); float real = in.nextFloat(); long number2 = in.nextLong(); double real2 = in.nextDouble(); String string = in.nextLine(); String string2 = in.nextLine(); Data 33 12 333 44.22 End Now, what is stored in number, real, number2, real2, string, string2 ?

26 Arithmetic Expressions
String string = in.nextLine(); nextLine() returns the rest of the line Arithmetic reads do not consume the separator Thus, nextLine() following an arithmetic read returns the separator, the empty string if the arithmetic value was the last value on a line How can you solve the problem?

27 Arithmetic Expressions
Java prefix increment operator: ++ int age; age = 8; ++age; 8 age 9 age

28 Arithmetic Expressions
Java postfix increment operator: ++ int age; age = 8; age++; 8 age 9 age

29 Arithmetic Expressions
Java prefix decrement operator: -- int dogs; dogs = 100; --dogs; 100 dogs 99 dogs

30 Arithmetic Expressions
Java postfix decrement operator: -- int dogs; dogs = 100; dogs--; 100 dogs 99 dogs

31 Arithmetic Expressions
Which form to use? When the increment (or decrement) operator is used in a “stand alone” statement solely to add one (or subtract one) from a variable’s value, it can be used in either prefix or postfix form USE EITHER dogs--; dogs;

32 Compound Arithmetic Expressions
Precedence Rules that determine which operator is applied first in an expression having several operators

33 Compound Arithmetic Expressions
Operator Precedence Highest ( ) (operations within parentheses) (postfix increment and decrement) ++ -- (prefix increment and decrement) + - (unary plus and minus) * / % (multiplication, division, modulus) Lowest (addition and subtraction) Can you see why increment and decrement operators might be problems in compound expressions?

34 Compound Arithmetic Expressions
Left-to-right associativity In an expression having two operators with the same priority, the left operator is applied first In Java, the binary operators * , / , % , + , - are all left associative Expression means (9 - 5) - 1 4 - 1 3

35 Evaluate the Expression
7 * % 3 * (7 * 10) % 3 * % 3 * (5 % 3) * * (2 * 4) + 9 ( ) 71

36 Parentheses Use parentheses to change the usual order
Parts in () are evaluated first Evaluate (7 * (10 - 5) % 3) * (7 * 5 % 3) * (35 % 3) * 2 * 17

37 Compound Arithmetic Expressions
But… When the increment (or decrement) operator is used in a statement with other operators, the prefix and postfix forms can yield different results Prefix Increment (or decrement) then use Postfix Use then increment (or decrement)

38 Compound Arithmetic Expressions
int alpha; int num; num = 13; alpha = ++num * 3; What is alpha? alphs = num++ * 3; Did you foresee this problem from the precedence table ?

39 Compound Arithmetic Expressions
Type conversion The implicit (automatic) conversion of a value from one data type to another Widening conversion One that does not result in a loss of information Narrowing conversion One that may result in a loss of information How do type conversions happen?

40 Compound Arithmetic Expressions
Given int someInt; double someDouble; float someFloat; What happens in these cases? someDouble = 12; someInt = 4.5; someFloat = someDouble; someFloat = someInt * ;

41 Compound Arithmetic Expressions
Type casting The explicit conversion of a value from one data type to another (data type name) Expression someDouble = (double)12; someInt = (int)4.5; someFloat = (float)someDouble; someFloat = (float)someInt * (float)4;

42 Compound Arithmetic Expressions
What values are stored? double loCost; double hiCost; loCost = ; hiCost = ; loCost = (double) ((int) (loCost * )) / 100.0; hiCost = (double) ((int) (hiCost * ))

43 Compound Arithmetic Expressions
What is the difference between these statements? String answer = "The results are: " ; and String answer = " The results are:"; Conversion from number to string occurs only with the concatenation operator

44 Compound Arithmetic Expressions
What about converting from string to a numeric value? We instantiate a Scanner object with the string and use the Scanner input methods Scanner in = new Scanner(" "); int one = in.nextInt(); float two = in.nextFloat(); Scanner in = new Scanner(in.nextLine())

45 Value-Returning Methods
Additional methods of class String Method length returns an int value that is the number of characters in the string String name = “Donald Duck”; numChars; numChars = name.length(); instance method What is returned ?

46 Value-Returning Methods
Method indexOf searches a string to find a particular substring, and returns an int value that is the beginning position for the first occurrence of that substring within the string String stateName = “Mississippi”; int index; index = stateName.indexOf("is"); What is returned? (Remember the first position is 0 not 1) What is returned if the substring isn't there?

47 Value-Returning Methods
Method charAt returns the character at a specified position within the string String stateName = “Mississippi”; char letter; letter = stateName.charAt(5); What is returned?

48 Value-Returning Methods
Method substring returns a substring of a string, but does not change the string itself The first parameter specifies a starting position within the string The second parameter specifies the last position plus one String stateName = “Mississippi”; String substring; substring = stateName.substring(9, 11); What is returned?

49 Value-Returning Methods
Method trim returns a copy of a string with all whitespace characters removed from either end String myString = " Good morning Susy Sunshine "; System.out.println(myString.length()); System.out.println(myString.trim().length()); What is printed?

50 Value-Returning Methods
Class Math provides a collection of useful value-returning methods for common numeric functions Math.abs(x) returns the absolute value of X Math.cos(x) returns the cosine of X Math.sqrt(x) returns the square root of X Math.random()returns a random number between 0 and 1 Why is Math uppercase?

51 Class Time Designing a class to represent time
Immediately we have an ambiguous situation: Time of day with hours, minutes, and seconds Elapsed time where seconds only is appropriate Here we mean elapsed time, so our only attribute is seconds of type double

52 Class Time Constructors public Time() // default { seconds = 0.0; }
public Time(double newSeconds) { seconds = newSeconds; } public Time(int hours, int minutes, double new Seconds) { seonds = (double)(hours* minutes * 60) + newSeconds; }

53 Class Time Observers public double getTime() { return seconds; }
public int getHours() { return (int) seconds/3600; } public int getSeconds() { return seconds % 60.0) } getMinutes is more difficult…

54 Class Time We must remove hours before we can calculate minutes
public int getMinutes() { int remainingSeconds = (int) seconds % 3600; return remainingSeconds/60; } 5463 seconds is 1 hours, 31 minutes, and 3 second Prove it to yourself

55 Why is a toString method useful?
Class Time Other operations public String toString() { int hours = (int) sconds / 3600; int minutes = (int) seconds % 3600 / 60; return hours + ":" + minutes + ":" + seconds%60; } Why is a toString method useful?

56 Class Time Binary operation
Time myTime(300); Time yourTime(200); Time ourTime = myTime.plus(yourTime); public Time plus(Time otherTime) { return (new Time(seconds + otherTime.seconds);) } What are seconds and otherTime.seconds here? Time ourTime = yourTime.plus(myTime);

57 Class Time No class is complete until it is tested Test plan
A document that specifies how a class is to be tested Test plan implementation Writing and running a driver that implements the test cases specified in a test plan to verify that the class methods produce the predicted results

58 Class Time Test Plan

59 Class Time Implemented test plan

60 Extras I designed both the Difference Engine and the Analytical
Engine in the 1800s Who am I?

61 Extras - GUI Track Dialog box
A small temporary panel that appears on the screen, with which user can interact


Download ppt "Chapter 4 Numeric Types."

Similar presentations


Ads by Google