Java有八种基本数据类型,byte(1字节)、short(2字节)、int(4字节)、long(8字节)、float(4字节)、double(8字节)、char(2字节)、boolean。
今天做练习时遇到一点小问题,即基本数据类型所属变量类型不同而造成的默认值问题。
变量类型见下表:
1.成员变量
public class TestDemo {
byte a;
short b;
char c;
int d;
float e;
double f;
long g;
boolean h;
public static void main(String[ ] args) {
TestDemo t=new TestDemo();
System.out.println("byte默认值:"+t.a);
System.out.println("short默认值:"+t.b);
System.out.println("char默认值:"+t.c);
System.out.println("int默认值:"+t.d);
System.out.println("float默认值:"+t.e);
System.out.println("double默认值:"+t.f);
System.out.println("long默认值:"+t.g);
System.out.println("boolean默认值:"+t.h);
}
}
运行结果:
需注意的是,char类型的默认值不是空,而是空格(‘\u0000'),见图中蓝色区域。
2.静态变量
同成员变量结果一样,不再赘述。
3.局部变量
以main方法中为例
public class TestDemo {
public static void main(String[] args) {
byte a;
short b;
char c;
int d;
float e;
double f;
long g;
boolean h;
System.out.println("byte默认值:"+a);
System.out.println("short默认值:"+b);
System.out.println("char默认值:"+c);
System.out.println("int默认值:"+d);
System.out.println("float默认值:"+e);
System.out.println("double默认值:"+f);
System.out.println("long默认值:"+g);
System.out.println("boolean默认值:"+h);
}
}
编译无法通过,报如下错误:
由上述结果,可以看到,基本数据类型作为局部变量使用时必须添加初始值。