when I am coding this at class level
int a;
a=5;
it throws error : \"identifier expected\"
But when I declare it as a local variable li
You can not write code into the class, only in method, constructor or into initializer {} block. That is why you get syntax error. Probably you want to use initializer block like this:
class my{
int a;
{
a=1;
}
}
When you're doing this at class level, you're allowed to combine declaration and assignment in just one statement, like:
class A {
int a = 5;
}
Otherwise, you have to wrap the assignment withing a block (constructor, method, initializer block). For example:
class A {
int a;
public A() { a = 5; } //via constructor
void setA() { a = 5; } //via method
{ a = 5; } //via initializer block
}
The reason following:
int a=5;
declared at class level does not produce compile time error when:
void m1() {
int a;
a=5;
}
is declared because m1()
has its own scope.
For instance, if don't declare and access variable a
, it would refer to class's field, where as when you declare a
locally, you'd always refer to one declared inside a
.
PS : You cannot do following at class level:
int a;
a=5;
You'd have to:
int a=5;
Assigning a value to variable is called as expression. We could not write any expression in a class. We could do the same in method bodies. Basically we could right expressions when scope is defined and hence allowed in method.