How do I execute other applications from Java?

The following program allows you to run / execute other application from Java using the Runtime.exec() method.

package org.kodejava.lang;

import java.io.IOException;

public class RuntimeExec {
    public static void main(String[] args) {
        //String command = "/Applications/Safari.app/Contents/MacOS/Safari";
        String command = "explorer.exe";

        try {
            Process process = Runtime.getRuntime().exec(new String[]{command});
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I get path / classpath separator?

OS platform has a different symbol used for path separator. Path separator is a symbol that separate one path element from the other. In Windows the path separator is a semicolon symbol (;), you have something like:

.;something.jar;D:/libs/commons.jar

While in Linux based operating systems the path separator is a colon symbol (:), it looks like:

.:something.jar:/libs/commons.jar

To obtain the path separator you can use the following code.

package org.kodejava.lang;

import java.util.Properties;

public class PathSeparator {
    public static void main(String[] args) {
        // Get System properties
        Properties properties = System.getProperties();

        // Get the path separator which is unfortunately
        // using a different symbol in different OS platform.
        String pathSeparator = properties.getProperty("path.separator");
        System.out.println("pathSeparator = " + pathSeparator);
    }
}

How do I get environment variables?

Environment variables are a set of dynamic values that can affect a running process, such as our Java program. Each process usually have their own copy of these variables.

Now we would like to obtain the available variables in our environment or operating system, how do I do this in Java? Here is a code example of it.

package org.kodejava.lang;

import java.util.Map;
import java.util.Set;

public class SystemEnv {
    public static void main(String[] args) {
        // We get the environment information from the System class. 
        // The getenv method (why shouldn't it called getEnv()?) 
        // returns a map that will never have null keys or values 
        // returned.
        Map<String, String> map = System.getenv();

        Set<String> keys = map.keySet();
        for (String key : keys) {
            // Here we iterate based on the keys inside the map, and
            // with the key in hand we can get it values.
            String value = map.get(key);
            System.out.println(key + " = " + value);
        }
    }
}

Here are some results on my machine.

...
M2 = C:\ProgramData\chocolatey\lib\maven\apache-maven-3.5.0\bin
JETTY_HOME = C:\ProgramData\chocolatey\lib\jetty\tools\jetty-distribution-9.4.31.v20200723
USERNAME = wsaryada
ProgramFiles(x86) = C:\Program Files (x86)
M2_REPO = C:\Users\wsaryada\.m2
SPRING_HOME = C:\ProgramData\chocolatey\lib\spring-boot-cli\spring-2.2.4.RELEASE
M2_HOME = C:\ProgramData\chocolatey\lib\maven\apache-maven-3.5.0
JAVA_HOME = C:\Program Files\Java\jdk1.8.0_161
OS = Windows_NT
COMPUTERNAME = KRAKATAU
CATALINA_HOME = C:\tools\apache-tomcat-10.0.11
...

How do I create a beep sound?

package org.kodejava.awt;

import java.awt.*;

public class BeepExample {
    public static void main(String[] args) {
        // This is the way we can send a beep audio out.
        Toolkit.getDefaultToolkit().beep();
    }
}

Using Runtime.exec() method we can do something like the code snippet below to produce beep sound using powershell command.

try {
    Process process = Runtime.getRuntime().exec(
            new String[]{"powershell", "[console]::beep()"});

    int errorCode = process.waitFor();
    int exitValue = process.exitValue();
    System.out.println("errorCode = " + errorCode);
    System.out.println("exitValue = " + exitValue);
} catch (Exception e) {
    throw new RuntimeException(e);
}

We can also execute external command using ProcessBuilder class like the following code snippet:

try {
    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.command("powershell", "[console]::beep()");
    Process process = processBuilder.start();

    int errorCode = process.waitFor();
    int exitValue = process.exitValue();
    System.out.println("errorCode = " + errorCode);
    System.out.println("exitValue = " + exitValue);
} catch (Exception e) {
    throw new RuntimeException(e);
}

How do I sort an array of objects?

In this example we are going to learn how to sort an array of objects. We start by using an array of String objects as can be seen in the code snippet below. We sort the contents of the array using Arrays.sort() method and print the sorted result. It was really simple.

String names[] = {"Bob", "Mallory", "Alice", "Carol"};
Arrays.sort(names);
System.out.println("Names = " + Arrays.toString(names));

Next, we will sort an array of our own object. It is a bit different compared to sorting an array of primitives. The first rule is we need our object to implements the Comparable interface. This interface have one contract we need to implement, the compareTo() contract.

The basic rule of the compareTo() method is to return 0 when objects value are equals, 1 if this object value is greater and -1 if this object value is smaller. In the Person class below we simply call the String object compareTo() method. See the Person class below for more details.

package org.kodejava.util.support;

public class Person implements Comparable<Person> {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public int compareTo(Person person) {
        return this.name.compareTo(person.name);
    }

    public String toString() {
        return name;
    }
}

In the snippet below we create four Person objects. We sort the Person object based on their name using the Arrays.sort() method and print out the array values.

Person persons[] = new Person[4];
persons[0] = new Person("Bob");
persons[1] = new Person("Mallory");
persons[2] = new Person("Alice");
persons[3] = new Person("Carol");
Arrays.sort(persons);
System.out.println("Persons = " + Arrays.toString(persons));

This is the main class where you can run all the snippet above:

package org.kodejava.util;

import org.kodejava.util.support.Person;

import java.util.Arrays;

public class ObjectSortExample {
    public static void main(String[] args) {
        String[] names = {"Bob", "Mallory", "Alice", "Carol"};
        Arrays.sort(names);
        System.out.println("Names = " + Arrays.toString(names));

        Person[] persons = new Person[4];
        persons[0] = new Person("Bob");
        persons[1] = new Person("Mallory");
        persons[2] = new Person("Alice");
        persons[3] = new Person("Carol");
        Arrays.sort(persons);
        System.out.println("Persons = " + Arrays.toString(persons));
    }
}

This snippet will print the following output:

Names = [Alice, Bob, Carol, Mallory]
Persons = [Alice, Bob, Carol, Mallory]