Something like
String name = String.format("%s_%s%s_%s",n1,n2,n3,n4);
Using the String.format function
Using the String.format style (similar to C's 'printf' syntax) allows you to see the structure of your final string more clearly even when variable names are long. Overall it makes code easier to read then using the + operator, because you're separating your formatting text from the list of values you want in that format.
Answer from Chad Okere on Stack OverflowSomething like
String name = String.format("%s_%s%s_%s",n1,n2,n3,n4);
Using the String.format function
Using the String.format style (similar to C's 'printf' syntax) allows you to see the structure of your final string more clearly even when variable names are long. Overall it makes code easier to read then using the + operator, because you're separating your formatting text from the list of values you want in that format.
String name = n1 + "_" + n2 + n3 + "_" + n4;
How to format multiple string parameters in Java - Stack Overflow
How to format and print multiple strings in Java - Stack Overflow
java - Do I have to specify a variable for each identical argument in String.format? - Stack Overflow
Help with String.format
If you want to put the result in a String you can use :
String result = String.format("%-30s %-30s %-30s", divName, heading1, heading2);
Then you can print it or use it in another places
To get formatting on each of them you need to pass them separately to printf rather than combining them into one string with +.
System.out.printf("%-30s %-30s %-30s", divName, heading1, heading2);
From the docs:
The format specifiers for general, character, and numeric types have the following syntax:
%[argument_index$][flags][width][.precision]conversionThe optional argument_index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by
"1$", the second by"2$", etc.
String.format("%1
s %1
s %1
s", hello);
Another option is to use relative indexing: The format specifier references the same argument as the last format specifier.
For example:
String.format("%s %<s %<s %<s", "hello")
results in hello hello hello hello.