Tuesday, November 29, 2016

How does System.out.println works in Java

In this post,we will understand and learn How does System.out.println works in Java. Earlier, i have shared what is main() method in java and how it works?. Today, we will learn what is the use of System.out.println and how it works. Some times Interviewer asks you when you are interview room What is System.out.println explain it individually. So you must be in a position to explain him about each part in it.


The above line is used to display message to the command window. Now, we will understand from the above line one by one

System:

System is a predefined class in  java.lang package that provides access to the system.This class contains final modifier that means it can not be inherited by other classes.

Out:  
It is a static variable in System class. out is called a field in System class,when we call this field, a PrintStream class object will be created internally. So, we can call the print() method as shown below.

Example:  System.out.print("hi java");

Thus, the expression System.out refers to Object an type PrintStream. 

println():

It is a public method in PrintStream class to display the data values.



Let us understand this concept with example then you can understand easily:

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

{
System.out.println("Hello Java");
}
 

 The main aim of writing above program is simply display a string "Hello Java". In java, print() method is used to display something on the console. 

print("Hello Java");

But the above statement is not the correct way of calling a method in java. A method should be called by using Objectname.methodname(). So to call print()method,we should create an object to the class to which print() method belongs. Here print() method belongs to PrintStream class, so,we should call print() method by creating an object to PrintStream class like below:

PrintStream obj.print("Hello Java");

But it is not possible to create the object PrintStream class directly,an alternative is given to us. That is System.out.

System.out gives the PrintStream class object. This object,by default represents the standard output device that is monitor.So the string"Hello Java" sent to the monitor.

Note:  Every Java Statement in Program ends with semicolon(;)


I hope you enjoy this page and follow me for latest updates and share this post in social media like facebook,linkedin,twitter..



 




 


No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...