Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a typesafe alternative to String.format(...)

Tags:

java

string

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.

like image 409
My-Name-Is Avatar asked Mar 01 '14 15:03

My-Name-Is


People also ask

Is string format bad?

Avoid using String. format() when possible. It is slow and difficult to read when you have more than two variables.

Is string format faster than concatenation Java?

Therefore, concatenation is much faster than String.

Which format is used for 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.

What is the string .format method used for?

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.


1 Answers

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()...

like image 131
lreeder Avatar answered Oct 07 '22 01:10

lreeder