• char与byte的差别


    非常多刚開始学习的人(包含我,已经学了一年多java了)肯会对char和byte这两种数据类型有所疑惑,相互混淆,今天特地查了好多资料,对byte和char两种数据类型进行了总结和比較,先将结果与大家分享:


            byte 是字节数据类型 ,是有符号型的,占1 个字节;大小范围为-128—127 。char 是字符数据类型 ,是无符号型的,占2字节(Unicode码 );大小范围 是065535 ;char是一个16位二进制的Unicode字符,JAVAchar来表示一个字符 。


            以下用实例来比較一下二者的差别:

    1、Char是无符号型的,能够表示一个整数,不能表示负数;而byte是有符号型的,能够表示-128—127 的数;如:

    char c = (char) -3; // char不能识别负数,必须强制转换否则报错,即使强制转换之后,也无法识别
    System.out.println(c);
    byte d1 = 1;
    byte d2 = -1;
    byte d3 = 127; // 假设是byte d3 = 128;会报错
    byte d4 = -128; // 假设是byte d4 = -129;会报错
    System.out.println(d1);
    System.out.println(d2);
    System.out.println(d3);
    System.out.println(d4);

    结果为:

    ?
    1
    -1
    127
    -128


    2、char能够表中文字符,byte不能够,如:

    char e1 = '中', e2 = '国';
    byte f= (byte) '中';	//必须强制转换否则报错
    System.out.println(e1);
    System.out.println(e2);
    System.out.println(f);

    结果为:



    45


    3、char、byteint对于英文字符,能够相互转化,如:

    byte g = 'b';	//b相应ASCII是98
    char h = (char) g;
    char i = 85;	//U相应ASCII是85
    int j = 'h';	//h相应ASCII是104
    System.out.println(g);
    System.out.println(h);
    System.out.println(i);
    System.out.println(j);
    结果为:
    98
    b
    U
    104



    欢迎增加"Java梦之队" 学习群:226159645




  • 相关阅读:
    Best Time to Buy and Sell Stock
    Permutations II
    数组中最大和的子数组
    基于Socket.IO的Client封装
    Java中的ThreadLocal功能演示
    基于WebSocket的client封装
    Socket接口开发和测试实践
    自动化测试用例的原子性
    [CF1477C] Nezzar and Nice Beatmap
    [CF1477B] Nezzar and Binary String
  • 原文地址:https://www.cnblogs.com/yxwkf/p/4512179.html
Copyright © 2020-2023  润新知