Results 1 to 2 of 2
  1. #1
    ssk2659 is offline Member
    Join Date
    Jan 2015
    Posts
    48
    Rep Power
    0

    Default Why am I getting NullPointerException in the method?

    Hello... I'm still stuck in the same collatedExam method problem but Why am I getting NullPointerException in this line r[index] = new Exam(r[index].getFirstName(), r[index].getLastName(), r[index].getID(), r[index].getExamType(), r[index].getScore()); fn the method ?
    Java Code:
    public static Exam[] collateExams(Exam[] exams)
    	{
    		//Exam [] r = new Exam[exams.length];
    		Exam[] r = new Exam[exams.length]; 
    		int [] position = new int[exams.length];
    		int index = 0;
    		
    		for (int i = 0; i < exams.length; i++)
    		{
    			if(exams[i].getExamType() == 'm')
    			{
    				r[index] = new Exam(r[index].getFirstName(), r[index].getLastName(), r[index].getID(), r[index].getExamType(), r[index].getScore());
    				
    			}
    return r;
    		}

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,716
    Rep Power
    18

    Default Re: Why am I getting NullPointerException in the method?

    A NullPointerExpression occurs whenever you use a variable or expression as if it had a non-null value when, in fact, it's value is null.

    So an expression like r[index] will cause problems if r is null. index itself is primitive, so null values aren't a problem.

    Even if r is ok, r[index].getFirstName() will give an NPE if r[index] is null. Notice that even if r[index].getFirstName() is null that won't be a problem at the line reported. If a null argument to the Exam constructor causes a problem it will be reported somewhere else (in the Exam code).

    So we have candidates for being null: r and r[index]. It's worth pausing at this point and verifying that nothing else on that line absolutely must have a non-null value. You may be able to see why the first isn't a problem. But, in any case, the strategy is (a) find out which is null using System.out.println()

    Java Code:
    System.out.println("About to start the for loop");
    System.out.println("r = " + r);
    System.out.println("r[index] = " + r[index]);
    for (int i = 0; i < exams.length; i++)
    {
        // etc
    (b) Once you have found the culprit, go back through your code to where you had thought you had given it a non-null value and figure out why that didn't happen.
    Last edited by pbrockway2; 02-15-2015 at 05:53 AM.

Similar Threads

  1. Replies: 1
    Last Post: 12-12-2013, 08:08 PM
  2. Replies: 7
    Last Post: 04-11-2013, 06:31 AM
  3. Replies: 2
    Last Post: 03-23-2012, 05:53 AM
  4. Replies: 15
    Last Post: 10-30-2011, 07:02 AM
  5. Replies: 1
    Last Post: 10-17-2011, 02: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
  •