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);
}
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);
}
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)
.
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, from0
to65535
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
orlong
:...
The additive operators + and - (§15.18)
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
Because 'a'
has been implicitly converted to its unicode value summing it with 0.