Atom256-1 - 7 months ago 37

Java Question

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

`radius`

`double radius = 0.5d;`

double pi = 3.1415926535d;

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

Will the area be defined as

`pi*radius^2`

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

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[]);
Code:
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
```

Source (Stackoverflow)