user2240664
user2240664

Reputation: 193

Nullpointer exception Java

I am a beginner in Java and I have a few problems with null. I need help with understanding the following questions. I have answered them correctly, however I do not know the exact reason behind them.

Question:

Suppose that tracks has been declared with type ArrayList and consider the following:

public Track mostPlayed() {
    Track most = tracks.get(0);
    int i = 1;
    while(i < tracks.size()) {
        Track t = tracks.get(i);
        if (t.getPlayCount() > most.getPlayCount()) {
             most = t;
        }
        i++;
    }
return most;
}

Suppose that a NullPointerException is thrown during an execution of the mostPlayed method. Assuming single-threaded execution, only one of the following lines of code is possible because of this exception. Which one?

I had picked line 2 as it seemed the only logical answer, but I would like further explanation behind it as I don't understand the concept completely.

Upvotes: 0

Views: 181

Answers (3)

Osama Javed
Osama Javed

Reputation: 1442

Java is an object oriented programming language and Objects serve as a basic building block.

In many real life there are cases where objects cannot be created.

A null object represents a special value which says that this object does not exist.

For e.g If I say Person p;. At this point java will assign null value to p. Now If I try something like p.getName() , obviously java will not be able to give me the name of the person since I never created one. Therefore whenever you try to access something using a variable which is null, java trows an error.

There are lots of resources covering this topic if you need a better understanding. Please note that using default/place holder values like null is a very common concept used in even non object oriented languages.

For your question above. Tracks can be null since someone can just do ArrayList<Tracks> tracks and never initialize it using the new keyword.

Furthermore you can do tracks.add(null); which stores a null value into the list. Therefore when you do a tracks.get(i) , you might receive a null value.

And as explained above invoking get or getPlayCount() can therefore cause null pointer exceptions.

I would highly recommend you read up on some of the introductory materials on Java since I believe this topic would be discussed thoroughly in such materials.

Upvotes: 0

Daniel Pereira
Daniel Pereira

Reputation: 2785

The line Track most = tracks.get(0); can throw a NullPointerException since the code does not show if track was initialized. If it was not, it will be null and it there is no method get in null (there is no method at all, actually).

Upvotes: 0

Thierry
Thierry

Reputation: 5233

t.getPlayCount() can throw a NullPointerException if the ArrayList tracks contains a 'null' at some index.

and also Track most = tracks.get(0); can throw a NullPointerException if tracks is not initialized.

Upvotes: 4

Related Questions