Results 1 to 3 of 3
  1. #1
    eva
    eva is offline Member
    Join Date
    Dec 2007
    Posts
    49
    Rep Power
    0

    Default multiple declaration of a variable

    Please review the code sample below:

    Java Code:
    	for(int i=1;i<10;i++)
    		{
    			System.out.println(i);
    		}
    		
    		int i=0;
    		
    		while(i<21)
    		{
    			System.out.println(i);
    			i++;
    		}
    I declared variable twice. Complier is not complaining and the code works fine. Why there isn't "Multiple declaration of i" error?

    - PEACE

  2. #2
    kureikougaiji is offline Member
    Join Date
    Nov 2007
    Posts
    15
    Rep Power
    0

    Default try

    maybe the compiler interpreted the variable i as a local i inside that for loop, and all other i's outside are different... i think... peace also...

  3. #3
    tim's Avatar
    tim
    tim is offline Senior Member
    Join Date
    Dec 2007
    Posts
    435
    Rep Power
    7

    Default See variable scopes

    Hello eva

    When you use a block ({}) or create a for loop you are creating a scope. :D When a variable is created in a scope, it only exists in that scope:
    Java Code:
    [COLOR="RoyalBlue"]// here i does not exist[/COLOR]
    for(int i=1;i<10;i++){
    	[COLOR="RoyalBlue"]// here i exist in the scope of the for loop[/COLOR]
    	System.out.println(i);
    }
    [COLOR="RoyalBlue"]// here i does not exist[/COLOR]
    int i=0;
    [COLOR="RoyalBlue"]// here i exist in the parent scope[/COLOR]
    while(i<21){
    	[COLOR="RoyalBlue"]// here i still exist in the parent scope[/COLOR]
    	System.out.println(i);
    	i++;
    }
    Eyes dwelling into the past are blind to what lies in the future. Step carefully.

Similar Threads

  1. Declaration
    By asifahmed in forum New To Java
    Replies: 1
    Last Post: 04-05-2008, 06:38 AM
  2. public declaration ('undeclaring')
    By Jadellll in forum New To Java
    Replies: 2
    Last Post: 03-17-2008, 09:50 PM
  3. Array size declaration
    By JT4NK3D in forum New To Java
    Replies: 3
    Last Post: 01-18-2008, 11:37 PM
  4. JSP Declaration Directive
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-10-2007, 06:42 PM
  5. Function declaration problem.
    By snooze-g in forum Advanced Java
    Replies: 3
    Last Post: 07-18-2007, 10:15 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •