javaprintln

Why would you use '"%d", variable' when you can simply type the variable name?


I was wondering why my professor would type

System.out.println("%d", myRank);

instead of

System.out.println(myRank);

from my point of view the latter is inherently more efficient and has the same effect

I've tried both and they perform the same, so I am quite confused as to why the former is used at all


Solution

  • First of all, System.out.println("%d", myRank); will not compile.

    You can use System.out.printf or String.format(...) inside printf

    For a single argument, as you mentioned, it does not make much sense. The value of String.format (or printf) can be seen when you have string concatenation and it makes the code more readable and easier to maintain.

    For example, you can print the following message:

    System.out.printf("my rank is %d, which is nice. and my friend's rank is %d. which is lower than mine", myRank, friendRank);
    

    Instead of:

    System.out.printf("my rank is " + myRank + ", which is nice. and my friend's rank is " + friendRank + ". which is lower than mine");