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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With