How do I know the memory size in virtual machine?

If you want to know the free memory and the total memory available in the Java runtime environment then you can use the following code snippet to check.

package org.kodejava.example.lang;

public class MemoryExample {
    public static void main(String[] args) {
        long freeMemory = Runtime.getRuntime().freeMemory();
        long totalMemory = Runtime.getRuntime().totalMemory();

        System.out.println("Free Memory  = " + freeMemory);
        System.out.println("Total Memory = " + totalMemory);
    }
}

Here is the result of the code snippet above:

Free Memory  = 125550264
Total Memory = 128974848

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.example.lang;

import java.io.IOException;

public class RuntimeExec {
    public static void main(String[] args) {
        String command = "explorer.exe";

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

How do I terminate a Java application?

In an application we sometimes want terminate the execution of our application, for instance because it cannot find the required resource.

To terminate it we can use exit(status) method in java.lang.System class or in the java.lang.Runtime class. When terminating an application we need to provide a status code, a non-zero status assigned for any abnormal termination.

package org.kodejava.example.lang;

import java.io.File;

public class AppTerminate {
    public static void main(String[] args) {
        File file = new File("config.xml");

        int errCode = 0;
        if (!file.exists()) {
            errCode = 1;
        } else {
            errCode = 0;
        }

        // When the error code is not zero go terminate
        if (errCode > 0) {
            System.exit(errCode);
        }
    }
}

The call to System.exit(status) is equals to Runtime.getRuntime().exit(status). Actually the System class will delegate the termination process to the Runtime class.