public class test{
pubilc static void main(String []args){
byte a = 2;
int b = 652;
byte c = a +b;
System.out.println(c);//654
}
}
这代码没什么问题但是编译不通过,我们拿int去接收就会编译成功(有问题先不要慌,慢慢来)
int c = a + b;
**************************************************************************************************************
再看一下下面这串代码
public class test{
public static void main(String []args){
int a =100;
byte f = 120;
int b = 250;
int e = a +f;
long c = a + b;
System.out.println(c);//350
System.out.println(e);//220
}
}
我们能看到这串代码编译能过,而且能输出
*************************************************************************************************************
public class test{ public static void main(String [ ]args){ byte a = 120;int b=1235;
float c = a+b;
System.out.println(c);//编译还是通过输出1355.0(不要忘了单精度型后面有一个.0)
}
}
*************************************************************************************************************
public class test{
public static void main(String [ ]args){
short s = 453;
doublc c = s;
System.out.println(c);//输出453.0
}
}
根据刚才代码比较,我们可以得出一下结论
当容量小的数据类型的变量与容量大的数据类型的变量做运算是时,结果将容量小的自动提升为容量大的数据类型。 byte——》char——》short——》int ——》long ——》float——》double 容量的大小指的是,表示数的范围的大和小.比如:float容量要大于long的容量 public class test{ public static void main(String [ ] args){ char a = 'a'; int b = 10; int c = a +b; System.out.println(c); short p = 10; short e = a+p;//这里已经编译不了出错了 char o = a+p;//这里已经编译不了出错了 } }根据以上这串代码我们修改一下我们原来的结论
byte、char、short、int ——》long ——》float——》double当byte、char、short三种变量做运算时,结果为int 类型
自动类型提升结论1.当容量小的数据类型的变量与容量大的数据类型的变量做运算是时,结果将容量小的自动提升为容量大的数据类型。
2.byte、char、short、int ——》long ——》float——》double 当byte、char、short三种变量做运算时,结果为int 类型 容量的大小指的是,表示数的范围的大和小.比如:float容量要大于long的容量 2.强制类型转换 强制类型转换其实就是自动类型提升运算的逆运算.例如:
int a =128;
byte b= (byte)a;
System.out.println(b);
如果我们不在a前面加byte就会出现编译失败(如下图) 强制类型转换注意点: 1.需要使用强转符:( ) 2.使用强制类型转换时,可能会导致精度损失 double d = 3.1; //精度损失例子1 int i = (int)d;//截断操作 System.out.println(i); //没有精度损失 long q =123; short w = (short)q; //精度损失 int e = 128; byte b = (byte)e; System.out.println(b);//-128 3.String类型变量使用 1.String属于引用数据类型,翻译为:字符串 2.声明String类型变量时,使用一对" " 3.String可以和8种基本数据类型变量做运算,且只能是连接运算:+ 4.运算结果仍然是String类型 int number = 1001; String numberStr = "学号"; String info = numberStr + number;//+:连接运算 boolean a = true; String b = info + b1;//+:连接运算 String练习1 char c = 'a'; 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 各输出什么: String练习2//要想输出* *下面代码哪个正确
System.out.println("* *"); // * *
System.out.println('*' + 't' + '*'); //93
System.out.println('*' + "t" + '*'); //* *
System.out.println('*' + 't' + "*"); //51*
System.out.println('*' + ('t' + "*")); //* *



