Reputation: 37
I would like to pose 2 questions for the following program
class WriteDemo{
public static void main(String args[]){
int b;
b = 'x';
System.out.write(b);
System.out.write('\n');
}
}
'x'
for the variable b which is an integer?System.out.write('\n');
nothing appears on the screen.Upvotes: 1
Views: 861
Reputation: 6580
when you run
System.out.write(b);
you're actually calling this method at PrintStream class
/**
* Writes the specified byte to this stream. If the byte is a newline and
* automatic flushing is enabled then the <code>flush</code> method will be
* invoked.
*
* <p> 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 <code>print(char)</code> or <code>println(char)</code>
* methods.
*
* @param b The byte to be written
* @see #print(char)
* @see #println(char)
*/
public void write(int b) {(...)
so if you flush your printer explicitly (or print a newline, as stated in the javadoc), you'll see the "x"
System.out.write(b);
System.out.flush();
about using 'x' as integer, I assume you're talking about what int number does x represent and how to print it.
Notice that if you do
System.out.println(b);
It will show you 120 because println will end up calling String.valueOf(b)
Upvotes: 3
Reputation: 201507
In reverse order,
The result of the program that appears on the screen is x. in case i remove the final line System.out.write('\n'); nothing appears on the screen. Why is this happening?
Because the '\n' flushes the output buffers. You could also use,
System.out.write(b);
System.out.flush();
Your first question,
How can we use the character 'x' for the variable b which is an integer?
JLS-5.1.2 provides for the widening -
19 specific conversions on primitive types are called the widening primitive conversions:
...
char
toint
,long
,float
, ordouble
Upvotes: 3