Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

\x Escape in Java?

Tags:

java

escaping

hex

I was wondering if there is a similar hex (\x) escape in Java like there is in C++. For example:

char helloworld[] = "\x48\x45\x4C\x4C\x4F\x20\x57\x47\x52\x4C\x44"; printf("%s", helloworld); 

There is no hex (\x) escape in Java from what it appears so far. Is there an alternative that is just as easy to use without having to concat a bunch of hex numbers together?

like image 887
David Avatar asked Aug 31 '10 22:08

David


People also ask

How do you escape the symbol in Java?

A character with a backslash (\) just before it is an escape sequence or escape character.

What is escape code in Java?

Escape sequences are used to signal an alternative interpretation of a series of characters. In Java, a character preceded by a backslash (\) is an escape sequence. The Java compiler takes an escape sequence as one single character that has a special meaning.

How do you escape unicode characters in Java?

According to section 3.3 of the Java Language Specification (JLS) a unicode escape consists of a backslash character (\) followed by one or more 'u' characters and four hexadecimal digits. So for example \u000A will be treated as a line feed.


2 Answers

Strings in Java are always encoded in UTF-16, so it uses a Unicode escape: \u0048. Octal characters are supported as well: \110

like image 160
erickson Avatar answered Oct 05 '22 20:10

erickson


Note that Unicode escapes are parsed quite early. It can come as a surprise when

  String s = "text\u000d\u000a"; 

causes a compiler error because you should have used "text\015\012" or "text\r\n"

like image 33
tschodt Avatar answered Oct 05 '22 20:10

tschodt