How do I check if a string starts with a pattern?

The example below demonstrate the Matcher.lookingAt() method to check if a string starts with a pattern represented by the Pattern class.

package org.kodejava.regex;

import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherLookingAtExample {

    public static void main(String[] args) {
        // Get the available countries
        Set<String> countries = new TreeSet<>();
        Locale[] locales = Locale.getAvailableLocales();
        for (Locale locale : locales) {
            countries.add(locale.getDisplayCountry());
        }

        // Create a Pattern instance. Look for a country that start with
        // "I" with an arbitrary second letter and have either "a" or "e"
        // letter in the next sequence.
        Pattern pattern = Pattern.compile("^I.[ae]");
        System.out.println("Country name which have the pattern of " +
                pattern.pattern() + ": ");

        // Find country name which prefix matches the matcher's pattern
        for (String country : countries) {
            // Create matcher object
            Matcher matcher = pattern.matcher(country);

            // Check if the matcher's prefix match with the matcher's
            // pattern
            if (matcher.lookingAt()) {
                System.out.println("Found: " + country);
            }
        }
    }
}

The following country names is printed as the result of the program above:

Country name which have the pattern of ^I.[ae]: 
Found: Iceland
Found: Iran
Found: Iraq
Found: Ireland
Found: Italy

How do I trim the capacity of an ArrayList?

For minimizing the storage used by an ArrayList to the number of its elements we can use the ArrayList.trimToSize() method call. In the code below we create an instance of ArrayList with the initial capacity set to 100. Later we only add five data into the list. To make the capacity of the ArrayList minimized we call the trimToSize() method.

package org.kodejava.util;

import java.util.ArrayList;

public class ListTrimToSize {
    public static void main(String[] args) {
        // Create an ArrayList with the initial capacity of 100.
        ArrayList<String> list = new ArrayList<>(100);
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("E");
        list.add("F");

        System.out.println("Size: " + list.size());

        // Trim the capacity of the ArrayList to the size
        // of the ArrayList. We can do this operation to reduce
        // the memory used to store data by the ArrayList.
        list.trimToSize();
    }
}

How do I get process ID of a Java application?

The code below show you how to get the process ID of a Java application. We can use the ManagementFactory.getRuntimeMXBean().getName() to get the process ID. In Windows the method return a string in the form of [PID]@[MACHINE_NAME].

Since JDK 10, we can use ManagementFactory.getRuntimeMXBean().getPid() method to get the process ID. This method returns the process ID representing the running Java virtual machine.

package org.kodejava.lang.management;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;

public class GetProcessID {
    public static void main(String[] args) {
        RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();

        // Get name representing the running Java virtual machine.
        // It returns something like 35656@Krakatau. The value before
        // the @ symbol is the PID.
        String jvmName = bean.getName();
        System.out.println("Name = " + jvmName);

        // Extract the PID by splitting the string returned by the
        // bean.getName() method.
        long pid = Long.parseLong(jvmName.split("@")[0]);
        System.out.println("PID  = " + pid);

        // Get the process ID representing the running Java virtual machine.
        // Since JDK 10.
        pid = ManagementFactory.getRuntimeMXBean().getPid();
        System.out.println("PID = " + pid);

    }
}

Here is the result of the code above:

Name = 35656@Krakatau
PID  = 35656
PID  = 35656

How do I find and replace string?

The code below demonstrates the use Matcher.appendReplacement() and Matcher.appendTail() methods to create a program to find and replace a sub string within a string.

Another solution that can be used to search and replace a string can be found on the following example: How do I create a string search and replace using regex?.

package org.kodejava.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AppendReplacementExample {
    public static void main(String[] args) {
        // Create a Pattern instance
        Pattern pattern = Pattern.compile("[Pp]en");

        // Create matcher object
        String input = "Please use your Pen to answer the question, " +
                "black pen is preferred.";
        Matcher matcher = pattern.matcher(input);
        StringBuilder builder = new StringBuilder();

        // Find and replace the text that match the pattern
        while (matcher.find()) {
            matcher.appendReplacement(builder, "pencil");
        }

        // This method reads characters from the input sequence, starting
        // at the beginning position, and appends them to the given string
        // builder. It is intended to be invoked after one or more
        // invocations of the appendReplacement method in order to copy
        // the remainder of the input sequence.
        matcher.appendTail(builder);

        System.out.println("Input : " + input);
        System.out.println("Output: " + builder);
    }
}

Here is the result of the above code:

Input : Please use your Pen to answer the question, black pen is preferred.
Output: Please use your pencil to answer the question, black pencil is preferred.

How do I print a file using the default registered application?

The example code below shows you how to print a file using the default registered application’s print command for the corresponding file type. As an example, on Windows notepad.exe is the default application for printing a .txt file.

To print a file using the default registered application we call the java.awt.Desktop.print(File) method. The print() method takes a parameter of File, which is the reference to a file to be printed. The code snippet below, when run on Windows, will open notepad.exe and print the data.txt file.

package org.kodejava.awt;

import java.awt.*;
import java.io.File;
import java.io.IOException;

public class RunningDefaultAppPrint {
    public static void main(String[] args) {
        File file = new File("data.txt");
        try {
            Desktop desktop = Desktop.getDesktop();

            // Prints a file with the native desktop printing facility, 
            // using the associated application's print command.
            desktop.print(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}