Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between System.out.printf and String.format

Tags:

java

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.

like image 474
sutoL Avatar asked Jun 20 '10 17:06

sutoL


People also ask

Is string format the same as printf Java?

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 .

What is system out printf?

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.

What is the difference between the system out Println () system out print () and system out printf () methods when would you use each?

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.

What is the difference between Println and format?

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.


1 Answers

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.

like image 119
BalusC Avatar answered Oct 05 '22 23:10

BalusC