Atom256-1 Atom256-1 - 1 year ago 55
Java Question

When declaring a variable with an equation, what happens to the memory allocation?

I was wondering if declaring a variable with an equation will recall the equation every time I'll use the variable or just the result of the equation.

For example, I have a variable that is defined as the area of a circle of radius


double radius = 0.5d;
double pi = 3.1415926535d;
double area = Math.pow(radius,2)*pi;

Will the area be defined as
or as 0.78539816337? In other words, will the computer do the calculations every time or only once and reuse that value?

If this writing forces the computer to repeat the calculations, how could I improve it? (The code will be doing billions of operations using variables declared like that)

Answer Source

It'll be calculated only once. Let's say you want to use area in the next line, so your code looks like:

double radius = 0.5d;
double pi = 3.1415926535d;
double area = Math.pow(radius,2)*pi;
double x = area;

Now let's examine the bytecode:

public static void main(java.lang.String[]);
      0: ldc2_w         #2          // double 0.5d
      3: dstore_1
      4: ldc2_w         #4          // double 3.1415926535d
      7: dstore_3
      8: dload_1
      9: ldc2_w         #6          // double 2.0d
      12: invokestatic  #8         // Method java/lang/Math.pow:(DD)D
      15: dload_3
      16: dmul
      17: dstore        5
      19: dload         5
      21: dstore        7
      23: return

The value of area is stored in the line:

17: dstore        5

and when you want to use the variable area, it's simply loaded and not recalculated:

19: dload         5
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download