user6912729
user6912729

Reputation:

why the output displays 3 and not a char in java

i would understand why the output is 3 and not a char ('5' unicode character)

char c='5';
c = (char) (c - 2);
System.out.println(c); 

and could you please explain what's the difference beetween code ASCII and unicode character ?

thank you in advance :)

Upvotes: 0

Views: 56

Answers (2)

Michael
Michael

Reputation: 44240

It is a character. It's a character representing the numeral 3, just as '3' is a character on your keyboard.

When you subtract one from a character, you get the character immediately before that. For example, 'B' - 1 = A.

You start with the character '5' and subtract two, giving the character '3'. If you subtracted 6, you would not get -1, you'd get a random character ('/' I think).

Basically this subtraction works because the characters 0 - 9 are stored contiguously.

Upvotes: 2

Eran
Eran

Reputation: 394026

The output is the char '3', not the number 3.

When you subtract 2 from the char '5' and cast the result to char, you get the char '3'.

The char type is a numeric primitive type. Each character has a corresponding integer value between 0 and 2^16-1. The integer value of the character '3' is smaller by 2 than the value of the character '5'.

Upvotes: 1

Related Questions