Saturday, 12 December 2015

How does System.out.print() work in Java

Java Tutorial
How does System.out.print() work in Java?
To understand System.out.print() we need to understand the methods in Java. In Java there are two type of methods:
1.       static method
2.       Instance method (or non-static method)
Static methods can be called by class name. for example:
class staticMethodClass
{
        //User defined static method
        public static void staticMethod()
{
        System.out.println(“Inside static method”);
}
//main method. Its n entry point for java class. You can read more about main method here.
public static void main(String args[])
{
        //calling static method using class name classname.methodname();
        staticMethodClass. staticMethod();
}
}


o/p Inside static method

To call a non-static method we need to create an object first and then we can invoke the non-static method inside static method. We will discuss the scope of static and non-static methods later.
For ex:
class nonStaticMethodClass
{
        //User defined non-static method
        public void nonStaticMethod()
{
        System.out.println(“Inside non-static method”);
}
//main method. Its n entry point for java class. You can read more about main method here.
public static void main(String args[])
{
        //object creation
        nonStaticMethodClass object1=new nonStaticMethodClass();
        //calling non static method through object
        object1. nonStaticMethod ();
}
}


o/p Inside non-static method

Now I am coming to the discussion of how System.out.print() works in java.
Here print() is a method and it comes under PrintStream. Now question will arise that if print is a method of PrintStream class then why can’t we create an object of PrintStream and call print method just like below:

PrintStream object=new PrintStream();
Object.print();
  
Ans is we can’t create a direct object of PrintStream class. An alternative is given to us i.e System.out
Here System is class name and out is a static variable in System class. When we call out, a PrintStream  object will be created and through which we can call print() as System.out.println()

Below code snippet will explain you in better way how out is being declared in System class and how print() in PrintStream class
//the System class belongs to java.lang package
class System {
  public static final PrintStream out;
  //...
}

//the Prinstream class belongs to java.io package
class PrintStream{
public void println();
//...
}


No comments:

Post a Comment