Numbers and Arrays
Widening and narrowing Numeric types are arranged in a continuum: double float long int short byte, char 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 Wider Narrower
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 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 myArray
Indexing into arrays To reference a single array element, use array- name [ 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 Examples: x = myArray[1]; // sets x to 3 myArray[4] = 97; // replaces 11 with 97 m = 5; y = myArray[m]; // sets y to 13 w = myArray[m + 1] // sets w to 17 z = myArray[myArray[3]]; // sets z to myArray
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