JAVA学习Day10之数据类型的扩展

    科技2022-07-12  126

    数据类型扩展

    整数扩展

    进制问题 二进制:以0b开头(01)十进制:无开头(0123456789)八进制:以0开头(01234567)十六进制:以0x开头(0123456789ABCDEF) (A是10,F是15) public class YSHG1 { public static void main(String[] args) { int i = 10; int i2 = 0b10; int i3 = 010; int i4 = 0x10; System.out.println(i); System.out.println(i2); System.out.println(i3); System.out.println(i4); } }

    浮点数扩展

    float和double是有问题的

    public class YSHG2 { public static void main(String[] args) { float f = 0.1f; double d = 1.0/10; System.out.println(f==d); // ==================================================================== float d1 = 123456789987654321f; float d2 = d1 + 1; System.out.println(d1==d2); } }

    备注:==号可以来表示是否相等

    问题:

    分割线之前:输出为false。若正常输出都为0.1。分割线之后:输出为true。 原因: 有限离散舍入误差接近但不等于

    注意:最好完全避免使用浮点数进行比较

    面试题:银行业务(钱数)怎么表示?

    BigDecimal(数学工具类)

    字符扩展

    数据类型强制转换

    public class YSHG3 { public static void main(String[] args) { char c1 = 'a'; char c2 = '中'; System.out.println(c1); System.out.println((int)c1);//数据类型强制转换 System.out.println(c2); System.out.println((int)c2); } }

    此处输出: a 97 中 20013

    原因:所有的字符本质还是数字

    编码问题:unicode (2字节,0 -65536) 表:(97 = a,65 = A )

    (U0000 UFFFF) public class YSHG3 { public static void main(String[] args) { char c3 ='\u0061'; System.out.println(c3); } } 此处输出 a

    转义字符

    public class YSHG3 { public static void main(String[] args) { System.out.println("Hello\tWorld"); } } 此处输出 Hello World

    布尔值扩展

    public class YSHG3 { public static void main(String[] args) { boolean flag = true; if (flag==true); {}//新手 if (flag);{}//老手 } }

    if (flag==true); {}

    if (flag);{}

    以上两者一样,代码要精简易读,以后几乎见不到第一种

    有趣的东西

    public class YSHG3 { public static void main(String[] args) { String sa = new String("Hello World"); String sb = new String("Hello World"); System.out.println(sa==sb); //============================================================== String sc = "Hello World"; String sd = "Hello World"; System.out.println(sc==sd); } }

    1.分割线之前输出false 2.分割线之后输出true

    要从内存级别分析

    Processed: 0.009, SQL: 8