This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Variable declaration in a loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Variable declaration in a loop" Watch "Variable declaration in a loop" New topic

Variable declaration in a loop

Martin Rennix
Ranch Hand

Joined: Sep 30, 2001
Posts: 34
I've got a syntax question: is the following code legal in Java:

I think it is ok because it compiles, but it looks odd (I come from a C background where this is illegal). Is it better to declare the variable x outside the loop first?

[This message has been edited by Cindy Glass (edited October 04, 2001).]
Martin Rennix
Ranch Hand

Joined: Sep 30, 2001
Posts: 34
Damn pre tags! Here it is again properly formatted!
for (i=0; i<10; i++)
int x = someValue();
Bosun Bello
Ranch Hand

Joined: Nov 06, 2000
Posts: 1510
Yes, it's legal. If it compiles, it is...


So much trouble in the world -- Bob Marley
timothy zimmerman
Ranch Hand

Joined: Jun 26, 2001
Posts: 149
It is legal but it may be better to declare x outside of the loop and with each pass simply assign it a new value
int x = 0;
for (i=0; i<10; i++)
x = someValue();
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
You get two different effects depanding on where you declare the variable. If you declare it inside the block, then it is local to the block, and POOF! it is gone when that execution of the block completes.
If you want the value to survive the block and be visible outside the block, then you need to declare it outside.

"JavaRanch, where the deer and the Certified play" - David O'Meara
I agree. Here's the link:
subject: Variable declaration in a loop
Similar Threads
Java "math" ?
Substituting the value to the equation(loop)
array algorithm
endless loop question