-2

Why is this declaration wrong? This declaration leads to identifier expected error

class Abc{
    static ArrayList<Integer> p;
    p = new ArrayList<Integer>(); // identifier expected error
} 

2 Answers2

2

You have a freestanding assignment statement in your class body. You can't have step-by-step code there, it has to be within something (an initializer block, a method, a constructor, ...). In your specific case, you can:

  • Put that on the declaration as an initializer

    static ArrayList<Integer> p = new ArrayList<>();
    
  • Wrap it in a static initialization block

    static {
        p = new ArrayList<Integer>();
    }
    

More in the tutorial on initializing fields.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

This is the right way to do it :

import java.util.ArrayList;

public class Abc {
    static ArrayList<Integer> p;
    static {    
        p = new ArrayList<Integer>(); // works
    } 
}
ibenjelloun
  • 7,425
  • 2
  • 29
  • 53
RCInd
  • 344
  • 2
  • 13