Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
936 views
in Technique[技术] by (71.8m points)

printing - Is there a good reason to use "printf" instead of "print" in java?

I haven't had the chance to take any serious low-level programming courses in school. (I know I really should get going on learning the "behind-the-scenes" to be a better programmer.) I appreciate the conveniences of Java, including the ability to stick anything into a System.out.print statement. However, is there any reason why you would want to use System.out.printf instead?

Also, should I avoid print calls like this in "real applications"? It's probably better to to print messages to the client's display using some kind of UI function, right?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The printf method of the PrintStream class provides string formatting similar to the printf function in C.

The formatting for printf uses the Formatter class' formatting syntax.

The printf method can be particularly useful when displaying multiple variables in one line which would be tedious using string concatenation:

int a = 10;
int b = 20;

// Tedious string concatenation.
System.out.println("a: " + a + " b: " + b);

// Output using string formatting.
System.out.printf("a: %d b: %d
", a, b);

Also, writting Java applications doesn't necessarily mean writing GUI applications, so when writing console applications, one would use print, println, printf and other functions that will output to System.out.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...