Java Arrays vs C++ Arrays


Generally speaking, there is not much difference between the Java and C or C++ arrays. As a C / C++ programmer you will find it very easy to understand and work with arrays in Java.

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++
into 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: 

Type
Value
boolean
false
char
'\u0000'
byte, int, short, long, float, double
0
any reference type e.g. a class object
null

In Java, array bounds are checked and an out-of-bounds array index always causes a runtime error.