DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

+ Reply to Thread
Results 1 to 2 of 2
  1. #1
    Join Date
    Feb 2005
    Posts
    1

    Variable Initialiazation

    I'm here would like to know about the variable declaration.
    I found that if we define more than one variable with the same name, it will be an error - >1.e: Variable 'test' is already defined in this method.
    But we fefined it inside the loop (as shown below), it has no error, may I know why??? how it works techinically?

    Define out of the loop
    int test = 1;
    int test = 2;


    Define inside the loop

    for(int count=0;count<5;count=count+2){

    int test = 1;
    }

    pls advice.....

  2. #2
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    That one does not compile. The test defined
    outside the for-loop's brackets has a scope that covers
    the one inside the loop brackets and therefore is a
    duplicate definition. If the variables in your example are
    class-vrliables ans your loop is inside a method, then
    the its ok.

    this fails to compile:

    Code:
    int b=4; // definition scope covers form here to the end of the method that contains the loop
    .
    .
    for (int i=0;i<5;i++) {
          int b=7;  // double definition
    }
    this is ok:
    Code:
    for (int i=0;i<5;i++) {
          int b=7; // definition scope is from here to the first right-bracket
    }
    int b=4; // this has no 'backwards' scope
    Check out the java rules on variables' definition scope.
    eschew obfuscation

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


Top DevX Stories

Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL


Sponsored Links