Java基本数据类型测试

Java共有8种基本数据类型(今天看到Bruce Eckel的Thinking in Java第三版上把void也作为了一种基本数据类型,但这是讲不通的),其大小及包装器类型如下:
基本类型           大小(bit)    包装器类型
boolean            ----            Boolean
char                   16          Character
byte                    8            Byte
short                 16            Short
int                     32           Integer
long                    64        Long
float                  32             Float
double               64        Double

另外还有两个提供高精度计算的类:BigInteger和BigDecimal,但二者都没有对应的基本数据类型。
这里我主要讲一下基本数据类型初始化问题:
若类的某个成员是基本数据类型,即使没有进行初始化,Java也会确保它获得一个默认值,如下
基本类型         默认值
boolean        false
char              '\u0000'(null)
byte             (byte)0
short            (short)0
int                0
long            0L
float              0.0f
double          0.0d
但需要注意的是:只有当变量作为类的成员使用时,Java才确保给定其默认值
我们可以通过如下程序来测试:
public class TestT
{
static byte b;
static short s;
static int i;
static long l;
static char ch;
static float f;
static double d;
static boolean bool;
static String str = new String();
public static void main(String[] args)
{
//int x;
//System.out.println(x);   //错误提示:可能未初始化变量x。这就印证了上面红色部分的提示
System.out.println(b);    //0
System.out.println(s);     //0
System.out.println(i);       //0
System.out.println(l);        //0
System.out.println(ch);     //null(其实就什么都没输出)
System.out.println(f);       //0.0
System.out.println(d);      //0.0
System.out.println(bool);    //false
System.out.println(str);    //null(其实就什么都没输出)
}
}

在这个例子中我不仅列出了基本数据类型初始化问题,也给出了一个String对象的例子,str的输出为空,因此我们可以做出如下总结:
各种数据类型默认值为(即没有进行显式初始化):
数值型:0
boolean:false
char:null
对象:null

最终我们不能忘了:只有当变量作为类的成员使用时,Java才确保给定其默认值。

显然对象并不在此列

转自:http://hi.baidu.com/hoyah/blog/item/528e75cfe6419c0f93457e58.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值