什么是空?

null是任何东西的实例吗?

null属于哪个集合?

它在内存中是如何表示的?


当前回答

Java中的Null (tm)

在C和c++中,"NULL"是头文件中定义的常量,其值如下:

    0

or:

    0L

or:

    ((void*)0)

取决于编译器和内存模型选项。严格地说,NULL不是C/ c++本身的一部分。

在Java(tm)中,“null”不是关键字,而是null类型的特殊文字。它可以强制转换为任何引用类型,但不能转换为任何基本类型,如int或boolean。null字面量的值不一定是0。并且不可能强制转换为null类型或声明该类型的变量。

其他回答

Java中的null类似于c++中的nullptr。

c++程序:

class Point
{
    private:
       int x;
       int y;
    public:
       Point(int ix, int iy)
       {
           x = ix;
           y = iy;
       }
       void print() { std::cout << '(' << x << ',' << y << ')'; }
};
int main()
{
    Point* p = new Point(3,5);
    if (p != nullptr)
    {
       p->print();
       p = nullptr;
    }
    else
    {
        std::cout << "p is null" << std::endl;
    }
    return 0;
}

Java中的相同程序:

public class Point {
    private int x;
    private int y;
    public Point(int ix, int iy) {
        x = ix;
        y = iy;
    }
    public void print() { System.out.print("(" + x + "," + y + ")"); }
}
class Program
{
    public static void main(String[] args) {
        Point p = new Point(3,5);
        if (p != null)
        {
            p.print();
            p = null;
        }
        else
        {
            System.out.println("p is null");
        }
    }
}

现在你从上面的代码中明白什么是Java中的空了吗?如果没有,那么我建议你学习C/ c++中的指针,然后你就会明白。

注意,在C语言中,与c++不同,nullptr是未定义的,但使用NULL代替,这也可以在c++中使用,但在c++中nullptr比NULL更可取,因为C语言中的NULL总是与指针相关,所以在c++中,后缀“ptr”被附加在单词的末尾,而且所有字母现在都是小写的,但这并不重要。

在Java中,每一个类非原语类型的变量都是对该类型或继承的对象的引用,null是空类对象引用,但不是空指针,因为在Java中没有“指针”这样的东西,而是使用对类对象的引用,Java中的null与类对象引用有关,所以你也可以称它为“nullref”或“nullrefobj”,但这很长,所以就叫它“null”。

在c++中,你可以为可选成员/变量使用指针和nullptr值,即没有值的成员/变量,如果它没有值,那么它等于nullptr,所以在Java中如何使用null例如。

简短准确的回答,正式回答您的所有问题:

3.10.7. 空文字 空类型有一个值,即空引用,由 null literal null,由ASCII字符组成。 空字面值总是null类型。

只有赋值为null类型的引用才会被分配。您不需要为引用分配任何值(对象)。 这样的分配取决于JVM将占用多少引用以及将在哪个内存区域分配引用。

An interesting way to see null in java in my opinion is to see it as something that DOES NOT denote an absence of information but simply as a literal value that can be assigned to a reference of any type. If you think about it if it denoted absence of information then for a1==a2 to be true doesn't make sense (in case they were both assigned a value of null) as they could really could be pointing to ANY object (we simply don't know what objects they should be pointing to)... By the way null == null returns true in java. If java e.g. would be like SQL:1999 then null==null would return unknown (a boolean value in SQL:1999 can take three values : true,false and unknown but in practise unknown is implemented as null in real systems)... http://en.wikipedia.org/wiki/SQL

Java中有两大类类型:基本类型和引用类型。声明为基元类型的变量存储值;声明为引用类型的变量存储引用。

String x = null;

在本例中,初始化语句声明了一个变量“x”。" x "存储字符串引用。这里是空的。首先,null不是一个有效的对象实例,因此没有为它分配内存。它只是一个值,指示对象引用当前没有引用对象。

什么是空?

这没什么。

null是任何东西的实例吗?

不,因为它什么也不是,它不可能是任何事物的实例。

null属于哪个集合?

没有任何集合

它在内存中是如何表示的?

如果一些参考指向它,比如:

Object o=new Object();

在堆内存中,分配给新创建对象的空间。o指向内存中指定的空间。

现在 o=null;

这意味着现在o不再指向对象的内存空间。