search
Login

Categories


C Books Guide and List
C++ Books Guide and List
Best Java Books

3.8k questions

4k answers

117 comments

10.7k users

0 votes
83 views
asked Expert 15k points 15 23 30

1 Answer

0 votes
It is common to declare a variable and assign a value to it in the initialization part. The variable declared will be visible to the expression and update parts as well as to the statement block.

For example, the following for statement loops five times and each time prints the value of i. Note that the variable i is not visible anywhere else since it is declared within the for loop.

public class MainClass {

  public static void main(String[] args) {
    for (int i = 0; i < 5; i++) {
        System.out.println(i + " ");
    }
  }
}
The initialization part of the for statement is optional.

public class MainClass {

  public static void main(String[] args) {
    int j = 0;
    for (; j < 3; j++) {
      System.out.println(j);
    }
    // j is visible here
  }

}
answered Expert 11.4k points 14 22 28

Related questions

0 votes
2 answers 38 views
0 votes
1 answer 19 views
19 views
asked rajesh Guru 39.1k points 10 21 33
0 votes
1 answer 32 views
32 views
asked john Guru 27.1k points 31 50 97
0 votes
1 answer 7 views
7 views
asked smith Geek 15.3k points 16 41 63
0 votes
1 answer 13 views
13 views
asked john Guru 27.1k points 31 50 97
...