For composing error, logging or any other String
messages the String.format(...)
method can be used. Unfortunately this method isn't type safe, hence the follwoing source will throw an IllegalFormatException
String s = String.format("My message has %d characters !", "30");
Is there any other alternative for composing such messages, except of the StringBuilder
class.
My personal opinion is that the composed message gets harder to read by using a StringBuilder instance.
Avoid using String. format() when possible. It is slow and difficult to read when you have more than two variables.
Therefore, concatenation is much faster than String.
In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Parameter: The locale value to be applied on the format() method.
The Java String. format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale.
Using String.format()
with only the %s format specifier is effectively typesafe (type opaque might be a better term) since every object will implement a toString()
method, and even null objects are handled.
Of course, you have little control over the actual format of the string if you are not implementingtoString()
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With