8
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.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Kevin
  • 23,174
  • 26
  • 81
  • 111
  • 7
    Java is NOT JavaScript! – Patrick Apr 17 '13 at 13:38
  • Duplicate of http://stackoverflow.com/questions/6002366/invalid-character-constant – devrobf Apr 17 '13 at 13:39
  • Preventing missunderstandings. Javascript is not the same as Java. JS is a script language, developed by Netscape Inc. in the early ninethees. Java is a object orientated language to develop mainingly standalone applications, developed by Sun Inc. – Reporter Apr 17 '13 at 13:41
  • 2
    As mentioned above, java is not javascript and you SHOULDN'T use the same code in java and javascript files. About your question: `'` in java is used for character literals and `"'` is used for string literals. `'\' '` is not a valid character literal in java, while '\'' is. So you should write that statement as `... + "' " ... + "''"`. – khachik Apr 17 '13 at 13:41

1 Answers1

28

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194