हिंदी

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 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
  क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
अध्याय 6: Variables and Expressions - SHORT ASSIGNMENTS [पृष्ठ १३६]

APPEARS IN

धीरज मेहरोत्रा Computer Science [English] Class 12
अध्याय 6 Variables and Expressions
SHORT ASSIGNMENTS | Q 34. | पृष्ठ १३६
Advertisements
Share
Notifications



      Forgot password?
Use app×