wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Variable Scope Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Variable Scope" Watch "Variable Scope" New topic
Author

Variable Scope

Ritu Kapoor
Ranch Hand

Joined: Oct 03, 2004
Posts: 102
On compiling the following program, I get compilation error because of //1
but when I put the line //1 at //2. It compiles fine.

Why is it happening so?

Code:
---------------------------------------------------------------------------

public class Class01 {
public static void main(String args[]){

char digit='c';
int index; //1

for(int index=0;index<10;index++){
switch(digit){
case 'c':
int i1;
default:
int i2;
}
}//FOR
//2

}
}

--------------------------------------------------------------------------
Debbie Tom
Greenhorn

Joined: Sep 12, 2005
Posts: 11
Hi Ritu,

U get compilation error because,
u are redefining variable-index in the same scope.(scope is determined by the {})

Wen u put tat in //2 the scope of index is over and u are creating another varaible.so u dont get error.
Ritu Kapoor
Ranch Hand

Joined: Oct 03, 2004
Posts: 102
Hi Debbie,

But when we execute a program, variables are the first to get created, no matter whether they are created in the begining or at the bottom of the program.

I'm still confused.

Rgds,
Ritu
Sandeep Chhabra
Ranch Hand

Joined: Aug 28, 2005
Posts: 340
Hi,
well i think that the scope of index in for loop should be local, therefore there should be no problem with redefining the variable inside For.
Moreover at many places we use shadowing:
eg:



Here in the above example the scope of a is local just like the scope of variable index in your example.
then i dont that there is any such problem with redefining variable-index.

may be something else.

Sandy


Regards<br />Sandy<br />[SCJP 5.0 - 75%]<br />[SCWCD 1.4 - 85%]<br />------------------<br />Tiger, Tiger burning bright,<br />Like a geek who works all night,<br />What new-fangled bit or byte,<br />Could ease the hacker's weary plight?
Debbie Tom
Greenhorn

Joined: Sep 12, 2005
Posts: 11
Ritu,

Here the scope of the variable matters.

public class Class01 {
public static void main(String args[]){

char digit='c';
int index; //1

for(int index=0;index<10;index++){
switch(digit){
case 'c':
int i1;
default:
int i2;
}
}//FOR
//2

}
}
Here u can see variables index declared within main method.This is redeclaring a variable.





public class Class01 {
public static void main(String args[]){

char digit='c';
//1

for(int index=0;index<10;index++){
switch(digit){
case 'c':
int i1;
default:
int i2;
}
}//FOR
int index;//2

}
}
In this one variable is declared within main method and other declared as part of class.

Hope this helps!
Sandeep Chhabra
Ranch Hand

Joined: Aug 28, 2005
Posts: 340
How does it Matters if you put variable before just For or Just after For
i think the scope remains same in both the cases
Debbie Tom
Greenhorn

Joined: Sep 12, 2005
Posts: 11
public class Class01 {
public static void main(String args[]){

char digit='c';
//1
int index=0;
for(;index<10;index++){
switch(digit){
case 'c':
int i1;
default:
int i2;
}
}//FOR
//2
int index=8;
}


}

This gives error.Saying tat variable is already declared in main.

But...

public class Class01 {
public static void main(String args[]){

char digit='c';
//1
;
for(int index=0;index<10;index++){
switch(digit){
case 'c':
int i1;
default:
int i2;
}
}//FOR
//2
int index=8;
}

This dosent give error.
Wat i think is the scope of a varible declared in for getz over with the for loop.
Ritu Kapoor
Ranch Hand

Joined: Oct 03, 2004
Posts: 102
Hi,

Things are still confusing

I understand the shadowing concept, lets take an example:
---------------------------------------------------------
class abc{
int i=10;
public void display(int i){
System.out.println(i);
}
public static void main(String a[]){
new abc().display(20);
}
}

In this case the output will be 20. Now this is what we called shadowing.
----------------------------------------------------------
Similarly in this case also, we should get error at //1, because we're
trying to do the same thing.


public class Class01 {
public static void main(String args[]){

char digit='c';
int index; //1

for(int index=0;index<10;index++){
switch(digit){
case 'c':
int i1;
default:
int i2;
}
}//FOR
}//MAIN
}//CLASS

I elaborated just to clarify my doubt. Please bear with me.
anand phulwani
Ranch Hand

Joined: Sep 10, 2005
Posts: 242
i think i should revise my shadowing concepts....
coz this is also not running


It gives the following error
Class01.java:9: index is already defined in main(java.lang.String[])
int index=0;
^
1 error


Thanks and Regards, Anand
SCJP 5.0 310-055 73%, SCWCD 1.4 310-081 78%, IBM DB2 9 Fundamentals 000-730 62%
Debbie Tom
Greenhorn

Joined: Sep 12, 2005
Posts: 11
code
___________________________________________________________________
class for1
{
public static void main(String[] args)
{
int k;
for(int i=0;i<10;i++){
int k;
}
int i;
}
}
_______________________________________________________________________

Gives error "k is already defined in main()"
This means tat for loop doesnt create a scope of it own.

But the declaration of a variable within for loop, has a scope tat ends with for loop.Tatz why wen the declaration is placed before for loop..
it clashes with the scope.

But wen placed after for loop. the scope of the created variable ends with for so it gives no error.

This is my assumption.Any comments on this?
A Kumar
Ranch Hand

Joined: Jul 04, 2004
Posts: 979
class for1
{
public static void main(String[] args)
{

for(int i=0;i<10;i++){
int k;
}
int i;

System.out.println(k);//here i am trying to access a variable in the for loop and the error is it cannot access
Then why is that a variable declared outside for loop is having scope
inside..

Tx
}
}
agrah upadhyay
Ranch Hand

Joined: Sep 01, 2005
Posts: 579
Mr. Riwaj,
Shadowing is Meant In Cases Such as Same Variable name In a class And This Class' Method.This Is NOT Meant For IN SAME Method.
So, In 'D Same Method If U Redeclare a variable,Compile Time Error 'll Be There.
I think Ur Doubt Is Clear Now.
Agrah.B.Tech 3rd Year
srikanth reddy
Ranch Hand

Joined: Jul 28, 2005
Posts: 252
thats true tom ....


Thanks & Regards<br /> <br />-Srikanth
A Kumar
Ranch Hand

Joined: Jul 04, 2004
Posts: 979
Hi,

With the above explanation...even my piece of code becomes irrelevant...

Regards
Amit Goel
Ranch Hand

Joined: Dec 07, 2000
Posts: 50
Hi Ritu,

This is a fresh explaination irrespective of the comments given by others..

if u declare index at line 1 ,

then scope of "index" variable is for the whole main method and as 'for' block comes inside main method , it is available for 'for' also. and it will give compilation error.

where as if u declare 'index' at line 2
the scope of 'index' declared in 'for' block gets over earlier only as scope of 'index' declared inside 'for' is only that block and not the whole main method. so when u declare it again after 'for' completes , it is taken that index declared at line 2 with scope of main method . and 'for' loop is not related to it as it has come prior to the declaration of line 2.

i hope this explaination helps.

Regards,


Amit<br /> <br />The Less I have, The more I gain..Off the Beaten Path, I Reign.
Ritu Kapoor
Ranch Hand

Joined: Oct 03, 2004
Posts: 102
Hi Amit,

I got what you're trying to say but the problem is if we can't redeclare
'index' variable in the same scope then why the following program is not giving compilation error.

Code:
---------------------------------------------------------
class abc{
int i=10;
public void display(int i){
System.out.println(i);
}
public static void main(String a[]){
new abc().display(20);
}
}

In this case the output will be 20.

----------------------------------------------------------
But in the following case we're doing the same thing, then why we are getting compilation error.

public class Class01 {
public static void main(String args[]){

char digit='c';
int index; //1

for(int index=0;index<10;index++){
switch(digit){
case 'c':
int i1;
default:
int i2;
}
}//FOR
}//MAIN
}//CLASS


Thanks,
Ritu
Amit Goel
Ranch Hand

Joined: Dec 07, 2000
Posts: 50
Hi Ritu ,

Okay the explaination is like this..

In the first case, where you have declared int i,
YOu have declared int i at class level, which makes it instance variable and int i declared inside the method as a parameter becoems a local variable which shadows the class level variable.

So in the method if u access i, it will be accessing the local variable i and not the one declared at class level, to access instance variable i, u 'll use 'this' operator.

In the second example, it is not the same case as expalined above.

okay, shadowing happens in cases of parameter passing and inheritence (only when u extend classes).

so ur first example is case of shadowing.

and ut second example gives compilation error as there is no shadowing involved and it breaks the rules of variable declaration where my earlier explaination gets valid.

i know u'r bit confused. just read a bit more about shadowing and variable declaration.

As i don't log on to javranch often, if u have any problems or clarifications , u can contact me at amitg@nds.com or amitgoel1287@yahoo.com.

Regards,
Amit
rajesh godbole
Ranch Hand

Joined: Jan 10, 2003
Posts: 31
I think we are confusing ourselves with local and member variable. Member variable when declared in methods, shadows local variable and not another member variable.
Thomas Drew
Ranch Hand

Joined: Sep 15, 2004
Posts: 47
Ritu, I thank the problem is in forward Declarations. I like you thought that java supported forward delclaration. But, when i tried to compile the following code it also produced an error that index could not be found.

index++;
int index = 0;

Reversing the order allowed the code to compile and run. So when you placed the int index = 0 before the for loop an error results because the index had been declared. When you place the index varable after the loop the index varible is no longer in scope so there is no duplication.

hopes this helps Thomas
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
In answer to the very fist post in this thread: Read section 14.4.2 of the Java Language Specification:

The scope of a local variable declared in a for statement is the rest of the for statement, including its own initializer.

If a declaration of an identifier as a local variable of the same method, constructor, or initializer block appears within the scope of a parameter or local variable of the same name, a compile-time error occurs.

Thus the following example does not compile:

class Test {
public static void main(String[] args) {
int i;
for (int i = 0; i < 10; i++)
System.out.println(i);
}
}

This restriction helps to detect some otherwise very obscure bugs.


Below the for-loop, the i in the for-loop is out of scope, so it is ok to define a "new" int i there.
[ September 15, 2005: Message edited by: Barry Gaunt ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Juan Rolando Prieur-Reza
Ranch Hand

Joined: Jun 20, 2003
Posts: 236
Originally posted by Barry Gaunt:
Read section 14.4.2 of the Java Language Specification ...


The Spec http://java.sun.com/docs/books/jls/download/langspec-3.0.pdf
also makes a distinction between shadowing and obscuring (and hiding).
See section 6.3.
[ September 15, 2005: Message edited by: john prieur ]

Juan Rolando Prieur-Reza, M.S., LSSBB, SCEA, SCBCD, SCWCD, SCJP/1.6, IBM OOAD, SCSA
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Variable Scope