009.关于默认赋值和null的讨论

1.对于基本数据类型,默认赋值为0

package com.qx.courseTwo;

public class Person
{
    int age;
}
复制代码
package com.qx.courseTwo;

public class Entrance
{
    public static void main(String[] args) {
        Person p = new Person();
        System.out.println(p.age);
    }
}
复制代码

     输出结果为:0

2.对于引用数据类型,p有所指向时即拥有内存权限时

复制代码
package com.qx.courseTwo;

public class Person {

    void eat()
    {
        System.out.println("Person is eating!");
    }

}
复制代码
复制代码
package com.qx.courseTwo;

public class Student
{
    void study()
    {
        System.out.println("student is study!");
    }
}
复制代码
复制代码
package com.qx.courseTwo;

public class Entrance
{
    public static void main(String[] args) {
        Person p = null;
        System.out.println(p.age);
        p.test();
    }
}
复制代码

替换代码:

复制代码
package com.qx.courseTwo;

public class Person {
    Student student;

    void test() {
        student.study();
    }

//    void eat()
//    {
//        System.out.println("Person is eating!");
//    }
}
复制代码

上述2所有代码运行结果:空指针

替换代码:

复制代码
package com.qx.courseTwo;

public class Person {
   Student student;
   
   void test()
   {
       System.out.println(student);
   }
}
复制代码

 

上述所有代码运行结果:null

3.总结

1.默认值的不同境遇

①int a;

②Student student;

对于①首先大家可以看到的是int是一个基本数据类型,但没有初始化,但因为是基本数据类型, java会给a一个默认的0

对于②来说,student这个凭证没有任何权限,并且Student 并不是基本数据类型,没有默认赋值,所以student就等于null

2.null造成的结果

假设Student 有一个成员变量,grade。则正确的访问是 Student student=new Student ();

student.grade去访问,因为这个时候student已经有了一块内存的凭证。但是如果仅仅是Student student; student并没有被赋予任何内存的凭证。所以这个时候如果调用student.grade就一定会报错。具体就是空指针的错误,会造成程序崩溃。

 

posted @   李林林  阅读(67)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示