How to define an array in Java?
In Java, you can define an array using the following method:
- To declare an array variable, use the type of array and square brackets [], then use the keyword new to create the array object. For example, you can declare and create an integer array using the following syntax:
- Declare and create an integer array with a length of 5.
- You can use braces {} to directly initialize the values of array elements. For example, you can declare and initialize a string array as follows:
- Declare and initialize a string array with the names “Alice”, “Bob”, and “Charlie”.
Important points to remember:
- The size of an array (i.e. the number of elements) is determined when the array object is created, and once it is determined, the size of the array cannot be changed.
- The array index starts from 0 and the maximum index is the size of the array minus 1.
- An array can store different types of data, but typically, an array only stores one type of data.