user8586459
user8586459

Reputation:

Warning in java changes with the scope of cast

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

Answers (1)

GhostCat
GhostCat

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

Related Questions