Why null pointer exception is thrown ?
package com.codegym.task.task08.task0824;
/*
Make a family
*/
import java.util.ArrayList;
public class Solution {
public static void main(String[] args) throws Exception {
Human Anu = new Human("Anu",false,27,null);
Human Faiza = new Human("Faiza",false,25,null);
Human Ricky = new Human("Ricky",true,29,null);
ArrayList<Human> children = new ArrayList<>(), father = new ArrayList<>(), mother = new ArrayList<>();
children.add(Anu); children.add(Faiza); children.add(Ricky);
Human Samita = new Human("Samita",false,56,children);
Human Jatin = new Human("Jatin",true,62,children);
father.add(Jatin); mother.add(Samita);
Human Subhani = new Human("Subhani",false,70,father);
Human Yogindar = new Human("Yogindar",true,77,father);
Human Meena = new Human("Meena",false,69,mother);
Human Prajosh = new Human("Prajosh",true,76,mother);
System.out.println(Prajosh);
System.out.println(Meena);
System.out.println(Subhani);
System.out.println(Yogindar);
System.out.println(Samita);
System.out.println(Jatin);
System.out.println(Anu);
System.out.println(Ricky);
System.out.println(Faiza);
}
public static class Human {
String name;
boolean sex;
int age;
ArrayList<Human> children;
public Human(String name, boolean sex, int age, ArrayList<Human> children)
{
this.name = name;
this.sex = sex;
this.age = age;
this.children = children;
}
public Human(String name, boolean sex, int age)
{
this.name = name;
this.sex = sex;
this.age = age;
}
public String toString() {
String text = "";
text += "Name: " + this.name;
text += ", sex: " + (this.sex ? "male" : "female");
text += ", age: " + this.age;
int childCount = this.children.size();
if (childCount > 0) {
text += ", children: " + this.children.get(0).name;
for (int i = 1; i < childCount; i++) {
Human child = this.children.get(i);
text += ", " + child.name;
}
}
return text;
}
}
}