What is the scope of a variable declared within the initialization clause of a for statement in Java? Provide an example code fragment.
Advertisements
प्रश्न
What is the scope of a variable declared within the initialization clause of a for statement in Java? Provide an example code fragment.
दीर्घउत्तर
Advertisements
उत्तर
- 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
या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
