How do I create a repeated sequence of character?

This example shows you how to create a repeated sequence of characters. To do this, we use the Arrays.fill() method. This method fills an array of char with a character.

package org.kodejava.util;

import java.util.Arrays;

public class RepeatCharacterExample {
    public static void main(String[] args) {
        char c = '*';
        int length = 10;

        // creates a char array with 10 elements
        char[] chars = new char[length];

        // fill each element of the char array with '*'
        Arrays.fill(chars, c);

        // print out the repeated '*'
        System.out.println(String.valueOf(chars));
    }
}

As the result you get the x character repeated 10 times.

**********

For one-liner code, you can use the following code snippet, which will give you the same result.

public class Test {
    public static void main(String[] args) {
        String str = new String(new char[10]).replace('\u0000', '*');
    }
}

Or

import java.util.Collections;

public class Test {
    public static void main(String[] args) {
        String str = String.join("", Collections.nCopies(10, "*"));
    }
}

How do I use StringTokenizer to split a string?

The code below is an example of using StringTokenizer to split a string. In the current JDK this class is discouraged to be used, use the String.split(...) method instead or using the new java.util.regex package.

package org.kodejava.util;

import java.util.StringTokenizer;

public class StringTokenizerExample {
    public static void main(String[] args) {
        StringTokenizer st =
            new StringTokenizer("A StringTokenizer sample");

        // get how many tokens inside st object
        System.out.println("Tokens count: " + st.countTokens());

        // iterate st object to get more tokens from it
        while (st.hasMoreElements()) {
            String token = st.nextElement().toString();
            System.out.println("Token = " + token);
        }

        // split a date string using a forward slash as delimiter
        st = new StringTokenizer("2021/09/14", "/");
        while (st.hasMoreElements()) {
            String token = st.nextToken();
            System.out.println("Token = " + token);
        }
    }
}

Here is the result of this sample code:

Tokens count: 3
Token = A
Token = StringTokenizer
Token = sample
Token = 2021
Token = 09
Token = 14

How do I check a string starts with a specific word?

To test if a string starts with a specific prefix we can use the String.startsWith(String prefix) method. This method returns a boolean true as the result if the string starts with that specified prefix. The String.startsWith() method checks the prefix in case-sensitive manner.

The following code snippet give us a small example how to use this method, but instead of just straightly checks using the startsWith() method, we add a scanner that allows us to input the prefix that we want to test.

package org.kodejava.lang;

import java.util.Scanner;

import static java.lang.System.in;

public class StringStartsWithExample {
    private static final Scanner scanner = new Scanner(in);

    public static void main(String[] args) {
        String text = "The quick brown fox jumps over the lazy dog";
        System.out.println("Text: " + text);

        System.out.print("Type the prefix to test: ");
        String search = scanner.nextLine();

        // Check if the text start with the search text.
        if (text.startsWith(search)) {
            System.out.println("Yes, the fox is the quick one");
        } else {
            System.out.println("The fox is a slow fox");
        }
    }
}

The code snippet print the following output:

Text: The quick brown fox jumps over the lazy dog
Type the prefix to test: The quick brown fox
Yes, the fox is the quick one

How do I check a string ends with a specific word?

The String.endsWith() method can be used to check if a string ends with a specific word. It will return a boolean true if the suffix is found at the end of the string object.

In this example we will start the code by creating a class called StringEndsWithExample. This class has a standard main() method that makes the class executable. In the main() method we create a string variable called str and assign a text to it.

On the following line you can see an if conditional statement to check it the str string ends with "lazy dog". If it ends with that words then the corresponding block in the if statement will be executed.

package org.kodejava.lang;

public class StringEndsWithExample {
    public static void main(String[] args) {
        String str = "The quick brown fox jumps over the lazy dog";

        // well, does the fox jumps over a lazy dog?
        if (str.endsWith("lazy dog")) {
            System.out.println("The dog is a lazy dog");
        } else {
            System.out.println("Good dog!");
        }

        // Ends with empty string.
        if (str.endsWith("")) {
            System.out.println("true");
        }

        // Ends with the same string.
        if (str.endsWith(str)) {
            System.out.println("true");
        }
    }
}

Another thing that you need to know is that the endsWith() method will return true if you pass in an empty string or another string that is equals to this string as the argument. This method is also case-sensitive.

When you run the code snippet above you can see the following lines printed out:

The dog is a lazy dog
true
true

How do I implement a Singleton pattern?

Singleton Pattern is used when we want to allow only a single instance of a class can be created inside our application. This pattern ensures that a class only have a single instance by protecting the class creation process, which can be done by defining the class constructor with private access modifier.

To get an instance of a singleton we provide a getInstance() method, this will be the only method that can be accessed to get an instance of the singleton class.

package org.kodejava.pattern.factory;

public class Singleton {
    private static Singleton instance = new Singleton();

    private Singleton() {
    }

    public static synchronized Singleton getInstance() {
        return instance;
    }

    public void doSomething() {
        for (int i = 0; i < 10; i++) {
            System.out.println("i = " + i);
        }
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Clone is not allowed.");
    }
}

There are some rules that need to be followed when we want to implement a singleton.

  • From code above we can see that a singleton has a static variable to keep it sole instance.
  • We need to set the class constructor into private access modifier. By this we will not allow any other class to create an instance of this singleton because they have no access to the constructor.
  • Because no other class can instantiate this singleton how can we use it? the answer is the singleton should provide a service to it users by providing some method that returns the instance, for example getInstance().
  • When we use our singleton in a multi threaded application we need to make sure that instance creation process not resulting more that one instance, so we add a synchronized keywords to protect more than one thread access this method at the same time.
  • It is also advisable to override the clone() method of the java.lang.Object class and throw CloneNotSupportedException so that another instance cannot be created by cloning the singleton object.

And this is how we use the singleton class.

package org.kodejava.pattern.factory;

public class SingletonDemo {
    public static void main(String[] args) {
        // Gets an instance of Singleton class and calls the
        // doSomething method.
        Singleton singleton = Singleton.getInstance();
        singleton.doSomething();
    }
}