1 / 78

Chapter 3

Chapter 3. Numerical Data. Objectives. Understand n umerical data type . Write arithmetic expressions in Java. Evaluate arithmetic expressions using the precedence rules. Describe how the memory allocation works for objects and primitive data values. Learn to use standard classes

nishi
Télécharger la présentation

Chapter 3

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 3 Numerical Data

  2. Objectives • Understand numerical data type. • Write arithmetic expressions in Java. • Evaluate arithmetic expressions using the precedence rules. • Describe how the memory allocation works for objects and primitive data values. • Learn to use standard classes • Math – for math expressions • GregorianCalendar - for manipulating date information such as year, month, and day. • DecimalFormat - for formating numerical data • Integer, …,Long - Convert input string values to numerical data • System.in, System.out - Perform input and output.

  3. JavaData Types Data Types supported by Java: • primitive types • numeric types • integer type: byte, char, short, int, long • floating-point type: float, double • boolean • reference types • class • interface • array Notes: • Instances of primitive types are values but not objects; only instances of reference types are objects.

  4. Integer types • name representation range • byte8-bit 2's complement -128~127 • short16-bit 2's complement -32768~32767 • int32-bit 2's complement -2147483648 to 2147483647 • long64-bit 2's complement -263~263-1 (19 digits) • char16-bit Unicode '\u0000' to '\uffff‘ • or 0 ~ 65535

  5. floating-point and boolean types • name representation range • float 32-bit, IEEE 754 1.40239846e-45 ~ 3.40282347e+38 • double 64-bit, IEEE 754 4.94065645841246544e-324 • ~ 1.79769313486231570e+308 Representation: • non-zero value: v = S x M x 2^E • For float: S is +/- 1, M is a positive integer less than 2^24, and E is an integer in the inclusive range -149 to 104. • For double: S is +/- 1, M is a positive integer less than 2^53, and E is an integer in the inclusive range -1045 to 1000. • special values defined in IEEE 754: • +0, -0, +infinity, -Infinity, NaN. • note: 0/0.0 => NaN, • 1/0.0 => Infinity instead of overflow or divide by zero.

  6. IEEE 754 float-point single precision layout • 0x7f800000 => positive infinity. • 0xff800000 => negative infinity. • 0x7f800001 ~ 0x7fffffff or 0xff800001~0xffffffff => NaN. • Java use 0x7fc00000 as the canonical value of NaN. • Distinct values of NaN are only accessible by use of the Float.floatToRawIntBits(float) • In all other cases, let s, e, and m be three values that can be computed from the argument: • int s = ((bits >> 31) == 0) ? 1 : -1; • int e = ((bits >> 23) & 0xff); // s bit is ignored by mask of 0xff • int m = (e == 0) ? (bits & 0x7fffff) << 1 : (bits & 0x7fffff) | 0x800000; • the floating-point result is s · m · 2 e-150.

  7. (exponent) s e (man’tissa) b31 b15 b30 b14 b29 b13 b12 b28 b11 b27 b10 b26 b9 b25 b24 b8 b23 b7 b22 b6 b21 b5 b4 b20 b3 b19 b2 b18 b17 b1 b0 b16 m IEEE 754 float-point single precision layout • value is determined as follows: • 0. s = (b31 == 0 ? 1: -1); • 255> e > 0 => value = s x (1.m)2 x 2 e –127 = s x (1m) x 2 e - 150 • e = 0 => value = s x (b22.b21---b00)2 x 2 e-127 = s x (m 0)2 x 2 e - 127-23 • e=255 && m == 0 => value = ( s == 0 ? Infinity : -Infinity) • e = 255 && m != 0 => value = NaN; canonical NaN = 0181022

  8. Literals • A literal is the source code representation of a constant value of a primitive type, or some specific object (of the type String, null, array or Class). • Literal: • IntegerLiteral : 123, 123l, 12400L • FloatingPointLiteral: 123.4, 1.2e12, 12f, 12.3d • BooleanLiteral: true, false • CharacterLiteral: ‘a’, ‘\u123’, ‘\377’,… • StringLiteral: “a book”,“tab\t and newline \n” • NullLiteral: null • ArrayLiteral: new int[]{1,2,3}. • ClassLiteral: String.class

  9. Integer Literals • An integer literal may be expressed in decimal (base 10), hexadecimal (base 16), or octal (base 8): • It is of type int unless suffixed with ‘L’ or ‘l’. • IntegerLiteral: • DecimalIntegerLiteral • HexIntegerLiteral • OctalIntegerLiteral • DecimalIntegerLiteral: • 0 • [1-9] [0-9]* [lL]? Ex: 123, 123l, 1243L • HexIntegerLiteral: • 0 [xX] [0-9a-fA-F]+ [lL]? Ex: 0X1aB4, 0x23L, 0xffff • OctalIntegerLiteral: • 0 [0-7]+[lL]? Ex: 000, 0377, 01177L

  10. Floating-Point Literals • FloatingPointLiteral: • Digits . Digits? Exp? FloatType? • . Digits Exp? FloatType? • Digits Exp FloatType? • Digits Exp? FloatType • Exp: [eE] [+ -]? Digits • FloatType: [fFdD] • Digits: [0-9]+ • A FP literal is of type double unless it is suffixed with ‘F’ or ‘f’. • Ex: • 12.34e12d, 1.23E-2, <= cf: 12.34e12d • .11, .12E12f, • 12e-2, 1e12D <= cf: 0x1e12L • 33e2f, 33D Space in the literal not allowed

  11. Boolean Literals • The boolean type has two values, represented by the literals true and false, formed from ASCII letters. • A boolean literal is always of type boolean. • BooleanLiteral: • true • false

  12. Character Literals • expressed as a character or an escape sequence, enclosed in ASCII single quotes. • A character literal is always of type char. • CharacterLiteral: • ' SingleCharacter ' • ' EscapeSequence ' • SingleCharacter: • Any Character but not any of ' \ CR LF • ‘c‘ => compile-time error • It is a compile-time error for a line terminator to appear after the opening ' and before the closing '.

  13. Example: • The following are examples of char literals: • 'a' '%' '\t' '\\' '\'' • '\u03a9' '\uFFFF' '\177' '’ ‘‘ • Which of the following are correct literals: • ‘\u000a’, // this is LF • ‘\n’, // this is escape seq of LF • ‘\u000D’, // this is CR • ‘\r’ • Note: Characters written in unicode escape form ( \uxxxx ) will be converted to real chars before normal lexical analysis.

  14. String Literals • consists of zero or more characters enclosed in double quotes. • Each character may be represented by an escape sequence. • always of type String • StringLiteral: • " StringCharactersopt “ // empty string “” allowed • StringCharacters: • StringCharacter • StringCharacters StringCharacter • StringCharacter: • Any Character but not any of " \ CR LF • EscapeSequence

  15. Example: • “a b c \u000d sd \u000a” // error!! • “This is a two-line string“ //err! string can not across multilines • “ a b c \r sd \n” // OK • "" // the empty string • "\"" // a string containing " alone • "This is a string" // a string containing 16 chars • "This is a " + // actually a string-valued • “two-line strings” // constant expression, formed // from two string literals cf: we use octal literal 036 to represent int number 0x1e(= 30) but use ‘\36’ or ‘\036’ to represent char ‘\u001e’

  16. Escape Sequences for Character and String Literals • Escape sequences allow for the representation of • some nongraphic characters, (TAB, LF, CR, …) • the single quote(‘), double quote(“), and backslash(\) characters in character and string literals. • EscapeSequence: • \b /* \u0008: backspace BS */ • \t /* \u0009: horizontal tab HT */ • \n /* \u000a: linefeed LF */ • \f /* \u000c: form feed FF */ • \r /* \u000d: carriage return CR */ • \" /* \u0022: double quote " */ • \' /* \u0027: single quote ' */ • \\ /* \u005c: backslash \ */ • OctalEscape/* \u0000 to \u00ff: from octal value */

  17. Octal Escape • OctalEscape:// can represent only the first 256 chars • \ OctalDigit// [0-7] : \0 ~ \7 • \ OctalDigit OctalDigit// [0-7][0-7]: \00 ~\77 • \ ZeroToThree OctalDigit OctalDigit// [0-3][0-7][0-7] • // \000~\377

  18. The Null Literal and separators • The null type has one value, the null reference, represented by the literal null, which is formed from ASCII characters. • A null literal is always of the null type. • NullLiteral: • null Notes:Unlike C, in java • true ≠ 1 • false ≠ 0 ≠ null

  19. Operators • The following 37 tokens are the operators, formed from ASCII characters: • > < == <= >= !=// relational • + - * / %// arithmetic • ! && ||// conditional logical operations • ?:// ternary conditional operation • ++ --// PRE/POST INCR/DECR • & | ^ ~ << >> >>>// Bit and boolean operation • = += -= *= /= &= |=// Assignments ^= %= <<= >>= >>>= • x *= y + zmeans x = x * (y + z) and the like.

  20. Manipulating Numbers • In Java, to add two numbers x and y, we write x + y • Before actual addition of the two numbers, we must declare their data type. • If x and y are integer (variables), we write int x, y; or int x;int y;

  21. Variables • When the declaration is made, memory space is allocated to store the values of x and y. • x and y are called variables. • A variable has three properties: • A memory location to store the value, • The type of data stored in the memory location, and • The name used to refer to the memory location. • Sample variable declarations: int x;int v, w, y;

  22. Numerical variables • There are six numerical data types: byte, short, int, long, float, and double. • Sample variable declarations: int i, j, k;// default = 0 or no value float numberOne, numberTwo; long bigInteger; double bigNumber; • At the time a variable is declared, it also can be initialized. • int count = 10, height = 34;

  23. Data Type Precisions The six data types differ in the precision of values they can store in memory.

  24. Assignment Statements • We assign a value to a variable using an assignment statements. • The syntax is <variable> = <expression> ; • Examples: sum = firstNumber + secondNumber;avg = (one + two + three) / 3.0;

  25. Arithmetic Operators • The following table summarizes the arithmetic operators available in Java. • division: • 10 / 3 = 3; -10 / 3 = -3 • 10 / -3 = -3 ; -10 /-3 = 3. • 10 / 0  Exception 10.0 /0  +Infinite This is an integer division where the fractional part is truncated.

  26. Arithmetic Expression • How does the expression x + 3 * y get evaluated? Answer: x is added to 3*y. • We determine the order of evaluation by following the precedence rules. • A higher precedence operator is evaluated before the lower one. • the same precedence, • evaluated left to right (left association) for most operators. • Ex: 5 - 3 -2 means (5 – 3 ) – 2 instead of 5 – ( 3 – 2). • right to left (right association) • Ex: 2 ^ 3 ^ 4 means 2^(3^4)

  27. Precedence Rules

  28. The Modulo Operator: a%b • Used with integer types • Returns the remainder of the division of b by a • For example: int a = 57; b = 16 ; c = a%b; • c now has the value 9, the remainder of 57 divided by 16 • Integer / and % in java not the same as in normal arithmetic: • rules: • x = y (x/y) + x % y --- always hold. • x / y = sign(x/y) | x/ y| = x/y with fraction part removed; • x%y = x – (x/y) *y = sign(x) (|x|%|y|) always holds • ex: -10 / -3 = 3; -10 % -3 = -1; // -10 / 3 = ? ; -10 % 3 = ? • ex: 10 / -3 = -3; 10 % -3 = 1;

  29. Type Casting • If x is a float and y is an int, what will be the data type of the following expression? x * y The answer is float. • The above expression is called a mixed expression. • promotionrules for mixed expressions: • In a mixed expression, operand of low precision is automatically converted (casted; widen) into the high precision type before evaluation. • ex: 3.2 + 4 promotes to • 3.2 + (double) 4 or 3.2 + 4d

  30. Type conversions • Java allows conversions between values of various numeric types. • Except for boolean, values of all primitive types can be converted. • Basic types of conversions: • Widening conversion: • int  long; float double; char  int; … • always safe except for int float, double; longdouble. • automated performed by Java • Narrowing conversion: long  int; double  float;… • must use the cast () operators; (except for int literal, which can be downcasted to the required integral type automatically if it is inside the range of the left variable ). • not always safe. • Ex: • int i =13; byte b = i; // compiler error • short s = 134 ; // ok!! though 134 is int type, it is a literal.

  31. Use cast for narrowing conversion • Ex: • int i = 13; • byte b = (byte) i; // force i to be converted to a byte • i = (int) 13.456 // force double literal 13.456 to int 13 • i = (int) –12.6 // i == -12 • i = Integer.MAX_VALUE // i = 2147483647 • float j = i // need not cast, but data loss; j = 2.14748365E9 • j == i ? true : false // will return true! why ? • Math.round(), Math.floor(), Math.ceil() perform other types of conversion. • short v.s. char: • short s = (short) 0xffff; // s = -1; 2’s comlement • char c = ‘\uffff’; // char behaves like unsigned short • int i1 = s; // i1 = -1 • int i2 = c; // i2 = 65535

  32. Java Primitive Type Conversion rules

  33. conversion rules • precision order of numeric types • byte < (short ; char) < int < long < float < double • short and char are incomparable. • i.e., • short s; char c; • s = c // error! must use (short) c. • widening conversion • low precision  high precision • automatcally done by javac; cast () not needed • narrowing conversion • high precision  low precision • must use cast ()

  34. Type case x to float and then divide it by 3. Type cast the result of the expression x / y * 3.0 to int. Explicit Type Casting • format: • ( <data type> ) <expression> • Example (float) x / 3 (int) (x / y * 3.0)

  35. A higher precision value cannot be assigned to a lower precision variable. Implicit Type Casting • Consider the following expression: double x = 3 + 5; • The result of 3 + 5 is of type int. However, since the variable x is double, the value 8 (type int) is promoted to 8.0 (type double) before being assigned to x. • Notice that it is a promotion. Demotion is not allowed. int x = 3.5;

  36. The reserved word final is used to declare constants. These are constants, also called named constant. These are called literal constant. Constants • We can change the value of a variable. If we want the value to remain the same, we use a constant. final double PI = 3.14159;final int MONTH_IN_YEAR = 12;final short FARADAY_CONSTANT = 23060;

  37. Primitive vs. Reference • Numerical data are called primitive data types. • Objects are called reference data types, because the contents are addresses that refer to memory locations where the objects are actually stored.

  38. int firstNumber, secondNumber; A. Variables are allocated in memory. firstNumber = 234; secondNumber = 87; firstNumber 234 secondNumber A 87 B B. Values are assigned to variables. Primitive Data Declaration and Assignments State of Memory Code

  39. number 237 35 A. The variable is allocated in memory. A B B. The value 237 is assigned to number. C number = 35; C. The value 35 overwrites the previous value 237. Assigning Numerical Data int number; number = 237; State of Memory Code

  40. customer Customer Customer A B A. The variable is allocated in memory. B. The reference to the new object is assigned to customer. C C. The reference to another object overwrites the reference in customer. Assigning Objects Customer customer; customer = new Customer( ); customer = new Customer( ); State of Memory Code

  41. clemens twain Customer A B A. Variables are allocated in memory. B. The reference to the new object is assigned to clemens. C C. The reference in clemens is assigned to customer. Having Two References to a Single Object Customer clemens, twain, clemens = new Customer( ); twain = clemens; State of Memory Code

  42. int age; age = JOptionPane.showInputDialog( null, “Enter your age”); Type Mismatch • Suppose we want to input an age. Will this work? • No. String value cannot be assigned directly to an int variable.

  43. int age; String inputStr; inputStr = JOptionPane.showInputDialog( null, “Enter your age”); age = Integer.parseInt(inputStr); Type Conversion • Wrapper classesare used to perform necessary type conversions, such as converting a String object to a numerical value.

  44. Other Conversion Methods

  45. Sample Code Fragment //code fragment to input radius and output //area and circumference double radius, area, circumference; StringradiusStr = JOptionPane.showInputDialog( null, "Enter radius: " ); radius = Double.parseDouble(radiusStr); //compute area and circumference area = PI * radius * radius; circumference = 2.0 * PI * radius; JOptionPane.showMessageDialog(null, "Given Radius: " + radius + "\n" + "Area: " + area + "\n" + "Circumference: " + circumference);

  46. Overloaded Operator + • The plus operator + can mean two different operations, depending on the context. • <val1> + <val2> is an addition if both are numbers. If either one of them is a String, the it is a concatenation. • Evaluation goes from left to right. output = “test” + 1 + 2; output = 1 + 2 + “test”;

  47. double num = 123.45789345; DecimalFormat df = new DecimalFormat(“0.000”); //three decimal places 123.45789345 123.458 System.out.print(num); System.out.print(df.format(num)); The DecimalFormat Class • Use a DecimalFormat object to format the numerical output.

  48. 3.5 Standard Output • The showMessageDialog method is intended for displaying short one-line messages, not for a general-purpose output mechanism. • UsingSystem.out, we can output multiple lines of text to the standard output window.

  49. Standard Output Window • A sample standard output window for displaying multiple lines of text. • The exact style of standard output window depends on the Java tool you use.

  50. The print Method • We use the print method to output a value to the standard output window. • The print method will continue printing from the end of the currently displayed output. • Example System.out.print( “Hello, Dr. Caffeine.” );

More Related