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.

4

1 Answer

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like