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!