Appending a byte to String in java using escape sequence

I wish to append a byte i.e. 16 = 0x10 to a String, using escape sequence to do it in single line of code:

String appendedString = new String('\16'+"String");

This results in a hex representation of appendedString = 0x0E,0x74,0x72,0x69,0x6E,0x67

using a \2 like this:

String appendedString = new String('\2'+"String");

works fine resulting in a hex representation of appendedString = 0x02,0x74,0x72,0x69,0x6E,0x67

using a \10:

String appendedString = new String('\10'+"String");

results in a hex representation of appendedString = 0x08,0x74,0x72,0x69,0x6E,0x67

Someone may kindly explain this and suggest a solution. Thanks.

Jon Skeet
people
quotationmark

\10 is in octal which is why you're getting U+0008.

I don't believe there are any escape formats which use decimal; I'd suggest using the \uxxxx format, or specific escape sequences for supported characters (\r, \n etc). So for the second case you could use \u000a - or just use \n in this case. For the first, you'd use \u0010.

See section 3.10.6 of the JLS for more details about escape sequences.

I'd also strongly recommend that you stop thinking of these as bytes - they're characters (or UTF-16 code units, if you want to be really precise).

people

See more on this question at Stackoverflow