Reputation: 761
I think I'm having a little doubt with the concept of println()
method.
I tried the following code:
Object one = 1;
System.out.println(one);
one = "String";
System.out.println(one);
one = null;
System.out.println(one.toString()); // To explicitly throw an Exception
The expected output is and indeed I get this sometimes:
1
String
Exception in thread "main" java.lang.NullPointerException
at MainClass.main(MainClass.java:18) <5 internal calls>
However running multiple times, we can see see the following outputs, as well:
1
Exception in thread "main" java.lang.NullPointerException
at MainClass.main(MainClass.java:18) <5 internal calls>
String
or
Exception in thread "main" java.lang.NullPointerException
at MainClass.main(MainClass.java:18) <5 internal calls>
1
String
Then, I thought of performing similar operation in Python. Below is the snippet:
var = 'Hello';
print var;
var = 6;
print var;
del var;
print var;
And yes, the similar behavior. The traceback message output preference cannot be determined. Sometimes, its printed at the top, sometimes in the middle or sometimes at the bottom.
I think it must be something related to synchronized
buffer output. Not sure, it could be.
Can anyone help me out in getting this concept?
Upvotes: 0
Views: 241
Reputation: 533880
This is due to the fact you have two output streams System.out
and System.err
and they are not co-ordinated or always in order.
You can do
Object one = 1;
System.err.println(one);
Object one = "String";
System.err.println(one);
one = null;
System.out.println(one.toString());
or
Object one = 1;
System.out.println(one);
Object one = "String";
System.out.println(one);
one = null;
try {
System.out.println(one.toString());
} catch (Exception e) {
e.printStackTrace(System.out);
}
What you should do is use a logger. The logger will be configured to write everything to either System.out or System.err so you will get a predictable out put.
I think it must be something related to synchronized buffer output.
Both System.out
and System.err
are synchronized. They don't use the same lock as they are not the same object, though this wouldn't matter because the two streams they write to can be read in any order.
Upvotes: 1