How to set an environment variable in Java using exec?

There are overloaded exec methods in which you can include an array of environment variables. For example exec(String command, String[] envp).

Here's an example (with proof) of setting an env variable in a child process you exec:

public static void main(String[] args) throws IOException {

    String[] command = { "cmd", "/C", "echo FOO: %FOO%" };
    String[] envp = { "FOO=false" };

    Process p = Runtime.getRuntime().exec(command, envp);
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String s = reader.readLine();
    System.err.println(s);
}

However, that sets the variable in the env of the created process, not of your current (Java) process.

Similarly, if you are creating a process from Ant (as you mention in comments to aix) using the exec task, then you can pass environment variables to the child process using nested env elements, e.g.

<exec executable="whatever">
   <env key="FOO" value="false"/>
</exec>

This won't work. When you start a new process, that process receives a copy of the environment. Any changes it then makes to environment variables are made within that copy, and at no point will become visible to the caller.

What are you actually trying to achieve?