KDjava
KDjava

Reputation: 2455

What to do without System.out, to print on console?

I have been stuck with a problem that was asked recently at an interview. The problem was stated as:

Suppose you don't have access to System class in Jdk API. You cannot use ECHO also. You are in JRE 5 environment. How will you print anything on the console?

The question really started with -- Why has Java given us the PrintStream object System.out? And why is it final? Isn't there any other way to print anything on console?

Upvotes: 7

Views: 15566

Answers (6)

Vinayakumar K
Vinayakumar K

Reputation: 3

I found out a way today to achieve the question. I am using org.apache.log4j for this answer. There are many other ways as said by many here. Thanks.

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

public class HelloByLogger {

    private final static Logger logger = Logger.getLogger(HelloByLogger.class);

    public static void main(String[] args) {

        BasicConfigurator.configure();

        logger.info("From Logger... Ola!");

    }
}

Upvotes: 0

Stephen C
Stephen C

Reputation: 718906

The interview question as stated is pretty perverse (i.e. artificial), and solving it involves stepping outside of pure Java. This is certainly not something that you would consider doing under normal circumstances.

Other answers have given you some semi-solutions ... if you really, really have to do this. (I say semi-solutions because they mostly don't deal with the case where the application's stdout / stderr streams have been redirected to somewhere other than the console. And that is the only "real" aspect of this problem ...)

If you can use the System class (on JDK 6) ... the clean way to print to the console (e.g. if System.out has been redirected) is to use System.console() method to get a Console object, and use that to get a Writer.

Note however that if the JVM has no associated console, console() will return null.


The question really started with -- Why has Java given us the PrintStream object System.out ?? And why is it final?? Isn't there any other way to print anything on console.??

The answers are:

  1. For convenience.
  2. So that random code doesn't accidentally clobber it. (Or deliberately if you need to worry about untrusted code running in your JVM.) But trusted code actually can change System.out by calling System.setOut(...). This does some behind the scenes magic to safely change the state of the final variable. (I believe that the JIT compiler is aware of this, and treats those 3 final variables differently.)
  3. Yes. See above, and (yuck!) the other Answers.

Upvotes: 2

Unni Kris
Unni Kris

Reputation: 3095

You can use the JDK's logger (java.util.logging.Logger).

This is how you create a logger in your java class.

import java.util.logging.Logger;

private final static Logger LOGGER = Logger.getLogger(MyClass.class .getName()); 

Also You could use log4j for the same purpose.

Upvotes: 2

Aniket Inge
Aniket Inge

Reputation: 25705

PrintStream is final because it does everything the windows console /can/ do. Also its the same with "Console" being a const class in C#. The classes encapsulate everything the console can do, and it does in one specific way only. You can't "make it better" because at one point, it is upto the OS to handle it.

There are plenty of ways to output something on screen:

  1. Write your own OutputStream the way @eis did it
  2. Use JNI and invoke a method in a native DLL/SO that invokes a native function like printf()
  3. Use Runtime.getRuntime().exec() and call echo program and the list follows.

+1 to @eis

Upvotes: 4

eis
eis

Reputation: 53482

You could bypass the System object if you want to. System.out does a lot of extra stuff (handling unicode, for instance), so if you really want just the raw output and performance, you actually probably even should bypass it.

import java.io.*;

public class PrintOutTest {
  public static void main(String args[]) throws IOException {
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new
      FileOutputStream(FileDescriptor.out), "ASCII"), 512);
    out.write("test string");
    out.write('\n');
    out.flush();
  }
}

This has been elaborated a bit further in here.

Upvotes: 16

bsiamionau
bsiamionau

Reputation: 8229

As documantation says,

The System class contains several useful class fields and methods. It cannot be instantiated.

So, as you can see, System class is kind of container for different useful functions. All this fields and methods are static, so it's not any reason to extend it.
Java gives us static PrintStream out because it's default way to communicate with program - using console.
If you're not agree with me, please, tell me.

Upvotes: 1

Related Questions