Phoenix_uy Phoenix_uy - 4 months ago 5x
Java Question

Java String.format adding spaces to integers

I have a small piece of code that i don't understand the output.

This output is adding spaces to my string format text. I'm doing something wrong?

public class HelloWorld{

public static void main(String []args){
int a1 = 540;
int a2 = 492;
int a3 = 200;
int a4 = 500;
int a5 = 600;
String a = "/share.html?title=%1s&description=%2s&image=%3s&width=%4s&height=%5s";
String b = String.format(a, a1, a2, a3, a4, a5);

The output is:

/share.html?title=540&description=492&image=200&width= 500&height= 600

Why there are those spaces on the last width and height?


Remove the numbers from your format specifiers:

String a = "/share.html?title=%s&description=%s&image=%s&width=%s&height=%s";

Using a numerical value inside the format specifier like you did, you are specifying the minimal width of the output - this is the reason why you do not see any spaces for your first three values.

If you want to reference a particular parameter instead of letting the formatter evaluate them in the order they are specified, you can specify an argument index in the form n$ where n is the index of the referenced parameter (like 1$, 2$, ...).

See also java.util.Formatter for more information.

Instead of %s, you could also specify %d since all your arguments are of type int.