3

I was wondering when you do a calculation in java like this:

float x;
if (x/2f>10f) {}

does it have to do the division every time you run it or during the compilation stage does it inline it with the correct value?

I'm guessing the latter since the value of x can change? Am I making sense? I want to know if it's worth my time to precalculate certain values instead of repeating them or if its already done for me.

As you can tell, I don't have any formal education with programming, I'm just curious about it.

If I'm using the word inlining incorrectly please excuse me, as I haven't attempted C in a long time.

edit: thanks for replying, it seems obvious to me, and i feel silly for asking, that it cant be compile time if the value of x is variable, but what if its initialized and declared as final? because i read that operations on literals are compile time, so how about constants...so...

final float x=1f; if (x/2f>10f) {}

Colby Ray
  • 125
  • 1
  • 8
  • This would always be calculated at runtime. – Zephyr Jul 04 '18 at 05:37
  • The compiler might know you're not setting anything to x. So the if statement will always be true so inline true? – Sam Orozco Jul 04 '18 at 05:42
  • 3
    Possible duplicate of [Are arithmetic operations on literals calculated at compile time or run time?](https://stackoverflow.com/questions/33040680/are-arithmetic-operations-on-literals-calculated-at-compile-time-or-run-time) – ernest_k Jul 04 '18 at 05:56
  • You need to provide more context than that snippet, because at face value that snippet should lead to a compilation error due to x not being initialized. – Mark Rotteveel Jul 04 '18 at 07:18
  • This will lead to a compilation error cause `x` is not initialized. But assuming that it has a fixed value that you won't change from inizialization to the `if` guard your code will be optimized by the compiler cause you don't have any reason to evaluate it more than once if the value `x` doesn't change. – simo-r Jul 04 '18 at 07:36

2 Answers2

1

In the code snipped that you provide, assuming that it's inside a method, "x" is not initialized, this step is checked at compile stage, calculating is done at runtime.

wtsiamruk
  • 339
  • 3
  • 16
  • Your answer is not correct because the compiler will try to evaluate the expression at compile time and optimize it if values in the expression don't change over time. – simo-r Jul 04 '18 at 07:41
0

Since "x" is not initialized. calculation will be done at run-time.