• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why we dont add element to arraylist out side the metod or constructor

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
if i write a program like bellow
it gives compile time error that packege listA doesnot exist

import java.util.*;
public class Strtok {


List listA = new ArrayList();

listA.add(new Integer(9));


}

if we write like bellow then it dont give anyy error it compiles and run

import java.util.*;
public class Strtok {

public void kcp(){
List listA = new ArrayList();

listA.add(new Integer(9));


ArrayList kcp=new ArrayList();
//kcp.add(lj);
//ArrayList kcp1=kcp;
}
}

can some one tell me what is the cause behind this
 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please use code tags.

In your first example, the method call is dangling in the class. Directly inside a class you can have declarations (constructors, methods, fields, nested classes) and static / initializer blocks only, no direct method calls.
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
collection you are populating must be inside a method or in a static block at class level....
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
And welcome to the Ranch
 
Rob Spoor
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

syed Imran wrote:collection you are populating must be inside a method or in a static block at class level....


Not static of course, since the List is not static. An initializer block (a static block but without the static key word) is what you probably meant.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic