杰瑞科技汇

Java中null=null会报错吗?

Excellent question. This touches on a fundamental concept in Java: how the operator works.

Java中null=null会报错吗?-图1
(图片来源网络,侵删)

Let's break it down.

The Short Answer

Yes, in Java, null == null evaluates to true.

The Detailed Explanation

To understand why, we need to look at what the operator does in Java.

What Compares

In Java, the operator compares two things based on their type:

Java中null=null会报错吗?-图2
(图片来源网络,侵删)
  • Primitive Types (e.g., int, double, boolean): compares the values. For example, 5 == 5 is true.
  • Reference Types (e.g., String, Object, any custom class): compares the memory addresses (or "references") of the objects. It checks if two references point to the exact same object in memory.

The Nature of null

The null keyword is a special literal in Java. It is not an object. It represents the "absence of a value" or "no object."

When you declare a reference variable and don't initialize it to point to an object, it automatically holds the value null.

String myString; // myString is null by default
Object myObject = null; // myObject is explicitly set to null

Putting It All Together: null == null

When you write null == null, you are comparing two references that both hold the special null value.

  • Neither null points to an actual object in memory.
  • They both represent the same concept: "no object."

Therefore, the Java language specification defines that null == null must be true. It's a consistent and logical rule. If two references are both "not pointing to anything," they are considered equal in this context.

Java中null=null会报错吗?-图3
(图片来源网络,侵删)

Code Example

Here is a simple, runnable example that demonstrates this.

public class NullComparison {
    public static void main(String[] args) {
        // Declare two reference variables and set them to null
        String str1 = null;
        String str2 = null;
        // Compare them using ==
        boolean result = (str1 == str2);
        // Print the result
        System.out.println("Is str1 == str2? " + result); // Output: Is str1 == str2? true
        // Let's compare a null reference to a non-null one
        String str3 = "Hello World";
        boolean result2 = (str1 == str3);
        System.out.println("Is str1 == str3? " + result2); // Output: Is str1 == str3? false
    }
}

Output:

Is str1 == str2? true
Is str1 == str3? false

Important: vs. .equals() for Objects

A common point of confusion is mixing up and .equals(). It's crucial to understand the difference, especially when dealing with objects like String.

  • : Checks if two references point to the exact same object in memory.
  • .equals(): Checks if two objects are logically equivalent (i.e., their contents are the same).

Example with String

public class EqualsVsEquals {
    public static void main(String[] args) {
        // Create two String objects with the same content
        String s1 = new String("hello");
        String s2 = new String("hello");
        // s1 and s2 are two different objects in memory
        System.out.println("s1 == s2: " + (s1 == s2));       // Output: false (different memory addresses)
        // But their content is logically the same
        System.out.println("s1.equals(s2): " + s1.equals(s2)); // Output: true (same content)
        // --- The special case for String literals ---
        // Java can optimize string literals to point to the same object in a special area of memory called the "String Pool".
        String s3 = "hello";
        String s4 = "hello";
        System.out.println("s3 == s4: " + (s3 == s4));       // Output: true (same object in the pool)
        System.out.println("s3.equals(s4): " + s3.equals(s4)); // Output: true (same content)
    }
}

What about null.equals()?

This is a critical pitfall. You cannot call a method on a null reference. It will result in a NullPointerException.

String myString = null;
// This will cause a crash at runtime!
// boolean result = myString.equals("some text"); // Throws NullPointerException

The safe way to compare for content is to always check for null first:

String s1 = null;
String s2 = "test";
// Safe way to compare for equality
if (s1 == null) {
    // If s1 is null, they can only be equal if s2 is also null
    boolean areEqual = (s2 == null);
    System.out.println("Are they equal? " + areEqual); // true
} else {
    // If s1 is not null, we can safely call .equals()
    boolean areEqual = s1.equals(s2);
    System.out.println("Are they equal? " + areEqual); // false
}

Summary

Concept Description Example
null == null Always true. Compares the absence of an object. boolean b = (null == null); // b is true
for Objects Checks if two references point to the same memory location. s1 == s2 (are they the exact same object?)
.equals() for Objects Checks if two objects are logically equivalent (their contents are the same). s1.equals(s2) (do they represent the same thing?)
Calling .equals() on null Causes a NullPointerException. null.equals("anything") // CRASH!
分享:
扫描分享到社交APP
上一篇
下一篇