There are two ways to right-align text in Java: 1. Use the printf() method and use the "%-10s" specifier in the format string, where 10 represents the output field width; 2. Use String.format() method, also uses the "%-10s" specifier in the format string to right-align the returned format string.
#How to right align in Java?
There are two main ways to right-align text in Java:
1. Use the printf() method
The printf() method accepts A format string containing %flags[.precision]s specifiers that control the output format. To align right, you can use - flag.
<code class="java">System.out.printf("%-10s", "Right-aligned");</code>
This will output:
<code>Right-aligned</code>
where 10 represents the width of the output field.
2. Use the String.format() method
The String.format() method also accepts a formatted string, but it returns a formatted character string instead of printing it directly to the console. To right-align, you can use the %flags[.precision]s specifier, where the - flag means right-align.
<code class="java">String formatted = String.format("%-10s", "Right-aligned"); System.out.println(formatted);</code>
This will output the same results as above.
The above is the detailed content of How to right align in java. For more information, please follow other related articles on the PHP Chinese website!