For 2- or higher dimensional arrays, the "array constant" way in C++ will give real arrays, and each array will take a contiguous block in memory. Because of this, multiple-dimension arrays can be treated as one-dimension in C++. For the same reason, programmers need know the size of array at the time of declaration. However, for Java arrays, the lengths of each element in a 2-D array can be totally different, where each element is a 1-D array. Hence, in Java, multiple-dimension arrays cannot be treated as one-dimension at all.
Here, I list and compare the ways to declare and initialize arrays in C++ and Java.
Statements | C++ | Java |
---|---|---|
int array[5]; | Y | N |
int[5] array; | N | N |
int array[]; | N | Y |
int[] array; | N | Y |
int array[5] = {1,2,3,4,5}; | Y | N |
int array[] = {1,2,3,4,5}; | Y | Y |
int[] array = {1,2,3,4,5}; | N | Y |
int array[5] = new int[5]; | N | N |
int array[] = new int[5]; | N | Y |
int array[] = new int[5]{1,2,3,4,5}; | N | N |
int array[] = new int[]{1,2,3,4,5}; | N | Y |
int* array; | Y | N |
int* array = new int[5]; | Y | N |
int* array = new int[]{1,2,3,4,5}; | N | N |
int* array = new int[5]{1,2,3,4,5}; | N | N |
int* array1, array2; | array2 is int | N |
int[] array1, array2; | N | array2 is int[] |
int []array1, array2; | N | array2 is int[] |
int array1[], array2; | N | array2 is int |
int []array1, []array2; | N | N |
int []array1, array2[]; | N | array2 is int[][] |
Summary:
- In C++, array name is a constant; in Java, array name is a variable.
- In C++, pointers can be used for an array; in Java, there are no pointers.
- In C++, brackets must appear after array name for declaration and access; in Java, brackets can appear before the array name for declaration.
- In C++, if the array is not initialized during declaration, the size must be specified; in Java, no constants can exist within brackets when declaration.
- In C++, initialization cannot be done using new for an array (not pointer here); in Java, this is possible, like the initialization of a pointer in C++.
- In Java, if use new to initialize an array, the size in brackets and the value array cannot appear at the same time; otherwise, Java compiler doesn't know how to decide the size.
- In C++, if use new to initialize a pointer array, no customized array can be specified. Instead, all elements of the array will be initialized with the default constructor. If the type doesn't have a default constructor, this is a compile-time error.
- In C++, the * after type only specifies the first pointer variable; in Java, the [] after type specifies all array variables in that declaration line.
- In Java, if declare more than one variables in a single line, all brackets for the second to last variables must be placed after the variable name, and the brackets before the first variable will apply to all variables in the line.
Related Posts:
new and delete
Object Initialization
No comments:
Post a Comment