Characters have built-in int values ​​in Java?

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

public static void permutations(int n) { System.out.print('a' + 0); } 
+6
source share
4 answers

a is of type char , and characters can be implicitly converted to int . a is represented as 97 because it is the code point 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 println(int) .

Related: What is encoded Java char stored in?

+5
source

Yes. char (s) have a built-in int value in Java. JLS-4.2.1. "Integral types and values" (partially),

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

...

For char , from '\u0000' to '\uffff' inclusive, i.e. from 0 to 65535

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

JLS-4.2.2. Entire operations , in particular

Numeric operators that result in a value of type int or long :

...

Additive operators + and - ( Β§15.18 )

+4
source
 System.out.println('a' + 0); // prints out '97' 

'a' is implicitly converted to its unicode value (it's 97), and 0 is an integer. So: int + int β†’ int

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

So: char + string -> string

+2
source

Because 'a' was implicitly converted to its unicode value, adding it to 0.

+1
source

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


All Articles