• Post Reply Bookmark Topic Watch Topic
  • New Topic

difference between Arraylist declarations  RSS feed

 
Nabanita Sarkar
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone please explain the these two types of ArrayList declarations as follows:

ArrayList<String> locationCells;

and

ArrayList<String> locationCells= new ArrayList<String>();;
 
Christian Dillinger
Ranch Hand
Posts: 200
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both declarations declare "locationCell" to be an ArrayList which can contain String. The first is not initialized and is "null" (things like "locationCells.size()" won't work => NullPointerException), the second is initialized and can be used.
 
Liutauras Vilda
Sheriff
Posts: 4918
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, you could see declaration like:
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Christian Dillinger wrote:The first is not initialized and is "null" ...

Only if the variable is a member variable of a class, and not a local variable in a method.

Member variables are implicitly initialized to null. Local variables must be initialized, and if you don't and you try to use the variable, you'll get an error from the compiler.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!