English

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 for statement in Java is known as loop scope.
  • In Java, a variable declared in the initialization part of a for loop 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 for loop 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?
Chapter 6: Variables and Expressions - SHORT ASSIGNMENTS [Page 136]

APPEARS IN

Dheeraj Mehrotra Computer Science [English] Class 12
Chapter 6 Variables and Expressions
SHORT ASSIGNMENTS | Q 34. | Page 136
Advertisements
Share
Notifications



      Forgot password?
Use app×