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.
Recent blog posts
- Free: Introduction To Functional Programming video training course
- The #1 functional programming (and computer programming) book
- The User Story Mapping Workshop process
- Alvin Alexander, Certified Scrum Product Owner (CSPO)
- Alvin Alexander is now a Certified ScrumMaster (CSM)
- Our “Back To Then” app (for iOS and Android)
- A Docker cheat sheet
- Pushing a Scala 3 JAR/Docker file to Google Cloud Run
- Reading a CSV File Into a Spark RDD (Scala Cookbook recipe)
- Reading a File Into a Spark RDD (Scala Cookbook recipe)