Java基础复习——数据类型、变量和数组

Java基础复习——数据类型、变量和数组

“学而时习之,不亦说乎!”

Java基础类型
不应将一个中型类型的宽度(width)看成是他所小韩的存储位置的数量,而应当其理解成定义这种类
型的变量和表达式的行为。只要类型符合声明他的时候的规定,Java运行时环境就可随意使用任意大
小(的空间)。
整形
名称宽度范围
long64-9 223 372 036 854 775 808 ~ 9 223 372 036 854 775 807
int32-2 147 483 648 ~ 2 147 483 647
short16-32 768 ~ 32 767
byte8-128 ~ 127
浮点型
名称宽度大致范围
double 644.9e-324 ~ 1.8e+308
float321.4e-045 ~ 3.4e+038
字符型
名称宽度
char16

Java使用Unicode表示字符,Unicode是许多字符集的统一体,需要16位的宽度。
住:有关Unicode的更多信息,可在http://www.unicode.org找到。

程序:
//char variables behave like integers.
class CharDemo2 {
public static void mian(String[] args) {
char ch1;
ch1 = 'X';

System.out.println("ch1 contains " + ch1);
ch1++;
System.out.println("ch1 is now " + ch1);
}
}

输出:
ch1 contians X
ch1 is now Y
尽管ch1是字符型,但在执行算数操作时,也可将它看成整形类型。

变量的作用域

在嵌套定义变量的时候,注意不能江边两证名称和外部作用域中的变量相同的名称。
程序:
//Thisprogram will not compile
class ScopeErr {
public static void main(String[] args) {
int bar = 1;
{
int bar = 2; //Compile-time error - bar already defined!
}

Java类型转换
强制转换不兼容的类型

由小变大时,可自动进行转换;但有大变小时,需要强制转换。
如将int强制转换成一个byte时,如果整数值超出了byte的范围,则将以byte的范围为模(即,用整数
值除以byte范围所得的余数)减少。
程序:
//Demonstrate casts.
class Conbersion {
public static void main(String[] args) {
byte b;
int i = 257;
double d = 323.142;

System.out.println("/nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " "+ b);
System.out.println("/nConversion of double to int.");
d = (int) i;
System.out.println("d and i " + d + " "+ i);
System.out.println("/nConversion of double to byte.");
d = (byte) b;
System.out.println("d and b " + d + " "+ b);
}
}

输出:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67

当值257被强制转换成一个byte变量时,结果是257除以256(byte 的范围)的余数,也就是1。.....
自动类型提升

byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;

a * b的结果很容易超出byte操作数的范围。为解决这类问题,当求值一个表达式时,Java自动将byte
,short或char操作数提升为int。所以在执行表达式a * b是,使用的是整形,而不是byte型。

虽然自动提升有用,但也会引起编译错误。
例如:
byte b = 50;
b = b * 2; //Error!Cannot assign an int to byte!

在这个 b * 2 表达式中 b 已被提升为 int 型,结果当然是 int 型,付给byte型变量当然会出错。
如果能理解溢出的后果,则应当使用如下的强制转换:
byte b = 50;
b = (byte)b * 2;

【Java基础复习——数据类型、变量和数组】数组
有new分配的数组中的元素会被自动初始化成0。

    推荐阅读