System.out.println

Last modified on June 30th, 2015 by Joe.

This Java tutorial is to explain what System.out.println is and how it works. It is love at first type. How many times have we used System.out.println till now? It is one of the most number of times compiled statement in the history of java. We shortly call it SOP.

Along with Java’s System.out.println(), at the end of this tutorial I have given a list of popular languages and their equivalent of it.

System-out-println-block-diagram

What is System.out.println

System.out.println is a Java statement that prints the argument passed, into the System.out which is generally stdout.

Structure of System.out.println

Following is the skeletal structure of System.out.println in the JDK source. Through this code snippet the essential parts are highlighted and its given for better understanding.

System-out-println-class-diagram

public final class System {
    static PrintStream out;
    static PrintStream err;
    static InputStream in;
    ...
}

public class PrintStream extends FilterOutputStream {
    //out object is inherited from FilterOutputStream class
    public void println() {
    ...
}

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 printed 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) {}
	}
}

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, we should be aware that a logging component should be used and System.out.println should be avoided. Why?

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. 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.

System.out.println and Performance

There is a general notion that System.out.println are bad for 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 System.out.println 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 System.out.println()

Sometimes we feel System.out.println is a long statement to print. 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 difference 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?");
}
}
}

System.out.println Equivalent 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').

System.out.println("Bye");

Comments on "System.out.println"

  1. Nelson says:

    Excellent Java tutorial to read. Enjoyed it!

    With a simple title, you have packed much stuff inside and got complete detail about System.out.println

    Thanks

  2. sudheer says:

    Great Post on SOP. Its very useful. The list of System.out.println() equivalent in other languages is cool

  3. Anders says:

    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. It’s good to know many programming languages.

  4. 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…

  5. Ramana says:

    System.out.println() is step 1 while starting with java and you nailed it.

  6. Ramesh says:

    simply super article, I didn’t knew that out belonged to out is an object of type PrintStream till now. javapapers is the best Java tutorials collection in the web.

  7. Adriana says:

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

  8. 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 :(
    :)

  9. Joe says:

    @Anders,

    I agree with you, learning multiple languages is good and the other point on stderr.

  10. papun says:

    “out” is a static member and thats how we access it from System class. Thanks for this simple explanation. All your Java tutorials are nice. i love this blog

  11. sandhya says:

    nice article on Java fundamentals. Never knew System.out.println has so much to it and good to refresh basics again

  12. Collins says:

    you simply have a way to make people understand. Is there a way to download all these Java tutorials alone?

  13. Anil Kumar says:

    It’s awesome. I am impressed a lot. Thank you Joe for providing such good information about Java SOP. I am using System.out.println daily in my Java programming but never cared about it till now. thanks for making me learn about it in detail.

  14. Deepti says:

    Oh man, only you can write a such tutorial on so obvious topic. There is so much to System.out.println, Thanks. Please keep posting such tutorials… enjoyed reading….

  15. Corey says:

    Great man…really fantastic job …keep writing more and more such Java tutorials. The block diagram for System.out.println is nice. The style looks similar to the ones done in Khan Academy. Cool!

  16. 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.

  17. GN says:

    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 ,Hibernate etc.

  18. Tamilanban says:

    Hi joe, i am also from chennai. it is the first time i am seeing your Java tutorials. You are doing great. next time please brief About Thread Concept in Java

  19. ankur says:

    Hi Joe,

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

  20. Joe says:

    @Ankur, I use PhotoShop for general drawings. For UML, I use WhiteStarUML (a fork of StarUML).

  21. Akai says:

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

  22. Dew says:

    Superb Joe! Excellent explanation for System.out.println, thanks.

  23. Selman says:

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

  24. Jai says:

    Awesome Joe, I have now completely understood what is under System.out.println. i am new to java your way of explaining is easy to understand for me. Please write more tutorials on Java basics.

  25. Boaz says:

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

  26. Savi says:

    good one Joe.. Now I know how System.out.println works! Keep going with the good work and i m loving the page layout what u have used..:)

  27. Alice says:

    Thanks dude!
    Very nice notes…. You blog feels like reading out of a notebook.

  28. Linda says:

    Very nice tutorial. Simple and easy to understand. Thanks.

  29. Jain says:

    Very Nice with little little words. Excellent tutorial for beginners. couple of weeks before I was asked in a Java interview as “How System.out.println works”. I should have read this tutorial before attending that interview. Thanks Joe for all your tutorials.

  30. aishu says:

    great job! System.out.println can’t be explained in a better way!

  31. santhosh says:

    good post .. All your Java tutorials are very informative .

  32. Scott says:

    Good work Joe.. keep it up.

  33. k.maheswari says:

    its nice. Similar to System.out.println, can you please write about inline functions in Java and how they are invoked.

  34. 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

  35. Fatima says:

    A very good Article on SOP. Now I understood what “out” is in System.out.println Thanks for sharing.

  36. 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?

  37. Campbell says:

    What a wonderful explanation for System.out.println() Its Really helpful………
    Thankyou very much

  38. 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 …

  39. Arun says:

    Good tutorial!!

    BufferedReader reader = new BufferedReader(System.in);
    The constructor of BufferedReader requires an object of type Reader as argument
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

  40. abhigyan says:

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

  41. Irfan Shaikh says:

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

  42. Gonzalez says:

    Awesome Work on Java Dude.

  43. goutham says:

    Great explaination for System.out.println. Hats off to your in-depth tutorials.

  44. sangita says:

    Really nice explanation.

  45. Madhu Penubolu says:

    its really worth reading….. nowhere we can see such simple and in depth tutorial

  46. Pravin Singh says:

    very nice and powerful thought

  47. 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 Hibernate).
    I found your Java Tutorials and it is wonderful. It is very good to get the fundamentals.

    I want to say “Thanks” for your efforts.

  48. Patrick says:

    Impressive man! You have got a nice blog.
    I am new to programming and you Java fundamentals tutorials are good read. Thanks.

  49. 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[])
    {
    }
    }

  50. Sarah says:

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

  51. Manjula says:

    Simply superb… really nice joe

  52. Lopez 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.

  53. Abhishek says:

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

  54. Charitra Choudhary says:

    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

  55. Vaishali says:

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

  56. Himanshu says:

    its static member of class System

    as you can see its called as System.out

  57. 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?

  58. 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.

  59. Richard 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”);
    }
    }

  60. Roberts says:

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

  61. Krunal Shah says:

    You must have to use SOP inside method.

  62. Preeti says:

    SOP is very nicely explained…. Thanks Joe…

  63. 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.

  64. 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.

  65. 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.

  66. Marty says:

    Explained the System.out.println very clearly…Good Job and thanks…

  67. yogesh prajapati says:

    useful Java tutorial, thanks.

    I want to know where out variable initialized in the System.out.println context

  68. 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. :)

  69. vreddykumar says:

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

  70. 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?

  71. Karthikeyan says:

    Joe, Its really an amazing article. System.out.println is a basic thing in Java. But reading this gave me more knowledge about it. Keep rocking !

  72. Turner says:

    System.out.println is the most used statement in Java when learning it. Nice you explained it in detail.

Comments are closed for "System.out.println".