Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 203
giri Avatar asked Nov 30 '22 11:11

giri


1 Answers

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.

like image 167
Bill the Lizard Avatar answered Dec 03 '22 00:12

Bill the Lizard