I am studying java, I know Java variable scope, such as class level, method level, block level. However, when I try to practice the variable scope, I meet the error in my code. my code is as following:
public class HelloWorld {
public static void main(String[] args) {
int c;
for (int i=0; i <5; i++) {
System.out.println(i);
c = 100;
}
System.out.println(c);
}
}
when I run this code, it display the error: the c variable might not have been initialized, but when I change my code to the following:
public class HelloWorld {
public static void main(String[] args) {
int c=0;
for (int i=0; i <5; i++) {
System.out.println(i);
c = 100;
}
System.out.println(c);
}
}
The code will print 100.
How should I understand the scope in my code?