What is the difference between "System.out.println" and "System.out.printf" in java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gautamz07
    New Member
    • Sep 2013
    • 26

    What is the difference between "System.out.println" and "System.out.printf" in java

    Code:
    for(String x: s)
    System.out.printf("%s" , x);
    Why is "%s" used here ? :((
  • Nepomuk
    Recognized Expert Specialist
    • Aug 2007
    • 3111

    #2
    While println will take a String, print it and add a new line at the end, printf will take a formatted String and not add a new line at the end. A formatted String means, that you can do stuff like this:
    Code:
    for(int i=1; i<=10; i++) {
       System.out.printf("The given number is %d and it is %s\n", i, (i % 2 == 0 ? "even" : "odd"));
    }
    This will print
    Code:
    The given number is 1 and it is odd.
    The given number is 2 and it is even.
    The given number is 3 and it is odd.
    The given number is 4 and it is even.
    The given number is 5 and it is odd.
    The given number is 6 and it is even.
    The given number is 7 and it is odd.
    The given number is 8 and it is even.
    The given number is 9 and it is odd.
    The given number is 10 and it is even.
    So in short: %s is used when you want to have a String at that place, %d is used for integers.

    Comment

    Working...