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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because in Java
charis an integral data type, whose values are 16-bit unsigned integers representing UTF-16 code units. Sincecharis 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:
You’ll see the output:
(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
intvalue assignment tocharnormally gives you a "possible loss of precision" compiler error, as the following code will demonstrate: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 theintvariable could take any value from -2147483648 to 2147483647, inclusive, most of which are out of range for thecharvariable to contain.