What is the null literal and how can it be used in Java applications?

How many of you have encountered a NullPointerException? Today, we would like to discuss the null literal and how it can be used in Java. Feel free to share more in the comments.

The null literal in Java represents the absence of a value or a reference that doesn’t point to any object. According to my research, the null keyword in java is a literal. It is neither a data type nor an object. Null represents the absence of a value. If you assign a null to an object of string Class, it does not refer to any value in the memory.

The null cannot be assigned to primitive data types. The reserved word null is case sensitive and cannot be written as Null or NULL as the compiler will not recognize them and will certainly give an error.
null is used as a special value to signify: 1. It can also be used to initialise variables

String str = null; // str does not reference any object

  • Uninitialized state
  • Termination condition
  • Non-existing object
  • An unknown value

The null is used to express a particular value within a program. They are constant values that directly appear in a program and can be assigned now to a variable.

2. Checking for Null Values
NullPointer exception is thrown when you try to use a variable with a null value, so to avoid it, you need to check the NullPointerException as I did below

if (str != null) {
    System.out.println(str.length());
} else {
    System.out.println("String is null");
}

Enter fullscreen mode Exit fullscreen mode

  1. Explicitly Dereferencing You can use null to dereference an object and release its memory, then it will be eligible for garbage collection.
MyClass obj = new MyClass();
obj = null; // The object previously referenced by obj is now eligible for garbage collection

Enter fullscreen mode Exit fullscreen mode

Did you know that, you can explicitly add null values in ArrayLists.

List<String> list = new ArrayList<>();
list.add(null); // Adds a null value to the list

Enter fullscreen mode Exit fullscreen mode

Here I mentioned a few of what I have found. Share more in the comments to help others, including me, who want to know more.

原文链接:What is the null literal and how can it be used in Java applications?

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
Smash the waves would rather get in the way of the reef hill, also not willing to take a step back.
海浪宁可在挡路的礁山上撞得粉碎,也不肯后退一步
评论 抢沙发

请登录后发表评论

    暂无评论内容