creating object in for loop

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hostel
    New Member
    • Feb 2007
    • 17

    creating object in for loop

    [CODE=Java]public class mainclass1 {
    public static void main(String[] args) {
    for(int i= 0;i<1;i++)
    a obj = new a();
    }
    }

    class a{
    }
    [/CODE]

    In the above program if you try to create an object with in "for" loop then you will get an error stating "not a statement "
    ex:
    [CODE=Java]for(int i= 0;i<1;i++)
    a obj = new a();[/CODE]


    but if you try to create an object with brackets then it will create without an error
    ex:
    [CODE=Java]for(int i= 0;i<1;i++) {
    a obj = new a();
    }[/CODE]

    why is it so , and whats the problem , Please explain it.

    Thanks in advance.
  • BigDaddyLH
    Recognized Expert Top Contributor
    • Dec 2007
    • 1216

    #2
    Please enclose your posted code in [code] tags (See How to Ask a Question).

    This makes it easier for our Experts to read and understand it. Failing to do so creates extra work for the moderators, thus wasting resources, otherwise available to answer the members' questions.

    Please use [code] tags in future.

    MODERATOR

    Comment

    • BigDaddyLH
      Recognized Expert Top Contributor
      • Dec 2007
      • 1216

      #3
      That's just how the syntax is defined. You can unravel it here: http://java.sun.com/docs/books/jls/t...ntax.html#18.1

      Basically, the body of a for loop can be many things, including a block {...}, but the body can't be a LocalVariableDe clarationStatem ent. What's the lesson? None, really. Most Java developers automatically put braces around their loop bodies -- problem, solved.

      Comment

      Working...