Skip to content
Advertisement

How I can index the array starting from 1 instead of zero?

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

  Products[] products = reports[i].getDecisions;

  for (int j = 0; j < products.length; j++) {

  }
}

Here I want to index the inner for loop starting from 1 , but it is not working as expected, I also changed the j

Advertisement

Answer

Java arrays are always 0-based. You can’t change that behavior. You can fill or use it from another index, but you can’t change the base index.

It’s defined in JLS §10.4, if you are interested in it.

A component of an array is accessed by an array access expression (§15.13) that consists of an expression whose value is an array reference followed by an indexing expression enclosed by [ and ], as in A[i].

All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement