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

How to determine whether an object is null in java

尚
Original
2019-12-23 15:26:334064browse

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

If you change the above code to the following code:

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

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!

Statement:
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