Results 1 to 3 of 3
  1. #1
    Tom_Snake is offline Member
    Join Date
    Oct 2011
    Posts
    18
    Rep Power
    0

    Default Check instance variable if null

    Hey guys, doing a linked list project in school.
    The list is implemented in a class, and nodes are stored as a different class within the LinkedList class.
    So, I'm trying to verify that the instance variable next != null before doing a certain thing with the information, but the null pointer exception is thrown when trying to verify this.
    here be code:
    Java Code:
            ListElement<T> test = null;
            int testSize = 0;
            if(first != null){
                test = first;
                testSize = 1;
            }
            while(test.next != null){
                test = test.next;
                testSize++;
            }
    The compiler highlights the test.next != null, where test.next is null by default, but may point to other ListElements. Whats my logical flaw here?

    /T.S

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default Re: Check instance variable if null

    You set test to null initially, then only reassign it to something non-null if first != null.
    So if 'first' is null then so is test, so test.next gives you an NPE.

  3. #3
    Tom_Snake is offline Member
    Join Date
    Oct 2011
    Posts
    18
    Rep Power
    0

    Default Re: Check instance variable if null

    Of course. After a while with the code you miss even the simplest of logical flaws. Thank you, a small change and it'll work like a charm.

    /T.S

Similar Threads

  1. Updating the Instance Variable of a Class
    By Leo11221 in forum New To Java
    Replies: 19
    Last Post: 12-01-2011, 06:07 PM
  2. How to check instance of a generic class?
    By chan_nguyen in forum New To Java
    Replies: 7
    Last Post: 09-08-2010, 05:20 AM
  3. Naming a class instance with a variable
    By pikalex88 in forum New To Java
    Replies: 3
    Last Post: 09-30-2008, 07:27 PM
  4. Instance Variable In Servlet
    By javarishi in forum Java Servlet
    Replies: 3
    Last Post: 06-14-2008, 09:28 AM
  5. Instance variable
    By Jack in forum New To Java
    Replies: 2
    Last Post: 07-04-2007, 05:00 AM

Posting Permissions

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