What is the scope of a variable declared within the initialization clause of a for statement in Java? Provide an example code fragment.
Advertisements
Question
What is the scope of a variable declared within the initialization clause of a for statement in Java? Provide an example code fragment.
Long Answer
Advertisements
Solution
- The scope of a variable declared within the initialization clause of a
forstatement in Java is known as loop scope. - In Java, a variable declared in the initialization part of a
forloop can be accessed and used only within that loop. Its scope extends from its declaration through the loop condition, update expression, and loop body. - The variable cannot be accessed outside the
forloop because its scope ends when the loop statement is completed.
Example:
for (int i = 1; i <= 5; i++)
{
System.out.println(i);
}
Explanation:
In this example, i is declared inside the for loop and prints numbers from 1 to 5. It can be accessed only within the loop, not outside it.
shaalaa.com
Is there an error in this question or solution?
