Results 1 to 5 of 5
  1. #1
    stuckonjava is offline Senior Member
    Join Date
    Jan 2012
    Posts
    151
    Rep Power
    3

    Default Quick Question!!!!!!!!

    public class Question1{
    private List myList;

    public static void main (String[] args){
    myList = newLinkedList();
    myList.add("one");
    myList.add("two");
    System.out.println(myList);
    }
    }


    Could someone please explain why this doesn't compile whilst this does:

    public class Question1{
    private List myList;

    public void execute(){
    myList = newLinkedList();
    myList.add("one");
    myList.add("two");
    System.out.println(myList);
    }
    public static void main (String[] args){
    new Question1().execute():
    }
    }


    Thank you

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default Re: Quick Question!!!!!!!!

    What errors do you get?

  3. #3
    stuckonjava is offline Senior Member
    Join Date
    Jan 2012
    Posts
    151
    Rep Power
    3

    Default Re: Quick Question!!!!!!!!

    the first one doesn't compile because 'private list myList;' is not static. I don't understand why this works for the second one though

  4. #4
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default Re: Quick Question!!!!!!!!

    In the first one you are directly referencing an instance variable through main. Since this is an instance variable, it only exists in an instance of the object in which it belongs. In the second approach you create an object and then refer to it's integers with the 'new' line. In approach 1, change the variable to

    Java Code:
    private static List myList;

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,237
    Rep Power
    19

    Default Re: Quick Question!!!!!!!!

    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

Similar Threads

  1. Quick question
    By Qsc in forum New To Java
    Replies: 6
    Last Post: 07-25-2011, 04:36 AM
  2. Really quick question
    By shadycharacter in forum New To Java
    Replies: 2
    Last Post: 04-22-2010, 10:06 PM
  3. Quick question
    By sAntA199 in forum New To Java
    Replies: 2
    Last Post: 12-09-2009, 03:01 AM
  4. One last quick question
    By jigglywiggly in forum New To Java
    Replies: 7
    Last Post: 01-26-2009, 08:53 AM
  5. Quick Question
    By Spenc in forum New To Java
    Replies: 3
    Last Post: 09-22-2008, 02:26 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •