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.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. We'll get the 
            // fourth character of each color in the array because the 
            // index is zero based.
            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 create a console progress bar?

The code below demonstrates how to create a progress bar in a console program. The trick is to print the progress status using a System.out.print() and add a carriage return character ("\r") at the end of the string to return the cursor position to the beginning of the line and print the next progress status.

package org.kodejava.lang;

public class ConsoleProgressBar {
    public static void main(String[] args) {
        char[] animationChars = new char[]{'|', '/', '-', '\\'};

        for (int i = 0; i <= 100; i++) {
            System.out.print("Processing: " + i + "% " + animationChars[i % 4] + "\r");

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

        System.out.println("Processing: Done!");
    }
}

How do I calculate process execution time in higher resolution?

This example demonstrates how to use the System.nanoTime() method to calculate processing execution time in higher resolution. The processing time calculated in nanoseconds resolution.

package org.kodejava.lang;

public class NanoSecondsTimerResolution {
    public static void main(String[] args) {
        // Get process execution start time in nanoseconds.
        long start = System.nanoTime();
        System.out.println("Process start... " + start);

        try {
            Thread.sleep(5000); // Simulate a long process.
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Get process execution finish time in nanoseconds.
        long finish = System.nanoTime();
        System.out.println("Process finish... " + finish);

        // Calculate the process execution time.
        long execTime = finish - start;
        System.out.println("Processing time = " + execTime + "(ns)");
    }
}

How do I count the number of occurrences of a char in a String?

This example show you how to count the number of a character occurrences in a string. We show two ways to do it, using the String.replaceAll(String regex, String replace) method and creating a loop that check every char in the String and count the matched char.

package org.kodejava.lang;

public class CharCounter {
    public static void main(String[] args) {
        String text = "a,b,c,c,e,f,g,g,g,g,h";

        // Use the CharCounter.countCharOccurrences() method to count.
        int numberOfLetterC = CharCounter.countCharOccurrences(text, 'c');
        System.out.println("Letter c = " + numberOfLetterC);

        // Other solution is to use the String.replaceAll() method. We'll
        // replace the chars other than the counted char with an empty string.
        // To get the char occurrences we count the length of the remaining
        // string.
        int numberOfComma = text.replaceAll("[^,]", "").length();
        System.out.println("Comma    = " + numberOfComma);

        int numberOfLetterG = text.replaceAll("[^g]", "").length();
        System.out.println("Letter g = " + numberOfLetterG);
    }

    /**
     * Count number of specified char occurrences in the specified string.
     */
    private static int countCharOccurrences(String source, char target) {
        int counter = 0;

        // Loop through the string and increment the counter if the
        // target character found in the string. 
        for (int i = 0; i < source.length(); i++) {
            if (source.charAt(i) == target) {
                counter++;
            }
        }
        return counter;
    }
}

How do I get all annotations?

To obtains all annotations for classes, methods, constructors, or fields we use the getAnnotations()method. This method returns an array of Annotation

In the following example we tried to read all annotations from the sayHi() method. First we need to obtain the method object itself. Because the sayHi() method has parameters, we need to pass not only the method name to the getMethod() method, but we also need to pass the parameter’s type.

The getAnnotations() method returns only annotation that has a RetentionPolicy.RUNTIME, because other retention policy doesn’t allow the annotation to available at runtime.

package org.kodejava.lang.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class GetAllAnnotation {
    private final Map<String, String> data = new HashMap<>();

    public static void main(String[] args) {
        GetAllAnnotation demo = new GetAllAnnotation();
        demo.sayHi("001", "Alice");
        demo.sayHi("004", "Malory");

        try {
            Class<? extends GetAllAnnotation> clazz = demo.getClass();

            // To get the sayHi() method we need to pass not only the method
            // name but also its parameters type so the getMethod() method
            // return the correct method for us to use.
            Method method = clazz.getMethod("sayHi", String.class, String.class);

            // Get all annotations from the sayHi() method. But this actually
            // will only return one annotation. Because only the HelloAnnotation
            // annotation that has RUNTIME retention policy, which means that
            // the other annotations associated with sayHi() method is not
            // available at runtime.
            Annotation[] annotations = method.getAnnotations();
            for (Annotation annotation : annotations) {
                System.out.println("Type: " + annotation.annotationType());
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    @MyAnnotation("Hi")
    @HelloAnnotation(value = "Hello", greetTo = "Everyone")
    public void sayHi(String dataId, String name) {
        Map<String, String> data = getData();
        if (data.containsKey(dataId)) {
            System.out.println("Hello " + data.get(dataId));
        } else {
            data.put(dataId, name);
        }
    }

    private Map<String, String> getData() {
        data.put("001", "Alice");
        data.put("002", "Bob");
        data.put("003", "Carol");
        return data;
    }
}
package org.kodejava.lang.annotation;

public @interface MyAnnotation {
    String value();
}

Check the HelloAnnotation on the following link How do I create a simple annotation?.

The result of this code snippet:

Hello Alice
Type: interface org.kodejava.lang.annotation.HelloAnnotation