In Java, how does System.out refer to PrintStream class? - java

I'm a beginner learning Java with some knowledge of C++, and the System.out.println(); is confusing me right now. So System is the class, out is a variable that can call a method?? According to: http://journals.ecs.soton.ac.uk/java/tutorial/getStarted/application/objects.html
out is a class variable, and a variable is a storage location in the computer memory that has a type name and content. It's not an object like string that can use methods like .getLength(). The way the website explains it is that out refers to an instance of PrintStream class, but how?

It's not an object
This is where your reasoning is going wrong. System.out is (a reference to) an object.
The type of the reference is PrintStream, as documented in the Javadoc. This means that you can call PrintStream's methods on System.out, e.g.:
System.out.println();

out doesn't call a method : out is a variable holding an object (an instance of PrintStream) on which you can call a method.
For example :
System.out.println("hey!");
You could also do
void print(PrintStream ps, Object o) {
ps.println(o);
}
...
print(System.out, "hey!");

More strictly, it's a public static field that is a reference to an object of type PrintStream, so yes, you can call methods on it.
Java references are roughly analogous to C pointers (at least in the way they are used, obviously there are significant differences).

Out is a public static field of the class named System.
Because it's public, you can call methods on it.
Its type is PrintStream.
The best way to learn is to read the documentation:
http://docs.oracle.com/javase/6/docs/api/java/lang/System.html
Notice the part at the top where it describes in, out, and err.

System.out is a particular instance of PrintStream, whose output is linked to the equivalent of the C++ stdout

System is a final class which has a final variable out holding a object of PrintStream class on which we can call println() method.

Actually the out parameter in System.out.println(String args[]) is a static field in System class. Whenever a field is declared it should have certain datatype. In this class the out field is defined as static PrintStream out;.
It means the datatype of out is PrintStream class.In this way System.out will actually represents a object of PrintStream class. With this object we are calling println() method of PrintStream class.

Think of System class roughly like this :
package java.lang;
public final class System {
public final static PrintStream out;
}
here out is a static final variable of "type" Printstream.
Since it is a static variable, we can call it by "ClassName.variableName" without creating any object of System class, so we do System.out.
Now, out is a reference variable of "PrintStream" class. Till now, only this reference variable is created and it is not referring to any "object" of Printstream class.
But System class creates object of PrintStream when it is loaded in memory.
For this, see methods initializeSystemClass() and setOut0() in below link which is complete source code of System class. (Dont be overwhelmed by this enormous code, just be assured that there is "new PrintStream()" called inside System (here at line 1095)).
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/System.java
so, when we have an object of PrintStream class, our out reference variable can easily call a method on it, right? This is how we call System.out.println()

Related

Why doesn't System.out return a null object? [duplicate]

Firstly regrets if this is a very basic question and i promote that I'm still a code monkey.
I was asked in an interview to elucidate System.out.println();
I explained the following way
//this class belongs to java.lang package
class System{
public static PrintStream out;
}
//this class belongs to java.io package
class PrintStream{
public void println..
}
I've explained that System.out is valid since this is the way we access static variables in java, and out is an object of PrintStream and hence we can access its methods, In sum as
System.out.pritnln();
he asked me to simulate a similar kind of program,i traced and it did not work,since System.out is returning null
my question is where is out object instantiated in java ? Is it a predefined object if I'm not wrong. what should be the meticulous explanation for this.
Technically what should we call out? Is out a variable of type PrintStream type or should one say it as an object of type PrintStream ?
System.out is initialized to null when the class is instantiated. This is set by the nullPrintStream() method in System.java, which just returns null.
When the JVM has initialized, it calls the initializeSystemClass() method. This method calls the native method setOut0() which sets the out variable to the appropriate value.
This may seem weird but it is a necessary operation for the following reasons:
out cannot be set statically to the value because System needs to be one of the first loaded classes (before PrintStream).
out must be final so that its value cannot be directly overridden by a user.
Since out cannot be set statically, and is final, we must override the semantics of the language using a native method, setOut0().
I hope that helps your understanding.
System.out is a normal static attribute, it was set by the JVM through the initializeSystemClass() method during JVM initialization. You can even change it (although it's not recommended) by simply calling System.setOut(printOutStream);, where printOutStream is the stream you want to use as standard output.
Here's a nice article detailing how does System.out.println() work.
System.out is provided by the JVM. By the time your main method is called, System.out is open and ready for use.
See http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#out
In the Oracle Java runtime libraries, it is instantiated natively using the registerNatives() native method which is called (via a static initializer) on loading the System class. This is however an implementation detail.
You can also set System.out directly using System.setOut().
Out in System.out.pritln is a static field (object) of PrintWriter in System class and println is a method of PrintWriter.
Reference :
System : http://docs.oracle.com/javase/6/docs/api/java/lang/System.html
PrintWriter : http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html
There is no need to go for net and documentation even. We can simply say javap java.lang.System this gives you list of all static fields, method prototypes that belong to System class.
We can get details of any java class using javap, provided you know its package and classname
out is public static object of PrintStream defined in System class.
When System class get initialized, it calls its initializeSystemClass() method, here is the code:
FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
In this code setOut0() is a native function implemented in System.c:
JNIEXPORT void JNICALL
Java_java_lang_System_setOut0(JNIEnv *env, jclass cla, jobject stream)
{
jfieldID fid =
(*env)->GetStaticFieldID(env,cla,"out","Ljava/io/PrintStream;");
if (fid == 0)
return;
(*env)->SetStaticObjectField(env,cla,fid,stream);
}
This is a standard JNI code that sets System.out to the argument passed to it, this method calls the native method setOut0() which sets the out variable to the appropriate value.
System.out is final, it means it cannot be set to something else in initializeSystemClass() but using native code it is possible to modify a final variable.
System.out.println();
here println is an object of printstream class.We can't directly create object for printstream class. Out is an object of system class. out is called field in system class. while calling system.out it indirectly creates object for printstream class. hence we can call println() method using System.out.prontln().

what is the difference in java objects created with "new" and the ones that do not use "new"

What is the difference between creating an object with and without "new"?
example:
Thing someThing = new Thing();
vs.
Path filePath = Path.get("C:\\......)
In the first example I understand that when instantiating the object, that "new" is allocating memory for a the someThing object and that the memory location is referenced by someThing.
My text book says " You create a Path object" by using the second example. Is the difference just how the object is stored or memory is allocated? I am not sure why you would create an object this way.
In the second case you are using a static method which is internally creating the object or passing a reference to an existing object. This is a common pattern particularly when the APIs wish to hide an internal implementation (as is the case here).
There is no difference. The second example is a factory method.
You pass in a few parameters and that method will call new at some point on the actual instance class of the Path.
While it behaves like a constructor, there are also differences which should be pointed out: Static factory methods do not have to return the current type, but can also return a subtype, where in contrast a constructor creates an instance of the current class. (Hypothetical) Example:
public static Path create(String name) {
return new AbsolutePath(name); // subclass/implementation of Path
}
From an implementation point, this gives you a lot of flexibility for later extensions. You can for example implement some logic, which decides which concrete type to create within the method. You could cache instances and return them. You could return the same instance every time (Singleton). Etc.
Further aspect: You can actually give meaningful names to static factory methods, so code is easier to read:
public static Path createAbsolute(String name) { ... }
public static Path createRelative(String name) { ... }
With the first option you are sure you are creating a new object (more or less, java.lang.* classe are a bit special)
Let's take the second option:
Path filePath = Path.get("C:\\......)
Nothing assures you the instance you are storing in filePath is a Path one, it can be an instance of a subclass of Path. Something similar occurs with Calendar: Calendar is an abstract class, so
Calendar c=Calendar.getInstance();
The variable c is actually a GregorianCalendar.
Another difference:
class Singleton {
private Singleton s=null;
private Singleton(){};
public static Singleton getSingleton() {
if (s==null) {
s=new Singleton();
}
return s;
}
}
No matter how many times you call getSingleton, you will only create one object.
when you are using new keyword then an object of the particular class is created.
Here Thing someThing = new Thing();
something is an object of Thing class
Path filePath = Path.get("C:\......)
Path is a class having static method get() which accepts String arguments and it returns Path something like
public static Path get(String arg)
{
return path;
}
The memory is allocated by the method call to Path.get in the second instance. This allows the library to go through its own initialisation routines for a Path variable and which may perform additional checks. New just allocates memory. The memory may also be sorted and stored internally in some structure too, such that it doesn't constantly reload the same object via caching. I, personally, always call the factory methods rather than new up an object myself, however it could be considered to be a style thing, as pretty much everything that may be done with a factory method may also be achieved via a constructor.
In your examples, you are assuming that an object is created without a "new". That is an incorrect assumption. The object was created with "new" in the second example as well.
Just because you can't see the "new" doesn't mean it's not called in the function.

What is the type of System.out in Java?

I am just a newbie in Java. I was wondering the way System.out.println() is used. Out is a static field inside System class. The type of out is PrintStream. But when I saw the constructor of PrintStream class, it takes a parameter of type OutputStream and as far as I know we cannot create the object of an abstract class. In that case we must pass some subclass's object to the constructor of PrintStream. What is that class? Same is the System.in. It is also InputStream's reference but what is the type of object it points to as the InputStream is abstract?
PrintStream wraps BufferedOutputStream, which wraps FileOutputStream, which is writing into the console, which has its own FileDescriptor.
A simple way to view the structure of a class is to examine it in a debugger.
As you can see #Andremonify's description is basically what you have.
FileDescriptor
0 is System.in
1 is System.out
2 is System.err
3+ is used for other files
Yes out is of PrintStream type. And constructor of PrintStream takes OutputStream type. OutputStream is abstract class. But any superclass refrence can refer subclass object without casting, so PrintStream's constructor has OutputStream refrence, but this refrence must be referring one of OutputStream's subclass like FileOutputStream
There are a couple more things to say about the implementation of System.out.
The actual implementation class of System.out is not specified. The javadocs don't say what it is. We observe (in various way) that Oracle Java and OpenJDK Java implement the "stack" in a particular way (see other answers), but this could change in the future.
The System::setOut(PrintStream) method can be used to modify what System.out is bound to. If that happens, any assumptions about implementation classes may be incorrect.
It turns out that you can do this:
System.setOut(null);
so System.out could be null. However, with current implementations, System.out won't be null unless you set it to null.
All that is actually guaranteed by the specifications is that the value of System.out will have a type that is assignment compatible with PrintStream.

Constructor is static or non static

As per standard book constructor is a special type of function which is used to initialize objects.As constructor is defined as a function and inside class function can have only two type either static or non static.My doubt is what constructor is ?
1.)As constructor is called without object so it must be static
Test test =new Test();//Test() is being called without object
so must be static
My doubt is if constructor is static method then how can we frequently used this inside
constructor
Test(){
System.out.println(this);
}
Does the output Test#12aw212 mean constructors are non-static?
Your second example hits the spot. this reference is available in the constructor, which means constructor is executed against some object - the one that is currently being created.
In principle when you create a new object (by using new operator), JVM will allocate some memory for it and then call a constructor on that newly created object. Also JVM makes sure that no other method is called before the constructor (that's what makes it special).
Actually, on machine level, constructor is a function with one special, implicit this parameter. This special parameter (passed by the runtime) makes the difference between object and static methods. In other words:
foo.bar(42);
is translated to:
bar(foo, 42);
where first parameter is named this. On the other hand static methods are called as-is:
Foo.bar(42);
translates to:
bar(42);
Foo here is just a namespace existing barely in the source code.
Constructors are non-static. Every method first parameter is implicit this (except static) and constructor is one of that.
Constructors are NOT static functions. When you do Test test =new Test(); a new Test object is created and then the constructor is called on that object (I mean this points to the newly created object).
The new keyword here is the trick. You're correct in noting that in general, if you're calling it without an object, a method is static. However in this special case (i.e., preceded by the new keyword) the compiler knows to call the constructor.
The new operator returns a reference to the object it created.
new Test(); // creates an instance.
The System.out.println(this); is called after the new operator has instantiated the object
Not static. Read about constructors http://www.javaworld.com/jw-10-2000/jw-1013-constructors.html.
Neither.
Methods can be divided into 2 types: static/non-static methods, aka class/instance methods.
But constructors are not methods.
When we talk about static class then it comes to our mind that methods are called with class name,But in case of constructor ,Constructor is initialized when object is created So this proves to be non-static.
Constructors are neither static (as called using class name) or non-static as executed while creating an object.
Static:
Temp t= new Temp();
The new operator creates memory in the heap area and passes it to the constructor as Temp(this) implicitly. It then initializes a non-static instance variable defined in a class called this to the local parameter variable this.
Below example is just for understanding the concept, if someone tries to compile it, it will give the compile-time error.
class Temp{
int a;
Temp this; //inserted by compiler.
Temp(Temp this){ //passed by compiler
this.this=this; // initialise this instance variable here.
this.a=10;//when we write only a=10; and all the non-static member access by this implicitly.
return this; // so that we can't return any value from constructor.
}
}
Constructor is static because:
It is helping to create object.
It is called without object.
Constructor is used to initialize the object and has the behavior of non-static methods,as non-static methods belong to objects so as constructor also and its invoked by the JVM to initialize the objects with the reference of object,created by new operator

out in System.out.println()

Firstly regrets if this is a very basic question and i promote that I'm still a code monkey.
I was asked in an interview to elucidate System.out.println();
I explained the following way
//this class belongs to java.lang package
class System{
public static PrintStream out;
}
//this class belongs to java.io package
class PrintStream{
public void println..
}
I've explained that System.out is valid since this is the way we access static variables in java, and out is an object of PrintStream and hence we can access its methods, In sum as
System.out.pritnln();
he asked me to simulate a similar kind of program,i traced and it did not work,since System.out is returning null
my question is where is out object instantiated in java ? Is it a predefined object if I'm not wrong. what should be the meticulous explanation for this.
Technically what should we call out? Is out a variable of type PrintStream type or should one say it as an object of type PrintStream ?
System.out is initialized to null when the class is instantiated. This is set by the nullPrintStream() method in System.java, which just returns null.
When the JVM has initialized, it calls the initializeSystemClass() method. This method calls the native method setOut0() which sets the out variable to the appropriate value.
This may seem weird but it is a necessary operation for the following reasons:
out cannot be set statically to the value because System needs to be one of the first loaded classes (before PrintStream).
out must be final so that its value cannot be directly overridden by a user.
Since out cannot be set statically, and is final, we must override the semantics of the language using a native method, setOut0().
I hope that helps your understanding.
System.out is a normal static attribute, it was set by the JVM through the initializeSystemClass() method during JVM initialization. You can even change it (although it's not recommended) by simply calling System.setOut(printOutStream);, where printOutStream is the stream you want to use as standard output.
Here's a nice article detailing how does System.out.println() work.
System.out is provided by the JVM. By the time your main method is called, System.out is open and ready for use.
See http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/System.html#out
In the Oracle Java runtime libraries, it is instantiated natively using the registerNatives() native method which is called (via a static initializer) on loading the System class. This is however an implementation detail.
You can also set System.out directly using System.setOut().
Out in System.out.pritln is a static field (object) of PrintWriter in System class and println is a method of PrintWriter.
Reference :
System : http://docs.oracle.com/javase/6/docs/api/java/lang/System.html
PrintWriter : http://docs.oracle.com/javase/6/docs/api/java/io/PrintWriter.html
There is no need to go for net and documentation even. We can simply say javap java.lang.System this gives you list of all static fields, method prototypes that belong to System class.
We can get details of any java class using javap, provided you know its package and classname
out is public static object of PrintStream defined in System class.
When System class get initialized, it calls its initializeSystemClass() method, here is the code:
FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
In this code setOut0() is a native function implemented in System.c:
JNIEXPORT void JNICALL
Java_java_lang_System_setOut0(JNIEnv *env, jclass cla, jobject stream)
{
jfieldID fid =
(*env)->GetStaticFieldID(env,cla,"out","Ljava/io/PrintStream;");
if (fid == 0)
return;
(*env)->SetStaticObjectField(env,cla,fid,stream);
}
This is a standard JNI code that sets System.out to the argument passed to it, this method calls the native method setOut0() which sets the out variable to the appropriate value.
System.out is final, it means it cannot be set to something else in initializeSystemClass() but using native code it is possible to modify a final variable.
System.out.println();
here println is an object of printstream class.We can't directly create object for printstream class. Out is an object of system class. out is called field in system class. while calling system.out it indirectly creates object for printstream class. hence we can call println() method using System.out.prontln().

Categories