We can use JVM arguments to limit the memory allocated for JVM heap etc.
I would like to know whether we can hard coded these values inside the java program during the development time, instead of adding JVM arguments in the command line when we run the program. Is it possible?
My first question should be, why are you setting it at all? The server JVM sets the maximum to 1/4 of the main memory size and this is reasonable for most applications. You could change this by building you own JVM or you could create an alias like
alias java="java -Xmx30g"
What you can do is check the memory usage periodically and kill the process if you use more. This is a very bad idea of course.
Instead what you can do is run the program again with the same arguments but with the maximum heap size you want. I.e. you can Runtime.exec.
You cant change it as it reserves the maximum memory size on start up.
BTW There is a common misconception that the heap is the only memory which matters. This is not true as the JVM, the threads stacks, native memory etc all use some memory so you cans et the heap to be 100 MB but the JVM could be using 300 MB.