Is array access in Java expensive compared to C++? If so, what is the reason?

Yes, array access in Java is more expensive than array access in C and C++.

Bounds checking in Java slows down array access

The reason that accessing an element in an array in Java is expensive is because of the fact that Java performs bounds checking every time an element in an array is accessed. Bounds checking is where an access to an array index is checked against the size of the array – and an exception is thrown if that array index is out of bounds, and larger than the size of the array. So, if an array has a size of 30, but you try to access the element at index 45, then Java will throw an exception because of the bounds checking feature. And because Java checks the size of the array before accessing the element at index 45, that is an extra operation that is more expensive compared to C and C++, which do not perform bounds checking.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.

Leave a Reply

Your email address will not be published.