May I know what is the difference between the two in java? I am reading a book and it uses both methods to display strings.
Using printf() , String. format() or Formatter is essentially the same thing. The only thing that differs is the return type - printf() prints to the standard output stream (typically your console) and String. format() returns a formatted String .
System.out.printf("The String object %s is at hash code %h%n", s, s); String class format( ) method: You can build a formatted String and assign it to a variable using the static format method in the String class. The use of a format string and argument list is identical to its use in the printf method.
print() The only difference between println() and print() method is that println() throws the cursor to the next line after printing the desired result whereas print() method keeps the cursor on the same line. print() method.
println is short for "print line", meaning after the argument is printed then goes to the next line. printf is short for print formatter, it gives you the ability to mark where in the String variables will go and pass in those variables with it.
The first one writes to the stdout and the second one returns a String
object.
Which to use depends on the sole purpose. If you want to display the string in the stdout (console), then use the first. If you want to get a handle to the formatted string to use further in the code, then use the second.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With