Programming Example 2: Java Style

Introduction

This program illustrates the basic style guidelines for a Java program. Students will be expected to follow these style guidelines in every program that they write during the semester. Almost every software development organization requires its programmers to follow some style guidelines. It makes it much easier for other programmers to read and understand your code.

Basic Style Elements

As you read through this example, look for the following style elements:

  1. Identifiers: Identifiers should have some semantic meaning. When you read a name, you should have some sense of what it refers to. Avoid single character names or very short names whose meaning is ambiguous.
  2. Variable names: When naming a variable use all lower case. If the name of the variable is composed of two or more words, capitalize the first letter in any words that follow the first. Run the words together, don't use any spaces.
  3. Constant names: When naming a constant, use all upper case letters. If the name is made up of multiple words, use the underscore character to separate the words.
  4. Curly Braces: Place the opening curly brace "{" so that it lines up with the left edge of the class, method, or control statement that it goes with. Place the closing curly brace "}" in the same column as the opening curly brace.
  5. Indentation: When you start a block of code with an opening curly brace, indent all of the code that follows the opening curly brace at least three spaces.
  6. Spaces: The Java compiler ignores spaces, but using spaces liberally can make your code much more readable. For example, always put spaces around binary operators, like "+"
  7. Blank lines: Inserting blank lines between groups of statements makes the code more readable by separating one group of related statements from another.
  8. Magic Numbers: A magic number is any literal value coded into your program, other than 1, -1, and 0. Using magic numbers makes it difficult to maintain your code. To avoid using magic numbers, declare the value that you want to use as a constant, and then use that constant in your program.

This example program is located here.