学习java第四天

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' + "*"));//*    *

如有错误请指正

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值