One, the introduction

I was having dinner with my buddies the other day and I was talking about why NULL was put first. Brother said: “The reason for null is to avoid null Pointers.” Is that really the case?

Second, the inquiry

Why do null-pointer exceptions occur? A null pointer exception will be raised if you reference a null object and perform a series of operations on the object.

public static void main(String[] args) { Integer obj = null; If (obj == null){system.out.println ("obj = null"); }}Copy the code

Output result:



As it turns out, this has nothing to do with null Pointers!

Three, why to write so?

Avoid obj = null in if. Is this true?

public static void main(String[] args) { Integer obj = null; /*if (obj == null) {system.out.println ("obj = null"); If (obj = null) {system.out.println ("obj = null"); }}Copy the code

In fact, if I write obj = null, I’m going to get a compile-time exception, and I’m not going to get a compile-time exception, so what do you say? Why did you write that? I think it’s just a personal style of programming!

Fourth, the end

I am Cheers! , just entered the workplace of a small white, welcome you big guy artillery! Thank you very much!