3

Why am I getting a NullPointerException with this code?

public static void main(String args[]) throws FileNotFoundException {

    int i = 0;
    Job[] job = new Job[100];
    File f = new File("Jobs.txt");
    Scanner input = new Scanner(f);

    while (input.hasNextInt()) {
        job[i].start = input.nextInt();
        job[i].end = input.nextInt();
        job[i].weight = input.nextInt();
        i++;
    }
}

I get the error at the very first line of the while loop on its very first run-through. I also have a separate class:

public class Job {
    public int start, end, weight;
}

and the text file:

0 3 3
1 4 2
0 5 4
3 6 1
4 7 2
3 9 5
5 10 2
8 10 1

Thank you.

3
  • Thanks all! Simple mistake, simple answer. Commented Oct 29, 2013 at 14:18
  • Happens to every programmer, Someday :) Commented Oct 29, 2013 at 14:27
  • NPE problem without a stacktrace. Commented Nov 4, 2013 at 8:14

3 Answers 3

8

NullPointerException

Thrown when an application attempts to use null in a case where an object is required. These include:

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

    Job[] job = new Job[100];

As of now all values in array are null. Because you not inserted any Job objects inside.

  job[i].start = input.nextInt(); // job[i]  is null.

What you have to do is just initialize a new Job object and assign to the current index.

Becomes,

while (input.hasNextInt()) {
        Job job = new Job(); 
        job.start = input.nextInt();
        job.end = input.nextInt();
        job.weight = input.nextInt();
        job[i] =job;
        i++;
    }
Sign up to request clarification or add additional context in comments.

Comments

5

See 4.12.5. Initial Values of Variables:

For all reference types (§4.3), the default value is null.

You need to initialize job array before trying to access it, now it's like writing null.start, which of course causes NullPointerException.

1 Comment

@sᴜʀᴇsʜᴀᴛᴛᴀ Was looking for that for about 3 mins :D
4

You just initialized an array of Job type, you haven't initialized each element in the array, hence the exception.

 while (input.hasNextInt()) {
        job[i] = new Job(); // initialize here
        job[i].start = input.nextInt();
        job[i].end = input.nextInt();
        job[i].weight = input.nextInt();
        i++;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.