class A {
int n;
n=1;
}
Error: identifier expected pointing n=1;
Why am I getting this error?
class A {
int n;
n=1;
}
Error: identifier expected pointing n=1;
Why am I getting this error?
Replace the code with int n = 1;
And this question seems to be the duplicate of Java instance variable declare and Initialize in two statements.
I don't have enough privileges, someone with the privileges, please label it as 'duplicate'.
Solution as already pointed in other answers is:
writing int n =1;
as single line.
But if you want to understand the reason for this error, it is that you cannot have statements inside the class body. Statements can only be inside methods/constructors/initialization blocks as @Eran pointed out.
When you do
int n = 1;
in single line, it's a special statement/expression and is called definition. So it's allowed as a special case.
Read more about statements and expressions here: JAVA statements and expressions