Short syntax for array initialization
We can use Java’s shortcut syntax for declaring and initializing arrays with specific values. Instead of declaring and initializing the array separately, we can use curly braces ({}
) to specify the elements directly. Take a look at the following example:
int[] ages = {31, 7, 5, 1, 0};
This code creates an array of integers and initializes it with the specified values. The size of the array is determined by the number of elements inside the curly braces.
Actually, our previous arrays had values already as well, because when you create an array using the new
keyword, Java automatically initializes the elements with default values based on their data type. The default values are as follows:
- Numeric types (
byte
,short
,int
,long
,float
,double
):0
or0.0
char
: ‘\u0000
’ (the Unicodenull
character)boolean
:false
- Reference types (objects and arrays):
null
For example, say you create an array of...