Q:

System.getenv() returns null when super user

If I run echo $XDG_CURRENT_DESKTOP and sudo echo $XDG_CURRENT_DESKTOP in Ubuntu, I get Unity in both cases. If I in Java write System.getenv("XDG_CURRENT_DESKTOP"), it returns Unity when I run the program without super user privileges but it returns null when I run it with sudo. What is going on here?
public class GetEnv {
        public static void main(String[] args) {
                System.out.println(System.getenv("XDG_CURRENT_DESKTOP"));
        }
}

This is the output:
$ echo $XDG_CURRENT_DESKTOP
$ Unity
$ sudo echo $XDG_CURRENT_DESKTOP
$ Unity
$ javac GetEnv.java
$ java GetEnv
$ Unity
$ sudo java GetEnv
$ null

A:

Because your sudo is wrong.
sudo echo $XDG_CURRENT_DESKTOP

will be expanded to
sudo echo Unity

before executing it as root.
If you want to preserve the setting from the user running sudo you need to define the environment variable which should be preserved in the sudo configuration.
Defaults:suboptimal    env_keep += "XGD_CURRENT_DESKTOP", !requiretty
suboptimal    your_host=NOPASSWD: /user/bin/java

then you could run your command as
sudo java GetEnv

which should show you the setting of the calling user. In your case Unity.

