0

my first question, I'm a beginner.

Please refer to the below code, I tried to define j twice and java compiler give me an error, I totally understand.

My question here is if I cannot define a variable twice, why the "char c = ..." inside the loop is working. from the logic, when the loop body execute first time, the char c variable is defined, when the loop body execute the second time, because the char c is already defined, it should throw an error, but it didn't. Why?

public class test{
    public static void main(String[] args){
        int j=1;
        for (int i=0; i<10; ++i){
            char c = (char)(Math.random()*26+97);
            System.out.println(i+1+" = "+c);
        }
        int j=2;
    }
}

Thanks

B.Hong
  • 79
  • 1
  • 8
  • 3
    Your `char c` has its scope limited to the _current_ iteration of the loop, and will be dismissed afterwards. There is no duplicate declaration in this case. – Arnaud Jul 13 '17 at 12:53
  • You declare variables at *compile* time. It does not matter how often the code is *executed*. – Timothy Truckle Jul 13 '17 at 12:54
  • You could declare your variable as `final`, too, inside a loop. Those declarations live just inside the block, that is, every iteration has to recreate them... – Usagi Miyamoto Jul 13 '17 at 12:54
  • I **just** saw the dupetarget for this, where is it... – T.J. Crowder Jul 13 '17 at 12:55
  • [Found it](https://stackoverflow.com/questions/26692795/why-can-i-create-multiple-instances-with-the-same-name-in-a-loop), added it to the one RealSkeptic flagged. – T.J. Crowder Jul 13 '17 at 13:02

4 Answers4

3

why the "char c = ..." inside the loop is working

Because the for loop has its own scope, so there will be a different variable in each iteration.

So in total your code will create 10 different variables.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
1

The variable c lives only in the scope of the for loop. When the iteration ends the variable dies, so it can be redeclared in the next iteration.

Guy
  • 46,488
  • 10
  • 44
  • 88
0

Declarations are checked by the compiler. They are executed during, well, execution.

The compiler sees that the variable is declared inside a scope, and that's all it cares about. It doesn't check how often the code inside that scope is executed.

0

Whenever you declare a variable within braces that variable exists only inside those braces, that is, any code outside the braces cannot access the variable.

if(true) {
    char c = 'x';
}
 c = 'y';    // Error

This is because once outside the scope, the variable no longer exists.

This is what is happening in your code

for (int  i=0; i < 5; i++)
{
   char c = 'x'; // variable created on each iteration hence no error
}
 c = 'y'; // error since variable gets destroyed