0

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 :)

  • 1
    Possible duplicate of [What's the difference between ASCII and Unicode?](https://stackoverflow.com/questions/19212306/whats-the-difference-between-ascii-and-unicode) – Daedric Jul 13 '17 at 10:20
  • 1
    The subtraction turns the character `'5'` into the character `'3'`. See e.g. [this ASCII table](http://www.asciitable.com/) to understand why. – Some programmer dude Jul 13 '17 at 10:21
  • 1
    What do you mean "not a char"? It's the char `'3'` - it's unclear what you're asking. – Jon Skeet Jul 13 '17 at 10:22
  • A key conceptual difference is that ASCII has one encoding while Unicode has several. Now that you know that, you can forget about ASCII. You are not—and possibly won't ever be—writing code that uses ASCII. XML, HTML, etc use Unicode. Java, .NET, JavaScript, SQL (NCHAR, NVARCHAR) use the UTF-16 encoding of Unicode. `char` is a UTF-16 code unit. – Tom Blodget Jul 13 '17 at 15:14

2 Answers2

2

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.

Michael
  • 41,989
  • 11
  • 82
  • 128
1

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'.

Eran
  • 387,369
  • 54
  • 702
  • 768