![]() |
|
Java Arrays vs C++ Arrays, Free online Core Java Programming Tutorial, Learn Java Programming Language online for free... |
| Lessons | Java Arrays vs C++ Arrays |
|
||||||||||
|
In C++, when we declare an array, storage for the array is allocated. In Java, when we declare an array, we really only declare a pointer or reference to an array; storage for the array itself is not allocated until we use the "new" keyword. This difference is elaborated below: C++ int A[10]; // A is an array of length 10 A[0] = 5; // set the 1st element of array A JAVA int [ ] A; // A is a reference / pointer to an array A = new int [10]; // now A points to an array of length 10 A[0] = 5; // set the 1st element of the array pointed to by A In both C++ and Java we can initialize an array using values in curly braces. Here's the example Java code: int [ ] myArray = {13, 12, 11}; // myArray points to an array of length 3 // containing the values 13, 12, and 11 In Java, a default initial value is assigned to each element of a newly allocated array if no initial value is specified. The default value depends on the type of the array element as shown below:
In Java, array bounds are checked and an out-of-bounds array index always causes a runtime error.
Next >>> Lesson No. 5: Arrays Operations In Java
|