Reputation: 4356
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.
Upvotes: 4
Views: 660
Reputation: 159165
Since String
is immutable, the compiler actually converts +=
to
c = c + i;
which compiles to
c = new StringBuilder().append(c).append(i).toString();
and StringBuilder has append
overloads for all the primitive types.
Upvotes: 4
Reputation: 178303
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.
Upvotes: 7