Reputation:
Suppose that int b = 99
. Why does system.out.write(b)
print "c" instead of 99? At the same time using PrintWriter
I get actual value of b (99) even if b = 'c'?
Upvotes: 2
Views: 254
Reputation: 6984
Both output 'c' exactly the same and as to be expected. System.out.write and PrintWriter.write both output the same result... 'c'
int b = 99;
System.out.write(b);
System.out.flush();
System.out.println("");
PrintWriter x = new PrintWriter(System.out);
x.write(b);
x.flush();
outputs
c
c
Look at the number 99 on this chart http://www.asciitable.com/
Here is what the documentation says about the System.out.write method
Note that the byte is written as given; to write a character that will be translated according to the platform's default character encoding, use the print(char) or println(char) methods.
The PrintWriter has an overloaded method for passing a String. But in this case when you pass a number which it converts to a char.
Writes a single character. Overrides: write(...) in Writer Parameters:c int specifying a character to be written.
It appears your problem is that you are using the println method for the PrintWriter but not for System.out, just use the println method in System.out and you will get the same results. This is because you are using an overloaded constructor which accepts and prints an integer but for write the method takes the number and converts it to a char, that is just what it is for.
Upvotes: 1
Reputation: 5318
Suppose that int b = 99. Why does system.out.write(b) print "c"
and
99 = 0x63
Upvotes: 3
Reputation: 5868
The thing is System.out.write(int)
would consider the argument as byte and would write it to stream.
In your case since you passed 99
which is U0063
, hence c
is printed.
Upvotes: 3