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 Java Basics Getting Started with Java Strings and Variables

Adam Sawicki
Adam Sawicki
15,967 Points

System.out println

Hey, I wonder what is the difference between using console class (method printf) and using System.out.println. In second case you don't have to import extra library.

3 Answers

I think some more complicated examples from the Java Documentation would be helpful to illustrate how printf is best used; it's not just a replacement for concatenating variables, as it will format the variable as defined by the converter/flag included.

      long n = 461012;
      System.out.format("%d%n", n);      //  -->  "461012"
      System.out.format("%08d%n", n);    //  -->  "00461012"
      System.out.format("%+8d%n", n);    //  -->  " +461012"
      System.out.format("%,8d%n", n);    // -->  " 461,012"
      System.out.format("%+,8d%n%n", n); //  -->  "+461,012"

      double pi = Math.PI;
      System.out.format("%f%n", pi);       // -->  "3.141593"
      System.out.format("%.3f%n", pi);     // -->  "3.142"
      System.out.format("%10.3f%n", pi);   // -->  "     3.142"
      System.out.format("%-10.3f%n", pi);  // -->  "3.142"
      System.out.format(Locale.FRANCE, "%-10.4f%n%n", pi); // -->  "3,1416"

      Calendar c = Calendar.getInstance();
      System.out.format("%tB %te, %tY%n", c, c, c); // -->  "May 29, 2006"
      System.out.format("%tl:%tM %tp%n", c, c, c);  // -->  "2:34 am"
      System.out.format("%tD%n", c);    // -->  "05/29/06"

The link to the Java docs above includes a full list of the converters and flags used in these examples, if you're interested.

Hi Adam,

The biggest difference upfront is that you can use printf to format a string with variables.

System.out.printf("The value of the float variable is %f," +
"while the value of the integer variable is %d, " +
"and the string is %s", floatVar, intVar, stringVar); 

Hope that helps!

Adam Sawicki
Adam Sawicki
15,967 Points

That's right but why this is better than System.out.println("blablabla" + var1 + "blablabla" + var2 )? I can see the advantage that you can all variables in one place but there is more?