Java Reference
In-Depth Information
7. SomeClass.doSomething(number); //Legal.
SomeClass.doSomething(a[2]); //Legal.
SomeClass.doSomething(a[3]); //Illegal. Index out of bounds.
SomeClass.doSomething(a[number]); //Legal.
SomeClass.doSomething(a); //Illegal.
8. public static void oneMore( int [] a)
{
for ( int i = 0; i < a.length; i++)
a[i] = a[i] + 1;
}
9. public static int outOfOrder( double [] a)
{
for ( int index = 0; index < a.length
1; index++)
if (a[index] > a[index + 1])
return (index + 1);
return
1;
}
10. This method is legal but pointless. When invoked, it has no effect on its argu-
ment. The parameter a is a local variable that contains a reference. The reference
does indeed get changed to a reference to an array of double the size of the argu-
ment, but that reference goes away when the method ends. A method can
change the values of the indexed variables of its argument, but it cannot change
the reference in the array variable used as an argument.
11. public static double [] halfArray( double [] a)
{
double [] temp = new double [a.length];
for ( int i = 0; i < a.length; i++)
temp[i] = a[i]/2.0;
return temp;
}
12. The method will compile and run. The array returned has the correct values for
its elements. However, the method will change the values of its array argument.
If you want to change the values in the array argument, a void method would
make more sense. If you want to return an array, you should probably return a
new array (as in the version in the previous subsection), not return a changed
version of the argument array.
13. /**
Precondition: numberUsed <= argumentArray.length;
the first numberUsed indexed variables of argumentArray
have values.
Returns an array of length numberUsed whose ith element
is argumentArray[i] - adjustment.
*/
Search WWH ::




Custom Search