Download - Chapter 4 Numeric Types
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
byte 8 bits
short 16 bits
int 32 bits
long 64 bits
Sizes of Integral Types
9
Numeric Data Types
Type Size in Bits Minimum Value to Maximum Value
byte 8 -128 127
short 16 -32,768 32,767
int 32 -2,147,483,648 2,147,483,647
long 64 -9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807
Range of Integral Types
10
Numeric Data Types
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
0 1 1 0 0 0 1 1
1 byte = 8 bits
11
Numeric Data Types
216 = 65536
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
-32768 . . . . 0 . . . . 32767
0 1 0 0 1 0 1 00 1 1 0 0 0 1 1
How many numbers can be represented in 2 bytes?
12
Numeric Data Types
2.7E4 means 2.7 x 10 4 =
2.7000 =
27000.0
2.7E-4 means 2.7 x 10 - 4 =
0002.7 =
0.00027
Scientific Notation
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
18.4 500. .8 -127.358
Scientific notation is also ok
1.84E1 5E2 8E-1 -.127358E3
14
Type Size in Bits Range of Values
float 32 +1.4E - 45 to
+3.4028235E+38
double 64 +4.9E - 324 to
+1.7976931348623157E+308
Numeric Data Types
Floating-point size and range
15
Numeric Data Types
Literal numeric values in JavaLiteral Type0 int0L long2007 int18005551212L long18005551212 invalid (too long)0.0 double0.0f float2.001E3 double2.001E3F float1.8E225F invalid (exponent too large)
16
Numeric Declarations
Named constant declaration
final double PI = 3.14159;
final String HOME = “Texas”;
final int TEXAS_TEMP = 95;
Variable declaration
double taxIncreae;
char initial;
int dailyTemp;
17
Arithmetic Expressions
Arithmetic expression 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 * 4.5 is 41.85
18
Arithmetic Expressions
Arithmetic Operators
+ Unary plus
- Unary minus
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
Divisionand
Modulusneed moreexplanation
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 / 4 has value 2
11.0 / 4.0 has value 2.75
11 / 4.0 has value 2.75
11 / 0 invalid (cannot divide by 0)
11.0 / 0 has value infinity
20
Arithmetic ExpressionsModulus (%)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
3.13158
What isstored innumber,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
3.13158
Now,what is
stored innumber,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
8
int age;
age = 8;
++age;
age
9
age
Java prefix increment operator: ++
28
Arithmetic Expressions
8
int age;
age = 8;
age++;
age
9
age
Java postfix increment operator: ++
29
Arithmetic Expressions
100
int dogs;
dogs = 100;
--dogs;
dogs
99
dogs
Java prefix decrement operator: --
30
Arithmetic Expressions
100
int dogs;
dogs = 100;
dogs--;
dogs
99
dogs
Java postfix decrement operator: --
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
dogs--; --dogs;
USE EITHER
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 decrementoperators might be problems in compound expressions?
34
Compound Arithmetic ExpressionsLeft-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 9 - 5 - 1 means (9 - 5) - 1
4 - 1
3
35
7 * 10 - 5 % 3 * 4 + 9
(7 * 10) - 5 % 3 * 4 + 9
70 - 5 % 3 * 4 + 9
70 - (5 % 3) * 4 + 9
70 - 2 * 4 + 9
70 - (2 * 4) + 9
70 - 8 + 9 (70 - 8) + 9
62 + 9
71
Evaluate the Expression
36
Parentheses
Use parentheses to change the usual order
Parts in () are evaluated first
Evaluate (7 * (10 - 5) % 3) * 4 + 9
(7 * 5 % 3) * 4 + 9
(35 % 3) * 4 + 9
2 * 4 + 9
8 + 9
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;What is alpha?
Did youforesee
thisproblemfrom the
precedencetable
?
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 * 3.5 + 4;
41
Compound Arithmetic Expressions
Type casting
The explicit conversion of a value from one data type to another
(data type name) ExpressionsomeDouble = (double)12;
someInt = (int)4.5;
someFloat = (float)someDouble;
someFloat = (float)someInt * 3.5 + (float)4;
42
Compound Arithmetic Expressions
What values are stored?double loCost;
double hiCost;
loCost = 12.342;
hiCost = 12.348;
loCost = (double) ((int) (loCost * 100.0 + 0.5))
/ 100.0;
hiCost = (double) ((int) (hiCost * 100.0 + 0.5))
/ 100.0;
43
Compound Arithmetic Expressions
What is the difference between these statements?String answer = "The results are: " + 27 + 9;
and
String answer = 27 + 9 + " 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 methodsScanner in = new Scanner("43 55.0");
int one = in.nextInt();
float two = in.nextFloat();
Scanner in = new Scanner(in.nextLine())
…
45
Value-Returning Methods
Additional methods of class StringMethod length returns an int value that is the number
of characters in the string String name = “Donald Duck”;
numChars;
numChars = name.length();
instance method
Whatis
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 stringString stateName = “Mississippi”;
int index;
index = stateName.indexOf("is");
What is returned? (Remember the firstposition 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 stringString 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 timeImmediately 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
Constructorspublic Time() // default
{ seconds = 0.0; }
public Time(double newSeconds)
{ seconds = newSeconds; }
public Time(int hours, int minutes,
double new Seconds)
{
seonds = (double)(hours*3600 + minutes * 60)
+ newSeconds;
}
}
53
Class Time
Observerspublic 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
Class Time
Other operationspublic 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 operationTime myTime(300);
Time yourTime(200);
Time ourTime = myTime.plus(yourTime);
public Time plus(Time otherTime)
{
return (new Time(seconds + otherTime.seconds);)
}
300 200
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 boththe Difference
Engine andthe Analytical
Engine inthe 1800s
Who am I?
61
Extras - GUI Track
Dialog box
A small temporary panel that appears on the screen, with which user can interact