Can somebody explain this ?
Hi All,
1)
publicclass A{
int i=10;// no error
}
2)
publicclass A
{
int i;
i=10;// error why ?
publicstaticvoid main(String args[]){}
}
3)
publicclass A
{
publicstaticvoid main(String args[]){
int i;
i=10;// no error
}
}
Why I am getting error in example 2.
<identifier> expected
Please explain this.
Thank in advance
-AKJ
int i=10;
declares and initializes a field (when place directly into the class' body), that's just fine.
int i;
i = 10;
declares a field and executes a statement, that tries to assign a value to it. Statements can't be placed direcly into the class' body, they have to be contained in a constructor, a method or a static initializer block.
the third example that you present doesn't declare a field at all, but rather a local variable.
Hi,
in your first class A you assign value to i in a same declaration, its default , so no error,
but in your second class A you declare i and assign value in new line or new statement,
that line must inside any of your business method,
third class A , you see,
you declare i as local variable in main (), so you assign a value for i in next statement or any where inside that main() block,
so no error,
one more different ,
first & second class A : i is the member of that class
third class A : i is the local variable of main method, its not a member of class
> declares a field and executes a statement, that tries
> to assign a value to it. Statements can't be placed
> direcly into the class' body, they have to be
> contained in a constructor, a method or a static
> initializer block.
Or a non-static initializer block.
dwga at 2007-7-29 18:55:26 >

> > declares a field and executes a statement, that
> tries
> > to assign a value to it. Statements can't be
> placed
> > direcly into the class' body, they have to be
> > contained in a constructor, a method or a static
> > initializer block.
>
> Or a non-static initializer block.
Ok ... i thought I've covered all bases, but I always forget those .. probably because I use them even less often than static initializer blocks ...