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
- Business Analyst: How to write accurate software requirements
- Business Analyst: A simple secret to running a great meeting
- One thing a business analyst should ask about any requirement
- Business Analysts and Use Case quality: Questions to ask yourself when writing a Use Case
- The three things a Business Analyst should think about during meetings
- Testing web applications Selenium with Scala 3 and ScalaTest
- Scala Cookbook 2021: A best-selling new release in OOP and FP
- Salar Rahmanian's newsletter (and Functional Programming, Simplified)
- Our “Back To Now” app: Now available on iOS and Android
- An Android location “Fused Location Provider API” example