Printing a Java array

Suppose you have have the following arrays

int[] a = new int[] {1, 2, 3};
String[] b = new String[] {"a", "b", "c"};

The easiest way to print the arrays would be to:

import java.util.Arrays;

class PrintArray {
    public static void main(String[] args) {
    	int[] a = new int[] {1, 2, 3};
    	String[] b = new String[] {"a", "b", "c"};
    	System.out.println(Arrays.toString(a));
    	System.out.println(Arrays.toString(b));
    }
}

output

[1, 2, 3]
[a, b, c]

If you are using Java 4 or earlier, you can use the following code:

import java.util.Arrays;

class PrintArray {
    public static void main(String[] args) {
    	int[] a = new int[] {1, 2, 3};
    	String[] b = new String[] {"a", "b", "c"};
			Integer[] c = new Integer[] {new Integer(1), new Integer(2)};
    	System.out.println(Arrays.asList(a));
    	System.out.println(Arrays.asList(b));
			System.out.println(Arrays.asList(c));
    }
}

output

[[I@5b565b56]
[a, b, c]
[1, 2]

As you can see from the output. Arrays.asList() does not work with primitive types.

class PrintArray {
    	int[] a = new int[] {1, 2, 3};
    	String[] b = new String[] {"a", "b", "c"};
    	Integer[] c = new Integer[] {new Integer(1), new Integer(2)};

    	for (int i = 0; i < a.length; i++) {
    		System.out.print(a[i] + " ");
    	}
    	System.out.println();
    	
    	for (int i = 0; i < b.length; i++) {
    		System.out.print(b[i] + " ");
    	}
    	System.out.println();
    	
    	for (int i = 0; i < c.length; i++) {
    		System.out.print(c[i] + " ");
    	}
    }
}

This old fashion code will work for primitives and objects and with any version of Java.