How do I get the path from where a class is loaded?

This examples shows how to get a path name or location from where our class is loaded.

package org.kodejava.lang;

public class CodeSourceLocation {
    public static void main(String[] args) {
        CodeSourceLocation csl = new CodeSourceLocation();
        csl.getCodeSourceLocation();
    }

    private void getCodeSourceLocation() {
        // The location from where the class is loaded.
        System.out.println("Code source location: " +
            getClass().getProtectionDomain().getCodeSource().getLocation());
    }
}

The code snippet print the following output:

Code source location: file:/F:/Wayan/Kodejava/kodejava-example/kodejava-lang/target/classes/

How do I validate email address using regular expression?

In this example we use the String‘s class matches() methods to match a string to be a valid email address based on the given regex.

This example also demonstrate the power of regular expression to validate an email address. Using regular expression makes it easier to validate data such as email address. After the code you’ll see the meaning of the regular expression used in the code below.

package org.kodejava.lang;

public class EmailAddressValidation {
    private static final String EMAIL_REGEX =
            "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$";

    public static void main(String[] args) {
        EmailAddressValidation validator = new EmailAddressValidation();

        System.out.println("isValid = "
                + validator.isValidEmailAddress("[email protected]"));
        System.out.println("isValid = "
                + validator.isValidEmailAddress("[email protected]"));
        System.out.println("isValid = "
                + validator.isValidEmailAddress("[email protected]"));
        System.out.println("isValid = "
                + validator.isValidEmailAddress("user.domain.co.id"));
    }

    /**
     * Validates email address against email regular expression.
     *
     * @param email an email address to check
     * @return true if email address is valid otherwise return false.
     */
    private boolean isValidEmailAddress(String email) {
        return email.matches(EMAIL_REGEX);
    }
}

The first ^[\\w-_\\.+]. The ^ symbols means check the first character. This the regex processor that the email address should start with a word character formed of alphanumeric value (a-z 0-9) or it can also be a hyphen, underscore, dot or a plus symbol.

The second part, *[\\w-_\\.]. The * symbol means match the preceding zero or more times. As the first part, this tell the regex processor to check for another zero or more characters, and it can also contain hyphen, underscore and a dot.

The third part, \\@([\\w]+\\.)+. This check that email address should contain the @ symbol followed by one or more word separated by the dot symbol.

The last part is, [\\w]+[\\w]$, this check that after the last period there should be another word for the domain suffix such as the co.uk or co.id. And the $ ask that the email address should end by a word character.

How do I create a multithreaded program?

Java language which was there when the language was created. This multithreading capabilities can be said like running each program on their on CPU, although the machine only has a single CPU installed.

To create a Thread program in Java we can extend the java.lang.Thread class and override the run() method. But as we know that Java class can only extend from a single class, extending Thread class makes our class cannot be inherited from another class. To solve this problem an interface was introduced, the java.lang.Runnable.

Let see the simplified demo class below. In the program below we’ll have three separated thread executions, the main thread, thread-1 and thread-2.

package org.kodejava.lang;

public class ThreadDemo extends Thread {
    public static void main(String[] args) {
        // Creates an instance of this class.
        ThreadDemo thread1 = new ThreadDemo();

        // Creates a runnable object.
        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 5; i++) {
                    sayHello();
                }
            }
        });

        // Set thread priority, the normal priority of a thread is 5.
        thread1.setPriority(4);
        thread2.setPriority(6);

        // Start the execution of thread1 and thread2
        thread1.start();
        thread2.start();

        for (int i = 0; i < 5; i++) {
            sayHello();
        }
    }

    public void run() {
        for (int i = 0; i < 5; i++) {
            sayHello();
        }
    }

    /**
     * The synchronized modifier ensure that two threads cannot execute the block
     * at the same time.
     */
    private static synchronized void sayHello() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Thread [" + Thread.currentThread().getName() +  "] ==> Hi...");
        }

        try {
            // Causes the currently executing thread to sleep for a random
            // milliseconds
            Thread.sleep((long) (Math.random() * 1000 + 1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Causes the currently executing thread object to temporarily pause
        // and allow other threads to execute.
        Thread.yield();
    }
}

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.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 a text to be checked for palindrome.
     * @return <code>true</code> if a text is palindrome.
     */
    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);
    }
}

How do I create a thread by implementing Runnable interface?

Here is the second way for creating a thread. We create an object that implements the java.lang.Runnable interface. For another example see How do I create a thread by extending Thread class?.

package org.kodejava.lang;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class TimeThread implements Runnable {
    private final DateFormat df = new SimpleDateFormat("hh:mm:ss");

    // The run() method will be invoked when the thread of this runnable object
    // is started.
    @Override
    public void run() {
        while (true) {
            Calendar calendar = Calendar.getInstance();
            System.out.format("Now is: %s.%n", df.format(calendar.getTime()));

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        TimeThread time = new TimeThread();

        Thread thread = new Thread(time);
        thread.start();
    }
}

An example result of this code are:

Now is: 07:18:39.
Now is: 07:18:40.
Now is: 07:18:41.
Now is: 07:18:42.
Now is: 07:18:43.