基本类型的初始化
我们先来看两个例子,看一下会发生什么问题,得到什么答案。
/*测试基本类型的初始化*/
public class InitPrimitive1
byte a;
short b;
int c;
long d;
float e;
double f;
char g;
boolean h;
public static void main(String[] args)
{
InitPrimitive1 aInit = new InitPrimitive1();
aInit.print();
}
public void print()
{
System.out.println("字节型,a = " + a);
System.out.println("短整型,b = " + b);
System.out.println("整数型,c = " + c);
System.out.println("长整型,d = " + d);
System.out.println("单精度型,e = " + e);
System.out.println("双精度型,f = " + f );
System.out.println("字符型,g = " + g);
System.out.println("布尔型,h = " + h);
}
}
/*测试基本类型初始化*/
public class InitPrimitive2
{
public static void main(String[] args)
{
InitPrimitive2 aInit = new InitPrimitive2();
aInit.print();
}
public void print()
{
byte a;
short b;
int c;
long d;
float e;
double f;
char g;
boolean h;
System.out.println("字节型,a =" + a);
System.out.println("短整型,b =" + b);
System.out.println("整数型,c =" + c);
System.out.println("长整型,d =" + d);
System.out.println("单精度型,e =" + e);
System.out.println("双精度型,f =" + f);
System.out.println("字符型,g =" + g);
System.out.println("布尔型,h =" + h);
}
}
我们先看一下这两段代码的区别:
这八个基本类型的变量声明位于不同的位置,再就没有什么区别了。再看一下运行结果。
InitPrimitive1.java输出结果:
字节型,a = 0
短整型,b = 0
整数型,c = 0
长整型,d = 0
单精度型,e = 0.0
双精度型,f = 0.0
字符型,g =
布尔型,h = false
InitPrimitive2.java输出结果:
InitPrimitive2.java:23:variable a might not have been initialized
InitPrimitive2.java:24:variable b might not have been initialized
InitPrimitive2.java:25:variable c might not have been initialized
InitPrimitive2.java:26:variable d might not have been initialized
InitPrimitive2.java:27:variable e might not have been initialized
InitPrimitive2.java:28:variable f might not have been initialized
InitPrimitive2.java:29:variable g might not have been initialized
InitPrimitive2.java:30:variable h might not have been initialized
下面来解释一下。在1当中我们声明的是全局变量,在2中声明的是局部变量,可以得到基本类型初始化的规则:
基本类型作为全局变量时可以不用初始化,系统会自动初始化,这个自动初始化的值我们称为默认值,如果作为局部变量时,程序必须初始化,系统不会为局部变量进行初始化工作。
posted on 2007-05-09 11:30
心随Wǒ动 阅读(366)
评论(0) 编辑 收藏