class HelloWorld {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
System.out.write(97);
System.out.write('\n');
System.out.write(1889);
System.out.write('\n');
}
}
output of this program is
A
a
a
How does the following line produce a as the output.
System.out.write(1889);
Because 1889 % 256 = 97
. There are 256 ASCII characters, so the mod operator
is used to get a valid character.
According to this answer System.out.write(int)
writes the least significant byte to the output in a system-dependent way. In your case, the system decided to write it as a character.
1889 == 0000 0111 0110 0001
97 == 0000 0000 0110 0001
The right-most octet is the same for both numbers. As @Cricket mentions, this is essentially the same as taking the modulus of the number you pass in and 256.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With