In Java, arrays are objects that store multiple values of the same data type. Java allows two syntaxes to declare an array:An array in Java is an object that stores multiple values of the same data type under a single name. Unlike C/C++, Java arrays are objects and follow strict type rules.
In Java, arrays can be declared using two syntaxes:
type[] variable;
type variable[];
For single array declarations, there is no difference between the two syntaxes.
int[] arr1 = new int[5];
int arr2[] = new int[5];
Both statements:
- Declare an integer array
- Behave identically at compile time and runtime
- Produce the same result
Example:
class GFG {
public static void main(String[] args) {
int[] arr1 = {10, 20, 30, 40, 50};
int arr2[] = {1, 2, 3, 4, 5};
for (int x : arr1)
System.out.println(x);
for (int x : arr2)
System.out.println(x);
}
}
Output
10 20 30 40 50 1 2 3 4 5
Explanation:
- arr1 is declared using the Java-recommended syntax int[] arr1, while arr2 uses the C/C++-style syntax int arr2[]; both create integer arrays with no functional difference.
- The enhanced for loop iterates over each array and prints all elements one by one.
- Difference in Multiple Array Declarations
The difference appears only when declaring multiple variables in one statement.
Declaration:
int[] a, b; // Both Variable a and b are arrays. (Correct)
int a[], b; // a is an integer array, while b is an integer variable. (Valid but not recommended)
Example:
public class GFG{
public static void main(String[] args) {
int[] a, b; // both are arrays
int c[], d; // c is array, d is int
a = new int[3];
b = new int[5];
c = new int[2];
d = 10;
System.out.println(d);
}
}
Output
10
Explanation:
- In int[] a, b;, the [] is associated with the data type, so both a and b are integer arrays.
- In int c[], d;, the [] is associated only with c, so c is an array while d is a normal int variable.
Multidimensional Arrays
For multidimensional arrays, both syntaxes behave the same.
int[][] a;
int a[][];
There is no functional or behavioral difference.
Recommended syntax:
int[] a;
Explanation:
- Clearly associates [] with the data type
- Avoids mistakes in multiple declarations
- Follows Java coding conventions
- Improves readability and maintainability
The int a[] syntax exists mainly for C/C++ compatibility.
Note: Always attach [] to the type, not the variable.