1.基本数据类型转换
1.自动类型转换
容量小的类型自动转换为容量大的数据类型。数据类型按容 量大小排序为:
byte,short,char之间不会相互转换,他们三者在计算时首先转换为int类型。
2.强制类型转换
1.大->小 会造成精度损失
class VariableTest
{
public static void main(String[] args)
{
double d1=12.9;
//精度损失例1
int i1=(int)d1;//截断操作
System.out.println(i1);
//没有精度损失
long l1=123;
short s2=(short)l1;
//精度损失例2
int i2 = 128;
byte b = (byte)i2;
System.out.println(b);//-128
}
}
2.
字符串不能直接转换为基本类型,但通过基本类型对应的包装类则可以实现把字符串转换成基本类型。
String s = 123;//编译错误
String s1 = "123";
int i = (int)s1;//编译错误
String运算只能是连接运算:+(前后变量连在一起),运算结果仍为String
练习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
练习2:
System.out.println("* *")//要求输出这个
System.out.println('*' + '\t' + '*');//93
System.out.println('*' + "\t" + '*');//* *
System.out.println('*' + '\t' + "*");//51*
System.out.println('*' + ('\t' + "*"));//* *
如有错误请指正