Please consider offering answers and suggestions to help other students!
And if you fix a problem by following a suggestion here,
it would be great if other interested students could see a short
"Great, fixed it!" followup message.
In the recorded lecture from 2023 corresponding to lecture 4 there was some code that was demonstrated to show how each time a for loop iterates, the variables are re-initialised. I was curious about what would happen if a global variable were used instead. Could you explain why I got the output I got in regards to scope and re-initialisation, when I ran my version of the code? Here are two screenshots: the first being the demonstrated code and the second being my code.
You say "each time a for loop iterates, the variables are re-initialized". The initialization of a variable is when it is first set to a value after being declared. Only variables that are declared within the scope that is the body of the loop are reinitialized.
In the code from the lecture, int j is declared (and initialized) within the body of the loop, and so its lifetime is only until the end of each iteration of the loop, and it effectively ceases to exist and is reinitialized at the start of the next iteration.
In your code, int bob is declared outside of the loop, and in the scope that is the body of the main method. It therefore lives until the end of the main method, and when the statement bob = 300; inside the for loop is executed, it will set bob to 300 on each iteration (even though after the first iteration, it is already 300).
The variable bob is accessible within the body of the loop because nested scopes can access any variables declared in the scopes that contain them.
I will also note that you used the term "global variable". Global variables are not really a thing in Java, and bob in particular is definitely not a global, but rather is a local variable in the scope of main (and hence in any nested scopes inside main).
For context for anyone who is confused, this student emailed the unit email inbox with the above question, and I answered their question and asked them to post their question and the result here for the benefit of other students. So the first message in the thread is the question, and the second is a reproduction of my answer.