| Author |
Shadowing variable doubt?
|
Joe Harry
Ranch Hand
Joined: Sep 26, 2006
Posts: 8795
|
|
Hi Guys, Consider the code below, Why it gives compiler error at line 2?? Anyone please!
|
SCJP 1.4, SCWCD 1.4 - Hints for you, SCBCD Hints - Demnachst, SCDJWS - Auch Demnachst
Did a rm -R / to find out that I lost my entire Linux installation!
|
 |
Vinayagar Karpagam
Ranch Hand
Joined: Apr 09, 2006
Posts: 72
|
|
Hi, In line 2, k is redeclared. I dont think we can shadow a local variable by another local variable. So, it should give a compilation error. Shadowing happens only when a local variable is declared with same name as an instance variable. There should be a compilation error in line 3 also because "int" before j is not allowed.
|
 |
Prabhu Venkatachalam
Ranch Hand
Joined: Nov 16, 2005
Posts: 502
|
|
You have two variable with same name inside a single method which is not shawoding. you are duplicating the variable name. In your code make k as instance variable. It should work. hth,
|
Prabhu Venkatachalam<br />SCJP 1.4,SCWCD 1.4<br />prabhu.venkatachalam@gmail.com
|
 |
Joe Harry
Ranch Hand
Joined: Sep 26, 2006
Posts: 8795
|
|
|
Thanks guys for the help.
|
 |
hardikjava shah
Greenhorn
Joined: Dec 12, 2005
Posts: 13
|
|
Because you are declaring variable k twice in this method once on first line of main method int k; and another on line# 2 for (int i=0, k=0; i<2; i++,k++) {System.out.print(i);} here, int i=0, k=0 ==> int =0 and int k=0; Regards!
|
 |
Suguna Gollapally
Ranch Hand
Joined: Oct 31, 2006
Posts: 37
|
|
I compiled the program given,but i am getting error at line 3 class Test { public static void main(String args[]) { int k; for (int i=0, j=0; i<2; i++,j++) {System.out.print(i);} // 1 for (int i=0, k=0; i<2; i++,k++) {System.out.print(i);} // 2 for (int i=0, int j=0; i<2; i++,j++) {System.out.print(i);} // 3 cant have multiple declaration }}
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
|
|
|
Yes, well, the error pretty much tells you what you need to know: you can't do that. And you've already found alternate ways to do the same thing you were trying to do. They don't want you to repeat the "int" part of the declaration because if you did that, you could also write a loop that declares an int and a String, for example. Not that this is inherently wrong, necessarily, but the language designers made a conscious choice to limit how much complexity you are allowed to put into a single for statement. They allow more than one variable to be initialized, only if the variables are of the same type - and in that case, they can share the type declaration (the word "int" in this case); you don't have to repeat it.
|
"I'm not back." - Bill Harding, Twister
|
 |
 |
|
|
subject: Shadowing variable doubt?
|
|
|