开发者

what is the difference between (char)temp and Character.toChars(temp) and String.valueOf(Character.toChars(temp)) in java

I got the same result from these, what is the difference? which is better? temp is an int, read from reader.read()

System.out.print((char)temp);

System.out.print(Character.toChars(temp));

System.out.print(String.valueOf(Character.toChars(temp开发者_开发百科)));


The first two are basically the same, except you are calling the Character object instead of the primitive data type char. The third one is just another step which is not needed, System.out.print turns the input into a readable output string anyways, so there is no need to parse the char into a string.

The first way is a perfectly fine way of doing what you need done.


Normally, these three statements all do the same thing. And certainly, this is the case if temp contains a character that you have just read using Reader.read() and that character was not a UTF-16 surrogate character. (Whether this does the "right" thing or not depends on whether the default character encoding supports the character that you are trying to write.)

If temp contained a Unicode codepoint that was larger than 65535, then the first statement would end up mangling the codepoint, but the second and third statements would result in the correct representation of the character being output ... modulo the default character set issue.

If temp contained a UTF-16 surrogate character, then I'm not quite sure what would happen. I suspect that it would work. However, a literal reading of the javadoc for PrintStream.print(char) leaves open the possibility that even a UTF-16 to UTF-8 conversion might treat a single surrogate character as an error. However, this is moot unless your Reader was reading as stream that included Unicode codepoints larger than 65535.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜