Java Style Guide
While some programming languages share style characteristics, it’s still important to follow each language’s formatting conventions. We’ll give you an overview of the more common topics, but if you’re looking for something specific, Google compiled a good style guide.
Naming Conventions
As a rule, Java uses camel case (eg. camelCase
) for most names, including variables and methods. However, there are some variations depending on what you are naming.
Class and Interface names use pascal case (eg. PascalCase
), which is like camel case, except they start with a capital letter. For example, the linked list class is named LinkedList
, not linkedList
.
Constants do not use camel case, and instead use snake case (eg. snake_case
) with all uppercase letters. For example, if you wanted to store the constant pi, you could name it VALUE_OF_PI
.
Brackets and Parentheses
Brackets ({
and }
) must be used for all method and class declarations, as well as conditionals and loops that contain multiple lines of code.
While you can omit brackets for single line conditionals and loops, it’s best practice to use them for readability. For example,
if (true) {return false;}
is much more readable than
if truereturn false;
Along the same lines, parentheses ((
and )
) should be used for the arguments of the conditional or loop, as seen in the example above.
Indentations and Spacing
While the amount of whitespace doesn’t affect the compilation and running of code in Java, there are standards that help with readability.
All indentations should be two spaces, and there should be an indentation each time a new block (eg. loop, method, etc) is opened, as seen in the examples above.
There should be spaces before and after keywords and operators. For example, while
x=3;
is valid syntax, placing a space between each side of the operator keeps the code clear and readable:
x = 3;
Author
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full team