What are the different ways to define an array in Java?
In Java, there are several ways to define an array.
- Array literals can be used to initialize arrays by directly listing the elements inside curly braces. For example, int[] arr = {1, 2, 3, 4, 5};
- Create and initialize an array using the new keyword: You can use the new keyword to create an array of a specific length and assign initial values to each element. For example, int[] arr = new int[5]; creates an integer array of length 5.
- Creating multi-dimensional arrays using the new keyword: You can create multi-dimensional arrays by using the new keyword multiple times. For example, int[][] matrix = new int[3][3]; creates a 3×3 two-dimensional integer array.
- Creating arrays using the static methods of the Array class: You can use the static method newInstance() of the Array class to create an array. For example, int[] arr = (int[]) Array.newInstance(int.class, 5); creates an integer array of length 5.
- Creating an array using varargs parameters: You can create an array using varargs parameters. For example, public static void printValues(int… values) can accept any number of integer parameters and store them in an integer array.
These are common ways of defining arrays, just choose the appropriate one based on your specific needs.