Java Reference
In-Depth Information
easier to read, it is used in this topic's examples as in the following, which declares a
method that returns an integer array:
int[] makeRange(int lower, int upper) {
// body of this method
}
You can have statements, expressions, method calls on other objects, conditionals, loops,
and so on inside the body of the method.
Unless a method has been declared with void as its return type, the method returns some
kind of value when it is completed. This value must be explicitly returned at some exit
point inside the method, using the return keyword.
Listing 5.2 shows RangeLister , a class that defines a makeRange() method. This method
takes two integers—a lower boundary and an upper boundary—and creates an array that
contains all the integers between those two boundaries. The boundaries themselves are
included in the array of integers.
LISTING 5.2
The Full Text of RangeLister.java
1: class RangeLister {
2: int[] makeRange(int lower, int upper) {
3: int[] range = new int[(upper-lower) + 1];
4:
5: for (int i = 0; i < range.length; i++) {
6: range[i] = lower++;
7: }
8: return range;
9: }
10:
11: public static void main(String[] arguments) {
12: int[] range;
13: RangeLister lister = new RangeLister();
14:
15: range = lister.makeRange(4, 13);
16: System.out.print(“The array: [ “);
17: for (int i = 0; i < range.length; i++) {
18: System.out.print(range[i] + “ “);
19: }
20: System.out.println(“]”);
21: }
22:
23: }
5
 
Search WWH ::




Custom Search