3

Consider the below Java code,

import java.io.File;
import java.io.PrintStream;

public class Test {

    public final static PrintStream out = null;

    public static void main(String[] args) throws Exception {
        Test.out = new PrintStream(new File("/tmp/temp.txt"));
    }

}

It leads to below compilation error.

Test.java:9: error: cannot assign a value to final variable out
        Test.out = new PrintStream(new File("/tmp/temp.txt"));
            ^
1 error

The in-built java.lang.System class also has a similar declaration as shown below:

public final static PrintStream out = null;

Could somebody let me know how does this System.out get initialized?

JSN
  • 2,035
  • 13
  • 27
  • @SomeJavaGuy - So, I can use reflection to initialize my `Test.out`? – JSN Jul 27 '17 at 07:50
  • 1
    [see here](https://stackoverflow.com/questions/17131525/in-the-system-java-source-the-standard-input-output-and-error-streams-are-decl) there are proper setter and getter for it implemented in native code. [here´s an example question redirecting the output to a file](https://stackoverflow.com/questions/2851234/system-out-to-a-file-in-java) so you know how to apply it. – SomeJavaGuy Jul 27 '17 at 07:53
  • 1
    https://docs.oracle.com/javase/7/docs/api/java/lang/System.html , here it says it ain't final – Arun Sudhakaran Jul 27 '17 at 07:59
  • 2
    It gets even better: https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#setOut-java.io.PrintStream- – shmosel Jul 27 '17 at 09:08

0 Answers0