System.out.println

It is love at first type. I fell in deep love with it from the first moment I used it. Didn’t you? How many times have we used it till now? It is one of the most number of times compiled statement in the history of java. We fondly call it SOP. If you want to dive directly to topic, jump to the first heading.

I first learnt DBase III+ and the statement to print is ? "Hello World". Then I went on to to study umpteen number of languages courtesy a poorly planned curriculum. Instead, we should have spent more time on flip-flops.

At the end of this article I have summarized Pascal, C, C++, Lisp, Prolog, Cobol, Basic, Fortran – I studied all these in a 3 year post graduate program and more than that. As I told, I am still not sure of the difference it made. Learning multiple languages is good, but my humble opinion is, do it after spending more time on fundamentals like data structures, algorithms, discrete maths, computer architecture, etc. Okay, where did I left? Lets continue with our System.out.println for now.

What is System.out.println

System.out.println prints the argument passed, into the System.out which is generally stdout.

  • System – is a final class and cannot be inherited. As per javadoc, “…Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array…”
  • out – is a static member field of System class and is of type PrintStream. Its access specifiers are public final. This gets instantiated during startup and gets mapped with standard output console of the host. This stream is open by itself immediately after its instantiation and ready to accept data.
  • println – println prints the argument passed to the standard console and a newline. There are multiple println methods with different arguments (overloading). Every println makes a call to print method and adds a newline. print calls write() and the story goes on like that.

Change out of System.out.println

‘out’ object can be customized. out gets initialized by java runtime environment at startup and it can be changed by developer during execution. Instead of standard output, in default cases when you run a program through command line, the output is printing in the same command window. We can change that behavior using setOut method as below. In the following example, I have redirected the output to a text file in the same directory.

public class ChangeOut {
	public static void main(String args[]) {
		try {
			System.setOut(new PrintStream(new FileOutputStream("log.txt")));
			System.out.println("Now the output is redirected!");
		} catch(Exception e) {}
	}
}
Ads by Google

System.out.println vs loggers like Log4j

Log4J has mulitple levels for logging. If we are writing a real short program, just for experimental/learning purposes SOPs are fine. When we are developing a production quality software project, we should be aware that a professional logger should be used and SOPs should be avoided. Why?

  • Flexibility: a professional logger like log4j provides different levels for logging. We can seggregate the log message accordingly. For example, X messages should be printed only on PRODUCTION, Y messages should be printed on ERROR, etc.
  • Configurability: in just one parameter change we can switch off all the logging statements.
  • Maintainability: imagine if we have hundreds of SOPs littered all through the application, it would be difficult to maintain the program over a period.
  • Granularity: In an application, every single class can have a different logger and controlled accordingly.
  • Utility: Option for redirecting the message is limited in System.out, but in case of a logger you have appenders which provides numerous options. We can even create a custom ouput option and redirect it to that.

Having said all the above, we still use System.out.println for logging and debugging. Which should be strictly avoided. This is driven by (bad)habit. I want to share how a habit became a convention. In this case its a good habit. Its using ‘i’, ‘j’ as index in for-loop. In FORTRAN language, we need not declare integer variables. Variable names that start with i, j, k, l, m and n are integer variables. So, FORTRAN developers named for-loop index with i,j,k and that habit carried on to other languages. Just a habit and became a good convention!

System.out.println and Performance

There is a general notion that SOPs are bad in performance. When we analyze deeply, the sequence of calls are like println -> print -> write() + newLine(). This sequence flow is an implementation of Sun/Oracle JDK. Both write() and newLine() contains a synchronized block. Synchronization has a little overhead, but more than that the cost of adding characters to the buffer and printing is high.

When we run a performance analysis, run multiple number of SOP and record the time, the execution duration increases proportionally. Performance degrades when we print more that 50 characters and print more than 50,000 lines.

It all depends on the scenario we use it. Whatever may be the case, do not use System.out.println for logging to stdout.

Static Import to Shorten SOP

Someone complained that System.out.println is a loooong statement to print something. static import may shorten it a bit but it is not recommended, because it results in poor readability. I am just using this situation to explain static import and avoid using it in the below scenario.

import static java.lang.System.out;

public class ShortSOP {
public static void main(String[] args) {
out.println("Hello, world");
}
}

In Eclipse you have programmed shortcuts like ctrl + spac to help you out.

System.err and System.in

As a related section, I wish to discuss about ‘err’ and ‘in’. ‘in’ is associated with InputStream. Opposite to ‘out’, ‘in’ is used to get input from standard console generally keyboard.
‘err’ is associated with PrintStream and prints the argument to the standard error output stream. When you use eclipse kind of IDE you can see the differene in ouput between ‘out’ and ‘err’.

public class InOutErr {
public static void main(String args[]) {
try {

BufferedReader reader = new BufferedReader(System.in);
String filename = reader.readLine();

  InputStream input = new FileInputStream(filename);
  System.out.println("File opened...");

} catch (IOException e){
  System.err.println("Where is that file?");
}
}
}

Print in other languages

DBASE III+
? "Hello World"

C

 #include 
 #include 

 int main(void)
 {
  printf("Hello, world");
  return EXIT_SUCCESS;
 }

CPP

 #include 

 int main()
 {
 	std::cout << "Hello, World." << std::endl;
 }

BASIC

10 PRINT "HELLO WORLD"

FORTRAN

 PROGRAM HELLOWORLD
 10 FORMAT (1X,11HHELLO WORLD)
 WRITE(6,10)
 END

COBOL

 IDENTIFICATION DIVISION.
 PROGRAM-ID. Hello.
 ENVIRONMENT DIVISION.
 DATA DIVISION.
 PROCEDURE DIVISION.
	Display 'Hello, World'.
	STOP RUN.

LISP

	(DEFUN HELLO-WORLD ()
	(PRINT (LIST 'HELLO 'WORLD)))

PROLOG

go :-
	writeln('Hello World').

Yes, I sourced all this programs from Internet :-) How come you expect me to remember all these! System.out.println("Bye");

This Core Java tutorial was added on 29/04/2012.

«

»

150 Responses to “System.out.println”

  1. Shiv says:

    Excellent article to read. Enjoyed it! you rock!

    With a simple title, inside so many things to learn…

    Great Joe..

    • Sachin says:

      hello sir, I am new to java and I want to know that out is static variable of class System and of type PrintStream. I confused that how this out access or call the method println() which is defined in PrintStream class?

  2. Kumar P says:

    Lovely

  3. sudheer says:

    Great Post. Its very useful.

  4. Anders says:

    I do not agree with you about it is bad to learn many languages.
    Each language is designed to solve different problems in different ways. So by learning different languages, you learn different ways of solving problems, esp. if the languages are different, like Java, Prolog, Scheme and LISP etc. They are as different as a hammer and a screwdriver.
    You would not use a hammer to unscrew something from the wall or put together an IKEA furniture. So why do people think that they can program if they only know one computer language?
    So, as to know many different natural languages, It’s good to know many programming languages.

  5. Anders says:

    And yes, stdin, stdout and stderr are all from the Unix world. And to redirect stdout to some other fold, you start the program with “pgm1 >file.txt”. To redirect stdin to read from a text file instead of the keyboard, start with “pgm2 <file.txt". And this is powerfully, as you can make output from one program input from another, like "pgm1 ¦ pgm2". If you still want error messages come to the screen, you have to print on stderr.
    And, stdout and stdin is buffered, stderr isn't. So do NOT use stdout for info and error messages, use stderr…

    • buzz says:

      Why do you post such rubbish in reply to such a great article Mr know it all. Forgive me for being frank but both your comments are lacking.

      And not that it matters, but no, when you’re talking about stdin and stdout etc you should be talking about C not Unix, obviously, and I fail to see how any of that contradicts the article to begin with.

  6. santhana says:

    Really nice article….Good work..Keep it up…

  7. Anonymous says:

    good job thx :D

  8. Srikanth says:

    it is very nice….

  9. Anonymous says:

    Thank you for such a sweet article :)..Awesome it is..

  10. Ramana says:

    It is the basic thing one one should know while starting with java.

  11. Anonymous says:

    Superb Article…………

  12. Ramesh says:

    simply super article

  13. Very nice. Thanks for this writeup.

  14. Anonymous says:

    very nice topic
    sir,i hope
    u help us ………………

  15. Anonymous says:

    Very clean, very simple. Thank you.

  16. Anonymous says:

    Good article very nice … keep posting

  17. Adriana says:

    It’s a real joy to read something as simple yet as constructive as this.Good job!!

  18. Martin says:

    Really nicely written and with all details too.
    In Eclipse I usually only write ‘syso’, ctrl+space and it comes up! It is possible to define new templates like this, I have a few useful ones for log4j that I always need copy into each new workspace :(
    :)

  19. Joe says:

    @Anders,

    I agree with you, learning multiple languages is good. What I meant is, 3 years is too short to learn around 10 languages. In a 3 year computer science program I prefer spending more time on fundamentals like data structures, algorithms, discrete maths, computer architecture, etc. – I have updated the article since it is misleading. Thanks.

  20. papun says:

    nice posts i love this blog

  21. Srikanth S says:

    Good one Joe. Illustration on habbit and convention is quiet. Alteast, new to me!!

  22. Srikanth S says:

    I meant the illustration on habbit and convention is quiet good.

  23. Anonymous says:

    superb..article

  24. Kb201 says:

    Nice article

  25. sandhya says:

    nice article ,good to refresh again

  26. Anonymous says:

    you simply have a way to make people understand

    Thanks

    Prem

  27. Anil Kumar says:

    It’s awesome. We have impressed alot. Thank you Mr. Joe for providing information about our Java SOP.

  28. Deepti says:

    Please keep posting … the article is awesome enjoyed reading….

  29. Suresh says:

    Great man…really fantastic job …keep writing more…

  30. Dennis says:

    A simpler prettier version for Fortran:

    PRINT *,’ HELLO WORLD’
    END

    Notes:
    1) although IBM’s 1957 documentation did write it a FORTRAN, Fortran is not an acronym)
    2) required indenting
    3) lack of name for the program (later versions provided a 7 character name)
    4)The frequent separation of the “carriage control” character,i.e. the initial 1X in the FORMAT statement is unnecessary.

    Unfortunately the simple PRINT statement from the original Fortran was deprecated.

  31. Madhav says:

    good article

  32. pavan_krishna says:

    What is HttpTunneling?

  33. pavan_krishna says:

    how can we ask new questions other than through comments

  34. BharathiKannan Mahalingam says:

    Sounds Good.

  35. GN says:

    @who are commenting about that mistakes here : ppl its very easy to finger point on some one but very difficult to accept our faults also its very difficult to make something like this site which helps hundreds and thousands

    I am very happy with the look … when i read this site its look makes me feel as m reading my own notes …simple and super

    hope to more and more blogs for javaScript and frameworks like Spring ,Hibernet etc.

  36. Anonymous says:

    good one man

  37. pavan_krishna says:

    Why we use MVC architecture

  38. Tamilanban says:

    Hi joe, i am also from chennai.it is the first time i see ur site.u r doing great…next time please brief About Thread Concept..

  39. ankur says:

    Hi Joe,

    I like the illustration for flow of SOP.
    Can you please tell me which tool you use to create succh good diagrams.

    • Joe says:

      @Ankur, no special tools, I just use windows 7 paint tool. For UML, I use starUML (its very old but I like it and does the job)

  40. Akai says:

    In a “c” language printf statement why we use f in printf

    • Anonymous says:

      @Akai
      In c the printf() function, f means “formatted”, you print the formatted argument of printf() function. When you use %d the output will be formatted in integer value, when you use %f the output will be be formatted in float value, %c use with character value.

  41. Dew says:

    Superb Joe!!!!

  42. Selman says:

    “Change out of System.out.println” is good trick

  43. Jai says:

    Awesome Mr.Joe i am new to java hope i can get good knowledge from your blog

  44. Boaz says:

    Great article — looking forward to many more posts from you!

  45. Anonymous says:

    nice one !!

  46. Savi says:

    good one Joe.. Keep going with the good work and i m loving the page layout what u have used..:)

  47. Anonymous says:

    thanx dude!

  48. aanchal says:

    Thanks dude!
    Very nice notes…. I feel I am reading my own notes simple and have full explaination.

  49. Anonymous says:

    Great Stuff on SOP.

    Thanks -Amal

  50. raja says:

    it’s a Excellent article for all
    Thank you sir,

  51. HariKrishna says:

    nice article

  52. Anonymous says:

    yes………..right

  53. sugandha says:

    very nice article sir…..very simplified bt powerful 1….thanks

  54. Anonymous says:

    Nice1 joe!! Real helpful for a begginer who has no interest in languages!! U have made things simple and easier to understand..

  55. Arijit says:

    Nice Article!!!!

  56. Jain says:

    Very Nice with little little words

  57. aishu says:

    great job!!!!!!!!!!!

  58. santhosh says:

    good post .. very informative .

  59. Sunil Agrawal says:

    Very Good Explanation Joe.. Great Work.

  60. Vinaya says:

    Hey Joe. .
    This is really helpful.
    Thank you :)

  61. Anonymous says:

    Its the coolest blog :):):)

  62. Anonymous says:

    Its the coolest blog :):):)

  63. Gootam says:

    Good work Joe.. keep it up.

  64. k.maheswari says:

    its nice please send me the concept of inlinefunctions invoking at compile time or runtime

  65. Anonymous says:

    simply excellent!! keep it up!!

  66. Gaurav Garg says:

    very nice blog….i bruh up my concept
    thankss :)

  67. alam says:

    you define each and everything in very simple words.i m sure who read it get understand. excellent work done by joe sir

  68. Fatima says:

    A very good Article on SOP. Thanks for sharing.

  69. Arundev P says:

    Sir i have a doubt.

    i defined a class

    class Sample{
    public static void main(String[] args) {
    ArrayList x = new ArrayList();
    ArrayList y = x;
    ArrayList z = x;
    y.add(“this is to test the Sample”);
    System.out.println(z.get(0);
    }
    }
    Sir my doubt is that – inside the syso if i put z.get(0).toString() then am getting type cast exception :(. Cn u please explain y it is happening?

    • Gopi says:

      import java.util.ArrayList;

      public class Example {
      public static void main(String[] args) {
      ArrayList x = new ArrayList();
      ArrayList y = x;
      ArrayList z = x;
      y.add(“String value”);
      System.out.println(z.get(0));
      }

      }

      It won’t throw any exception. If you want pls copy the above code & compile it.

  70. Arundev P says:

    Sir i have a doubt.

    i defined a class

    class Sample{
    public static void main(String[] args) {
    ArrayList x = new ArrayList();
    ArrayList y = x;
    ArrayList z = x;
    y.add(“this is to test the Sample”);
    System.out.println(z.get(0);
    }
    }
    //Note:-
    //y list of type String
    //z list is of type StringBuffer

    Sir my doubt is that – inside the syso if i put z.get(0).toString() then am getting type cast exception :(. Cn u please explain y it is happening?

    Arundev P on August 6th, 2012 12:41 pm

  71. Vivek Mainali says:

    Very nice Mr.JOE

  72. Sunil says:

    it is a very nice article

  73. Maheshwar Singh says:

    Its Really helpful………
    Thankyou very much

  74. Savan Gandhi says:

    THANK YOU SO MUCH…!

    IT IS SIMPLE AND TRUE…!

    GOD BLESS YOU…!

  75. Yesh says:

    How is it that a static variable like out has a dot operator to a method (println) in a different class (PrintStream) ?

    The syntax seems strange …

  76. Arun says:

    Good Article !!
    A correction to one of the sample programs given:
    BufferedReader reader = new BufferedReader(System.in);
    The constructor of BufferedReader requires an object of type Reader as argument
    so the correct statement would be:
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

  77. abhigyan says:

    Nice job dude. Keep posting such pieces of writing. You cleared many a concepts for me.
    Thanx a lot

  78. H says:

    Cooool!

  79. wahid jan says:

    fabilous

  80. Romanov says:

    AWESOME WORK …. Thanks a TON

  81. Irfan Shaikh says:

    It’s great, all things about SOP are here..
    Beginners can easily understand…

  82. Kedarr says:

    Awesome Work on Java Dude.

  83. [...] is also clearly given as ‘unreachable statement’. We have a return followed by first system.out.println and after that line whatever code is there it will be unreachable and so this [...]

  84. goutham says:

    Great explaination for very simple thing. Hats off to ur Indepth knowledge.

  85. sangita says:

    Really nice explanation.

  86. Madhu Penubolu says:

    its really worth reading…..

  87. jaja says:

    jaj everywhere

  88. Pravin Singh says:

    very nice and powerful thought

  89. Pawan says:

    My name is Pawan and Please solve my Problem:
    Problem is:
    I want to know how to make “chat web-application” in j2ee using struts or servlet or jsp
    please solve this problem if you can
    Thanks Sir
    Your blog is always good for us:
    please inform me at : pawanbmr64@gmail.com

  90. Manoj Diwakar says:

    Hi Joe,
    I am new baby in Java. I have spent 8+ years in C++ and decided to learn new technologies (like core Java, Struts and Hibernet).
    I found your site is wonderful and very good to get the fundamentals.
    I love your site.

    I want to say “Thanks” for your efforts.

  91. Anonymous says:

    it nice

  92. Anonymous says:

    it’s good to know

  93. pavan says:

    Hi joe can we put System.out.println(); in class when am trying it is giving an error what is hte reason?
    Ex:
    abstract class Figure

    System.out.println(“hiiiii”);//giving error

    public static void main(String args[])
    {
    }
    }

  94. Anonymous says:

    i was confused with this concept but now it’s clear for me. Thnx gr8 post

  95. Prashant says:

    No doubt your contents are really good ; but more than that look and feel of your website is simply awesome.

  96. Manjula says:

    Simply superb… really nice joe

  97. Anonymous says:

    This is very useful..Thanks

  98. sandy says:

    thanks a lot. a good note

  99. Abhishek says:

    is that any difference between
    String []args And String args[] ??

  100. Anonymous says:

    Nice Article .Good work .please keep it going on……………

  101. Its a nice blog, i prefer my students to consider this section if they are interested in getting deep into System.out.println;

    Thanks Joe

  102. Anonymous says:

    what is Startup u mentioned?

  103. Vaishali says:

    What exactly out is static member of System class or object of class?

  104. Himanshu says:

    good article…………..but one thing i need to say you wrote system is a final class hence can not be “instantiated”………….i ant you to re consider this statement…..

    final classes can be “instantiated”

    • Joe says:

      Sorry, my mistake. I think I have written it after eating till my neck! Thanks Himanshu for notifying, I have fixed it.

  105. Anonymous says:

    awsmee.!!

  106. Abhinav says:

    In the above article u have mentioned that out is a static variable of System class and is OF TYPE printstream.

    What do u mean by type of printstream?
    Can u pls explain?

    • Joe says:

      What I meant is, ‘out’ is a static variable declared in ‘System’ class. So what variable is ‘out’? Is String or int or what is it? It is nothing but a PrintStream. Just open the java.lang.System API doc and we can see that variable declared in that class.

  107. raj says:

    Hi Joe,

    can we make the
    System.out.println(“hello”);
    to
    Raaj.gupta.println(“hello”);

    The Raaj.gupta.println(“hello”) should be work like System.out.println(“hello”)

    In one interview, i get the question.
    and my ans was we can not do.
    So please let me what will be right right.

    • Anonymous says:

      Try this:
      class Raaj {
      public final static PrintStream gupta = System.out;
      }

      public class Test{
      public static void main(String[] args) {
      Raaj.gupta.println(“Hello World”);
      }
      }

    • Joe says:

      These are all simple silly :-( tricks and I don’t think they are worth to be asked in an interview. But still, I know how interviews happen in our environment.

      If you read through the article, I have written a code snippet similar to what you have asked.

  108. [...] not use System.out.println as a tool to [...]

  109. Anonymous says:

    tell me one thing, is there any static polymorphism ? like Overloading…

    i think overloading is nothing, its just type of static polymorphism… ???

    is it true…??
    if it is true, then prove it, that overloading is static polymorphism n overriding is dynamic polymorphism .

    thank you.

  110. Anonymous says:

    very nice Joe

  111. ajit says:

    Nice summary on logger v/s SOP. I like it.

  112. Krunal Shah says:

    nice article to read… good job… keep it up…

  113. Preeti says:

    Very nicely explained…. Thanks Joe…

  114. Preeti says:

    very nicely explained.. Thanks..

  115. Raju says:

    Explained very clearly…Good Job and thanks…

  116. yogesh prajapati says:

    useful article…

    but i want to know where out variable initialized.

  117. Shilpa says:

    I reached this blog when I googled for a particular topic. Now I am going through multiple topics in your blog :)
    Good and simple look,
    well-explained concepts of importance and interest,
    the feel of learning new stuff from a knowledgeable person..

    Thank you Joe. You blog is simply great. :)

  118. vreddykumar says:

    I am very happy , this site is very good for freshers to understand the concepts ..

  119. Gulmeher Shaikh says:

    Very good article.
    Thanks for help.

  120. Kannan says:

    nice explanation

  121. alpha says:

    good 1

  122. Joseph says:

    நல்ல கட்டுரை

  123. Sreekanth says:

    Nice Explanation sir

    Guys ,you can also refer below link

  124. Sreekanth says:

    Nice Explanation sir…

    Guys,, you can also refer below link

    http://www.programmers99.com/2014/01/how-we-are-able-to-write.html

  125. sakshi tayal says:

    joe i really like ur way to represent the concepts…:)

  126. […] expectation is the code should compile now. Since there is only one System.out.println statement and that is straight forward. But what we get is an error and that too out of the […]

  127. […] Usage of System depends on the type of project you work on. You may not be using it in your project but still it is […]

  128. Shivi says:

    Really a nice article to start up with java…
    I would like to spend more time with javapapers.
    Joe can you advice me some strategy regarding preparations to crack SCJP exam as well?
    my email is ibabpo@gmail.com

  129. Karthikeyan says:

    Joe, Its really an amazing article. Keep rocking !

  130. […] like forEach() and peek() can only be executed using a side-effect. It can be useful for simple System.out.println for debugging small Java programs. The code block at the start of this tutorial is an example for […]

  131. karthikeyan says:

    hi, i have error from this line. i am using eclipse

    BufferedReader reader = new BufferedReader(System.in);

Leave a Reply