Discuss / Java / 打卡2019-05-20

打卡2019-05-20

Topic source

int a = 72;

int b = 105;

int c = 65281;

String res = "" + (char)a + (char)b  + (char)c;

System.out.println(res);

使用(char)的时候,72 105 65281是先转换为unicode码再映射是字符吗?

明明love0

#3 Created at ... [Delete] [Delete and Lock User]

 "" 这个为什么要加在(char)a前面,是什么原理啊,没看懂

xiao伟iii

#4 Created at ... [Delete] [Delete and Lock User]

加个 “” 就类似于你定义一个空的字符串在前面:

String str = "";
String s = str + (char)a + (char)b + (char)c;

有了第一个string,后面的 + 就是字符串的连接了操作符了,而不再是 char/int 的数值相加了。

YANGZY1202

#5 Created at ... [Delete] [Delete and Lock User]

廖老师在本节里说过:“Java的编译器对字符串做了特殊照顾,可以使用+连接任意字符串和其他数据类型。"

因此正如楼上所说,在Java中string+任何类型都会使其他类型转换成string并与之连接;

在本例中,String s = "" + (char)a + (char)b  + (char)c; 第一个空串能够使得后续的char全部转换成string后相连,从而得到我们需要的String s。

honnnnnnnnnng

#6 Created at ... [Delete] [Delete and Lock User]

 String s = "" +  a + b + c;


  • 1

Reply