System.out.println
from: https://javapapers.com/core-java/system-out-println/
System.out.println
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.
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.
- System - is a final class in java.lang package. 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 - is a method of PrintStream class. 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.
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.
public final class System { public final static PrintStream out; public final static PrintStream err; public final static InputStream in; } public class PrintStream extends FilterOutputStream { public void println() { //TODO } }
Change out of System.out.println
'out' 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 multiple 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?
- Flexibility: a logger like log4j provides different levels for logging. We can separate the log messages accordingly. For example, X messages should be printed only on PRODUCTION, Y messages should be printed on ERROR, etc.
- Reconfigurability: in just one parameter change we can switch off all the logging statements.
- Maintainability: imagine if we have hundreds of System.out.println 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 output 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. 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"); } }
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?"); } } }
低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。
持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。
转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。
- 上一篇
浅析电子商务平台的开发需要注意哪些问题?
随着互联网的迅猛发展,中国的电子商务市场经济超越了部分欧美国家。中国企业纷纷开始投入电商行业,电子商务平台开发成为首要考虑问题。接下来,飞进科技小编将从两大方面介绍如何搭建一个电子商务平台。 一般的电商平台开发技术有哪些?对于开发电商平台的技术有PHP、Java、JSP、ASP.NET、等语言,说句老实话,JSP、ASO.NET、属于比较老的技术语言了,慢慢地被PHP、Java开发技术取代。 PHP:是一种通用开源脚本语言,语法吸收了C语言、Java的特点,利于学习,使用广泛,主要适用于Web开发领域。将程序嵌入到HTML文档中去执行,执行效率比完全生成HTML标记的CGI要高许多;还可以执行编译后代码,编译可以达到加密和优化代码运行,使代码运行更快。 Java:是一种可以撰写跨平台应用程序的面向对象的程序设计语言。Java 技术具有卓越的通用性、高效性、平台移植性和安全性,广泛应用于PC、数据中心、游戏控制台、科学超级计算机、移动电话和互联网,电子商务大型平台与网站是电商平台使用的最好的开发语言。 其实选择什么样语言开发电子商务平台也是很重要的,客户可以谨慎考虑,或与身边懂得平台开发...
- 下一篇
Matplotlib 入门
最近一直在学习有关机器学习的内容,发现有关可视化的内容无法绕过,在网上搜索了很久,看了一些中英文的资料和书,这里主要是记录下来,主要供自己进一步学习之用。 本文适合零基础,但你需要对Python, Numpy, Pandas 有基本的了解。 首先完成以下的中文翻译资料的学习,原作者的github链接也一并奉上,你可以 clone 下来。学习这个课程的过程中,你需要了解的基本API函数: 完成了这个学习, 使用面向对象界面画图的一般步骤就是 建立一个 Figure 对象 在这个 Figure 里建立一个或n个 Axes 对象 这些 Axes 里分别画图、装饰 我们画完图以后一般要加上标题、图例这些元素。这些功能散布在 Matplotlib API 的各处 加标题可以使用 Axes 对象的 set_title 方法。坐标轴的标签可以使用 Axes 对象的 set_xlabel 和 set_ylabel 方法。图例可以使用 Axes 对象的 legend 方法创建。这 个函数会使用 Line2D 对象的 label 属性。注意 上一节最后的那一段代码,Ax.plot() 这一行我们并没有使用...
相关文章
文章评论
共有0条评论来说两句吧...
文章二维码
点击排行
推荐阅读
最新文章
- Mario游戏-低调大师作品
- CentOS关闭SELinux安全模块
- CentOS7,CentOS8安装Elasticsearch6.8.6
- CentOS8安装MyCat,轻松搞定数据库的读写分离、垂直分库、水平分库
- Docker安装Oracle12C,快速搭建Oracle学习环境
- Red5直播服务器,属于Java语言的直播服务器
- CentOS8编译安装MySQL8.0.19
- SpringBoot2整合MyBatis,连接MySql数据库做增删改查操作
- Springboot2将连接池hikari替换为druid,体验最强大的数据库连接池
- CentOS6,CentOS7官方镜像安装Oracle11G