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()





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.

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.

Need Your Help

Passing a Path with '&' to Batch File

windows batch-file path cmd

I am trying to pass a path to a batch file from another program. The other program uses BASIC as it's scripting language.

Cast Any of String to Int


I have a variable of type Any with runtime type of String which I want to cast to Int: