java

Invalid character constant in java


return (int) (feetPart) + '\' ' + inchesPart + '\''+'\'';

Why is the above invalid character constant, this works perfectly in JavaScript. I want to display height in feet and inches and was using this client side, but when I use the same in server side it shows Invalid character constant.


Solution

  • Why is the above invalid character constant

    Because of this part:

    '\' '
    

    That's trying to specify a character literal which is actually two characters (an apostrophe and a space). A character literal must be exactly one character.

    If you want to specify "apostrophe space" you should use a string literal instead - at which point the apostrophe doesn't have to be escaped:

    "' "
    

    Your whole statement would be better as:

    return (int) (feetPart) + "' " + inchesPart + "''";
    

    Or to use " instead of '' for the inches:

    return (int) feetPart + "' " + inchesPart + "\"";
    

    Note that it's not even clear to me that the original code would do what you wanted if it did compile, as I suspect it would have performed integer arithmetic on feetPart and the character...

    Your code would have been okay in Javascript, because there both single quotes and double quotes are used for string literals.