Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can I do with a hex String literal? [duplicate]

Tags:

java

hex

I'm learning Java, and I'm on a book chapter about hex String literals. It tells me that I can create a hex String literal in this format: "\uxxxx". So I tried this:

char c = '\u0010';
int x = c;
System.out.println(x);  // prints 16.

Firstly, why does the following hex String literal cause a compilation error? I was expecting that 'a' in hex would equal 10 in decimal.

char c = '\u000a';

Returns the following error:

..\src\pkgs\main\Main.java:360: error: illegal line end in character literal
                char c = '\u000a';

Secondly, because of my novice Java status, I'm currently not able to appreciate what hex String literals are used for. Why would I want to use one? Can someone please provide me with a "real world" example of their use? Thanks a lot.

like image 583
user2911290 Avatar asked Feb 28 '14 11:02

user2911290


2 Answers

The fact that the compiler gives an error is because the compiler will parse the \u000a to CR

char A = '\u000A';

therefore becomes...

char A ='
';

which results in a compile-time error. To avoid this error, always use the special escape characters '\n' (line feed) and '\r' (carriage return).

like image 198
Abimaran Kugathasan Avatar answered Sep 24 '22 19:09

Abimaran Kugathasan


As noted already, Unicode escapes are actually processed during compilation as a replacement:

Because Unicode escapes are processed very early, it is not correct to write '\u000a' for a character literal whose value is linefeed (LF); the Unicode escape \u000a is transformed into an actual linefeed in translation step 1 (§3.3) and the linefeed becomes a LineTerminator in step 2 (§3.4), and so the character literal is not valid in step 3. Instead, one should use the escape sequence '\n' (§3.10.6). Similarly, it is not correct to write '\u000d' for a character literal whose value is carriage return (CR). Instead, use '\r'.

This aspect of Unicode escapes is not just limited to character literals. For example, the following will print "hello world":

// \u000A System.out.println("hello world");

Another way to get special characters beyond an escape is to use an integer literal:

static final char NUL = 0x0000;

As for their usefulness, for one, because otherwise you'd have to copy and paste special characters or type them in with some keyboard combination. The other reason is that certain characters don't have a proper visual representation. Examples of this are null, escape, backspace and delete. Also code point 7, the bell character, which is actually an instruction for the computer to emit a beep when it gets printed.

like image 45
Radiodef Avatar answered Sep 24 '22 19:09

Radiodef