Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: NULL in constructor

Please I have this question which is a bit theoretical, but I would like to understand it.

Why if I pass a null argument to a constructor do I get a NullPointerException?

This is my example

new AttendeeDetail("Gus Goose","1151","15-01-2012",(Integer) null,null) 

This is the class:

public class AttendeeDetail {

    private String ticketholder_name;
    private String user_id;
    private String date_of_birth;
    private int tickets_purchased;
    private ArrayList<Ticket> tickets;

    public AttendeeDetail(String ticketholder_name, String user_id, 
        String date_of_birth, int tickets_purchased, ArrayList<Ticket> tickets) 
    {
        this.ticketholder_name=ticketholder_name;
        this.user_id=user_id;
        this.date_of_birth=date_of_birth;
        this.tickets_purchased=tickets_purchased;
        this.tickets=tickets;
    }
}
like image 839
Lisa Anne Avatar asked Oct 06 '14 07:10

Lisa Anne


People also ask

Can constructor return null in Java?

Java Constructors Never Return Null.

What is null constructor in Java?

In computer programming, a nullary constructor is a constructor that takes no arguments. Also known as a 0-argument constructor or no-argument constructors.

Can constructors in Java be void?

Note that the constructor name must match the class name, and it cannot have a return type (like void ). Also note that the constructor is called when the object is created. All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you.

Can you use == for null in Java?

== and != The comparison and not equal to operators are allowed with null in Java. This can made useful in checking of null with objects in java.


Video Answer


1 Answers

an int can't be null. If you really need to pass a null value, use the Integer type

like image 89
jhamon Avatar answered Sep 21 '22 11:09

jhamon