Is there anything like the ". format" Python method in Java?

Asked

Viewed 59 times

1

I have been studying the Java language and realized that I am using many concatenation signals (+).

And I remembered that in the Python language, there’s the method format, where keys can be used to decrease the use of concatenations.

I wonder if in Java it is possible to do the same thing?

  • https://docs.oracle.com/javase/10/docs/api/java/lang/String.html#format(java.lang.String,java.lang.Object...)

1 answer

2

In Java string concatenations with + are quite common. In most cases the compiler is smart enough to translate concatenations with + for concatenations using StringBuilder and append; in that way + is usually the most natural language for concatenating strings in Java. In cases where performance is important and the logic is too complex to be optimized by the compiler we can use StringBuilder directly.

For "advanced" formatting there is the method String.format that uses formatting strings very similar to the ones used in the function printf of the C.

String mensagem = String.format("%d %s custam $%0.2f", 6, "bananas", 1.74);

For "basic" formatting there is also the class MessageFormat who uses Patterns similar to the placeholders positional of format python.

String mensagem = MessageFormat.format("{0} {1} custam {2,number,currency}", 6, "bananas", 1.74);

Finally, it is also possible to use an external solution such as Better Strings that allows string interpolation in Java projects.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.