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();
    }
}

How do I know the length of a string?

To get the length of a String object we can use the String.length() method. This method returns the string length as an int value. The length of the string is equals to the length of the sequence of characters represented by this string object, and it is equals to the number of 16-bit Unicode characters in the string.

The following code snippet shows how to use the length() method. We create a string object name and assign a text to it. Call the method and store the length returned to the length variable and print it out. We can also use the length() method to check if the string is empty by checking if the length is equals to zero.

package org.kodejava.lang;

public class StringLengthExample {
    public static void main(String[] args) {
        String name = "Kode Java - Learn Java by Examples";

        // Get the length of the string specified by the name
        // variable.
        int length = name.length();
        System.out.println("Length = " + length);

        // Set name to an empty string and test if it is empty.
        name = "";
        length = name.length();
        if (length == 0) {
            System.out.println("The string is empty!");
        }
    }
}

If you run this code you will get the following output:

Length = 34
The string is empty!

How do I check string for equality?

To compare strings for their content equality we must use the String.equals() method. This method ensures that it will compare the content of both string instead of the object reference of the both string. This method returns true if both string in comparison have the same content.

Do not, never, use the == operator to compare string for its content. The == operator check for object reference equality, it returns true only if both objects point to the same reference. This operator returns false if the object doesn’t point to the same references.

package org.kodejava.lang;

public class StringEquals {
    public static void main(String[] args) {
        String s1 = "Hello World";
        String s2 = new String("Hello World");

        // This is good!
        if (s1.equals(s2)) {
            System.out.println("1. Both strings are equals.");
        } else {
            System.out.println("1. Both strings are not equals.");
        }

        // This is bad!
        if (s1 == s2) {
            System.out.println("2. Both strings are equals.");
        } else {
            System.out.println("2. Both strings are not equals.");
        }
    }
}

In the example above we deliberately create an instance of s2 string using the new operator to make sure that we have a different object reference. When you run the program it will give you the following result:

1. Both strings are equals.
2. Both strings are not equals.

How do I check if a string contains a specific word?

In this code example we are going to learn how to find a specific word or text inside a string. For this example we will utilize the java.lang.String class. The String class provides a method called String.indexOf(). It takes an argument of a String, which is the sub string that we want to find in the other string. You can imagine the sub string as a needle that we are going to find in the haystack.

If the word found more than once in the string, the indexOf() method returns the first index of a sub string found in the specified string. If the sub string can’t be found this method returns -1. The index of string returns by this method begin at zero. It means that the first letter in the string have the index number 0.

Another way that we can use is the String.contains() method. This method introduced in JDK 1.5. The method simply return a boolean value which is true or false indicating whether the string in search is found in the haystack. Let’s see the snippet below:

package org.kodejava.lang;

public class StringContainsExample {
    public static void main(String[] args) {
        String haystack = "Kodejava - Learn Java by Examples";

        // Checks to see if the word "Java" is found in the haystack
        // variable.
        String needle = "Java";
        if (haystack.indexOf(needle) != -1) {
            System.out.println("Found the word " + needle +
                    " at index number " + haystack.indexOf(needle));
        } else {
            System.out.println("Can't find " + needle);
        }

        // Or use the String.contains() method if you are not interested
        // with the index of the word.
        if (haystack.contains(needle)) {
            System.out.println("Eureka we've found Java!");
        }
    }
}

Running the example gave you the following result:

Found the word Java at index number 17
Eureka we've found Java!

How do I know if a character is uppercase?

In the previous example How do I know if a character is lowercase?, we’ve learned how to use the Character.isLowerCase() method. Now we will learn how to use the other method, which is the Character.isUpperCase() to determine if a letter is in an uppercase form. This method also return a boolean value that indicates whether the character is in uppercase form or not.

But first things first. Before you dive into the learning, make sure all other matters are taken care of, as learning to code will require your absolute dedication. If you are a student, you can use essay writing services to outsource some of your assignments. If you work full-time, consider taking a few days off. This way, you will get a clearer mind and more energy for studying.

Another way to check if a letter is in uppercase form is by comparing the type of the characters, that can be obtained using the Character.getType() method with a defined constant value Character.UPPERCASE_LETTER.

Below is the code snippet that demonstrate these methods.

package org.kodejava.example.lang;

public class CharacterIsUpperCaseExample {
    public static void main(String[] args) {
        char a = 'A';

        // Checks to see if a letter is a uppercase letter.
        if (Character.isUpperCase(a)) {
            System.out.println(a + " is an uppercase character.");
        }

        // Checks to see if a letter is an uppercase letter
        // by comparing the character type against
        // Character.UPPERCASE_LETTER constant value.
        int charType = Character.getType(a);
        if (charType == Character.UPPERCASE_LETTER) {
            System.out.println(a + " is an uppercase character.");
        }
    }
}

The above example give you the following result when it executed:

A is an uppercase character.
A is an uppercase character.