Numbers and Arrays

advertisement
Numbers and Arrays
Widening and narrowing
• Numeric types are
arranged in a continuum:
Wider
double
float
long
int
short
byte, char Narrower
• You can easily assign a
narrower type to a wider
type:
double wide;
int narrow;
wide = narrow;
• But if you want to assign a
wider type to a narrow
type, you have to cast it:
narrow = (int)wide;
• You must use a cast in
both directions for byte
and char
Mixed types
• If you mix numeric types, the narrower type is
automatically promoted to the wider type
– int narrow = 5;
double wide;
double anotherWide = wide + narrow;
• Integer division is when you divide one integer
type by another; the fractional part is discarded
– Example: narrow = 19 / 5; // result is 3
Math methods
• Converting a double to an int just discards the fractional
part:
(int)17.93 is 17
(int) –17.93 is -17
• double Math.floor(double)
– Given a double, returns (as a double) the largest integral value not
greater than the argument
Math.floor(17.93) returns 17.0
Math.floor(-17.93) returns –18.0
• double Math.ceil(double)
– Given a double, returns (as a double) the smallest integral value
not smaller than the argument
Math.ceil(17.93) returns 18.0
Math.ceil(-17.93) returns –17.0
A problem with simple variables
• One variable holds one value
– The value may change over time, but at any given time,
a variable holds a single value
• If you want to keep track of many values, you
need many variables
• All of these variables need to have names
• What if you need to keep track of hundreds or
thousands of values?
Multiple values
• An array lets you associate one name with a fixed (but
possibly large) number of values
• All values must have the same type
• The values are distinguished by a numerical index
between 0 and array length minus 1
myArray
0
1
2
3
2
3
5
7
4
5
6
7
8
9
11 13 17 19 23 29
• In this example, the name myArray refers to the entire array
• Subscripted names, such as myArray[4], refer to a single
element of the array
Indexing into arrays
• To reference a single array element, use arrayname [ index ]
• Indexed elements can be used just like simple
variables
– You can access their values
– You can modify their values
• An array index is sometimes called a subscript
Using array elements
myArray
0
1
2
3
2
3
5
7
4
5
6
7
8
9
11 13 17 19 23 29
• Examples:
• x = myArray[1];
• myArray[4] = 97;
• m = 5;
y = myArray[m];
w = myArray[m + 1]
• z = myArray[myArray[3]];
// sets x to 3
// replaces 11 with 97
// sets y to 13
// sets w to 17
// sets z to 19
Array values
• An array may hold any type of value
• All values in an array must be the same type
– For example, you can have:
• an array of int
• an array of String
• an array of Person
• an array of arrays of String
• an array of Object
The End
Download