Why is it allowed to declare a variable in a for loop?

  • A+

I'm a student currently learning java at school (Beginner) and I was wondering about something.
I have a basic knowledge of coding from other languages and I don't understand a particular thing in Java.
If I were to declare a variable (let's use an int as a example) inside a loop wouldn't that mean that I'm declaring 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 / declare 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).
I also know that you can't declare the same variable twice so I don't understand how the first example is legal.

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.


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