开发者

char c=7; Why this statement will execute in java without error?

char c=7;

The above statement will execute开发者_运维知识库 in java without error even though we are assigning a number to character. where 7 is not a character .Why will it execute?


Because in Java char is an integral data type, whose values are 16-bit unsigned integers representing UTF-16 code units. Since char is a numeric data type, when you assign it a numeric value, it just takes on the encoding of whatever Unicode character is represented by that value.

Run the following two lines of code:

char c = 65;
System.out.println("Character: " + c);

You'll see the output:

Character: A

(I would have used 7 like you did in the example, but that's an unprintable character.) The character "A" is printed because the decimal value 65 (or 41 hex) is encoded to that letter of the alphabet. See Joel Spolsky's article The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) for more information in Unicode.

Update:

In case you're talking about the fact that int value assignment to char normally gives you a "possible loss of precision" compiler error, as the following code will demonstrate:

int i = 65;
char c = i;
System.out.println("Character: " + c);

The answer is just what PSpeed mentioned in his comment. In the first (2-line) version of the code, the literal assignment works because the value is known at compile time. Since the value 65 is within the correct range for a char ('\u0000' to '\uffff' inclusive, or from 0 to 65535), the assignment is allowed to take place. In the second (3-line) version the assignment isn't allowed because the int variable could take any value from -2147483648 to 2147483647, inclusive, most of which are out of range for the char variable to contain.


Read http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Character.html particularly the Unicode Character Representations section. The raw value of a character has an integer equivalent.


An implicit conversion takes place. The compiler is able to validate the range.


Note the difference between the two outputs:

  int x = 47;
  System.out.println('[' + x + ']');  // 231 (= 91 + 47 + 93)
  System.out.println("[" + x + "]");  // [47]

A char is both a character and a number. (A floor wax and a dessert topping.)


It implicitly coverts to an ascii character.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜