-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
  • 879,024
  • 165
  • 1,615
  • 1,639
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
  • 6,040
  • 2
  • 17
  • 44
RCInd
  • 304
  • 2
  • 12