2

Possible Duplicate:
java: “final” System.out, System.in and System.err?

Direct setting of System.out,

System.out = null; //gives error that it is final and that's understood

But have a look at this:

System.setOut(null); //allows to set out ??

But how is that possible if out is final?

Community
  • 1
  • 1
Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120
  • It's a legacy thing. The detailed and correct answer is here: http://stackoverflow.com/questions/5951464/java-final-system-out-system-in-and-system-err – Kevin A. Naudé Dec 04 '12 at 21:21

3 Answers3

2

Its done on very low level. On Java level you cannot assign even null to final variable. Source code from JDK 1.7:

/**
 * Reassigns the "standard" output stream.
 *
 * <p>First, if there is a security manager, its <code>checkPermission</code>
 * method is called with a <code>RuntimePermission("setIO")</code> permission
 *  to see if it's ok to reassign the "standard" output stream.
 *
 * ...
 */
public static void setOut(PrintStream out) {
    checkIO();
    setOut0(out); //native method
}
bellum
  • 3,642
  • 1
  • 17
  • 22
1

In the first instance the static variable System.out is final so you cannot set it.

In the second instance you are calling a static method that will set standard output to a different stream.

Mark
  • 28,783
  • 8
  • 63
  • 92
1

The simple answer is that things that are written using native C, and especially library classes, don't necessarily have to play by the same rules as you and I writing pure Java.

edit: Upon further investigation, it turns out even you and I can change final fields (provided the security managed doesn't object). See https://stackoverflow.com/a/3301720/367273

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • its weird how we can break the semantics so easily, and all these are trick questions that can boggle anyone. Thanks for the link. – Narendra Pathai Dec 05 '12 at 03:30