Java Reference
In-Depth Information
6. Write a piece of code that declares an array called data with the elements 7 , -1 , 13 , 24 , and 6 . Use only one
statement to initialize the array.
7. Write a piece of code that examines an array of integers and reports the maximum value in the array. Consider
putting your code into a method called max that accepts the array as a parameter and returns the maximum value.
Assume that the array contains at least one element.
8. Write code that computes the average (arithmetic mean) of all elements in an array of integers and returns the answer as
a double . For example, if the array passed contains the values {1, -2, 4, -4, 9, -6, 16, -8, 25, -10} , the
calculated average should be 2.5 . You may wish to put this code into a method called average that accepts an array of
integers as its parameter and returns the average.
Section 7.2: Array-Traversal Algorithms
9. What is an array traversal? Give an example of a problem that can be solved by traversing an array.
10. Write code that uses a for loop to print each element of an array named data that contains five integers:
element [0] is 14
element [1] is 5
element [2] is 27
element [3] is -3
element [4] is 2598
Consider generalizing your code so that it will work on an array of any size.
11. Write a piece of code that prints an array of integers in reverse order, in the same format as the print method from
Section 7.2. Consider putting your code into a method called printBackwards that accepts the array as a parameter.
12. Describe the modifications that would be necessary to change the count and equals methods you developed in
Section 7.2 to process arrays of String s instead of arrays of integers.
13. Write a method called allLess that accepts two arrays of integers and returns true if each element in the first array
is less than the element at the same index in the second array. Your method should return false if the arrays are not
the same length.
Section 7.3: Reference Semantics
14. Why does a method to swap two array elements work correctly when a method to swap two integer values does not?
15. What is the output of the following program?
public class ReferenceMystery1 {
public static void main(String[] args) {
int x = 0;
int[] a = new int[4];
x = x + 1;
mystery(x, a);
System.out.println(x + " " + Arrays.toString(a));
x = x + 1;
mystery(x, a);
System.out.println(x + " " + Arrays.toString(a));
}
Search WWH ::




Custom Search