Georgios Tasioulis
Georgios Tasioulis

Reputation: 37

Using char and int being in System.out.write() statement

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');
   }
}
  1. How can we use the character 'x' for the variable b which is an integer?
  2. 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?

Upvotes: 1

Views: 861

Answers (2)

Leo
Leo

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

Elliott Frisch
Elliott Frisch

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 to int, long, float, or double

Upvotes: 3

Related Questions