class level error : expected in java

后端 未结 4 495
陌清茗
陌清茗 2021-01-29 13:36

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

相关标签:
4条回答
  • 2021-01-29 13:55

    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;
     }
    }
    
    0 讨论(0)
  • 2021-01-29 14:02

    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
    }
    
    0 讨论(0)
  • 2021-01-29 14:06

    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;
    
    0 讨论(0)
  • 2021-01-29 14:13

    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.

    0 讨论(0)
提交回复
热议问题