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

Error: identifier expected pointing n=1;

Why am I getting this error?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
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,591
  • 8
  • 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
  • 10,691
  • 12
  • 80
  • 114
0

However, this is possible:

public class A{
    int n;
    {
       n = 1;
    }
}
T D Nguyen
  • 7,054
  • 4
  • 51
  • 71