隐式类型转换不应该从char转换为String。(implicit type casting should not works from char to String. How is this pos

编程入门 行业动态 更新时间:2024-10-28 10:24:56
隐式类型转换不应该从char转换为String。(implicit type casting should not works from char to String. How is this possible ?)

从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.

更多推荐

本文发布于:2023-07-22 02:10:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1215990.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   类型   隐式   char   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!