-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
} 
4
  • put curly braces around 2nd line Commented Feb 16, 2018 at 9:09
  • 2
    or just do it like this: static ArrayList<Integer> p = new ArrayList<Integer>(); .. better would be to code to interfaces and use the more up to date way to work with generics: static List<Integer> p = new ArrayList<>(); Commented Feb 16, 2018 at 9:11
  • 1
    "Why is this declaration wrong?" p = new ArrayList<Integer>(); is not declaration, it is initialization. Commented Feb 16, 2018 at 9:14
  • 2
    @akshayapandey: It would still be wrong. Commented Feb 16, 2018 at 9:14

2 Answers 2

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.

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

Comments

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
    } 
}

2 Comments

that's a working way to do it, plenty of possible improvements though.
true. the code pasted is erroneous. what i meant was that this the correct syntax (braces)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.