/** This program demonstrates the usage of arrays in Java * @author A. T. Ozgelen */ import java.util.Arrays; public class ArrayDemo { public static void main(String[] args) { // checking the size of an array using length. if(args.length == 0) { System.out.println("Usage: java ArrayDemo "); System.exit(1); } // declaring an array int[] intArray; // this is considered to be the better form double doubleArray[]; // this too is legal // initializing an array intArray = new int[10]; // allocates the memory for 100 int values, all initialized to 0 doubleArray = new double[] {1.2, 3.1, 5.0}; // allocates and initializes the values for 3 double types // accessing and printing elements of an array System.out.println("doubleArray:"); for(int i = 0; i < doubleArray.length; i++) System.out.print(doubleArray[i] + " "); System.out.println("\n"); // using for(each) loop System.out.println("intArray:"); for(int elem: intArray) System.out.print(elem + " "); System.out.println("\n"); // using toString() method of Arrays class System.out.println("intArray using .toString():"); System.out.println(Arrays.toString(intArray) + "\n"); // assigning an array to another just creates another reference to the same array, // in other words, it does not create another copy as might be expected! int[] otherIntArray = intArray; intArray[2] = 5; System.out.println("otherIntArray[2]:" + otherIntArray[2]); System.out.println("intArray using .toString():"); System.out.println(Arrays.toString(intArray) + "\n"); // making a copy of an array int[] copyIntArray = Arrays.copyOf(intArray, intArray.length); intArray[2] = 7; System.out.println("intArray[2]:" + intArray[2]); System.out.println("copyIntArray[2]:" + copyIntArray[2]); } }