File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Variable declaration Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Variable declaration" Watch "Variable declaration" New topic
Author

Variable declaration

ravinderSingh singh
Ranch Hand

Joined: Nov 18, 2004
Posts: 41
When you declare a variable in a for or while loop, is a new variable created each time through the loop?

For example,

for (int i = 1; i < 10; i++) {
int var = 1;
}

Does this mean the variable var will be declared 10 times during execution of the loop?

Thanks
Elouise Kivineva
Ranch Hand

Joined: Feb 07, 2002
Posts: 154
Yes it will be created 10 x but it will also go out of scope 10 x.

loop execution starts
variable created
1st iteration of loop ends and variable goes out of scope (it's gone)
2nd iteration of loop starts
variable created
2nd iteration of loop ends and variable goes out of scope (it's gone)
and so on so forth
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
Does this mean the variable var will be declared 10 times during execution of the loop?


The variable is declared once. Declaring something is a compile-time directive, not an executable statement. Any initializer in the declaration ( var = 3 ) is an executable statement.

A variable declared inside a block { ... } is allocated memory on a push-down/pop-up stack every time the block is entered. The memory is given back every time the stack is exited. Statements in the block starting at the point of declaration can access the variable.

In a for while or do statement, the block is entered and exited with every repetition of the loop.
[ November 19, 2004: Message edited by: Mike Gershman ]

Mike Gershman
SCJP 1.4, SCWCD in process
 
Consider Paul's rocket mass heater.
 
subject: Variable declaration