6

Why does this code print 97? I have not previously assigned 97 to 'a' anywhere else in my code.

public static void permutations(int n) {
    System.out.print('a' + 0);
}
Rachel
  • 123
  • 1
  • 1
  • 4
  • 1
    Character literals in Java are 16-bit integer constants representing Unicode UCS-16 encoding values (not quite the same as Unicode code points, which are 21 bits). – Lee Daniel Crocker Dec 30 '14 at 01:07
  • Read [the Java tutorial on Unicode](http://docs.oracle.com/javase/tutorial/i18n/text/unicode.html) – Maarten Bodewes Dec 30 '14 at 01:07
  • char is an unsigned short value as all data is ultimately a binary number. The encoding is standard utf-16. This letter is one of the ASCII standard characters. It's encoding predates java by a few decades. – Peter Lawrey Dec 30 '14 at 09:19

4 Answers4

5

a is of type char and chars can be implicitly converted to int. a is represented by 97 as this is the codepoint of small latin letter a.

System.out.println('a'); // this will print out "a"

// If we cast it explicitly:
System.out.println((int)'a'); // this will print out "97"

// Here the cast is implicit:
System.out.println('a' + 0); // this will print out "97"

The first call calls println(char), and the other calls are to println(int).

Related: In what encoding is a Java char stored in?

Community
  • 1
  • 1
Sebi
  • 1,390
  • 1
  • 13
  • 22
  • I'm extremely hesitant to say that it can be implicitly converted to `int`; in most implementations it *is* an `int` with a much more restricted bound. – Makoto Dec 30 '14 at 02:21
  • In java terms, it is different datatype. While it is right to say that both are _integer_ data types (like `byte` or `long` are), they have different sizes and are distinct data types. While saying it is being `cast` would be right, sign-extending conversion also takes place. – Sebi Dec 30 '14 at 14:00
4

Yes. char(s) have intrinsic int value in Java. The JLS-4.2.1. Integral Types and Values says (in part),

The values of the integral types are integers in the following ranges:

...

For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535

And of course, when you perform integer arithmetic ('a' + 0) the result is an int.

JLS-4.2.2. Integer Operations says in part,

The numerical operators, which result in a value of type int or long:

...

The additive operators + and - (§15.18)

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2
System.out.println('a' + 0); // prints out '97'

'a' is implicitly converted to its unicode value (that's 97) and 0 is an integer. So: int + int --> int

System.out.println('a' + "0"); // prints out 'a0'

So: char + string --> string

ProgrammingIsAwsome
  • 1,109
  • 7
  • 15
1

Because 'a' has been implicitly converted to its unicode value summing it with 0.

nbro
  • 15,395
  • 32
  • 113
  • 196