dulaj sanjaya
dulaj sanjaya

Reputation: 1340

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);

Upvotes: 4

Views: 459

Answers (2)

jonhopkins
jonhopkins

Reputation: 3842

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.

Upvotes: 2

Cricket
Cricket

Reputation: 148

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

Upvotes: 9

Related Questions