如何检查int是否为null [英] How to check if an int is a null

查看:152
本文介绍了如何检查int是否为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Person 的对象。

它有几个属性;

int id;
String name;

我设置了一个人物对象,如人物p =新人(1, Joe);

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

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

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。)我需要知道ID是否包含Int。

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

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

但是,java不允许它。我该如何检查?

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

推荐答案

int 不为空,它可能是 0 如果没有初始化。

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

如果你想要一个整数能够为null,你需要使用 Integer 而不是 int

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; }

除了语句 if(person.equals(null))不能为真,因为如果 person 为null,则抛出 NullPointerException 。所以正确的表达式是 if(person == null)

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)

这篇关于如何检查int是否为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆