It's UWAweek 16 (1st semester, week 7)

help2005

This forum is provided to promote discussion amongst students enrolled in CITS2005 Object Oriented Programming.

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.

How do I ask a good question?
Displaying selected article
Showing 1 of 46 articles.
Currently no other people reading this forum.


 UWA week 11 (1st semester, week 3) ↓
SVG not supported

Login to reply

👍?
helpful
11:02am Tue 12th Mar, ANONYMOUS

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​).

The University of Western Australia

Computer Science and Software Engineering

CRICOS Code: 00126G
Written by [email protected]
Powered by history
Feedback always welcome - it makes our software better!
Last modified  5:07AM Sep 06 2023
Privacy policy