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?
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With