610 likes | 780 Views
Chapter 4 Numeric Types. 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
E N D
Chapter 4 • Numeric Types
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
Knowledge Goals • Be able to use additional operations associated with the String class • Understand how value-return methods work with numeric types
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
Skill Goals • Use java math methods in expressions • Format the statements in a class in a clear and readable fashion
Numeric Data Types • Integral Types • can represent whole numbers and their negatives when declared as byte, short, int, orlong • can represent single characters when declared as char Floating-Point Types • represent real numbers with a decimal point • declared as float or double
Numeric Data Types Sizes of Integral Types byte8 bits short16 bits int32 bits long64 bits
Numeric Data Types Range of Integral 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
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 1 byte = 8 bits 0 1 1 0 0 0 1 1
0 1 0 0 1 0 1 0 0 1 1 0 0 0 1 1 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 How many numbers can be represented in 2 bytes?
Numeric Data Types Scientific Notation • 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
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
Numeric Data Types Floating-point size and range • 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 • Literal numeric values in Java • Literal Type • 0 int • 0L long • 2007 int • 18005551212L long • 18005551212 invalid (too long) • 0.0 double • 0.0f float • 2.001E3 double • 2.001E3F float • 1.8E225F invalid (exponent too large)
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;
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
Arithmetic Expressions Arithmetic Operators + Unary plus - Unary minus + Addition - Subtraction * Multiplication / Division % Modulus Division and Modulus need more explanation
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
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)
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?
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
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
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 is stored in number, real, number2, real2, string, string2 ?
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 in number, real, number2, real2, string, string2 ?
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?
Arithmetic Expressions Java prefix increment operator: ++ int age; age = 8; ++age; 8 age 9 age
Arithmetic Expressions Java postfix increment operator: ++ int age; age = 8; age++; 8 age 9 age
Arithmetic Expressions Java prefix decrement operator: -- int dogs; dogs = 100; --dogs; 100 dogs 99 dogs
Arithmetic Expressions Java postfix decrement operator: -- int dogs; dogs = 100; dogs--; 100 dogs 99 dogs
Arithmetic Expressions • Which form to use? • When the increment (or decrement) operator is used in a “stand alone” statementsolely 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;
Compound Arithmetic Expressions • Precedence • Rules that determine which operator is applied first in an expression having several operators
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?
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 9 - 5 - 1 means (9 - 5) - 1 • 4 - 1 • 3
Evaluate the Expression • 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
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
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 differentresults • Prefix Increment (or decrement) then use • Postfix Use then increment (or decrement)
Compound Arithmetic Expressions • int alpha; • int num; • num = 13; • alpha = ++num * 3; • What is alpha? • alphs = num++ * 3; • What is alpha? Did you foresee this problem from the precedence table ?
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?
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;
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 * 3.5 + (float)4;
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;
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
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("43 55.0"); • int one = in.nextInt(); • float two = in.nextFloat(); • Scanner in = new Scanner(in.nextLine()) • …
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 ?
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?
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?
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?
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?
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?