abhinaykumar
hai Sookie can u xplain the statements u used in the static method........
Sure !
System.setOut(new PrintStream(new OutputStream(){
public void write(int b) {
}
}));
In the above statement, I am making
System.out to behave in such a manner that it prints/writes nothing as output in console. It is simply overriding the
write() method of
OutputStream abstract class. The concept that is used above is called as "
Anonymous inner classes". Alternatively you could do is , create a class that extends "
OutputStream" class and then overrides its "
write" method -just like I did in above statement and then instantiate that implementing class and pass as an argument to "
PrintStream" class .
Well, this was syntax related. Now what exactly that statement does is -
If you look at
System.out.println then
System.out is a
PrintStream type of class which calls
println() method of PrintStream to write anything on console and
println() calls "
write" method internally . If you look at the API carefully then you will find that
write() method is being overriden from
FilterOutputStream class which ultimately extends
OutputStream class. *sighs* Hope you understood the concept [As per me it was not at all a problem for JAVA BEGINNER until the beginner knows the ready made answer. 😀 ]
Now coming to the next line
Print_GreatJavaProgrammer.main(null);
Now this triggers the
main() method and tries to print "Java" from the
main() method but because we have already set the
write() method as below
public void write(int b) {
}
So, it will not print "Java" in the console.
Now coming to next line
System.setOut(printStreamOriginal); //where PrintStream printStreamOriginal=System.out;
Now using above statement , I am again setting the
System.out value to the one default provided by Java folks.
System.setOut(System.out). It will revert back the
System.out to original PrintStream
write() method. No overriding, nothing. Only default values.
Now coming to last line
System.out.println("Geat Java Programmer");
The above statement of static block works as normal Java program because we have already re-set the
System.out to default
print() method.
Finally
System.exit(0) to exit from this program and thread hopefully *just kidding* 😀
Hope you got the concept and if still any questions, feel free to ask. 😀 I think solution by ms_cs is quite easy to understand but will work only for few cases.