How do I align string print out in left, right, center alignment?

The following code snippet will teach you how to align string in left, right or center alignment when you want to print out string to a console. We will print the string using the printf(String format, Object... args) method. The format specifier / parameter defines how the string will be formatted for output and the args is the value that will be formatted.

The format parameter / specifier include flags, width, precision and conversion-characters in the order shown below. The square brackets in the notation means the part is an optional parameter.

% [flags] [width] [.precision] conversion-character
Flags Description
- left-align the output, when not specified the default is to right-align
+ print (+) or (-) sign for numeric value
0 zero padded a numeric value
, comma grouping separator for number greater that 1000
space will output a (-) symbol for negative value and a space if positive
Conversion Description
s string, use capital S to uppercase the strings
c character, use capital C to uppercase the characters
d integer: byte, short, integer, long
f floating point number: float, double
n new line

Width: Defines the field width for printing out the value of argument. It also represents the minimum number of characters to
be printed out to the output.

Precision: For floating-point conversion the precision define the number of digits of precision in a floating point value. For string value this will extract the substring.

To center the string for output we use the method from the Apache Commons Lang library. This method will center-align the string str in a larger string of size using the default space character (‘ ‘). You can supply the third parameter to define your own space character / string.

package org.kodejava.example.lang;

import org.apache.commons.lang3.StringUtils;

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class StringAlignment {
    private static Object[][] people = {
        {"Alice", LocalDate.of(2000, Month.JANUARY, 1)},
        {"Bob", LocalDate.of(1989, Month.DECEMBER, 15)},
        {"Carol", LocalDate.of(1992, Month.JULY, 24)},
        {"Ted", LocalDate.of(2006, Month.MARCH, 13)},

    public static void main(String[] args) {
        String nameFormat = "| %1$-20s | ";
        String dateFormat = " %2$tb %2$td, %2$tY  | ";
        String ageFormat = " %3$3s |%n";
        String format = nameFormat.concat(dateFormat).concat(ageFormat);
        String line = new String(new char[48]).replace('\0', '-');

  "Name", 22),
  "Birth Date", 16),
  "Age", 6));

        for (Object[] data : people) {
                data[0], data[1],
                ChronoUnit.YEARS.between((LocalDate) data[1],;


Here is the output of our code snippet above:

|         Name         |   Birth Date   | Age  |
| Alice                |  Jan 01, 2000  |   17 |
| Bob                  |  Dec 15, 1989  |   27 |
| Carol                |  Jul 24, 1992  |   24 |
| Ted                  |  Mar 13, 2006  |   10 |

Maven Dependencies


How do I generate random string?


import java.util.Random;

public class RandomString {
    public static final String SOURCES =

    public static void main(String[] args) {
        RandomString rs = new RandomString();
        System.out.println(rs.generateString(new Random(), SOURCES, 10));
        System.out.println(rs.generateString(new Random(), SOURCES, 10));
        System.out.println(rs.generateString(new SecureRandom(), SOURCES, 15));
        System.out.println(rs.generateString(new SecureRandom(), SOURCES, 15));

     * Generate a random string.
     * @param random the random number generator.
     * @param characters the characters for generating string.
     * @param length the length of the generated string.
     * @return
    public String generateString(Random random, String characters, int length) {
        char[] text = new char[length];
        for (int i = 0; i < length; i++) {
            text[i] = characters.charAt(random.nextInt(characters.length()));
        return new String(text);

Example string produced by the code snippets are:


How do I use string in switch statement?

Starting from Java 7 release you can now use a String in the switch statement. On the previous version we can only use constants type of byte, char, short, int (and their corresponding reference / wrapper type) or enum constants in the switch statement.

The code below give you a simple example on how the Java 7 extended to allow the use of String in switch statement.

package org.kodejava.example.basic;

public class StringInSwitchExample {
    public static void main(String[] args) {
        String day = "Sunday";
        switch (day) {
            case "Sunday":
            case "Monday":
            case "Tuesday":
            case "Wednesday":

How do I get char value of a string at a specified position?

The chartAt() method of the String class returns the char value at the specified index. An index ranges from 0 to length() - 1. If we specified an index beyond of this range a StringIndexOutOfBoundsException exception will be thrown.

These method use zero based index which means the first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

package org.kodejava.example.lang;

public class CharAtExample {
    public static void main(String[] args) {
        String[] colors = {"black", "white", "brown", "green", "yellow", "blue"};

        for (String color : colors) {
            // Get char value of a string at index number 3. Because
            // the index is zero based we'll get the fourth character
            // of each color in the array.
            char value = color.charAt(3);
            System.out.printf("The fourth char of %s is '%s'.%n", color, value);


Here is the program output:

The fourth char of black is 'c'
The fourth char of white is 't'
The fourth char of brown is 'w'
The fourth char of green is 'e'
The fourth char of yellow is 'l'
The fourth char of blue is 'e'

How do I determine whether a string is a palindrome?

This code checks a string to determine if it is a palindrome or not. A palindrome is a word, phrase, or sequence that reads the same backward as forward.

package org.kodejava.example.lang;

public class PalindromeChecker {

    public static void main(String[] args) {
        String text = "Sator Arepo Tenet Opera Rotas";

        PalindromeChecker checker = new PalindromeChecker();
        System.out.println("Is palindrome = " + checker.isPalindrome(text));

     * This method checks the string for palindrome. We use StringBuilder to
     * reverse the original string.
     * @param text
     * @return
    private boolean isPalindrome(String text) {
        System.out.println("Original text = " + text);

        String reverse = new StringBuilder(text).reverse().toString();
        System.out.println("Reverse text  = " + reverse);

        // Compare the original text with the reverse one and ignoring its case
        return text.equalsIgnoreCase(reverse);