Why can i make a variable in a for loop?

  • A+
Category:Languages

I'm a student learning java at school (Beginner) and I was wondering about something. I have basic knowledge in coding from small parts from other languages and I don't understand a special thing in Java. If I were to make a variable (let's use an int as a example) inside a loop wouldn't that mean that I'm making the same variable over and over?

This is what I mean:

for (int i = 0; i < 3; i ++) {     int x = 5; } 

Isn't it the same thing as this? (This one is incorrect)

int x = 5; int x = 5; 

If not, Why? Both of them are / make the same variable twice, though I know that in loops the variable is local and can't be used outside of the loop (I don't think thats the issue though). And I also know that you can't make the same variable twice so I dont understand how the first example is possible.

Thanks so much :D

This Question has be solved, Thanks to everyone that helped :D

 


for (int i = 0; i < 3; i ++) {     int x = 5; } 

is actually equivalent to:

{     int x = 5; } {     int x = 5; } {     int x = 5; } 

Each x variable is declared in a separate scope.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: