Why array in Java is safer than other programming languages like C & C++


Arrays are common feature of most of the programming languages. Most of the programming languages supports arrays for example C & C++.

Uses of arrays in C&C++ is not safe because because those arrays are only blocks of memory. If a program accesses the array outside of its memory block or uses the memory before initialization (common programming errors), there will be unpredictable results and this is very problematic for programmers.

While in java where safety was primary goal. A Java array is guaranteed to be initialized and cannot be accessed outside of its range. The range checking comes at the price of having a small amount of memory overhead on each array as well as verifying the index at run time, but safety and increased productivity is worth the expense.

When you create an array of objects in java, you are actually creating an array of references, and each of those references is automatically initialized null. When Java sees null, it recognizes that the reference in question isn’t pointing to an object. You must assign an object to each reference before you use it, and if you try to use a reference that’s still null, run time exception will thrown and you get to know about the problem.

We can also create an array of primitives and the compiler guarantees initialization because it zeroes the memory for that array.

Because of automatic initialization and range checking Java arrays are safer than C&C++ arrays.