0
class A {
    int n;
    n=1;
}

Error: identifier expected pointing n=1;

Why am I getting this error?

ROMANIA_engineer
  • 51,252
  • 26
  • 196
  • 186
deepam
  • 11
  • 1

3 Answers3

0

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'.

Community
  • 1
  • 1
Nabin Paudyal
  • 1,533
  • 7
  • 14
0

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

tryingToLearn
  • 9,007
  • 10
  • 70
  • 99
0

However, this is possible:

public class A{
    int n;
    {
       n = 1;
    }
}
T D Nguyen
  • 6,193
  • 4
  • 43
  • 63