简体   繁体   中英

Java: Arrays Exception in thread

Why the code doesn't print out the variable count that I changed threw creating array object?

public class EchoTestDrive {
public static void main(String args[]) {
    Echo[] pets;
    pets = new Echo[7];
    pets[0] = new Echo();
    pets[0].count = 43;
    pets[1].count = 50;
    **System.out.println(pets[0].count);**//doesn't prints out
    **System.out.println(pets[1].count);**//doesn't prints out
    //prints out: Exception in thread "main" java.lang.NullPointerException
    // at EchoTestDrive.main(EchoTestDrive.java:8)
}
}

Another class :

public class Echo {
int count = 0;
void hello(){
    System.out.println("helloooo... ");
   }
}
pets[1].count = 50;

This will raise java.lang.NullPointerException as pets[1] reference is null .

System.out.println(pets[0].count);

If you commented out the previous line, then this will definitely print 43.

System.out.println(pets[1].count);

If commented out pets[1].count = 50; line, then it would raise same java.lang.NullPointerException as pets[1] reference is null .

In short you forgot to initialise pets[1] which should be -

pets[1] = new Echo();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM