Integer numerical data types

advertisement
Integer numerical data types
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
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)
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
The various integer types in Java
• Integer types in Java:
Type name
(keyword)
Number of bytes
Range of values
byte
1
−128 . . . 127
short
2
−32768 . . . 32767
int
4
−2,147,483,648 . . .
2,147,483,647
long
8
−9,223,372,036,8
54,775,808 . . .
9,223,372,036,854,
775,807
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)
The various integer types in Java (cont.)
• Safe conversions:
byte ⇒ short ⇒ int ⇒ long
• Unsafe conversions:
long ⇒ int ⇒ short ⇒ byte
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
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);
}
}
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)
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 !!!
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
}
}
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)
Behind the scene of a safe and an unsafe
conversions (cont.)
• The statement y = (short) x; will achieve the following:
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)
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
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
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.
Integer operators
• Integer operators are arithmetic operators that manipulate
(operate on) integer values
• A integer operator only operates on integer values
• Specifically: An integer operator cannot operate on
floating point values (Nor can a floating point
operator operate 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)
Integer operators (cont.)
• Most of the integer (arithmetic) operators should look
familiar to you...
• (Except for the % operator)
Integer operators (cont.)
• Integer arithmetic operators:
Operator symbol
Operation
Note
+
addition
Binary operator, e.g.: 9 + 4 = 13
−
subtraction
Binary 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
( ... )
brackets
Changes order of computation
−
negation
Changes the sign of the value: −
4 = (−4)
(Read as: − 4 = negative 4)
Quotient and remainder
• From elementary school:
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
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
Quotient and remainder (cont.)
• Property of integer division:
dividend = quotient × divisor +
remainder
Example:
9/ 4= 2
-9 / 4 = -2
9 / -4 = -2
-9 / -4 = 2
9% 4= 1
-9 % 4 = -1
9 % -4 = 1
-9 % -4 = -1
9= 2*4 + 1
-9 = (-2)* 4 + (-1)
9 = (-2)*(-4) + 1
-9 = 2 *(-4) + (-1)
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,
• an integer operation
or
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)
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)
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:
9 / 5.0 (2 types of operands: integer and floating
point)
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.
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
Priority and associativity of the integer
arithmetic operators (cont.)
• Priority of the integer arithmetic operators:
Operator
Priority
Note
( .... )
Highest
− (negation)
Higher
Unary operator,
e.g.: −3
* / %
High
Binary operator,
e.g.: 4 * 5
+ −
Lowest
Binary operator,
e.g.: 4 + 5
Priority and associativity of the integer
arithmetic operators (cont.)
• Example 1:
Integer expression:
72 / 10 + 72 % 10
Evaluated as follows:
72 / 10 + 72 % 10
= 7 + 72 % 10
=7+2
=9
(This is how you compute the sum of the digits in the number
72 !!!)
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
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
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
Example using integers: convert seconds to
(hours, minutes, seconds)
• Problem description:
• Given n seconds
• Compute the number of hours, number of
minutes and number of seconds in n seconds
Example:
n = 15432 seconds
15432 = 4*(60*60) + 17*(60) + 12
= 4 hours + 17 minutes + 12 seconds
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.
• You can verify an algorithm by running the
algorithm by hand with a small example
• After you have Verify that the algorithm in pseudo code is
correct,
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 !!
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
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....)
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
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;
hours = n;
// n is now = remaining hours
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
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;
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.");
}
}
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
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
Programming example: tell the time of the day
(cont.)
• Problem description:
• Find the current time HH:MM:SS GMT
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
n = n / 60 = 100000 / 60 = 1666
*** part of answer
(total # minutes)
3. Find minutes in current time:
minutes = n % 60 = 1666 / 60 = 46
n = n / 60 = 1666 % 60 = 27
*** part of answer
(total # hours)
3. Find hours in current time:
hours = n % 27 = 27 % 24 = 3
*** part of answer
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
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
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");
}
}
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
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
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.
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.
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.
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.
Quiz: can you spot what is wrong with this
program
• Java program with an error:
public class Caveat2
{
public static void main(String[] args)
{
short a, b, c;
a = 2;
b = 3;
c = a + b;
}
}
// Compilation error !
Can you see why the statement c = a + b will cause a
compilation error ?
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);
Quiz: can you spot what is wrong with this
program (cont.)
• Note:
• This solution will not work:
c = (short) a + b;
because the casting operator (short) has a higher
priority than the + operation
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
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;
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;
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));
}
}
Exercise (cont.)
• Answers:
16
5
4
3
180
168
180
0
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
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
Programming trick: divisibility of numbers
• Examples:
12 is divisible by 2
12 is divisible by 3
12 is divisible by 4
12 is not divisible by 5
12 is divisible by 6
12 is not divisible by 7






12 % 2 = 0
12 % 3 = 0
12 % 4 = 0
12 % 5 = 2
12 % 6 = 0
12 % 7 = 5
Later in the course, we will use this property to find all
divisors of a number.
Overflow
• Range of the integer types in Java:
Type name
(keyword)
Number of bytes
Range of values
byte
1
−128 . . . 127
short
2
−32768 . . . 32767
int
4
−2,147,483,648 . . .
2,147,483,647
long
8
−9,223,372,036,8
54,775,808 . . .
9,223,372,036,854,
775,807
Overflow (cont.)
• When an operation results in a value that is outside the
range of a variable, then there is an overflow error
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);
}
}
Overflow (cont.)
• Output:
-1294967296
3000000000
(not 3000000000 !!!)
• Explanation:
• 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
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
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.
Download