javajshell

Why does adding println() at end of printf function not print out the new variable set in Jshell?


When you don't add println():

jshell> System.out.printf("5 * 2 = %d & 8 * 10 = %d", 5*2, 8*10)
5 * 2 = 10 & 8 * 10 = 80$9 ==> java.io.PrintStream@68de145

jshell> 

when you add println():

jshell> System.out.printf("5 * 2 = %d & 8 * 10 = %d", 5*2, 8*10).println()
5 * 2 = 10 & 8 * 10 = 80

jshell> 

why does println() stop from the new variable set to the print stream being printed out? Shouldn't the variable be printed out in Jshell before the new line from println()? please explain in beginner terms if possible.

Looked on google but found no exact answers.


Solution

  • In JShell, if an expression results in a value and you do not explicitly assign it to a variable, it will assign the value to a generated variable. You can see this with a simple expression:

    jshell> 4 + 3
    $1 ==> 7
    

    The expression 4 + 3 returned a value: 7. I did not assign it to a variable, so it assigned it to one for me. In this case, it was assigned to the variable $1. You can later use this variable (e.g., query it, reassign it, or even drop it).

    The same thing is happening in your question with printf. It's just a little harder to see because what you printed, and the result of the expression, were printed on the same line. You can separate this out.

    This is what you printed:

    5 * 2 = 10 & 8 * 10 = 80
    

    And this is the result of calling printf:

    $9 ==> java.io.PrintStream@68de145
    

    If you were to add a %n (newline) to your printf format, you'd see something like:

    jshell> System.out.printf("5 * 2 = %d & 8 * 10 = %d%n", 5*2, 8*10)
    5 * 2 = 10 & 8 * 10 = 80
    $2 ==> java.io.PrintStream@887af79
    

    So, why do you not see the $NUMBER ==> value when you use println? Because println does not return anything.

    Note that System.out is a PrintStream.