What happens to “System.out.println()” in executab

2019-01-20 08:44发布

问题:

Suppose I've created an executable jar from a code where I have used

System.out.println()

When we run the executable jar, there is no console. So, what happens to this line? How does java handle this situation?

EDIT 01:

NOTE: The situation is when I don't use a console to run the jar nor associate any console with it anyhow.

EDIT 02: Making things clearer:

I know that nothing will be printed anywhere as there is no console..! I want to know how java handle this line in this case? Is this line omitted when generating the bytecode for a executable jar? Or is this line just overlooked when there is no console? Or anything...

回答1:

There's nothing special about running code in an executable jar file. If you run it from a console, e.g. with java -jar foo.jar the output will still go to the console.

If you run the code in some way that doesn't attach a console - such as javaw on Windows, which is the default program associated with executable jar files - then the output won't go anywhere. It won't cause any errors - the text will just be lost.

Note that in that case, if you use System.console() instead, that will return null. So:

System.out.printf("Foo%n"); // No problem. Goes nowhere.
System.console().printf("Foo%n"); // Would throw a NullPointerException.


回答2:

The output is omitted, as long as you do not run your application from a console window (java -jar executable.jar). Furthermore, you can configure your Java installation such, that a console windows is launched as soon as you start a Java application. Output will be written to the JVM's console window then. You can find an article How do I enable and view the Java Console? on the official Java web site.



回答3:

I you open it from the console (java -jar YourJar.jar) the text gets printed in your console window.

If you open it in the explorer (or similar), you won't see the text

To clarify your second Edit: The bytecode is not omitted, because the compiler cannot know in what context the jar will be executed. The jar can always be called from console, in that case the println has to stay there.

In fact, many jar Files would be completely useless otherwise. There are plenty of Java programs that interact with the user by console in- and output. It is not neccessary for a java-Program to have a GUI (or to run completely in the background).