Home > Java > JavaBase > How to determine whether an object is null in java

How to determine whether an object is null in java

Release: 2019-12-23 15:26:33
Original
4065 people have browsed it

How to determine whether an object is null in java

The Java language supports two data types, namely basic data types and reference data types, and null is a special reference data type.

To determine whether an object is null, you can use if (obj == null) { }. The code is as follows:

// 判断对象是否为null
if (str1 != null) {
    int len = str1.length();
}
Copy after login

If you change the above code to the following code:

String str2 = "";
int num = str2.length();
System.out.println(num);    // 输出结果为0
Copy after login

No exception is thrown when running the above code, because str2 is a string object with a value of "" . "" represents an empty string with a length of 0, which will be allocated a space in the memory. str2 is an instantiated object that directly points to the "" memory space.

There are two main possibilities for generating empty objects:

1. The programmer forgot to instantiate himself, so the programmer must prevent this from happening and should carefully check his own code. Instantiate and initialize all objects you create.

2. The empty object is passed from other places and needs to be avoided by determining whether the object is null.

For more java knowledge, please pay attention to the java basic tutorial column.

The above is the detailed content of How to determine whether an object is null in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template