2

I am learning java and the answer of one question seems to be wrong: question: Which of the following are legal?

char c = 0x1234;//A
char c = \u1234;//B
char c = '\u1234';//C

in the book the answer is C, but I think it should be both A and C. Anyone please verify that for me?

4
  • 5
    Why don't you try it? Commented Oct 16, 2013 at 15:48
  • (A) is perfectly legal. Commented Oct 16, 2013 at 15:49
  • Numbers aren't characters. Commented Oct 16, 2013 at 15:49
  • Just B is incorrect, missing single quotes. Commented Nov 15, 2015 at 17:50

2 Answers 2

6

Both A and C are correct

char a = 0x1234;

The literal 0x1234 is a hex integer literal. Its value fits in the char primitive type, so it is valid;

char b = \u1234;//B

Is not valid notation and so won't compile.

char c = '\u1234';

char is

char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

So it's valid.

Sign up to request clarification or add additional context in comments.

Comments

1

char c = 0x1234;//A -- Correct

as it's value begins with 0X it is a valid hexadecimal value. Hence Correct.

char c = \u1234;//B --- Incorrect

Not a valid u code, as it's not surrounded with''.

char c = '\u1234';//C -- Correct

it is valid u code and is correctly surrounded by '', hence it is correct too.

3 Comments

Why? Explain your answer
char c = 0x1234; , as it's value begins with 0X it is a valid hexadecimal value. Hence Correct. char c = '\u1234'; it is valid u code and is correctly surrounded by '', hence it is correct too.
You should explain it in the answer itself - not everyone will read the comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.