• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Scope of variable declarartions in for loop

 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi there,
using JWhiz I found explained that you can't mix the declaration
of local for-loop variables and external variables.
But check out the following two class definitions MyClass1 and MyClass2.
The only difference is the location of 'int i;'
public class MyClass1
{
public static void main(String[] args)
{
for( int i = 0; i <= 2; ++i )
{
System.out.println(i);
}
int i;
}
}
public class MyClass2
{
public static void main(String[] args)
{
int i;
for( int i = 0; i <= 2; ++i )
{
System.out.println(i);
}
}
}
The question is:
Why is MyClass1 compiled without error while the compilation
of MyClass2 leads to the following compiler message:

MyClass2.java:7: i is already defined in main(java.lang.String[])
for( int i = 0; i <= 2; ++i )
^
1 error
Thanks in advance
Ruediger
 
Ranch Hand
Posts: 1157
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
In MyClass1 case, the *int i* declaration is scoped at the for loop level.So when you define *int i* again outside the for loop, it doesn't give compilation error.
In the MyClass2 case, when you define *int i* first outside the for loop this variable would also be applicable to all the loops that would be defined after this declaration, which includes for loop as well.Thus defining the variable in the for loop again gives a compilation error.

Remember the declaration is processed on as-is basis in the method.This means, if you have one more for loop with a int i initialization, after the last statement declaration of *int i* in MyClass1, you will get a compile-time error.
You would find this behaviour quite different from what happens at the class level.
For example ,

The above code will not give a compliation error.This means the value of i is initialized first.This didnot happen in MyClass1 case!
The following code will give a compilation error stating that the variable i is not defined.

Hope this helps,
Sandeep
SCJP2, OCSD(Oracle JDeveloper), OCED(Oracle Internet Platform)
[This message has been edited by Desai Sandeep (edited July 25, 2001).]
reply
    Bookmark Topic Watch Topic
  • New Topic