0

I've a code something similar to this.

public static final int[] VALUES = {1,2,3,4,5,6};

for(int i=0; i< VALUES.length; i++) {
    //Do something
}

Is it good to have VALUES.length as part of loop. Should I assign it to a variable and use it here?

In case of String array, I've seen it's been doing this way.

public static final String[] STR_VALUES = {"apple", "orange", "butterfly"};

int length = STR_VALUES.length();
for(int i=0; i< VALUES.length; i++) {
        //Do something
}

Since it's a performance optimization that we need not compute the length again and again. But in the case of int[] it looks like I'm using instance variable of a class. But these are primitives where does class coming into picture here? I'm getting confused.

How this is process? From where Do we get the value from? How can I see it?

Tom Taylor
  • 3,344
  • 2
  • 38
  • 63
  • 1
    See https://stackoverflow.com/questions/8781022/is-an-array-an-object-in-java – Andrew Henle Dec 04 '19 at 19:57
  • 1
    Yes, it is good style to have `VALUES.length` as part of the loop. IMHO putting it into a variable first (as in your second snippet) just overcomplicates things. Whether we’re talking primitives or object references makes no difference to the question. – Ole V.V. Dec 04 '19 at 20:11
  • In your second example it should also be just `STR_VALUES.length` without the round brackets, there’s no difference. – Ole V.V. Dec 04 '19 at 20:14
  • 1
    [this answer](https://stackoverflow.com/a/1965506/217324) on the duplicate target describes where arraylength comes from. – Nathan Hughes Dec 04 '19 at 20:16
  • @OleV.V. the second variant has even more issues, like attempting to declare an `int[]` array containing strings. And, of course, there’s no difference, as the OP’s second loop still uses `STR_VALUES.length` in the loop, instead of the new local variable. Note that you don’t have to declare the variable outside, you can use, e.g. `for(int i=0, len=VALUES.length; i – Holger Dec 05 '19 at 08:59
  • @Holger thanks for pointing it out. Actually I thought String[] but wrote it as int[] my bad ! :-( – Tom Taylor Dec 05 '19 at 09:13

0 Answers0