Java String format examples

A few days ago I was reminded of the Java String format method, and the ability to use printf syntax with this format method, so I thought I'd share a quick example of it here.

Here's a quick look at the String class format method syntax, which demonstrates the power and simplicity of this "Java printf" syntax:

String output = String.format("The user's first name is (%s)", firstName);

If you're familiar with C, C++, Objective C, Perl, and many other programming languages, you'll immediately recognize the printf syntax used there, and feel very comfortable with the format method.

As with other printf implementations, you can include multiple variables in your String format method, like this:

String result = String.format("%s is %d years old, er, young", "Al", 45)

And as one final note, if what you really want to do is print your output -- and not create a new, formatted String, as shown above -- use this Java method instead:

System.out.format("%s is %d years old, er, young", "Al", 45);

As you can see, this Java System.out.format method uses the same printf-style syntax, and can be used as a replacement for the older System.out.println method.

I hope these Java String formatting and printf-style examples have been helpful. For many more details, please see my devdaily.com tutorials:

Hopefully those string formatting tutorials will have all the information you need.

Valley Programming is currently a one-person business, owned and operated by Alvin Alexander. If you’re interested in anything you read here, feel free to contact me at “al” at (“@”) this website name (“valleyprogramming.com”), or at the phone number shown below. I’m just getting back to business here in November, 2021, and eventually I’ll get a contact form set up here, but until then, I hope that works.