How can I pad a String in Java?

To pad a string in Java, you can use the String.format() method and specify a width for the string. The format() method will add padding characters to the string to make it the specified width.

Here's an example of how to use format() to pad a string with spaces on the left:

String str = "Hello";
String padded = String.format("%10s", str);
System.out.println(padded);  // Outputs: "     Hello"

In this example, the width of the padded string is 10, and the padding character is a space. You can use a different padding character by specifying it in the format string, like this:

String str = "Hello";
String padded = String.format("%'#10s", str);
System.out.println(padded);  // Outputs: "#####Hello"

You can also pad the string on the right by using a negative width, like this:

String str = "Hello";
String padded = String.format("%-10s", str);
System.out.println(padded);  // Outputs: "Hello     "

You can use the format() method to pad strings with other data types as well, like integers or floating-point numbers. For more information, you can check the documentation of the String.format() method in the Java API.