0

Please help figure out why IntelliJ gives NullPointerException.

Exception in thread "main" java.lang.NullPointerException at ex3.Horse.about(Horse.java:16) at ex3.Horse.ride(Horse.java:21) at ex3.Hippodrome.main(Hippodrome.java:19)

Class Horse:

package ex3;

public class Horse {
    String name;
    int speed;
    String color;
    Boolean isMale;
    int age;

    void eat(){
        System.out.println("eating ... ");

    }

    void about(){
        String sex = (isMale) ? "Male" : "Female"; // тернарный оператор
        System.out.printf("name: %s, age: %d, sex: %s", name, age, sex);
    }

    void ride(){
        about();
        System.out.println("riding at speed: " + speed);


    }
}

And Class Hippodrome:

package ex3;

import java.util.Random;

public class Hippodrome {
    public static void main(String[] args) {
        Horse[] horses = new Horse[10];

        Random random = new Random();

        for (int i = 0; i < horses.length; i++) {
            horses[i] = new Horse();
            horses[i].name  = "Kon " + i;
            horses[i].age = 1 + random.nextInt(10);

        }

        for (Horse horse : horses) {
            horse.ride();
        }
    }
}
Alex K
  • 53
  • 5

1 Answers1

2

Boolean is a class, and as opposed to the primitive type boolean, when used as a field, its default value is null and not false.

That's why isMale will throw a NPE on the line String sex = (isMale) ? "Male" : "Female";

As @ACVM noted: You can fix this by initializing isMale to false or changing its type to boolean

Robin-Hoodie
  • 4,886
  • 4
  • 30
  • 63