r4dii
r4dii

Reputation: 3

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.

Upvotes: 0

Views: 70

Answers (2)

Slaw
Slaw

Reputation: 45806

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.

  • PrintStream#printf(String,Object...) returns a PrintStream object (specifically, it returns the same PrintStream object that printf was called on). Hence why you can do printf(...).println() (i.e., "method chain") in the first place.

  • PrintStream#println() returns void (i.e., nothing). There's nothing to (explicitly or implicitly) assign to a variable.

Note that System.out is a PrintStream.

Upvotes: 3

Beulah Evanjalin
Beulah Evanjalin

Reputation: 431

In Java, the printf() method serves as a means for formatted printing and is designed to return a reference to the PrintStream class. This PrintStream class includes an array of methods tailored for printing data to the output stream. One of the integral methods within this class is println(). enter image description here

I guess println() is included as a method in the PrintStream class because it serves as a fundamental and widely used approach to print data with line breaks, thus making it a valuable tool for output operations in Java.

Upvotes: 0

Related Questions