Last Updated: 26 March, 2023
In Java, an anonymous array is an array that is created without explicitly assigning it to a variable. Instead, it is created directly as an argument to a method or as a value in an expression.
Syntax to create single-dimensional anonymous array
new <data type>[] { <list of values with comma separator> };
Syntax to create multidimensional anonymous array
new <data type>[][] { {<list of values with comma separator>},
{<list of values with comma separator>} };
Example: Anonymous Int Array
Example: Anonymous char Array
Example: Anonymous String Array
Example: Anonymous Multidimensional Array
Anonymous arrays are useful when we need to create an array with a few elements and don't need to reuse the array later in the code. It can also be used to make the code more concise and readable by avoiding the need to assign a name to the array.
Let's understand an anonymous array with the help of given examples:
Example 1 : Single Dimensional Anonymous Array in Java
Output
J A V A
Example 1 : Multidimensional Anonymous Array in Java
Output
2 4 6 8
3 6 9 2
4 8 1 4
That's all guys, hope this Java article is helpful for you.
Happy Learning.
feedback@javabytechie.com