Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused with Java Objects

Tags:

java

arrays

I am a beginner with Java, and I am trying the following code:

public class MovieTestDrive {

    public static void main(String[] args) {
        Movie one = new Movie();
        one.title = "Gone with the Stock";
        one.playIt();
        System.out.println(one.title);   // Works!! one.title is equal to Dora

        Movie [] arr = new Movie[2];
        arr[0].playIt();
        System.out.println(arr[0].title); //Error: Null Pointer Exception

    }
}


class Movie {

        String title;

        void playIt() {
             title = "Dora";
        }

 }

Why does the code works in the assignment of a primitive variable while it doesn't when using an array?

like image 512
newbie Avatar asked Aug 17 '26 06:08

newbie


2 Answers

Because all you have in arr is an array of object references, but they're not initialized to point at any actual objects.

You also need to do:

arr[0] = new Movie();
arr[1] = new Movie();
like image 189
unwind Avatar answered Aug 19 '26 20:08

unwind


Nothing is in your movie array yet. You need to put objects in your array before you can act upon them.

Between "Movie [] arr = new Movie[2];" and "arr[0].playIt();", you need to assign Movie objects to your array in order to perform the .playIt() function and have anything actually occur.

like image 33
Zoot Avatar answered Aug 19 '26 19:08

Zoot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!