This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Can anyone please explain the code? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Can anyone please explain the code?" Watch "Can anyone please explain the code?" New topic
Author

Can anyone please explain the code?

Shankar Salunkhe
Greenhorn

Joined: Jul 17, 2012
Posts: 10
Hi,

Can anyone please explain the below code.
CODE : -

public class SampleClaass{

public static void main(String []args){
int a;
a='A';
System.out.write(a);
System.out.write('\n');
}
}

Why there is \n require for getting the output as : A.

If i removed the second System.out.write('\n');. The code get compile but unable to print the output.

Thanks in advance.
Shankar Salunkhe
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11153
    
  16

Try this:



There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Carina Caoor
Greenhorn

Joined: Jan 21, 2013
Posts: 7
This is what the docs says,

  • public void write(int b)
    Writes the specified byte to this stream. If the byte is a newline and automatic flushing is enabled then the flush method will be invoked.
    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


  • By the way just curious to know why the character is assigned to int datatype?
    Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 37957
        
      22
    You might get a hint from reading what the char datatype actually is. You will find it here in the Java Language Specification.
     
    It is sorta covered in the JavaRanch Style Guide.
     
    subject: Can anyone please explain the code?
     
    Similar Threads
    Difference between '\n' and '\r'
    How to convert integer array to character array
    diff between write and println function
    a thread code
    PrintStream class