Java – why are variables allowed to be declared in a for loop?
•
Java
I'm a student. I'm learning java at school. I'm confused about it
That's what I mean:
for (int i = 0; i < 3; i ++) { int x = 5; }
Isn't that the same thing? (this is incorrect)
int x = 5; int x = 5;
If not, why? They all declare the same variables / twice, although I know that variables are local in the loop and cannot be used outside the loop (I don't think this is a problem) I also know that you can't declare the same variable twice, so I don't understand how the first example is legal
Thank you very much: D
This problem has been solved. Thank all those who have helped: D
Solution
for (int i = 0; i < 3; i ++) {
for (int i = 0; i < 3; i ++) { int x = 5; }
In fact, it is equivalent to:
{ int x = 5; } { int x = 5; } { int x = 5; }
Each x variable is declared in a separate scope
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码