java基本类型与应用类型初始值总结
对于java变量来说,共有三种变量类型:局部变量、实例变量(成员变量)、类变量(静态变量)。
对于局部变量来说,在使用前必须先声明与初始化值,而实例变量和类变量在使用时可以不初始化,那么实例变量和类变量的默认值是多少呢?
首先看实例变量的验证:
public class Test { byte a; short b; int c; long d; float e; double f; char g; boolean h; String i; BigDecimal j; public static void main(String[] args) { Test test = new Test(); System.out.println("a="+test.a); System.out.println("b="+test.b); System.out.println("c="+test.c); System.out.println("d="+test.d); System.out.println("e="+test.e); System.out.println("f="+test.f); System.out.println("g="+test.g); System.out.println("h="+test.h); System.out.println("i="+test.i); System.out.println("j="+test.j); }
运行结果为:
a=0 b=0 c=0 d=0 e=0.0 f=0.0 g= h=false i=null j=null
结论1 :实例变量为整型时默认值为0,浮点类型为0.0,字符类型为空,boolean类型为false,引用类型初始值全部为null。
接下来看类变量的验证:
import java.math.BigDecimal; public class Test { static byte a; static short b; static int c; static long d; static float e; static double f; static char g; static boolean h; static String i; static BigDecimal j; public static void main(String[] args) { System.out.println("a="+Test.a); System.out.println("b="+Test.b); System.out.println("c="+Test.c); System.out.println("d="+Test.d); System.out.println("e="+Test.e); System.out.println("f="+Test.f); System.out.println("g="+Test.g); System.out.println("h="+Test.h); System.out.println("i="+Test.i); System.out.println("j="+Test.j); } }
运行结果为:
a=0 b=0 c=0 d=0 e=0.0 f=0.0 g= h=false i=null j=null
可以看到,结论2:类变量和实例变量的默认初始值是相同的:整型时默认值为0,浮点类型为0.0,字符类型为空,boolean类型为false,引用类型初始值全部为null,见下表:
| 参数类型 | 整型 | 整型 | 整型 | 整型 | 浮点型 | 浮点型 | 字符类型 | boolean类型 | 引用类型 |
|---|---|---|---|---|---|---|---|---|---|
| 关键字 | byte | short | int | long | float | double | char | boolean | 所有引用类型 |
| 实例变量默认值 | 0 | 0 | 0 | 0 | 0.0 | 0.0 | 空 | false | null |
| 类变量默认值 | 0 | 0 | 0 | 0 | 0.0 | 0.0 | 空 | false | null |

浙公网安备 33010602011771号