What is null in Java and matters needing attention in use

1. Null is neither an object nor a type. It is only a special value. You can assign it to any reference type, or you can convert null to any type, for example:

Integer i=null; Float f=null; String s=null;

However, null cannot be assigned to basic types, such as int, float, double, etc

Int k = null ------------ the compiler will report an error cannot convert from null to int

2. Null is a keyword, such as public, static and final. It is case sensitive. You cannot write null as null or null, otherwise the compiler will report an error

3. The wrapper class containing null value will throw a null pointer exception when Java unpacks to generate basic data types

For example:

Integer i=null; int k=i;--------------------------- Throw Java lang.NullPointerException

4. When traversing a set or array, you need to add null judgment, otherwise when the set or array contains null, an exception will be thrown

5. When using equals to judge whether the strings are equal, place the constant string to the left of equals to prevent null pointer exceptions

For example:

String[] arr1={"abc","123",null,"sky"}; for (String s1 : arr1) { boolean flag=s1.equals("sky"); } ------------ When the value is = null, a null pointer exception will be thrown, and S1 Equals ("sky") is changed to "sky" Equals (S1), you can avoid throwing exceptions

6. Difference between empty string and null

type

Null represents the value of an object, not a string. For example, declare a reference to an object, string a = null;

"" represents an empty string, that is, its length is 0. For example, declare a string string STR = "";

memory allocation

String str = null ; Indicates that a reference to a string object is declared, but the pointer is null, that is, it does not point to any memory space;

String str = ""; Means declaring a reference of string type whose value is "" empty string. This STR reference points to the memory space of the empty string;

In Java, variables and reference variables are stored in the stack, while objects (generated by new) are stored in the heap:

The above discussion on what null is in Java and the matters needing attention in use are all the contents shared by Xiaobian. I hope to give you a reference and support more programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>