How to add padding to the left with String.format() in Java

3 Answers

0 votes
import java.io.IOException;

public class Program {
    public static void main(String[] args) throws IOException {
        try {
 
            String[] arr = {"java", "c", "c#", "c++", "php"};
 
            for (int i = 0; i < arr.length; i++) {
                String s = String.format("'%13s'", arr[i]);
                System.out.println(s);
            }
 
        } catch (Exception e) {
            System.out.print(e.toString());
        }
    }
}


/*
run:

'         java'
'            c'
'           c#'
'          c++'
'          php'

*/

 



answered Nov 20, 2016 by avibootz
edited Jul 4, 2025 by avibootz
0 votes
class Main {
    public static void main(String[] args) {
        String paddedString = String.format("%10s", "Java").replace(' ', '*');
        
        System.out.println(paddedString);
    }
}


/*
run:

******Java

*/

 



answered Jul 4, 2025 by avibootz
0 votes
class Main {
    public static void main(String[] args) {
        String paddedNumber = String.format("%05d", 42); 
        
        System.out.println(paddedNumber);
    }
}


/*
run:

00042

*/

 



answered Jul 4, 2025 by avibootz
...