• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

while loop variable???  RSS feed

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if i declare a variable in a while loop can i use that variable outside the while loop?
 
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the scope of that variable is within the while loop

as soon as the program exits the while loop the variale is lost.

if you have a variable declared with the same name outside the while loop, that will be accessed outside the loop.

int i=5;
while(...)
{
int i=2;
// i=2 within the loop
}
// here i=5
 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

if you have a variable declared with the same name outside the while loop, that will be accessed outside the loop.



More correct way to say this would be, that if you declare a variable outside the loop, the variable's scope includes the loop. If you declare the variable inside the loop, the variable is accessible only within the loop.
 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you define a variable in any block of code then that variable is avilable inside that block and within all the blocks contained in that block.
For example:
Class
{
method
{
int i;
i is accessable here
for loop
{
i is accessable here
}
}
i NOT is accessable here
}
Hope this explains.

s choukse
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!