您的位置:首页 > 编程语言 > Java开发

Java基本数据类型测试

2011-12-19 16:38 225 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: