Why am I getting this result?

char ch = '3';
result = cube(ch);
// Call the method that accepts a char
System.out.println("Cubed 'char' = " + result);

Method cube

private static char cube(char c) {
    char result;
    result = (char) (c *c *c);
    return result;
}

When I run this code, I get the cube 'char' = 1579, I would like to know where this number comes from from my code. Help!

+4
source share
3 answers

When you are somewhat chartogether, they are upgraded toint .

The value int '3'is 51 (the ASCII value, as specified in JLS Sec 3.1 , the first 128 characters of the UTF-16 encoding is the same as the ASCII characters).

So '3' * '3' * '3' == 51 * 51 * 51 == 132651.

But 132651too large to embed it in charwhen pressed; so it overflows (twice, starting at Character.MAX_VALUE == 65535) and you get the value

   (char) (c * c * c)
== (char) 132651
== (char) (132651 % 65536)
== (char) 1579
== 'ث'

cube int ( long) result; int, : , , char. :

Cubed 'char' = 1579

.

, result:

System.out.println("Cubed 'char' = " + cube(ch));

Cubed 'char' = ث

Ideone demo

+8

A char Java - 16- 0 65535.

char ch = '3'; 51 ch. (Java ASCII 7 char, 51 - ASCII 3).

muliplication int. 51 * 51 * 51 132651 int. char, Java 65536 , , . ,

51 * 51 * 51 - 65536 - 65536, 1579

+2

: (51 ^ 3)% (2 ^ 16)

, andy , 51 ( ascii '3') ^ 3 , 2 ^ 16 ( java) , .

+1

Source: https://habr.com/ru/post/1658109/


All Articles