In this case, the constructs are largely interchangeable, but I think that the while if while loop is useful in some cases, for example, if some variables need to be saved through all iterations of the loop, but not needed if the loop never runs. (And it is assumed that this may not be so.) For example
if (condition) { LargeComplexObject object = new LargeComplexObject(); do { some action ... object.someMethod(); ... more actions } while (condition); }
This can be a useful optimization if the initialization of this object depends on time or memory, and it is expected that this cycle will be run only occasionally and will be skipped in most cases of the corresponding method. Of course, there are other cases where this can be useful, basically, I think if-do-while should be used if there are things that should be done before the loop starts, only when your loop is introduced.
source share