Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an object called Person.

it has several attributes in it;

int id;
String name;

i set a person object like Person p = new Person(1,"Joe");.

1.) I need to check if the object is not null; Is the following expression correct;

if (person == null){
}

Or


if(person.equals(null))

2.) I need to know if the ID contains an Int.

if(person.getId()==null){} 

But, java doesn't allow it. How can i do this check ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
134 views
Welcome To Ask or Share your Answers For Others

1 Answer

An int is not null, it may be 0 if not initialized.

If you want an integer to be able to be null, you need to use Integer instead of int.

Integer id;
String name;

public Integer getId() { return id; }

Besides the statement if(person.equals(null)) can't be true, because if person is null, then a NullPointerException will be thrown. So the correct expression is if (person == null)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...