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

Error: identifier expected pointing n=1;

Why am I getting this error?

2
  • 5
    n=1; can only appear in a method/constructor/initialization block. Commented Mar 23, 2016 at 11:15
  • I'm not sure if you know about you're asking.... Eran is right ! Commented Mar 23, 2016 at 11:24

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

However, this is possible:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.