java 8种基本数据类型的默认值
8种基本数据类型(primitive type)在只做了声明,而未被初始化的时候,他们的默认值
8种基本数据类型分别是:byte,short,int,long,(四种整型)
char()
float,double(两种浮点型)
boolean(一种用于 表示 真假的类型)
他们的默认值可以用用下代码测试:
PrimitiveType.java
public class PrimitiveType{
boolean t;
char c;
byte b;
short s;
int i;
long l;
float f;
double d;
void print(){
System.out.println("boolean "+t);
System.out.println("char "+c);
System.out.println("byte "+b);
System.out.println("short "+s);
System.out.println("int "+i);
System.out.println("long "+l);
System.out.println("float "+f);
System.out.println("double "+d);
}
public static void main(String args[]){
PrimitiveType pt=new PrimitiveType();
pt.print();
}
}
得出的结果为:
byte:0
short:0
int:0
long:0
char: _
float:0.0
double:0.0
boolean: false
除了这8种基本类型以外的变量(比如String,基本类型的数组),他们的默认值都是 null
××××××××××××××××××××××××××××××××××
各种变量(无论是基本的变量,还是其他对象类型的变量,数组类型的变量)
他们 在 没有被 显示初始化 的时候,jdk 都会自动赋予 默认值 给他们,
只不过要注意的是 全局变量 和 局部变量的 不同之处:
当 全局变量 没有被显示初始化,jdk会自动赋予 默认值给他,并且 ,当你 在其他地方引用 该变量的时候,编译器是不会报错的。
而局部变量 在没有被显示初始化情况下,jdk 同样也会自动 赋予他默认值,可不同之处就在于 ,你无法引用他,因为编译器会在 你要引用的位置报错。
这就是JDK的规定。
所以 局部变量 在声明的时候,最好直接 显示初始化他。
可以尝试将 上面的代码 改成 以下的,看看问题 是怎么出现的。
public class PrimitiveType{
public static void main(String args[]){
boolean t;
char c;
byte b;
short s;
int i;
long l;
float f;
double d;
System.out.println("boolean "+t);
System.out.println("char "+c);
System.out.println("byte "+b);
System.out.println("short "+s);
System.out.println("int "+i);
System.out.println("long "+l);
System.out.println("float "+f);
System.out.println("double "+d);
}
}
运行该代码,jdk的编译器就会报错(eclipse里的错误提示信息)。
java.lang.Error: Unresolved compilation problems:
The local variable t may not have been initialized
The local variable c may not have been initialized
The local variable b may not have been initialized
The local variable s may not have been initialized
The local variable i may not have been initialized
The local variable l may not have been initialized
The local variable f may not have been initialized
The local variable d may not have been initialized
所以,并不是象某些书上说的 “赋给 变量的 默认初始值在所有的情况下都适用”,至少在 sun 的java 运行环境 jdk 里,就不是都适用的。
最后,为了使 java 项目在哪里都可以成功运行,最好将所有需要用到的变量 都进行 显示初始化。
转自:java 8种基本数据类型的默认值
还没有评论,来说两句吧...