char ch = '3';
result = cube(ch);
// Call the method that accepts a char
System.out.println("Cubed 'char' = " + result);
The method cube
private static char cube(char c) {
char result;
result = (char) (c *c *c);
return result;
}
When I run this this code i get cubed 'char' = 1579, I would like to know where this number comes from within my code. Help!
When you multiple char
s together, they are promoted to int
.
The int
value of '3'
is 51 (the ASCII value; as stated in JLS Sec 3.1, the first 128 characters of UTF-16 encoding are the same as ASCII characters).
So '3' * '3' * '3' == 51 * 51 * 51 == 132651
.
But 132651
is too large to fit into a char
when you cast it; so it overflows (twice, since Character.MAX_VALUE == 65535
), and you get the value
(char) (c * c * c)
== (char) 132651
== (char) (132651 % 65536)
== (char) 1579
== 'ث'
But then you are assigning the result of the call to cube
to an int
(or long
) variable called result
; so it is promoted again to int
, and then concatenated to the string: this means that the integer value is appended to the string, not the char
. Hence:
Cubed 'char' = 1579
in the output.
Notice that if you call without assigning to result
:
System.out.println("Cubed 'char' = " + cube(ch));
then the output is
Cubed 'char' = ث
Ideone demo
A char
in Java is a 16 bit unsigned type with a range 0 to 65535.
Your code char ch = '3';
is actually assigning the value 51 to ch
. (Java mandates ASCII for the first 7 bits of the char
type and 51 is the ASCII value of the number 3).
Formally the multiplication happens just after the arguments to the muliplication are converted to int
. The result, 51 * 51 * 51 is 132651 and is an int
type. When you assign this to a char
, Java will subtract as many 65536 values as are necessary to pull the result into the accepted range. So your answer is
51 * 51 * 51 - 65536 - 65536 which is 1579
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With