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 trialupul jayalath
1,294 PointsSystem.out.println vs console.printf
Hi
I couldnt understand the exact difference between System.out.println method and console.printf method. I listened to the teacher's video and went through the similar question- but still it is not clear to me.
Are they same and do both methods print to the console? If they are different, what is the difference between them?
Thank you.
3 Answers
Bramyn Payne
19,589 PointsHello!
Both methods are similar, but they are slightly different. Yes, they both print to the console.
System.out.println
prints the input and then starts a new line.
However, System.out.printf
is more powerful because it also lets you format the string that you would like to print.
For example:
System.out.printf("length of String %s is %d", "abcd", "abcd".length());
Would output:
length of String abcd is 4
It is a bit confusing at first, but just know that if you want to format the string as above, you need to use System.out.printf
.
I hope this helps!
Bramyn Payne
19,589 PointsHey!
Here is a link to a Treehouse discussion where Craig Dennis answers a similar question.
Ultimately, they would do the same thing, but using console
will only print to the console. Using System.out
would allow you to print output to something other than the console. Also, you can use System.out
without importing anything. However, using console
you would need this import statement import java.io.Console;
.
Here is a link to Oracle's documentation. If you scroll down to the printf
method, it basically says that is a convenience method to output to the console.
I hope that helps clear things up.
upul jayalath
1,294 PointsThank you Bramyn.
From your explanation, I understand now System.out.println and System.out.printf (both are using 'out' static member field)
My concern is console.printf. console is a Console class object. Is this console.printf and System.out.printf same as well? If they are same, how the same printf method can be used in Console class's object and 'out' static member field?
Thank you for your help again.