Invalid character constant in java

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.

Leave a Comment