Reputation:
When I compile a program in java containing this :
ch = (char) ch - 32;
the terminal shows :
incompatible types: possible lossy conversion from int to char
ch = (char) ch - 32;
^
1 error
but this works
ch = (char) (ch - 32);
why is this happening? Thanks in advance.
Upvotes: 2
Views: 57
Reputation: 140457
Because
ch = (char) ch - 32;
is the same as
ch = ( (char) ch ) - 32;
As in:
ch = ch - 32;
Which first turns ch
into an int value. To subtract 32. Resulting in an int value. Which doesn't fit into a char (easily). Thus the compiler error.
One way around that: make sure that the cast applies to the result of the operation, not to the first operand.
ch = (char) ( ch - 32 );
Upvotes: 2