Java Reference
In-Depth Information
Methods that Return an Array
In Java, a method may return an array. You specify the return type for a method that
returns an array in the same way that you specify a type for an array parameter. For
example, the following is an example of a method that returns an array:
public static char
[]
upperCaseVersion(
char
[]
a)
{
char
[] temp =
new char
[a.length];
char
i;
for
(i = 0; i < a.length; i++)
temp[i] = Character.toUpperCase(a[i]);
return
temp;
}
Returning an Array
A method can return an array. The details are basically the same as for a method that
returns an object of a class type.
SYNTAX (FOR A TYPICAL WAY OF RETURNING AN ARRAY)
public static
Base_Type
[]
Method_Name(Parameter_List)
{
Base_Type
[] temp =
new
Base_Type
[
Array_Size
]
<Some code to fill
temp
goes here.>
return
temp;
}
The method need not be static and need not be public. You do not necessarily need to use
a local array variable such as
temp
.
EXAMPLE (ASSUMED TO BE IN A CLASS DEFINITION)
public static int
[] incrementedArray(
int
[] a,
int
increment)
{
int
[] temp =
new int
[a.length];
int i;
for (i = 0; i < a.length; i++)
temp[i] = a[i] + increment;
return
temp;
}