sebastiandaschner blog


Java code style operator new line formatting

monday, february 19, 2018

Last week, I discovered what helped me deciding on what I have struggled with for a longer time: whether to place operators such as &&, || or + on the same or next line.

When constructing boolean expressions or concatinating Strings, we might need to break long lines. According to the Google Java Style Guide, the break should come “before the symbol”, therefore:

String veryLong = "This is an example of a very, very, very, very, very, very, "
        + "very, very long String";

boolean found = strings.stream()
        .anyMatch(s -> s.startsWith("foo"));

if (someLogic() && someOtherLogic() && someMoreComplexLogic()
        || found)
    // ...

As you can see in this example, the +, || and also . operators are placed on the new line, before the next symbol. The exceptions to the rules are assignment operators, open parenthesis, commas, and lambda arrows.

I think this guide is consistent, makes sense and solves my problem to think about which one to go with over and over again ;-)

 

Found the post useful? Subscribe to my newsletter for more free content, tips and tricks on IT & Java: