4
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);
dulaj sanjaya
  • 1,290
  • 13
  • 25

2 Answers2

9

Because 1889 % 256 = 97. There are 256 ASCII characters, so the mod operator is used to get a valid character.

SkyWalker
  • 28,384
  • 14
  • 74
  • 132
Cricket
  • 148
  • 1
  • 5
2

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.

Community
  • 1
  • 1
jonhopkins
  • 3,844
  • 3
  • 27
  • 39