Download presentation
Presentation is loading. Please wait.
Published byJune Craig Modified over 9 years ago
1
Integer numerical data types
2
The integer data types (multiple !) The integer data types use the binary number system as encoding method There are a number of different integer types in Java The difference between the various integer types is in the size I.e., the number of bytes used in the encoding
3
The integer data types (multiple !) (cont.) Warning: Java considers an integer data type of different sizes as different data types !!! (We saw this also when we discussed the float and double)
4
The integer data types (multiple !) (cont.) The integer data types have very similar properties and operations as the floating point data types (float and double I will only highlight the differences I will be brief on properties and operations that are similar
5
The various integer types in Java Integer types in Java: Type name (keyword) Number of bytes Range of values byte1−128... 127 short2−32768... 32767 int4−2,147,483,648... 2,147,483,647 long8 −9,223,372,036,8 54,775,808... 9,223,372,036,854, 775,807
6
The various integer types in Java (cont.) Note: There is a strict hierarchy among the integer types: The byte type is the least accurate integer type The short type is the more accurate than the byte type The int type is the more accurate than the short type (and the byte type) The long type is the more accurate than the int type (and short and byte)
7
The various integer types in Java (cont.) Safe conversions: Unsafe conversions: byte ⇒ short ⇒ int ⇒ long long ⇒ int ⇒ short ⇒ byte
8
The various integer types in Java (cont.) Remember that in an arithmetic expression involving different types of values, Java will automatically convert a lower accuracy typed value to the higher accuracy type In other words: auto convert to byte value + short value -----------------> short value + short value byte value + int value -----------------> int value + int value... short value + int value -----------------> int value + int value
9
Behind the scene of a safe and an unsafe conversions Example of a safe conversion: public class Safe { public static void main(String[] args) { int x; short y; y = 1; x = y; // Safe conversion System.out.println(x); }
10
Behind the scene of a safe and an unsafe conversions (cont.) What happens inside the computer (behind the scene): The variable y is of the type short and has 16 bits It is assigned the value 1: (The bit pattern 00000000 00000001 encodes the number 1 in using 16 bits)
11
Behind the scene of a safe and an unsafe conversions (cont.) The statement x = y; will achieve the following: This statement copies the value from a short typed variable into an more accurate (wider) int typed variable. You cannot loose accuracy !!!
12
Behind the scene of a safe and an unsafe conversions (cont.) Example of an unsafe conversion: public class UnSafe { public static void main(String[] args) { int x; // x uses 4 bytes short y; // y uses 2 bytes x = 65538; // 65538 = 2^16 + 2 // Binary: 00000000 00000001 00000000 00000010 y = (short) x; // Unsafe conversion // y = 00000000 00000010 (lower half of x) // (Correct only for numbers < 65535) System.out.println(y); //***** Prints 2 !!! // Because 00000000 00000010 is equal to 2 }
13
Behind the scene of a safe and an unsafe conversions (cont.) What happens inside the computer (behind the scene): The variable x is of the type int and has 32 bits It is assigned the value 65538: (The bit pattern 00000000 00000001 00000000 00000010 encodes the number 65538 in using 32 bits)
14
Behind the scene of a safe and an unsafe conversions (cont.) The statement y = (short) x; will achieve the following:
15
Behind the scene of a safe and an unsafe conversions (cont.) This statement copies the last 16 bits from a int typed variable into an less accurate (narrower) 16 bits short typed variable. You have lost the upper 16 bits bits from the int type variable !!! The conversion will result in incorrect value for large values (values > 65535)
16
Behind the scene of a safe and an unsafe conversions (cont.) Example Program: (Demo above code) –Prog file: http://mathcs.emory.edu/~cheung/Courses/170/Syllabus/04/Progs/ UnSafe.java How to run the program: Right click on link and save in a scratch directory To compile: javac UnSafe.java To run: java UnSafe
17
Reading integer input from the keyboard The steps to read in an integer value from the keyboard is the same as those described for floating point values The only differences are: You need to define an int typed variable to receive the input (because we are reading in an integer number) You need to use the nextInt() method which will read in an integer value
18
Reading integer input from the keyboard (cont.) Summary of the steps to read in an integer value: We will look at an example a little bit later.
19
Integer operators Integer operators are arithmetic operators that manipulate (operate on) integer values A integer operator only operates on integer values The result of an integer operator is always an integer value (And the result of an floating point operator is always a floating point value) Specifically: An integer operator cannot operate on floating point values (Nor can a floating point operator operate on integer values)
20
Integer operators (cont.) Most of the integer (arithmetic) operators should look familiar to you... (Except for the % operator)
21
Integer operators (cont.) Integer arithmetic operators: Operator symbol OperationNote +additionBinary operator, e.g.: 9 + 4 = 13 −subtractionBinary operator, e.g.: 9 − 4 = 5 * multiplication Binary operator, e.g.: 9 * 4 = 36 / division (= quotient)Binary operator, e.g.: 9 / 4 = 2 %modulus (= remainder)Binary operator, e.g.: 9 % 4 = 1 (... )bracketsChanges order of computation −negationChanges the sign of the value: − 4 = (−4) (Read as: − 4 = negative 4)
22
Quotient and remainder From elementary school:
23
Quotient and remainder (cont.) The / operator (quotient) will always produce an integer result It does so by truncating the floating point division Examples: 9 / 4 = (floating point result = 2.25) = 2 -9 / 4 = (floating point result = -2.25) = -2 9 / -4 = (floating point result = -2.25) = -2 -9 / -4 = (floating point result = 2.25) = 2
24
Quotient and remainder (cont.) The % operator (remainder) will also produce an integer result The sign of the result is always equal to the sign of the dividend Examples: 9 % 4 = (floating point result = 2.25) = 1 -9 % 4 = (floating point result = -2.25) = -1 9 % -4 = (floating point result = -2.25) = 1 -9 % -4 = (floating point result = 2.25) = -1
25
Quotient and remainder (cont.) Property of integer division: Example: dividend = quotient × divisor + remainder 9 / 4 = 2 9 % 4 = 1 9 = 2 * 4 + 1 -9 / 4 = -2 -9 % 4 = -1 -9 = (-2)* 4 + (-1) 9 / -4 = -2 9 % -4 = 1 9 = (-2)*(-4) + 1 -9 / -4 = 2 -9 % -4 = -1 -9 = 2 *(-4) + (-1)
26
How to tell if "+", "-", "*" and "/" is a floating point or an integer operation You must have noticed that the "+", "-", "*" and "/" can represent: a floating point operation, or an integer operation
27
How to tell if "+", "-", "*" and "/" is a floating point or an integer operation (cont.) Special emphasis: The Java compiler (and you also) can tell the difference between integer division and floating point division by the operands used. Example 1: 9 / 5 (Operands are 2 integers => / is integer division) 9.0 / 5.0 (Operands are 2 floating point numbers => / floating point division)
28
How to tell if "+", "-", "*" and "/" is a floating point or an integer operation (cont.) Example 2: int a, b; double x, y; a / b (Operands are 2 integers ⇒ / is integer division) x / y (Operands are 2 floating point numbers ⇒ / floating point division)
29
How to tell if "+", "-", "*" and "/" is a floating point or an integer operation (cont.) The computer does not have any instructions that operates on operands of different types. Example: this operations cannot be performed directly: One of the operands must be converted into the other type before the operation can be performed. We focus on integer-only operations in this webnote. We will delay this discussion of mixed types operations for the next webnote. 9 / 5.0 (2 types of operands: integer and floating point)
30
Priority and associativity of the integer arithmetic operators Each arithmetic operator in Java has a priority and an associativity Operator priority was discussed in: http://mathcs.emory.edu/~cheung/Courses/170/Syllabu s/04/float-expr.html#priority Operator associativity was discussed in: http://mathcs.emory.edu/~cheung/Courses/170/Syllabu s/04/float-expr.html#associativity
31
Priority and associativity of the integer arithmetic operators (cont.) Priority of the integer arithmetic operators: Operator PriorityNote (.... )Highest − (negation)Higher Unary operator, e.g.: −3 * / %High Binary operator, e.g.: 4 * 5 + −Lowest Binary operator, e.g.: 4 + 5
32
Priority and associativity of the integer arithmetic operators (cont.) Example 1: (This is how you compute the sum of the digits in the number 72 !!!) Integer expression: 72 / 10 + 72 % 10 Evaluated as follows: 72 / 10 + 72 % 10 = 7 + 72 % 10 = 7 + 2 = 9
33
Priority and associativity of the integer arithmetic operators (cont.) Example 2: using the negation operator Integer expression: 22 - - 3 * - 4 + - - 1 Evaluated as follows: 22 - - 3 * - 4 + - - 1 = 22 - (-3) * - 4 + - - 1 = 22 - (-3) * (-4) + - - 1 = 22 - (-3) * (-4) + - (-1) = 22 - (-3) * (-4) + (+1) = 22 - 12 + 1 (Use associativity rule) = 10 + 1 = 11
34
Priority and associativity of the integer arithmetic operators (cont.) Example 3: using brackets Integer expression: (22 - - 3) * - (4 + - - 1) Evaluated as follows: (22 - - 3) * - (4 + - - 1) = (22 - (-3)) * - (4 + - - 1) = (22 - (-3)) * - (4 + - (-1)) = (22 - (-3)) * - (4 + 1) = 25 * - (4 + 1) = 25 * - 5 = 25 * (-5) = -125
35
Priority and associativity of the integer arithmetic operators (cont.) Example Program: (Demo above code) –Prog file: http://mathcs.emory.edu/~cheung/Courses/170/Syllabus/04/Progs/ Priority02.java How to run the program: Right click on link and save in a scratch directory To compile: javac Priority02.java To run: java Priority02
36
Example using integers: convert seconds to (hours, minutes, seconds) Problem description: Given n seconds Example: Compute the number of hours, number of minutes and number of seconds in n seconds n = 15432 seconds 15432 = 4*(60*60) + 17*(60) + 12 = 4 hours + 17 minutes + 12 seconds
37
Example using integers: convert seconds to (hours, minutes, seconds) (cont.) Advice on developing algorithms: Use a concrete example to discover the steps that need to be performed to solve the problem. Determine the steps that you must do to complete the task (solve the problem) Write down the steps in "psuedo code" (see below) Verify that the algorithm in pseudo code is correct. After you have Verify that the algorithm in pseudo code is correct, You can verify an algorithm by running the algorithm by hand with a small example
38
Example using integers: convert seconds to (hours, minutes, seconds) (cont.) Pseudo code: Pseudo code is a compact and informal high-level description of an algorithm Pseudo code uses the structural conventions of a programming language, but is intended for human reading (rather than machine reading). Pseudo code omits details that are not essential for human understanding of the algorithm, such as variable declarations In other words: Pseudo code are commands that are easy for humans to follow (no complex descriptions) Pseudo code are not Java statements !!
39
Example using integers: convert seconds to (hours, minutes, seconds) (cont.) Pseudo code is made up by yourself There is no "standard pseudo code" Requirement for pseudo code: An algorithm in pseudo code must be easily translated into any programming language
40
Example using integers: convert seconds to (hours, minutes, seconds) (cont.) Purpose: rapid prototyping algorithms An algorithm written in pseudo code is very easy to change You can correct errors easily in an algorithm written in pseudo code (Trust me, correcting errors in a large computer program is a pain - talk to someone in Microsoft....)
41
Example using integers: convert seconds to (hours, minutes, seconds) (cont.) Use a concrete example to determine the steps used to find (hours, minutes, seconds): Let n = 15432 seconds 1. We can find the # seconds as follows: 257 ------------- 60 / 15432 15420 -------- 12 So: 15432 seconds = 257 minutes + 12 seconds Or: 15432 seconds = 15432/60 minutes + 15432/60 seconds 2. Next we convert the remaining 257 minutes into hours: 4 -------- 60 / 257 240 ---- 17 Therefore: 257 minutes = 257/60 hours + 257%60 minutes
42
Example using integers: convert seconds to (hours, minutes, seconds) (cont.) Pseudo code: input n; // n = total number of seconds seconds = n % 60; // computes seconds n = n / 60; // n is now = remaining minutes minutes = n % 60; // computes minutes n = n / 60; // n is now = remaining hours hours = n;
43
Example using integers: convert seconds to (hours, minutes, seconds) (cont.) Verify the algorithm (in pseudo code): (use a small example, e.g. n = 15432) n = 15432; hours = 15432 / 3600 = 4 r = 15432 % 3600 = 1032 minutes = 1032 / 60 = 17 seconds = 1032 % 60 = 12
44
Example using integers: convert seconds to (hours, minutes, seconds) (cont.) Write the algorithm in Java (translate from pseudo code): import java.util.Scanner; public class Hours { public static void main(String[] args) { int n, r, hours, minutes, seconds; Scanner in = new Scanner(System.in); System.out.print("Enter # seconds: "); n = in.nextInt(); // in.nextInt() reads in an integer value seconds = n % 60; // computes seconds n = n / 60; // n is now = remaining minutes minutes = n % 60; // computes minutes n = n / 60; // n is now = remaining hours hours = n;
45
Example using integers: convert seconds to (hours, minutes, seconds) (cont.) System.out.print(n); System.out.print(" seconds = "); System.out.print(hours); System.out.print(" hours + "); System.out.print(minutes); System.out.print(" minutes+ "); System.out.print(seconds); System.out.println(" seconds."); }
46
Example using integers: convert seconds to (hours, minutes, seconds) (cont.) Example Program: (Demo above code) –Prog file: http://mathcs.emory.edu/~cheung/Courses/170/Syllabus/04/Progs/ Hours.java How to run the program: Right click on link and save in a scratch directory To compile: javac Hours.java To run: java Hours
47
Programming example: tell the time of the day Preliminary: The method System.currentTimeMillis() will return the following value: System.currentTimeMillis() returns the number of milli seconds (1/1000 second) since midnight, Jan 1 1970 in GMT
48
Programming example: tell the time of the day (cont.) Problem description: Find the current time HH:MM:SS GMT
49
Programming example: tell the time of the day (cont.) Use a concrete example to determine the steps used to find (hours, minutes, seconds): Let n = 100000000 millisec 1. Find total number of seconds since midnight, Jan 1 1970: n = n / 1000 = 100000000 / 1000 = 100000 (total # seconds) 2. Find seconds in current time: seconds = n % 60 = 100000000 % 1000 = 40 *** part of answer n = n / 60 = 100000 / 60 = 1666 (total # minutes) 3. Find minutes in current time: minutes = n % 60 = 1666 / 60 = 46 *** part of answer n = n / 60 = 1666 % 60 = 27 (total # hours) 3. Find hours in current time: hours = n % 27 = 27 % 24 = 3 *** part of answer
50
Programming example: tell the time of the day (cont.) Algorithm in pseudo code: n = System.currentTimeMillis(); // n = total # milli sec n = n / 1000; // n is now = total # sec seconds = n % 60; // Compute seconds in current time n = n / 60; // n is now = total # minutes minutes = n % 60; // Compute minutes in current time n = n / 60; // n is now = total # hours hours = n % 60; // Compute hours in current time
51
Programming example: tell the time of the day (cont.) Java program: public class ShowCurrentTime { public static void main(String[] args) { long nMillis; // We need long for accuracy !!! long n, hours, minutes, seconds; nMillis = System.currentTimeMillis(); n = nMillis/1000; // Total # Second; seconds = n % 60; // Seconds n = n / 60; // Total # minutes; minutes = n % 60; // Minutes n = n / 60; // Total # hours; hours = n % 24; // Hours
52
Programming example: tell the time of the day (cont.) System.out.print(hours); System.out.print(":"); System.out.print(minutes); System.out.print(":"); System.out.print(seconds); System.out.println(" GMT"); }
53
Programming example: tell the time of the day (cont.) Example Program: (Demo above code) –Prog file: http://mathcs.emory.edu/~cheung/Courses/170/Syllabus/04/Progs/ ShowCurrentTime.java How to run the program: Right click on link and save in a scratch directory To compile: javac ShowCurrentTime.java To run: java ShowCurrentTime
54
Automatic conversion to int in arithmetic operations It is extremely inconvenient for programmers to have to write conversion operations when values of different integer types are used in the same arithmetic expression Java makes writing programs less painful by providing a number of automatic integer conversions
55
Automatic conversion to int in arithmetic operations (cont.) Java's automatic integer conversion in arithmetic operations: Arithmetic operations on integer types: All values are converted to int type before an arithmetic operation (+, −, *, /, %) in performed. However, if one of the values in an arithmetic operation is long, then all values are converted to long type before the arithmetic operation in performed.
56
Automatic conversion to int in arithmetic operations (cont.) Example 1: short a = 2; int b = 3, c; c = a + b; // a (short) is first converted to an int value // Then the addition is performed.
57
Automatic conversion to int in arithmetic operations (cont.) Example 2: short a = 2, b = 2; int c; c = a + b; // a and b (short) is first converted to an int value // Then the addition is performed.
58
Automatic conversion to int in arithmetic operations (cont.) Example 3: int a = 2; long b = 3, c; c = a + b; // a (int) is first converted to an long value // Then the addition is performed.
59
Quiz: can you spot what is wrong with this program Java program with an error: Can you see why the statement c = a + b will cause a compilation error ? public class Caveat2 { public static void main(String[] args) { short a, b, c; a = 2; b = 3; c = a + b; // Compilation error ! }
60
Quiz: can you spot what is wrong with this program (cont.) Answer: Because all value are first converted to int, the RHS a + b will produce a result that is of the type int The receiving variable c has the type short A int typed value cannot be assigned to a short typed variable We must use a casting operator: c = (short) (a + b);
61
Quiz: can you spot what is wrong with this program (cont.) Note: This solution will not work: because the casting operator (short) has a higher priority than the + operation c = (short) a + b;
62
Automatic type conversion in the assignment operation The automatic safe conversion rule of the assignment operator = is also applicable to integer types Recall the safe integer conversions are: byte ⇒ short ⇒ int ⇒ long
63
Automatic type conversion in the assignment operation (cont.) These assignments are allowed: (because they are safe): long a; int b; short c; byte d; /* --------------------------------- Automatic conversion happens in all the following assignments --------------------------------- */ a = b; a = c; a = d; b = c; b = d; c = d;
64
Automatic type conversion in the assignment operation (cont.) You need casting operators to perform the following (unsafe) assignments: long a; int b; short c; byte d; /* ----------------------------------- Unsafe assignment requires casting ------------------------------------ */ b = (int) a; c = (short) a; c = (short) b; d = (byte) a; d = (byte) b; d = (byte) c;
65
Exercise What is the output of the following program public class Exercise1 { public static void main(String[] args) { int a = 15; int b = 24; System.out.println(b - a + 7); System.out.println(b - a - 4); System.out.println(b % a / 2); System.out.println(b % (a / 2)); System.out.println(b * a / 2); System.out.println(b * (a / 2)); System.out.println(b / 2 * a); System.out.println(b / (2 * a)); }
66
Exercise (cont.) Answers: 16 5 4 3 180 168 180 0
67
Exercise (cont.) Example Program: (Demo above code) –Prog file: http://mathcs.emory.edu/~cheung/Courses/170/Syllabus/04/Progs/ Exercise1.java How to run the program: Right click on link and save in a scratch directory To compile: javac Exercise1.java To run: java Exercise1
68
Programming trick: divisibility of numbers Fact: If a number x is divisible by the number d, then the remainder of the division of x by d is equal to zero
69
Programming trick: divisibility of numbers Examples: Later in the course, we will use this property to find all divisors of a number. 12 is divisible by 2 12 % 2 = 0 12 is divisible by 3 12 % 3 = 0 12 is divisible by 4 12 % 4 = 0 12 is not divisible by 5 12 % 5 = 2 12 is divisible by 6 12 % 6 = 0 12 is not divisible by 7 12 % 7 = 5
70
Overflow Range of the integer types in Java: Type name (keyword) Number of bytes Range of values byte1−128... 127 short2−32768... 32767 int4−2,147,483,648... 2,147,483,647 long8 −9,223,372,036,8 54,775,808... 9,223,372,036,854, 775,807
71
Overflow (cont.) When an operation results in a value that is outside the range of a variable, then there is an overflow error
72
Overflow (cont.) Example: public class Overflow { public static void main(String[] args) { int x, y, z; long a, b, c; x = 1000000; y = 3000; z = x * y; // 3,000,000,000 is outside the range of int System.out.println(z); a = 1000000; b = 3000; c = a * b; // 3,000,000,000 is within the range of long System.out.println(c); }
73
Overflow (cont.) Output: Explanation: -1294967296 (not 3000000000 !!!) 3000000000 You need more than 32 bits to represent the value 3,000,000,000 in the binary number system We do not have sufficient number of bits in an int variable to represent the value 3,000,000,000
74
Overflow (cont.) Example Program: (Demo above code) –Prog file: http://mathcs.emory.edu/~cheung/Courses/170/Syllabus/04/Progs/ Overflow.java How to run the program: Right click on link and save in a scratch directory To compile: javac Overflow.java To run: java Overflow
75
Overflow (cont.) What can you do about overflow ? You must know how large the values can be If you are not sure, then use the largest possible data type available.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.