基本数据类型作为类的成员变量时可以不赋予初值,在方法中输出也不会报错。
下面我们看看我们的八种数据类型的默认值是什么样的
上代码
package objectandclass;
import java.awt.SecondaryLoop;
public class VarText {
//整形变量
byte b;
short s;
int i;
long l;
//实型变量。
float f;
double d;
//布尔型
boolean bool;
//字符型
char c;
String str;
public VarText(){
System.out.println("各种整型成员变量的默认值:");
System.out.println("byte默认值:"+this.b+"short默认值:"+this.s+"int默认值:"+this.i+"long默认值:"+this.l);
System.out.println("各种实型成员变量的默认值:");
System.out.println("float默认值:"+this.f+"double默认值:"+this.d);
System.out.println("布尔型成员变量的默认值:");
System.out.println("boolean默认值:"+this.bool);
System.out.println("字符型成员变量的默认值:");
System.out.println("char默认值:"+this.c);
System.out.println("引用型成员变量的默认值");
System.out.println("String默认值:"+this.str);
}
输出的结果是这样:
各种整型成员变量的默认值:
1 byte默认值:0 short默认值:0 int默认值:0 long默认值:0
2 各种实型成员变量的默认值:
float默认值:0.0 double默认值:0.0
布尔型成员变量的默认值:
boolean默认值:false
字符型成员变量的默认值:
char默认值:
大家肯定会惊奇,为什么整形和实数型输出的结果会一样,
其实真正的结果如下:
总结
基本类型 | 默认值 |
---|---|
byte | 0 |
short | 0 |
int | 0 |
long | 0L |
float | 0.0f |
double | 0.0d |
char | ‘\u0000’ |
boolean | false |