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就一定会报错。具体就是空指针的错误,会造成程序崩溃。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构