Java Reference
In-Depth Information
The above method may be called as follows:
int[] ids = {10, 15, 19};
String str = arrayToString(ids); // Pass ids int array to arrayToString() method
Because an array is an object, the array reference is passed to the method. The method, which receives an array
parameter, can modify the elements of the array. Listing 15-4 illustrates how a method can change the elements of its
array parameter; this example also shows how to implement the swap() method to swap two integers using an array.
Listing 15-4. Passing an Array as a Method Parameter
// Swap.java
package com.jdojo.array;
public class Swap {
public static void main(String[] args) {
int[] num = {17, 80};
System.out.println("Before swap");
System.out.println("#1: " + num[0]);
System.out.println("#2: " + num[1]);
// Call the swpa() method passing teh num array
swap(num);
System.out.println("After swap");
System.out.println("#1: " + num[0]);
System.out.println("#2: " + num[1]);
}
// The swap() method accepts an int array as argument and swaps the values
// if array contains two values.
public static void swap (int[] source) {
if (source != null && source.length == 2) {
// Swap the first and the second elements
int temp = source[0];
source[0] = source[1];
source[1] = temp;
}
}
}
Before swap
#1: 17
#2: 80
After swap
#1: 80
#2: 17
 
Search WWH ::




Custom Search