I’m sure I’ve made some sort of extremely stupid mistake here.
I’ve got this code:
private static String generateRAM()
{
final long RAM_TOTAL = Runtime.getRuntime().totalMemory();
final long RAM_FREE = Runtime.getRuntime().freeMemory();
final long RAM_USED = RAM_TOTAL - RAM_FREE;
final long RAM_TOTAL_MB = RAM_TOTAL / 8 / 1024;
final long RAM_FREE_MB = RAM_FREE / 8 / 1024;
final long RAM_USED_MB = RAM_USED / 8 / 1024;
final double RAM_USED_PERCENTAGE = (RAM_USED / RAM_TOTAL) * 100;
return RAM_TOTAL_MB + "MB TOTAL / " + RAM_FREE_MB + "MB FREE / " + RAM_USED_MB + "MB USED (" + RAM_USED_PERCENTAGE + "%)";
}
This returns:
15440MB TOTAL / 11809MB FREE / 3630MB USED (0.0%)
The percentage is obviously incorrect.
How does this happen?
I am, to the best of my knowledge, doing all my maths right.
If I punch the given numbers into a calculator and find the percentage myself I get 23.5, my expected result.
I’m sure I’ve just made a horrible mistake that I’ll kick myself for, could anybody enlighten me?
Change this line
To
This is because Java is interpreting the result as a
long/longdivision, so the result will be alongvalue i.e. 5 / 10 => 0. By applying a factor of 1.0 of any of the operands, the compiler will do adouble/longoperation, that will result in adoublevalue.