这篇文章主要介绍了解读Javachar类型相加的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教


Java char类型相加问题

对于Java中的字符数据类型(也就是char类型),它在相加时不是像字符串那样是字符的连接,而是ASCII的相加,也就是说你如下这样写是没问题的

char a = 'A';
  
char b = 'B';
  
int c = a + b;    //不用强制类型转换

同时,由于char类型在相加时是ASCII码的相加,所以要转化为字符的连接可以用如下的方式:

char a = 'A';
  char b = 'B';
  String s1 = a + b + "";    //得到的结果是131,ASXCII码的相加
  String s2 = a + "" + b + "";    //得到的结果是AB,字符的连接

Java int类型和char类型相加是什么结果?

基本数据类型之间的运算规则:

byte、char、short -> int -> long -> float -> double

注意:byte、char、short这三种数据类型做运算时,结果为int型。

public static void main(String[] args) {
        char one = 'a';  //97
        char two = 'b';  //98
        int three = 10;
        String str = "hello";
        System.out.println(one + three);  //107
        System.out.println(one + str);    //ahello
        System.out.println(three + str);  //10hello
        System.out.println(one + 2);      //99
        System.out.println(one + two);    //195
}

运行结果:

image.png

char和int之间相加,char型会转换为int类型,最后结果为107.

char和char之间相加,最后结果也是int类型,最后结果为195.


点赞(0)

注释列表 共有 0 条评论

暂无评论
0
立即
投稿
发表
评论
返回
顶部