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?
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.
Yes its possible to print message without using System.out.println (""); System.out.write ("www.instanceofjava.com n".getBytes ()); System.out.format ("%s", "www.instanceofjava.com n") PrintStream myout = new PrintStream (new FileOutputStream (FileDescriptor.out));
You are probably studying JavaScript (not Java) on codecademy, where console.log would publish the logs content (visible on browser’s console in development mode). In Java, System.out.println would publish the content on the standard output stream, in a new line on every occurrence. The two are totally unrelated except they both write to stdout.
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.
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.
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:
printf()
Runtime.getRuntime().exec()
and call echo
program
and the list follows. +1 to @eis
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With