Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing console output in java

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);
like image 396
dulaj sanjaya Avatar asked Dec 19 '22 14:12

dulaj sanjaya


2 Answers

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

like image 161
Cricket Avatar answered Jan 06 '23 19:01

Cricket


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.

like image 23
jonhopkins Avatar answered Jan 06 '23 21:01

jonhopkins