Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

what is difference between "System.out.printf" and "console.printf"?

can you explain it in a very easy way?

2 Answers

Yanuar Prakoso
Yanuar Prakoso
15,196 Points

Hi there...

the easiest answer is Console is a wrapper of System.out. Well actually Console is a wrapper of both System.in and System.out which handle the input and output of data in Java. Meaning rather than using the long way of typing System.out.printf or System.in.readLine you can just use console.printf and console.readLine.

It also useful to reduce the risk of error typing for instance System.out.readLine instead System.in.readLine.

However, some console or IDE for Java programming have issues with Console that they failed to understand the functions. But for the treehouse workspace it is okay. The main purpose here I guess Craig just want to show you how Java handles input and output within its' environment without worrying about syntax errors.

As your journey continue in Java course you will learn more about System.out and System.in, please do not worry too much about it. Right now just play along and practice on the code first.

That is all for me. Any additional inputs are welcome. I hope this can help a little.

Ivan Penchev
Ivan Penchev
13,833 Points

Now what is the difference between

System.console().writer().println("hello from console");

and

System.out.println("hello system out");

If you run your application from command line I think there is no difference. But if console is unavailable System.console() returns null while System.out still exists. This may happen if you invoke your application and perform redirect of STDOUT to file.

Here is an example -

import java.io.Console; 
public class TestConsole 
{ public static void main(String[] args) 
{ Console console = System.console(); System.out.println("console=" + console); console.writer().println("hello from console"); } }

When I ran the application from command prompt I got the following:

$ java TestConsole console=java.io.Console@93dcd hello from console

but when I redirected the STDOUT to file...

$ java TestConsole >/tmp/test Exception in thread "main" java.lang.NullPointerException at TestConsole.main(TestConsole.java:8)

Line 8 is console.writer().println().

Here is the content of /tmp/test

console=null