1

I'm trying to convert an integer into its corresponding ascii value but getting different result than what I get in java.

Java

int c = 5032;
char c1 = (char)c;
System.out.print('==>' + c1);
//output ==> ?

Apex

string str = String.fromCharArray(new Integer[]{5032});
system.debug('==>' + str);
//output ==> Ꭸ

I believe java output is correct one, how can I achieve that same result in Apex?

1

In Java and Apex you are dealing with 16 bit characters (Unicode/UTF-16) not 8 bit characters (such as ASCII). Character 5032 in Unicode is this http://www.fileformat.info/info/unicode/char/5032/index.htm. (Some more detail in How does Java store UTF-16 characters in its 16-bit char type?.)

As you can imagine, supporting many thousands of character glyphs in a font is a lot of work: the output you are seeing for Java may just be an output representing the lack of a glyph in the font being used. The output you see in Apex is probably more correct.

2

Actually, the ASCII Code for the question mark character (?) is 63.

system.assertEquals('?', String.fromCharArray(new List<Integer> { 63 }));

Also, it does look like 5032 should correspond to the character output by Apex, according to this page.

1

In Apex Code and Java, strings are stored in UTF-8. The difference comes in the output of those characters (System.out vs System.debug). If you wrote the output to a file, and set the encoding to UTF-8, they should come out to be the same output. It's a matter of the stream's interpretation. Java, by default, outputs ASCII, while Apex Code always uses UTF-8. Technically, Java's output is incorrect, because it did not display the correct glyph for the specified character. If you were to use that same char in a string that were displayed in a GUI, there should be no difference between Java and Apex Code's output.

1

Essentially both your java and apex code are giving the right output. Java system.out.print to a console does not interpret the UTF-16 char, hence a "?". But now if you spool the char to a file(OutputStreamWriter(fos, "UTF16");) in your Java Code, you can see the right Unicode character. Apex "system.debug" spools the output to a file (Unicode), hence you see the expected Unicode char.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.