Your question is so generic that any answer will be vague. You will probably get much better answers if you can be more specific.
On what occasion we set the system properties in our code?
This is like asking "when should we use the + operator". The answer, not too surprisingly, is "only when you need to".
System properties let you configure parts of the Java runtime (or your application server, etc) to do things differently. When you find an issue and it turns out the correct solution to the problem is to configure the Java runtime to modify its behaviour, that's when you need to find whether there is a system property. If there is, you need to set it to a value that gets you the behaviour your want.
How do we determine the Key? i.e. How we will know what exact string we should give for Key?
Through documentation, really. Lets say you run into a problem whre foo.bar()
doesn't do what you think it would. Or it breaks in a case that's important to you. You should read the documentation for foo.bar()
. It might say that you can change the behaviour by setting a system property. Then you set that system property to the value mentioned in the documentation.
Watch out: some system properties can not be set at all. Or rather, you can set them, but changing them after your program has started (main(string[])
has been called) has no effect.
I have this little snippet I use to see all the currently set system properties and their values. Helps with exploration and getting some ideas:
final String SEPARATOR = "=";
Properties properties = System.getProperties();
for (Object property : properties.keySet()) {
String prop = (String) property;
System.out.println(prop + SEPARATOR + properties.getProperty(prop));
}