Both of these lines will write me letter A in a file
. Can someone tell me how are they different in internal working?
FileOutputStream fileOutputStream = new FileOutputStream("test.txt");
fileOutputStream.write(65);
fileOutputStream.write('A');
[EDIT]: I am more interested in how converting works in both of these cases. As I know what ASCII and UNICODE tables are.
Let's start with the javadoc for
FileOutputStream
. If you look at it you will see that there are threewrite
methods:So what does it tell us?
Clearly, when we call
fileOutputStream.write(65)
orfileOutputStream.write('A')
, we are NOT calling the first or second overloads of thewrite
method. We are actually calling the third one.Therefore when we call
fileOutputStream.write('A')
, thechar
value'A'
is converted to anint
value. This conversion is a primitive widening conversion fromchar
toint
. It is equivalent to doing an explicit type cast; i.e(int) 'A'
.Primitive widening casts from an integer type (e.g.
char
) to a larger integer type (e.g.int
) is simply a matter of making it bigger. In this case we just add 16 zero bits on the front. (Becausechar
is unsigned andint
is signed.)When we look at the ASCII and Unicode code tables we see that they both use the same value for the letter capital A. It is 65 in decimal or 41 in hexadecimal. In other words
(int) 'A'
and65
are the same value.So when you take the implicit widening conversion that happens,
fileOutputStream.write('A')
andfileOutputStream.write(65)
are actually callingwrite
with the same parameter value.Finally, the javadoc for
write(int)
refers to this javadoc which says:That explains how the
int
magically turns into abyte
.Note that this only prints something sensible because we picked a character in the ASCII character set. It so happens that Unicode chose to mirror the ASCII character set as the first 128 Unicode codepoints.
If you replaced
A
with some character outside of the ASCII charset, there is a good chance thatOutputStream::write(int)
would garble it.It is better to use a
FileWriter
rather than aFileOutputStream
when outputting text.