Java Reference
In-Depth Information
5.8 Important Points
1. An array stores a number of elements of the same type.
2. Once an array is created, its size cannot be changed.
3. A method that receives an array as a parameter can modify it. These changes will be
seen by the calling method. Alternatively, a method that takes as input a variable of
primitive type, such as an integer, cannot make changes to the variable that will be
seen by the calling method.
4. A two-dimensional array is stored as an array of one-dimensional arrays. These arrays
do not need to be of the same size, but must contain elements of the same type.
5. The new operator needs to be called to create an array. The operator allocates memory
and returns an identifier (or reference) of the memory location. Although the address
of the array can change during the execution of a program, the programmer will be
unaware of this change and the array reference that is returned by the operator new
will not change.
6. An array is usually traversed using a for loop.
7. Use the for-each for loop to examine the content of an array. The loop cannot be
used to modify the array. When we need to modify an array, or we want to examine
the indices of the elements in the array, we need to use the regular for loop.
8. Arrays can be used to describe parameters to a program that are defined as constants.
For example, an array of strings is used in the Trading Game application to describe
the commodities that can be traded in the game.
9. An array can be copied using deep or shallow copy. A deep copy copies the content of
the array, while a shallow copy just makes the two arrays point to the same content.
As a general rule, always use deep copy to copy arrays.
10. Use the Arrays.equals method to compare arrays. This will perform deep compar-
ison. Alternatively, using the “==” operator will perform shallow comparison. That
is, it will just compare the addresses of the two arrays.
5.9 Exercises
1. Write a method that takes as input an array of integers and returns the third smallest
number. Write a full program to test the method.
2. Write a method that takes as input an array of strings and returns the longest string.
Write a full program to test the method. Remember that s.length() will return the
length of the string s .
3. Write a method that takes as input a string and returns the array of characters
that compose the string. Write a full program to test the method. The expression
s.charAt(i) returns the character at position i of the string s .
 
Search WWH ::




Custom Search