Results 1 to 3 of 3
  1. #1
    Kagiso is offline Member
    Join Date
    Nov 2012
    Location
    Johannesburg, South Africa
    Posts
    92
    Rep Power
    0

    Question My code throws a NullPointerException.. How come ?

    Java Code:
    public class Unknown {
      public static void main(String args[]) {
            try {
                String arr[] = new String[10];
                arr = null;
                arr[0] = "one";
                System.out.print(arr[0]);
            } catch(NullPointerException nex) {
                System.out.print("null pointer exception");
            } catch(Exception ex) {
                System.out.print("exception");
            }
        }
    }
    I've got two questions...
    1st the variable arr is not declared, how does it go past the compiler?
    2nd the variable arr[0] points to a literal "one", how does the statement in line 7 throw a null pointer ecxeption?
    I no longer wish to take the ocjp exam
    Last edited by Kagiso; 04-27-2013 at 01:06 PM.

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,352
    Blog Entries
    7
    Rep Power
    20

    Default Re: My code throws a NullPointerException.. How come ?

    You set arr to null in line #5; you try to get element #0 in line #6 from something that is null ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    Kagiso is offline Member
    Join Date
    Nov 2012
    Location
    Johannesburg, South Africa
    Posts
    92
    Rep Power
    0

    Default Re: My code throws a NullPointerException.. How come ?

    OH how could I be so blind ? I pulled this question from a mock exam... & I didn't give the code a proper look
    I just rushed and made some silly assumptions

    THANKS A LOT Jos

Similar Threads

  1. Replies: 45
    Last Post: 04-10-2013, 03:33 PM
  2. HELP!! Code won't compile - NullPointerException
    By JuliaDavies in forum NetBeans
    Replies: 10
    Last Post: 03-21-2012, 09:29 AM
  3. HELP!! NullPointerException - code won't compile
    By JuliaDavies in forum NetBeans
    Replies: 2
    Last Post: 03-19-2012, 06:40 PM
  4. Replies: 1
    Last Post: 11-25-2009, 06:48 AM
  5. Recursive Class throws NullPointerException
    By freeBatjko in forum New To Java
    Replies: 5
    Last Post: 11-03-2009, 09:18 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
  •