java int == null_如何检查int是否为null

问题

我有一个名为Person的对象。

它有几个属性;

int id;

String name;

我设置了像Person p = new Person(1,"Joe");这样的人物对象。

1.)我需要检查对象是否为空;以下表达式是否正确;

if (person == null){

}

Or

if(person.equals(null))

2.)我需要知道ID是否包含Int。

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

但是,java不允许它。我该怎么做这个检查?

#1 热门回答(130 赞)

Anint不为空,可能是0if未初始化。

如果希望整数能够为null,则需要使用Integer而不是int。

Integer id;

String name;

public Integer getId() { return id; }

除了声明58590819不可能是真的,因为ifperson为null,那么aNullPointerException将被抛出。所以正确的表达是if (person == null)

#2 热门回答(37 赞)

原语没有空值。 int的默认值为0。

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

java中基元的默认值:

Data Type Default Value (for fields)

byte 0

short 0

int 0

long 0L

float 0.0f

double 0.0d

char u0000

boolean false

对象具有null作为默认值。

字符串(或任何对象)---> null

1.)我需要检查对象是否为空;以下表达式是否正确;

if (person == null){

}

上面的代码检查人是否为空。你需要做的

if (person != null){ // checks if person is not null

}

if(person.equals(null))

当person为null时,上面的代码将抛出NullPointerException。

#3 热门回答(10 赞)

原语int不能为空。如果你需要null,请使用Integer。

问题 我有一个名为Person的对象。 它有几个属性; int id; String name; 我设置了像Person p = new Person(1,"Joe");这样的人物对象。 1.)我需要检查对象是否为空;以下表达式是否正确; if (person == null){ } Or if(person.equals(null)) 2.)我需要知道ID是否包含Int。 if(person.getId()==null){} 但是,java不允许它。我该怎么做这个检查? #1 热门回答(130 赞) Anint不为空,可能是0if未初始化。 如果希望整数能够为null,则需要使用Integer而不是int。 Integer id; String name; public Integer getId() { return id; } 除了声明58590819不可能是真的,因为ifperson为null,那么aNullPointerException将被抛出。所以正确的表达是if (person == null) #2 热门回答(37 赞) 原语没有空值。 int的默认值为0。 if(person.getId()==0){} java中基元的默认值: Data Type Default Value (for fields) byte 0 short 0 int 0 long 0L float 0.0f double 0.0d char u0000 boolean false 对象具有null作为默认值。 字符串(或任何对象)---> null 1.)我需要检查对象是否为空;以下表达式是否正确; if (person == null){ } 上面的代码检查人是否为空。你需要做的 if (person != null){ // checks if person is not null } 和 if(person.equals(null)) 当person为null时,上面的代码将抛出NullPointerException。 #3 热门回答(10 赞) 原语int不能为空。如果你需要null,请使用Integer。
经验分享 程序员 微信小程序 职场和发展