§ 2.6布尔型数据
布尔型数据只有两个值,true和 false,且它们不对应于任何整数值,在流控制中常用到。
布尔型变量的定义如:
boolean b=true; //定义b为布尔型变量,且初值为 true
§ 2.7举 例
例 2.1.下例中用到了前面提到的数据类型 ,并通过屏幕显示它们的值 。
public class SimpleTypes{
public static void main( String args[] ){
byte b=0x55;
short s=0x55ff;
int i=1000000;
long l=0xfffL;
char c='c';
float f=0.23F;
double d=0.7E-3;
boolean bool=true;
System.out.println("b = "+b);
System.out.println("s = "+s);
System.out.println("i = "+i);
System.out.println("l = "+l);
System.out.println("c = "+c);
System.out.println("f = "+f);
System.out.println("d = "+d);
System.out.println("bool = "+bool);
}
}
编译并运行该程序,输出结果为:
C:\>java SimpleTypes
b = 85
s = 22015
i = 1000000
l = 4095
c = c
f = 0.23
d = 0.0007
bool = true
§ 2.8 各类数值型数据间的混合运算
1、自动类型转换
整型、实型、字符型数据可以混合运算 。 运算中 ,不同类型的数据先转化为同一类型,然后进行运算。转换从低级到高级,转换规则为 : www.Examzz.com
① (byte或 short) op int→ int
② (byte或 short或 int) op long→ long
③ (byte或 short或 int或 long) op float→ float
④ (byte或 short或 int或 long或 float) op double→ double
⑤ char op int→ int
其中 ,箭头左边表示参与运算的数据类型 ,op为运算符 (如加、减、乘、除等),右边表示转换成的进行运算的数据类型 。
例2.2
public class Promotion{
public static void main( String args[ ] ){
byte b=10;
char c='a';
int i=90;
long l=555L;
float f=3.5f;
double d=1.234;
float f1=f*b;
// float * byte -> float
int i1=c+i;
// char + int -> int
long l1=l+i1;
// long + int ->ling
double d1=f1/i1-d;
// float / int ->float, float - double -> double
}
}
2、强制类型转换
高级数据要转换成低级数据,需用到强制类型转换,如 :
int i;
byte b=(byte)i;
//把 int型变量 i强制转换为byte型这种使用可能会导致溢出或精度的下降,最好不要使用 。