The issue with your code is pretty simple:
new StringBuffer('M')
doesn't do what you think it does. There exists no constructor for StringBuffer
that expects a char
. Instead this constructor is called: StringBuffer(int capacity)
, with char
being implicitly converted to int
.
So basically your code doesn't create a new StringBuffer
containing a single character, but a StringBuffer
with the capacity matching the given character.
But there are aswell some other issues, like missing break
at the end of each case
, so after the switch-statement, word
will always be new StringBuffer('M');
The reason why this compiles is primitive widening conversion. Basically any integral data-type can be converted into another integral data-type, as long as the conversion is loss-less. Here are some links for further reading:
StringBuffer docs
Primitive Widening - JLS