<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
	<channel>
		<title><![CDATA[JavaRanch: Latest posts for the topic "Question Local Variable Scope"]]></title>
		<link>http://www.coderanch.com/forums/t/24/Programmer-Certification-SCJP/Local-Variable-Scope</link>
		<description><![CDATA[Latest messages posted in the topic "Question Local Variable Scope"]]></description>
		<generator>JForum - http://www.jforum.net</generator>
			<item>
				<title>Question Local Variable Scope</title>
				<description><![CDATA[The answer to the following from chapter 3 review question 8 surprise me<br /> <br /> public class Ouch {<br /> <br /> 	static int ouch = 7;<br /> 	public static void main(String[] args) {<br /> 		new Ouch().go(ouch);<br /> 		System.out.print(" " + ouch);<br /> <br /> 	}<br /> 	<br /> 	void go (int ouch)<br /> 	{<br /> 		<br /> 		ouch++;<br /> 		for(int ouch = 3; ouch &lt; 6; ouch++ );		<br /> 		System.out.print(" " + ouch);<br /> 	}<br /> <br /> }<br /> <br /> The answer is E Compilation fails. Since we are in the for loop, should the "go" method argument "ouch" be hidden by for-loop "ouch"? I know the answer is negative but why? Since the following WILL compile<br /> <br /> public class Ouch {<br /> <br /> 	static int ouch = 7;<br /> 	public static void main(String[] args) {<br /> 		new Ouch().go(ouch);<br /> 		System.out.print(" " + ouch);<br /> <br /> 	}<br /> 	<br /> 	void go (int ouch)<br /> 	{<br /> 		<br /> 		ouch++;<br /> 		for(int i = 3; i &lt; 6; i++ );<br /> 		<br /> 		int i = 2;<br /> 		<br /> 		System.out.print(" " + i);<br /> 	}<br /> <br /> }<br /> <br /> The point is I also defined the variable 'i' twice. However, the following will fail<br /> <br /> <br /> public class Ouch {<br /> <br /> 	static int ouch = 7;<br /> 	public static void main(String[] args) {<br /> 		new Ouch().go(ouch);<br /> 		System.out.print(" " + ouch);<br /> <br /> 	}<br /> 	<br /> 	void go (int ouch)<br /> 	{<br /> 		<br /> 		ouch++;<br /> 		<br /> 		int i = 2;<br /> 		<br /> 		for(int i = 3; i &lt; 6; i++ );<br /> 		<br /> 		<br /> 		<br /> 		System.out.print(" " + i);<br /> 	}<br /> <br /> }<br /> <br /> Note that I define variable i before the for loop. <br /> <br /> Thank you for your help<br /> <br /> -Cheung<br /> <br /> ]]></description>
				<guid isPermaLink="true">http://www.coderanch.com/forums/posts/preList/448768/1997290</guid>
				<link>http://www.coderanch.com/forums/posts/preList/448768/1997290</link>
				<pubDate><![CDATA[Mon, Jun 8 2009 17:18:07 MDT]]></pubDate>
				<author><![CDATA[Cheung Chau]]></author>
			</item>
			<item>
				<title>Question Local Variable Scope</title>
				<description><![CDATA[Cheung,<br /> <br /> In the book example you provided, the compilation fails because ouch is already in scope prior to the for loop which attempts to declare a variable that has the same name.<br /> <br /> <pre>  
for(int i = 3; i &lt; 6; i++ );

int i = 2;   </pre><br /> In this example a variable i is declared in the for loop, and when it goes out of scope the variable name is available again.<br /> <br /> <pre>   
int i = 2;

for(int i = 3; i &lt; 6; i++ );  
</pre><br /> This example fails for the same reason the book example failed, i is already in scope when the for loop attempts to create a variable of the same name.<br /> <br /> <br /> <br /> I too am studying for the SCJP.....so I hope I did not miss anything in this example.<br /> ]]></description>
				<guid isPermaLink="true">http://www.coderanch.com/forums/posts/preList/448768/1997356</guid>
				<link>http://www.coderanch.com/forums/posts/preList/448768/1997356</link>
				<pubDate><![CDATA[Mon, Jun 8 2009 19:34:16 MDT]]></pubDate>
				<author><![CDATA[Jim Toy]]></author>
			</item>
			<item>
				<title>Question Local Variable Scope</title>
				<description><![CDATA[Hi Cheung,<br /> <br /> please put the code within the code brackets. It's hard to read your code.<br /> <br /> cheers<br /> Bob]]></description>
				<guid isPermaLink="true">http://www.coderanch.com/forums/posts/preList/448768/1997479</guid>
				<link>http://www.coderanch.com/forums/posts/preList/448768/1997479</link>
				<pubDate><![CDATA[Tue, Jun 9 2009 00:53:56 MDT]]></pubDate>
				<author><![CDATA[Bob Wheeler]]></author>
			</item>
			<item>
				<title>Question Local Variable Scope</title>
				<description><![CDATA[The loop variable in the for loop has scope only inside the for loop. This would fail to compile<br /> <br /> <pre>for(int i = 10;i&lt;20;i++){
}
i = 20;  //error</pre><br /> <br /> So that's why when I do this<br /> <br /> <pre>for(int i = 10;i&lt;20;i++){
}
int i = 20;  //(1)</pre><br /> <br /> I'm not re-declaring i on (1). There is no i defined at that point. Also I think you need to try something like this to be completely clear about scopes of variables<br /> <br /> <pre>{
   int i = 7;
   int j = 10;
   {
      int i = 22;  //error
      j = 20;
      int k = 8;
   }
   k = 34;   //error
   int k = 78;
}</pre>]]></description>
				<guid isPermaLink="true">http://www.coderanch.com/forums/posts/preList/448768/1997485</guid>
				<link>http://www.coderanch.com/forums/posts/preList/448768/1997485</link>
				<pubDate><![CDATA[Tue, Jun 9 2009 01:04:31 MDT]]></pubDate>
				<author><![CDATA[Ankit Garg]]></author>
			</item>
			<item>
				<title>Question Local Variable Scope</title>
				<description><![CDATA[Hi guys,<br /> <br />    Thank you for your reply. Sorry Bob, I will put my code in code block next time (this time).<br /> <br /> Hi Jim,<br /> <br />    I am totally agree with your explaination on why it failed and that was reason I posted a different example that derived from the review question. However, the real question I would like to get at is whether variable ouch defined in the for loop should hide the method argument and why not? <br /> <br /> <pre>public class Ouch { 

   static int ouch = 7;  // 1.
   public static void main(String[] args) { 
      new Ouch().go(ouch); 
      System.out.print(&quot; &quot; + ouch); 
   } 

   void go (int ouch) {  // 2.
      ouch++; 
      for(int ouch = 3; ouch &lt; 6; ouch++ );  // 3.
      System.out.print(&quot; &quot; + ouch); 
   } 

}</pre> <br /> <br /> As you can see, static variable ouch at 1. was hidden by local variable ouch at 2. My question is why CAN'T for-loop variable ouch at 3.(which also is a local variable) hide the local variable ouch at 2.  If you read Ankit's reply we see that variable i defined in for-loop ONLY exist in the for-loop and so I believe for-loop does form a scope. If the for-loop forms a scope, why can it hide a variable. That's my original question<br /> <br /> Again, I know this is the fact. However, I wonder if there is a logical explaination.<br /> <br /> <br /> Ankit,<br /> <br />    Thank you for your reply. Please see my comment above and see if you can offer more insight. Thank<br /> <br /> -Cheung<br /> ]]></description>
				<guid isPermaLink="true">http://www.coderanch.com/forums/posts/preList/448768/1997809</guid>
				<link>http://www.coderanch.com/forums/posts/preList/448768/1997809</link>
				<pubDate><![CDATA[Tue, Jun 9 2009 08:33:19 MDT]]></pubDate>
				<author><![CDATA[Cheung Chau]]></author>
			</item>
			<item>
				<title>Question Local Variable Scope</title>
				<description><![CDATA[Cheung,   <br /> <br /> I think I understand you better now.  As to the why, the for loop is block scoped, but has to honor method scoped variables. <br /> <br /> My apologies if this is more than necessary ... i did this more for my benefit of working out the problem.    The variable defined in the for loop will not hide/shadow because the for block does not begin until after the for statement, so the variable initialized cannot conflict with others in the block. <br /> <br /> Here is an example I created....hopefully i commented it correctly <img src="http://www.coderanch.com/images/smilies/2786c5c8e1a8be796fb2f726cca5a0fe.gif" /> <br /> <br /> edit: By the way, I am really glad you posted this thread, it made me really think about scoping.<br /> <br /> <pre>  
public class ScopeRules {
      static int ouch = 5; // static, class scoped

    static {

        int free = 0;
        {
            int free=0; //invalid, duplicate in block scope
        }
    }

    static int free = 1;

    public static void main(String[] args) {

        {
            int ouch = 1; //local, shadowed
            {
                int ouch = 1; //invalid, duplicate in local scope
                int free = 1; //block scoped

            }

            int free = 1; //valid, no other

        }

    }
}
 </pre><br /> <br /> Line 8 is OK, it is a shadow, line 10 will fail, line 15 is ok because there is no other variable named 'free' in the block. <br /> <br /> From the K&B book pg 191 there are 4 scope types:<br /> * static, class level<br /> * instance, object level<br /> * local , method level<br /> * block , block level<br /> <br /> The question that jumps to my mind is ...why is it ok to declare ouch  on line 18.  I would say it is because it is method level scoped, and when the method is in scope on the stack arguments are passed by value.  So even though the method is free to extend beyond itself to the reference static/instance variables it still has the flexibility to re declare those names since they are not in scope.<br /> <br /> ]]></description>
				<guid isPermaLink="true">http://www.coderanch.com/forums/posts/preList/448768/1997938</guid>
				<link>http://www.coderanch.com/forums/posts/preList/448768/1997938</link>
				<pubDate><![CDATA[Tue, Jun 9 2009 11:55:53 MDT]]></pubDate>
				<author><![CDATA[Jim Toy]]></author>
			</item>
			<item>
				<title>Question Local Variable Scope</title>
				<description><![CDATA[Hi Jim,<br />  <br />    Thank you for taking the time. Again, "WHY" is what I am going for here. I did work out the logic you stated perfectly in your example before my original post - that's why you see the extra example I posted with variable i. What I mean is I would probably answer a similar question correctly in the exam. However, I am interested in knowing the following - let's say we have<br /> <br /> 1) static scope<br /> 2) instance scope<br /> 3) local scope<br /> 4) block scope<br /> <br /> Variable in local scope will hide a variable with the same name in either static or instance scope, but block scope variable CANNOT do the same thing to local scope variable. WHY? Again, I did get the fact but just need a logical explaination.<br /> <br /> I couldn't find any detail on this in the book.<br /> <br /> Sorry guys, this may not be the right forum to post this question because this is not about getting the exam question but learning <a href="http://www.javaranch.com" class="faq" title="A Friendly Place for Java Greenhorns" target="_new">Java</a>. However, the question did derived from one of the review question. Thank you for your reply and assisstance.<br /> <br /> -Cheung]]></description>
				<guid isPermaLink="true">http://www.coderanch.com/forums/posts/preList/448768/1997943</guid>
				<link>http://www.coderanch.com/forums/posts/preList/448768/1997943</link>
				<pubDate><![CDATA[Tue, Jun 9 2009 12:16:15 MDT]]></pubDate>
				<author><![CDATA[Cheung Chau]]></author>
			</item>
			<item>
				<title>Question Local Variable Scope</title>
				<description><![CDATA[Hi Jim,<br /> <br />    Sorry that I missed all the comment you made below your code block. However, I am still not very clear on what you mean by <br /> <br /> I would say it is because it is method level scoped, and when the method is in scope on the stack arguments are passed by value. So even though the method is free to extend beyond itself to the reference static/instance variables it still has the flexibility to re declare those names since they are not in scope<br /> <br /> Can you clarify?<br /> <br /> Here is my take on this - all local variables are defined on the stack and the stack won't allow code to define variable in the inner block with the same name outside that block. However, unlike static and instance variable, the order matters which mean the inner block won't see the any variable define after the inner block. This make define variable after the block with same name okay.<br /> <br /> I don't like the definition above becuase I made it up on the fly based on the review question. I wonder if anyone can offer a more logical and accurate explaination.<br /> <br /> Thank you<br /> <br /> -Cheung<br /> <br /> <br /> <br /> ]]></description>
				<guid isPermaLink="true">http://www.coderanch.com/forums/posts/preList/448768/1997994</guid>
				<link>http://www.coderanch.com/forums/posts/preList/448768/1997994</link>
				<pubDate><![CDATA[Tue, Jun 9 2009 15:04:07 MDT]]></pubDate>
				<author><![CDATA[Cheung Chau]]></author>
			</item>
			<item>
				<title>Question Local Variable Scope</title>
				<description><![CDATA[Like I think somebody said, the block has to honor the scope in which it occurs. <br /> <br /> If a block in a method declares a variable, that variable is scoped only to the block.  <br /> <br /> The method can subsequently declare a variable of the same name and type.<br /> <br /> But if the method declares the variable <i>before</i> the block attempts to declare it,<br /> the block version will cause a compiler error.<br /> <br /> So you listed the various scopes there and I imagine you're wondering why this is so. I think <br /> it is because those scopes are not necessarily independent of eachother.  At least here we see<br /> that the block scope can be controlled by the method scope in which it occurs, depending on<br /> the order of the declarations.]]></description>
				<guid isPermaLink="true">http://www.coderanch.com/forums/posts/preList/448768/1998043</guid>
				<link>http://www.coderanch.com/forums/posts/preList/448768/1998043</link>
				<pubDate><![CDATA[Tue, Jun 9 2009 17:20:08 MDT]]></pubDate>
				<author><![CDATA[Ken Truitt]]></author>
			</item>
			<item>
				<title>Question Local Variable Scope</title>
				<description><![CDATA[Ken,<br /> <br />       Thank you for your post. I wonder if you can extend on what you mean by scopes may be independent of each other. <br /> <br /> Hi all,<br /> <br />    <br />    Let's see if we can put a closure to this post. The following is directly from our <a href="http://www.javaranch.com" class="faq" title="A Friendly Place for Java Greenhorns" target="_new">Java</a> Language Specification <br /> <br />       <a class="snap_shots" href="http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html" target="_new" rel="nofollow">http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html</a><br /> <br />    Here is the part (directly from the language spec), I think (kind of) explain what we have here <br /> <br /> 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.<br /> <br /> Thus the following example does not compile:<br /> <br /> <br /> <pre>class Test {
	public static void main(String[] args) {
		int i;
		for (int i = 0; i &lt; 10; i++)
			System.out.println(i);
	}
}</pre><br /> <br /> This restriction helps to detect some otherwise very obscure bugs. A similar restriction on shadowing of members by local variables was judged impractical, because the addition of a member in a superclass could cause subclasses to have to rename local variables. Related considerations make restrictions on shadowing of local variables by members of nested classes, or on shadowing of local variables by local variables declared within nested classes unattractive as well. Hence, the following example compiles without error:<br /> <br /> <pre>class Test {
	public static void main(String[] args) {
		int i;
		class Local {
			{
				for (int i = 0; i &lt; 10; i++)
				System.out.println(i);
			}
		}
		new Local();
	}
}
</pre><br /> <br /> On the other hand, local variables with the same name may be declared in two separate blocks or for statements neither of which contains the other. Thus:<br /> <br /> <pre>class Test {
	public static void main(String[] args) {
		for (int i = 0; i &lt; 10; i++)
			System.out.print(i + &quot; &quot;);
		for (int i = 10; i &gt; 0; i--)
			System.out.print(i + &quot; &quot;);
		System.out.println();
	}
}</pre><br /> <br /> compiles without error and, when executed, produces the output:<br /> <br /> <b>0 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1</b><br /> <br /> <br /> I said "kind of" because I am still not totally sure about the following statement from the doc<br /> <br /> <blockquote class="uncited">
			<div>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.</div>
		</blockquote><br /> <br /> I hope someone can put in plain English. That's why I've always preferred Head First Java or Core Java over the formal Java specification  <img src="http://www.coderanch.com/images/smilies/283a16da79f3aa23fe1025c96295f04f.gif" /> <br /> <br /> <br /> <br /> -Cheung<br /> ]]></description>
				<guid isPermaLink="true">http://www.coderanch.com/forums/posts/preList/448768/1998518</guid>
				<link>http://www.coderanch.com/forums/posts/preList/448768/1998518</link>
				<pubDate><![CDATA[Wed, Jun 10 2009 08:17:24 MDT]]></pubDate>
				<author><![CDATA[Cheung Chau]]></author>
			</item>
			<item>
				<title>Question Local Variable Scope</title>
				<description><![CDATA[The statement you quoted is pretty awkward, but it breaks down to:<br /> <br /> If a variable declaration that appears in a method,constructor, or initializer block (ie a local variable) <br /> is within the scope of another local variable and has the same name, there will be a compiler error.<br /> <br /> In your example, the block variable is declared within a method that previously declared a same-typed<br /> variable of the same name.  This falls under the rule above.  But the rule above does not address the<br /> case where a block variable is declared within a method that subsequently declares a same-type,same-<br /> name variable as a local variable (outside of the block).  This compiles, but we would definately say that<br /> the scope of the block variable (in the second case) is within the scope of the local variable, because the<br /> scope of the local variable is the entire method. It appears that a local variable's scope <br /> is not the entire method in which it is declared, but only the part of the method that is defined *after* the<br /> local variable is first declared.  That understanding is consistent with the sentence from the language spec<br /> that you first quoted.<br /> <br /> Ken]]></description>
				<guid isPermaLink="true">http://www.coderanch.com/forums/posts/preList/448768/2000799</guid>
				<link>http://www.coderanch.com/forums/posts/preList/448768/2000799</link>
				<pubDate><![CDATA[Sat, Jun 13 2009 22:14:44 MDT]]></pubDate>
				<author><![CDATA[Ken Truitt]]></author>
			</item>
	</channel>
</rss>
