Java Standards and Conventions for this Course

This document contains a few of the common standards and conventions used in the Java programming language. You should follow these standards for this course. Marks are allotted for following proper coding standards/style/conventions on every assignment.

A more extensive list and description of Java programming standards is available at the Sun website, and it is recommended that you view these, also: Code Conventions for the Java Programming Language

Other recommended reading: Clean Code by Robert C. Martin. You can read this book for free on the Safari Online Books resource available on the Sheridan Library web site! Contact your professor if you need help getting access to this book. Every serious programmer should read this book after their first or second programming course.

Naming Conventions

Naming conventions for elements of the Java language should be followed to improve readability. Some languages include special prefixes that are prepended to variable and object names to identify the types of data or object. Java does not follow this standard, however other standards are used that are just as applicable.

Primitive and Object Variables

Variables that are defined as primitives or objects share the same naming conventions:

  • The variable name is self-documenting (its name should be a clear indication of what the variable contains)
  • The variable name starts with a lower case letter
  • If the variable name contains 2 or more words, the second and subsequent words start with a capital letter

Some examples: courseCode, totalSales, counter, empFirstName, myHouseInfo

Classes

Names of classes always start with a capital letter. This helps to differentiate between classes and variables in your code. Also, if the class name contains more than one word, each word in the class name should start with a captial letter.

Examples: System, Employee, ContractEmployee, MyWinnieThePoohDish

Methods

Method names follow the same rules as variable names. There are additional conventions for special methods such as Accessor methods and Constructor methods.

Accessor & Mutator Methods

Accessor methods always start with "get", or "is", depending on the data type of for that instance variable. Accessors usually start with "get", except for boolean instance variables, whose accessor methods always start with "is". Mutator methods begin with "set". After the "get", "set", or "is", the rest of the method name should be the data member name, camel-cased. For example, a mutator metohd for an object's firstName attribute should be called setFirstName() and it's accessor method should be called getFirstName().

Constructor Methods

Constructor methods are always given the name of the class. Therefore, since a class name always starts with a captial letter, the Constructor method also starts with a capital letter, and follows all other rules of naming classes.

Packages

The standard for package naming is to use the domain name backwards (for more info see Packages on Terminal Learning).

For assignments, you must use the package naming structure:

sheridanc.username.assignX

Where username is your Sheridan username and assignX is the name of your assignment. For example:

sheridanc.djarind.assign1

All package names must follow industry standard and syntax rules (e.g. all lower-case letters).

Code

Coding standards, as with other programming languages make your code easier to read. Other programmers are going to be reading your Java code, and you will have to read the code of other programmers. Both of these will be made easier if you follow proper standards such as indentation and spacing.

Indentation

Indentation in Java code is just as important as it is with other languages. You will find your Java code much easier to read and debug if you use proper indentation. The amount of indentation you use should be 4 spaces, according to the Java standard.

Indentation in Java code occurs in the following cases:

  • Inside each class definition
  • Inside each method definition
  • The body of an if statement, switch conditional, or similar structure
  • The body of any kind of loop
  • The body of a block
  • When extending a statement over multiple lines (the second and subsequent lines should be indented).

Check the example below for more detail.

Line Length

Industry standard for Java programs state that the length of a line should not exceed 80 characters.

If a statement is longer than 80 characters, break that statement up over multiple lines. The second and subsequent lines must be indented.

Example:

System.out.println("This is a very, very, very, very, "
    + "very, very, very, very, very, very, "
    + "very, very, long line of code.");

Note in the above example that if you have to break your long line in the middle of a String literal, you close the quotes, put the concatenation operator on the next line, then re-open the quotes and continue your String literal.

There are some other rules about breaking long lines such as:

  • Break a long line after a comma, not before.
  • Break a long line before an operator, so that the operator goes on the next line.
  • Don't break a long line before an opening parenthesis of a method: keep the parenthesis on the line and break at the next opportunity (or earlier).

Use end-of-line comments only if the total number of characters in the line, including the comment, is 80 characters or less. If your comment makes the line longer than 80 characters, place the comment above the statement, instead.

Most editors allow to to add a margin marker at a specific column to help you see where the 80 character mark is.

Spacing

Spacing in Java code also increases readability. Typically a space is left before class and method definitions, and before a comment line. You should also space related groups of statements (including variable declarations) together where appropriate. See the example below for more detail.

Exception to the rule regarding a blank line above a method header: When you start putting documentation like JavaDocs above your method to describe what your method does, you don't need the blank line. You just need to make sure there's a blank line above the line the comments start on!

Here is an example of a class (signatures only) and the indentation and spacing used:

import java.util.*;
import java.text.*;

public class IndentExample {

    private int anInstanceVar;
    private String anotherInstanceVar;

    public int someMethod(double anArgument) {

        // some code here
    }

    public static void main(String [] args) {

        // some more code here
    }

}

Braces

Braces in Java code are used to identify blocks of statements. A left brace { starts a block and a right brace } closes a block. Blocks of statements are used in the following cases:

Remember that variables declared inside a block are local to that block only.

Examples of blocks:

// class example
public class Employee {
    // class definition: inside a class block
}

// method example
public static void main(String[] args) {  // main() block
    
    // if stmt example
    if (val - 2 > 0) { // the if block
        // body of if statement
    } else { // the else block
        // body of if statement
    }
}

Brace Style

Brace style defines where you decide to put the opening brace of a block. There are two standard styles:

Either style is acceptable. Pick one and stick with it consistently.

Documentation

Documentation should be concise, complete, and written in your own words. Use proper spelling and grammar!! There's nothing less professional in your code than bad spelling/grammar in your documentation! :P

Documentation should not necessarily describe WHAT your code is doing, but WHY. When you say something like:

// iterating through an array
for (int i: numbers) {
    sum += i;
}

No kidding...? I can tell by the code that you're iterating through an array. Tell me why! This is better:

// getting the sum of array elements so we can calc the average
for (int i: numbers) {
    sum += i;
}

DO NOT document the ends of long lines like this:

System.out.printf("The interest is $%.2f.%n", investment * Math.pow((1 + rate)/100, years));   // calculates and displays the interest earned

Those kinds of statements are almost impossible to read in any standard editor!

It's better to place the comment above the line, like this:

// calculates and displays the interest earned
System.out.printf("The interest is $%.2f.%n", investment * Math.pow((1 + rate)/100, years));

If you want to use end-of-line comments, use them on short lines, such as variable/constant declarations:

double investment = 1000; // investment amount
int years = 10;           // number of years
double rate = .025;       // interest rate

If an end-of-line comment causes the line to be longer than 80 characters (including the comment), place the comment above the line instead.

Document each statement or related groups of statements by describing how the code applies to the logic of your program, and/or why you wrote those lines of code. You can use multi-line or single-line comments, whichever you're most comfortable with.

Examples

/* Name:  Sydney Greenstreet
 * Assignment:  Question 6
 * Program: Systems Analyst

 * Calculates pay for employees. Some employees work overtime and
 * are therefore paid for overtime hours.  Hours worked are 
 * entered by the user.
 */

import java.util.Scanner;

public class DoubleIfs6 {
    
    // constants for rates of pay
    public final static double REG_RATE = 10;
    public final static double OT_RATE = 15;

    // constant for overtime limit
    public final static double OT_HOURS = 40;
    
    public static void main(String[] args) {

        // create scanner for user input
        Scanner in = new Scanner(System.in);
        
        // need number of hours from user
        System.out.print("Enter number of hours worked: ");
        double hours = in.nextDouble();

        double pay = 0; // must be outside of ifs
        
        // if hours worked is under overtime limit
        // then pay using the regular rate
        if (hours <= OT_HOURS) {
            pay = hours * REG_RATE;

        // otherwise, if they worked overtime, calculate pay
        // using the overtime formula:
        } else {

           // pay regular rate for regular hours and overtime
           // rate for overtime hours
            pay = OT_HOURS * REG_RATE + (hours - OT_HOURS)
                * OT_RATE;
        }

        // show the total pay
        System.out.printf("Total Pay: $%.2f%n", pay);
    }
}

Another example:

/* Name:  Sydney GreenStreet
 * Assignment:  Question 2
 * Program: Systems Analyst

 * Displays a table of Fahrenheit to Celsius conversions based on
 * user input for the starting and ending value of the table.
 */

import java.util.Scanner;

public class Question2FahToCel {
    
    public static void main(String[] args) {

        // create scanner for user input
        Scanner in = new Scanner(System.in);
        
        // user specifies start value and end value
        System.out.print("Enter start value: ");
        int start = in.nextInt();
        System.out.print("Enter end value: ");
        int end = in.nextInt();
        
        // some column headings
        System.out.println("Fah.      Cel.");
        System.out.println("----------------");
        
        /* if the start value is larger than the end value
           then print the table from highest to lowest */
        if (start > end) {

            // displaying a table with each temperature
            for (int i = start; i >= end; i--) {

                // standard celsius formula
                double cel = (5.0 / 9.0) * (i - 32);

                // a row contains both fah. and cel. temperature
                System.out.printf("%5.1f %8.1f%n", (double)i,
                                  cel);
            }
        } else {  // start value must be lower: print from low to high
            
            // use a loop to display a table of temp conversions
            for (int i = start; i <= end; i++) {

                // standard celsius formula
                double cel = (5.0 / 9.0) * (i - 32);
                
                // a row contains both fah. and cel. temperature
                System.out.printf("%5.1f %8.1f%n", (double)i,
                                  cel);
            }
        }
    }
}

An example with methods:

/* Name:  Sydney GreenStreet
 * Assignment:  Question 3 with methods
 * Program: Systems Analyst

 * Calculate and display area and circumference of a circle
 * using methods.
 */

import java.util.Scanner;

public class Question3Circle {

    public static void main(String[] args) {
        
        // scanner for user input
        Scanner in = new Scanner(System.in);

        // user supplies the radius
        System.out.print("Enter radius: ");
        double radius = in.nextDouble();
        
        // circumference and area of circle
        double circumference = getCircumference(radius);
        double area = getArea(radius);
        
        // output needs to be formatted
        System.out.printf("Circumference: %.2f%nArea: %.2f",
            circumference, area);
    }
    
    /* Calculates and returns the circumference of a circle
     * with a specific radius.
     */
    public static double getCircumference(double rad) {

        // circle circumference 2PIradius
        return 2 * Math.PI * rad;
    }
    
    /* Calculates and returns the area of a circle with
     * a specific radius.
     */
    public static double getArea(double rad) {

        // circle area PI r^2
        return Math.PI * Math.pow(rad, 2);
    }
}