Search code examples
javawhile-loopconventions

Where to put braces in Java While loop?


I understand that Java ignores indentation and that curly-brace hierarchies are recommended to increase readability of code. I come from Python with decent experience and I am learning Java right now. I am completely new to Java and I don't yet know the "Good Coding Practice" that comes with writing while loops.

Here are 2 ways to create a basic while loop:

while ( booleanCondition = true ) {
    // do stuff
}

And the second way:

while (booleanCondition = true )
{
// do stuff
}

I am not one for splitting hairs over the number of lines of code, so the fact that the first loop is one line shorter is irrelevant to me. Personally, I like the second better because the loop is left-justified with only the condition on the top line. However, I don't want to start using this format if it is not recommended for Good Practice. Is the first way to do the while loop more/less recommended? What is the most common format if there is one?


Solution

  • Java conventions prescribe the first method.

    7.6 while Statements

    A while statement should have the following form:

    while (condition) {
        statements; 
    }
    

    This is also the most commonly used one.

    enter image description here

    But in the end, it's up to yourself. Just keep it consistent within the project.