Link Search Menu Expand Document

Java Conventions

Table of Contents

  1. Curly Braces
  2. Indentation
  3. Long Lines & Wrapping
  4. Spacing
    1. Spacing Between Methods
  5. Printing
  6. Naming
    1. Naming Conventions
    2. Descriptive Names

Java syntax is writing code in a way that allows it to compile. Conventions are things that don't affect whether the code will compile, but are just generally accepted as part of writing good Java code, and are things that you should adhere to ensure you are writing good, readable code.

Curly Braces

In Java, curly braces are used to compartmentalize blocks of code. Lots of languages use curly braces, and Java has its a convention for how to use them. An opening curly brace should be placed at the end of the line that opened it. The closing curly brace should be on a line by itself at the same level of indentation as the line with the opening curly brace, only if that brace terminates a statement or terminates the body of a method, constructor, or class. For example, there is no line break after the brace if it is followed by else.

public class HelloWorld {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            if (i % 2 == 0) {
                System.out.println("Hello World!");
            } else {
                System.out.println("Goodbye World!");
            }
        }
    }
}

Indentation

Indentation is an important way to help distinguish blocks of code. You should indent your program one tab further every time you open a curly brace { and indent one tab less every time you close a curly brace }.

A tab should generally be 3 or 4 spaces, and you can set the size of your tab in your compiler. The jGrasp default is 3 spaces

Take these two examples:

Bad
This method has no indentation, and is super hard to read as a result.
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
System.out.println("Hello world!");
}
}
}
Good
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        System.out.println("Hello world");
    }
}
}

Indentation makes code easier to read. It helps the reader see what code is nested where, and where structures like if statements and loops start and end.

If you're working in jGRASP, you can actually have jGRASP fix all your indentation for you! To the right of the Undo button is the Generate CSD button, which will automatically indent your code and add some structural annotations on your code, which can be removed with the next button to the right, the Remove CSD button.

Long Lines & Wrapping

To keep our code nice and compact and improve readability, lines of code should ideally max out at 80 characters, and should never exceed 100 characters in length. Lines that are too long should be broken up and wrapped to the next line.

Note that in jGrasp, you can check your line length by putting your cursor at the end of the line and check the bottom right corner. There should be something that says "Col:"" and then the number of characters in the line.

To break up a long comment, you can simply split the comment into two or more lines:

// THIS IS A BAD COMMENT
// this is a bad comment because it is just so gosh darn long that it just makes it so hard to read

// THIS IS A GOOD COMMENT
// this is a good comment because when it reaches the point where it is too long,
// the comment just moves to the next line

Breaking up lines of code is a little more complicated. Choosing where to break up your lines can be a little arbitrary, but it's usually best to break the line after things like commas and operators. IMPORTANT: You cannot break a String up between lines. If you want to break a String up, you need to use two separate Strings that are concatenated. There are two conventions for wrapping a line of code:

  1. You can leave a hanging indent of two tabs relative to the start of the first line, like so:
    // Because the String to be printed is so long, it gets wrapped to the next line
    public static void printReallyLongLine() {
     System.out.println("wow this line is so long it's like unreasonably long like" +
             "honestly it's so long why even");
    }
    
  2. Or, if the long line has something in parentheses, like a method header, you can align the code inside the parentheses, like so:
    public static void thisMethodHeaderIsReallyLong(int thing, int otherThing,
                                                 int moreThings, int anotherThing)
    

Note that these are very bad method and variable names, and you should not use these as an example. These are just examples of long lines.

Spacing

It might seem trivial, but maintaining good spacing throughout your program helps your code be more readable for human eyes. Most Java programmers follow the below spacing conventions for their programs:

codegood spacingbad spacing
class headerpublic class GoodSpacing {public class BadSpacing{
method headerpublic void method(int param, int param2) {public void method (int param,int param2){
method callmethod(7, 2, "string");method(7,2,"string");
for loopfor (int i = 0; i < 5; i++) {for(int i=0;i<5;i++){
while loopwhile (test) {while(test){
array initializationint[] arr = new int[5];int [] arr=new int [5];
variable initializationsint x = -5 * j + y % 2;int x=-5*j+y%2;

Note the spacing in expressions. Generally, you should always leave a space on either side of an operator (+, -, =, etc.). The only exceptions are ++, --, and using - to express negative numbers (i.e. -5 ).

Spacing Between Methods

Similar to spacing within lines of code, we want to ensure that we have spacing in the structure of our code to keep our code looking readable. You should always include a blank line between methods to make sure your code is easy to read through.

public class GoodSpacing {
    public static void main(String[] args) {
        ...
    }

    public static void method() {
        ...
    }

    public static void anotherMethod() {
        ...
    }
}

Printing

There are a few basic rules you should follow for printing in Java:

  • You should always print a blank line using System.out.println(). Printing an empty String (System.out.println("")) is considered bad style; it makes the intention to print a blank line less clear.
  • \n should never be used in print or println statements. In general, you shouldn't need to use \n in CSE 142.
  • Rather than have a bunch of adjacent print statements, you should combine them into one where you can.System.out.println("**") is much preferred to System.out.print("**"); System.out.println();. If this results in lines of code that are too long, you should see the section on long lines and wrapping; it is not acceptable to split prints into multiple statements because they are too long.

Naming

Naming Conventions

We have certain conventions for how we name things in Java. Here are the casing conventions we use for different kinds of names in Java:

Method & Variable Names
These should be camelCased, a convention where the first letter of every word after the first is uppercased.
Class Names
These should be PascalCased, a subset of camel casing where the first letter of the first word is also uppercased.
Constant Names
These should be SCREAMING_CASED, in all uppercase with words separated by underscores.

Descriptive Names

The name of a variable should describe the value it stores and what it represents. Similarly, the name of a method should describe the task of the method. As a general rule of thumb, class and variable names should be nouns, and method names should be verbs. Abbreviations should not be used unless they are generally accepted abbreviations or very obvious, like num for number. It's usually best to avoid abbreviations. Only the following one-letter variable names should be used:

  • Graphics g & Random r: These are okay only for these objects only because they're common Java conventions. Note that this only applies to these specific names; it does not extrapolate to naming other objects.
  • x and y (for coordinates): These are what we actually call Cartesian coordinates, so they're actually great variable names for this purpose (but, again, only for coordinates). Similarly, r is a good variable name for describing Polar coordinates (unfortunately there's no theta key, but if you can get the θ character it's also acceptable for a polar coordinate (a little more work than it's probably worth)).
  • Loop variable names: We use i-j-k for loop variable names because it is general programmer convention for for loops. i should be used for outer-loops, j for once-nested loops, k for twice nested loops, etc. Generally, if we use i-j-k convention for loop varaible names, we don't want to mix them with descriptive loop variable names. Descriptive loop variable names are okay, as is using i-j-k convention, but we want be consistent with one or the other. i-j-k convention should be used like this:
for (int i = 0; i < 10; i++) {
    for (int j = 0; j < i; j++) {
        for (int k = i; k > j; k++) {
            System.out.print("*");
        }
        System.out.print("+");
    }
    System.out.println();
    for (int j = 0; j < i; j++) {
        System.out.print("#");
    }
    System.out.println();
}