一、基本数据类型之间的运算规则:
前提:7种。不包含boolean类型
1.自动类型提升:
结论:当容量小的数据类型的变量与容量大的数据类型的变量做运算时,结果自动给提升为容量大的数据类型。
byte --> short --> int --> long --> float --> double
**特别的:当byte、char、short三种类型的变量做运算时,结果为int型(包括同种互相)
********************************************
class yunsuan{
public static void main(String[] args){
byte b1 = 2;
int i1 = 129;
//byte b2 = b1 + i1; 编译不通过
int i2 = b1 + i1;//编译通过
long l1 = b1 + i1;//编译通过
System.out.println(i2);
float f = b1 + i1;
System.out.println(f);//131.0
short s1 = 123;
double d1 = s1;
System.out.println(d1);//123.0
//*************特别地****************
char c1 = 'a';//97
int i3 = 10;
int i4 = c1 + i3;
System.out.println(i4);//107
short s2 = 10;
//char c3 = c1 + s2;//
byte b2 = 10;
//char c3 = c1 + b2;//编译不通过
//short s3 = b2 + s2;//编译不通过
//short s4 = b1 + b2;//编译不通过
//***********************************
}
}
二、强制类型转换:自动类型提升运算的逆运算。
说明:此时的容量大小指的是,表示数的范围的大和小。比如:float容量要大于long的容量。
1).需要使用强转符:()
2).注意:强制类型转换,可能导致精度损失。
********************************************
class qiangzhi{
public static void main (String[] args){
//精度损失1
double f1 = 19.9;
int i1 = (int)f1;//截断操作
System.out.println(i1);//19
//没有精度损失
long l1 = 123L;
short s1 = (short)l1;
System.out.println(s1);123
//精度损失2
int i2 = 1999;
byte b1 = (byte)i2;
System.out.println(b1);//-49
}
}
三、String类型变量的使用
1.String属于引用数据类型,翻译为:字符串
2.声明String类型变量时,使用一对""
3.String可以和8种基本数据类型变量做运算,且运算只能是连接运算:+
4.运算的结果仍然是String类型
********************************************
class Test01 {
public static void main(String[] args){
String s1 = "Hello!";
System.out.println("s1");
String s2 = "a";
String s3 = "";
//char c ='';编译不通过
//*******************
int number = 1037;
String numberStr = "学号:";
String info = numberStr + number;// +:连接运算
boolean b1 = true;
String infol = info + b1;//+ : 连接运算
System.out.println(infol);
//*********************
//练习1
char c = 'a';//97 A:65
int num = 10;
String str = "hello";
System.out.println(c + num + str);//107hello
System.out.println(c + str + num);//ahello10
System.out.println(c + (num + str));//a10hello
System.out.println((c + num) + str);//107hello
System.out.println(str + num + c);//hello10a
System.out.println(num + num + c + c + num + str + num + num + c + str);//214hello1010ahello
//练习2
//* *
System.out.println("* *");//可
System.out.println('*' + '\t' + '*');//不可
System.out.println('*' + "\t" + '*');//可
System.out.println('*' + '\t' + "*");//不可
System.out.println('*' + ('\t' + "*"));//可
}
}