Back to questions
JuniorTheoryCommon
What happens when the program is compiled and run?
public class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 3; i++) {
sum += i;
}
System.out.println(sum + " " + i);
}
}It does not compile
- Expecting
6 4: a variable declared in theforheader lives only inside the loop, soiis an unknown name after it and javac reportscannot find symbol. - Expecting a failure at run time: javac checks every name before the program runs, so nothing is printed, not even
sum.
- How would you change the code to print the value
ihas after the loop? - Can two loops, one after the other in
main, both declareint i?