A java program block starts with an open brace ({) and ends with a closing brace (}), right?

370    Asked by KunalJha in Java , Asked on Oct 10, 2022

Should curly braces be on their own line or not? What do you think about it?

if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
or should it be
if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
or even
if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();

Please be constructive! Explain why, share experiences, back it up with facts and references.


Answered by Kylie Hamilton

When I was a student I used to put curly braces on the same line, so that there are fewer lines, and the code gets printed on fewer pages. Looking at a single bracket character printed as the only thing in a line is annoying. (environment,paper wastage)


So coming to your question - a java program block starts with an open brace ({) and ends with a closing brace (}), right?

But when coding large applications, allowing some lines with only braces in them is affordable, considering the 'grouping' feeling it gives.

Whichever style you choose, be consistent so that it does not become an overhead for your own brain to process multiple styles in related pieces of code. In different scenarios (like above) I would say it is okay to use different styles, it's easier to 'switch context' at a high level.



Your Answer

Interviews

Parent Categories