Instructor: Dan Shiovitz
Name: _____________________________________________________________
null
and how is it used?
null
is a Java reserved word referring to the
empty reference. When a reference is created (on its own or
in an array) it is initialized to null
if no
explicit value is given. If you store null
into
an array location, it replaces whatever was there
previously, which generally means that object will be garbage
collected (ie, deleted). But this occurs no matter what you
assign into the array location: the old object will always
be removed.
Vector
objects.
Card[] gin = new Card[7]; gin[1] = new Card('A', "Clubs"); gin[2] = new Card('2', "Diamonds"); gin[5] = new Card('5', "Hearts");Ok, hmm. Every single person lost a point for forgetting that the length of an array is part of its memoryspace. Also, it's important to remember that empty spots in an array are initialized to
null
, and that names are references, and only
refer to the actual object indirectly. The actual diagram might look
something like this:
gin [ reference ] --------------+ | v ------------------------------------------------------------------- | length: -------------------------------------------------- | | 7 | | refer| refer| | | refer| | | | | null | ence | ence | null | null | ence | null | | | | | | | | | | | | | | | | ----------|------|--------------------|----------- | ----------------------|------|--------------------|---------------- | | | v +--v +-----------v ------ ------ ------ |Card| |Card| |Card| | 'A'| | '2'| | '5'| "Clubs"<----- | | ---->"Diamonds" "Hearts"<--- | ------ ------ ------
Show the output for the code fragment below in the box provided. Show a trace of your execution for partial credit (the more information given, the more likely we can follow your output).
char[][] grid = {{'Z', 'Y', 'X'}, {'W', 'V', 'U'}, {'T', 'S', 'R'}}; for (int i = 0; i < 3; i++) { for (int j = 2; j >= 0; --j) System.out.print(grid[j][i]); System.out.println(); }
RUX SVY TWZ
Write a static method that returns the number of values in an array which are below the mean value of the elements of the array. So, for instance, given the array [1 5 2 3 4], the method would return 2, since 1 and 2 are below the average (3) of the array. The method is passed one parameter, an array of integers, and you may assume all elements in the array have been initialized with positive values, and that the array has at least one element.
Also pretty straightforward, I hope.
public static int belowMean(int[] array) { int total = 0, mean = 0, count = 0; for (int i = 0; i < array.length; i++) total += array[i]; mean = total / array.length; // int division is ok here. why? for (int i = 0; i < array.length; i++) if (array[i] < mean) count++; return count; }