educative.io

Why does below code return null?

class Demonstration {

    public static void main( String args[] ) {

        (new SpecialPerson()).print();

    }

}

class SpecialPerson {

    String fullName = init();

    String name = "batman";

    public SpecialPerson() {

        name = "superMan";

    }

    private String init() {

        return name;

    }

    public void print() {

        System.out.println(fullName);

    }

}

Hello, @Atul,
The code returns null because we are calling the init() method, which is returning name before the name has been initialized. Hence, init() method returns null. For further clarity, try initializing the name variable before calling the init() method and see the outcome. Hope this answers your query. Feel free to ask any questions if you still have any confusion.

1 Like