Question:
How do you declare an array in java?
Answer:
Here is an example on how to declare and initial arrays.
Code:
import java.util.*; public class MyArray { public static void main(String[] args) { int[] array; // declare an array (not initialized) int[] array1 = new int[3]; System.out.println("array1: " + Arrays.toString(array1)); // declare and initialize int[] array2 = {1,2,3}; System.out.println("array2: " + Arrays.toString(array2)); // declare and initialize int[] array3 = new int[]{1,2,3}; System.out.println("array3: " + Arrays.toString(array3)); // two dimensional array (not initialized) int[][] array4 = new int[4][2]; System.out.println("array4: " + Arrays.deepToString(array4)); // two dimensional array and initialized int[][] array5 = { {1,2}, {1,2}, {1,2} ,{1,2}, {1,2} }; System.out.println("array5: " + Arrays.deepToString(array5)); } }
Output:
$ java MyArray array1: [0, 0, 0] array2: [1, 2, 3] array3: [1, 2, 3] array4: [[0, 0], [0, 0], [0, 0], [0, 0]] array5: [[1, 2], [1, 2], [1, 2], [1, 2], [1, 2]]