Java conventions

From wikinotes


Documentation

google conventions https://google.github.io/styleguide/javaguide.html
oracle conventions https://www.oracle.com/technetwork/java/codeconventions-135099.html

Package

//      {    prefix   }.{ package }
package com.willpittman.helloworld   // (inverted url) http://helloworld.willpittman.com

There are two components to a packagename, the prefix, and the rest.


Prefix: com.willpittman

  • Must be all lowercase/ASCII
  • Must refer to domain that control (name.com, name.net, name.org, ...)
  • Is an inverted url (a.com -> com.a)

Package: mypackage

  • Must be lowercase/ASCII
  • Should contain single main class
  • should match name of main class


Module

  • named after top-level-class, matching case (one-per-file)
  • statement order (one blank line between each)
    • license
    • package
    • imports (no wildcard imports)

Brackets/Lines/Misc

  • 100-ch limit
  • indent 2-spaces
  • continuation-indent at least 4-spaces
  • 1-vertical space between each class member (more allowed, but not encouraged)

Classes

class Raster
class ImageSprite
  • nouns
  • pascal-case

Interfaces

interface Animal
  • same rules as classes
  • some styleguides request prefix of 'I' to indicate is interface

Methods

class Animal {
    public void quack ();
    public void walk ();
    public void walkSlowly();
}
  • verbs
  • camelcase
  • lowercase first letter

Constant Variables

static final int MIN_WIDTH = 4;
static final int MAX_WIDTH = 999;
static final int GET_THE_CPU = 1;
  • uppercase
  • separated by underscores

Variables

int    i;
char   c;
float  myWidth;
  • camelcase
  • should not start with underscore or dollar sign (unclear if this is all variables)