0

what does this code tells the computer to do? P.s. The 'lights' is a boolean array.

for (int k = 1; k < lights.length; k++)
                lights[k] = !lights[k];
  • I highly recommend that you learn to use a debugger. This tool will allow you to step through your code and let you see what is happening on each line. – Jason Feb 14 '19 at 21:31

1 Answers1

7

It's basically toggling the boolean flags in the array (except the first one). A true flag will be set to false and vice-versa.

Note that any uninitialized items of a boolean array will be false in Java.

const lights = [false, false, false];

//toggling flags except the first one
for (let k = 1; k < lights.length; k++)
    lights[k] = !lights[k];
    
console.log(lights);
plalx
  • 42,889
  • 6
  • 74
  • 90
  • But in the code I have the items of the lights array have not been set to True or false, that has been just initialized. So are all the arrays items true or false by default somehow? – Altin Mullaidrizi Feb 14 '19 at 20:45
  • 1
    This looks like JavaScript, not Java like the question is tagged. – rgettman Feb 14 '19 at 20:45
  • @AltinMullaidrizi Could you show how the array initialization code looks like? – plalx Feb 14 '19 at 20:47
  • @plalx Here it is: boolean[] lights = new boolean[101]; – Altin Mullaidrizi Feb 14 '19 at 20:48
  • According to [this](https://stackoverflow.com/questions/3426843/what-is-the-default-initialization-of-an-array-in-java) all items (but the first one, given index starts at 1) would initialize to `false` and running the loop would set them all `true`. – plalx Feb 14 '19 at 20:50
  • @AltinMullaidrizi When you instantiate an array in Java the entries in the array are set to zero for a numeric type, false for boolean, or null for reference types, so your array will be filled with false when you first create it. – David Conrad Feb 14 '19 at 20:51
  • @plalx Running the loop would not set them all to true. The loop does not affect the item at `lights[0]`. – David Conrad Feb 14 '19 at 20:51
  • 1
    @DavidConrad Yeah, had already stated that in the answer and you were quick on the comment because I changed mine like 5 seconds after posting to point that out hehe. – plalx Feb 14 '19 at 20:53
  • Thanks! Now I completely understand how this code that first looked complex, works! – Altin Mullaidrizi Feb 14 '19 at 20:56