Passing an Array as a Method Parameter - Java Object Oriented Design

Java examples for Object Oriented Design:Method Parameter

Description

Passing an Array as a Method Parameter

Demo Code

public class Main {
  public static void main(String[] args) {
    int[] num = {7, 8};

    System.out.println("Before swap");  
    System.out.println("#1: " + num[0]);
    System.out.println("#2: " + num[1]);
    /*w  w  w.  j  a  v a  2s.c  om*/
    // Call the swpa() method passing the num array
    swap(num);  

    System.out.println("After swap");  
    System.out.println("#1: " + num[0]);
    System.out.println("#2: " + num[1]);
  }

  // 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;
    }
  }
}

Result


Related Tutorials