Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between i<=array.length and array.length>i

We've started using netbeans in our Java programming class, after using notepad++ for a while. While iterating through an array list. I used the following code:

for (int i=0; i<=randomarrayhere.length; i++)

Netbeans suggested to flip the position of i and array.length

for (int i=0; randomarrayhere.length>i; i++)

What do we gain by this?

Thanks!

like image 585
mythic Avatar asked Dec 04 '22 03:12

mythic


2 Answers

The first would throw an ArrayIndexOutOfBoundsException when i reaches randomarrayhere.length.

Aside from that (if you use i<randomarrayhere.length), there is no difference.

like image 139
M A Avatar answered Mar 23 '23 19:03

M A


you can either use randomarrayhere.length>i or i<randomarrayhere.length, but don't use randomarrayhere.length>=i or i<=randomarrayhere.length because if you call randomarrayhere[i] anywhere in your forloop you will get an Exception since array indices are zero-based.

like image 41
Nils O Avatar answered Mar 23 '23 18:03

Nils O