从char转换为String应该会导致以下错误:此代码:
char [] arr = {'H', 'e', 'l', 'l', 'o'}; String c = arr[1];错误:类型不匹配:无法从char转换为String
此代码:
char [] arr = {'H', 'e', 'l', 'l', 'o'}; String c = ""; for(char i : arr) { c += i; }作品。
Converting from char to String should cause the following error: This code:
char [] arr = {'H', 'e', 'l', 'l', 'o'}; String c = arr[1];Error :Type mismatch: cannot convert from char to String
This code :
char [] arr = {'H', 'e', 'l', 'l', 'o'}; String c = ""; for(char i : arr) { c += i; }Works.
最满意答案
+=运算符,如+运算符,将执行字符串转换 ,其中一个操作数是一个String ,另一个不是。
+=的代码将使用字符串转换将i从char转换为String以便连接到c ,一个String 。
根据JLS的第5.2节 ,带=的代码不会使用字符串转换,因为它不在可分配上下文的可接受转换列表中。
The += operator, like the + operator, will perform string conversion, when one of its operands is a String and the other isn't.
The code with += will use string conversion to convert i from a char to a String for concatenation to c, a String.
The code with = will not use string conversion, because it's not in the list of acceptable conversions for assignment contexts, according to the JLS, Section 5.2.
更多推荐
发布评论