Question

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?

Was it helpful?

Solution 4

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.

OTHER TIPS

Both works. This is actually based more towards the programmer's preference and style.

The second one is better since the bracket should start right below its name. It would be least confusing if you use nested loops or conditions. Anything nested would go one level inner and you would never make mistake of brackets and code would be perfectly readable.

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

In this you perfectly know which bracket is ending where. Every bracket ends right below it and there are no brackets in between. Simple and elegant style of coding.

Two schools of thought:

1) In 1997 Sun published a set of "Coding Conventions" for Java. They specify pretty much everything you can think of when it comes to writing Java code - indentation, variable naming, etc, etc: http://www.oracle.com/technetwork/java/codeconventions-150003.pdf . Follow those rules.

2) Do it however you'd like, but keep it consistent. There's any number of styles, etc out there (See: http://en.wikipedia.org/wiki/Indent_style) - pick one, use it in all files in a project.

It depend on the developer , but basically java doc and IDE prefer the 1st option. Also if the booleanCondition is boolean you dont need to check == with true :

while (booleanCondition) {
    // do stuff
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top