Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implicit type casting should not works from char to String. How is this possible ?

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.

like image 454
AchillesVan Avatar asked Dec 20 '22 01:12

AchillesVan


1 Answers

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.

like image 92
rgettman Avatar answered Dec 26 '22 00:12

rgettman