No history yet

Java Code Conventions

Structuring Your Project

Before you write a single line of Java, it helps to have a place for everything. A standard project structure is like having a well-organized filing cabinet. You know exactly where to find your source code, your tests, and other resources. This consistency is a lifesaver, especially when you start working with others or use build tools like Maven or Gradle.

Most Java projects follow a directory structure that looks something like this:

my-project/
├── pom.xml         // Or build.gradle for Gradle projects
└── src/
    ├── main/
    │   ├── java/     // Your main application source code goes here
    │   │   └── com/
    │   │       └── mycompany/
    │   │           └── app/
    │   │               └── App.java
    │   └── resources/  // Non-code files like configuration or images
    └── test/
        ├── java/     // Your test code goes here
        │   └── com/
        │       └── mycompany/
        │           └── app/
        │               └── AppTest.java
        └── resources/  // Files needed only for testing

The key takeaway is the separation between main and test code. Your application logic lives in src/main/java, while the code you write to test it lives in src/test/java. This clean separation keeps your project tidy and makes it clear what's part of the final application and what's for development and quality assurance.

Naming Things Right

There's a famous saying in programming: "There are only two hard things in Computer Science: cache invalidation and naming things." While we can't help with the first one today, we can definitely help with the second. Good naming conventions make your code easier to read and understand at a glance.

When it comes to naming variables, methods, functions, and classes in programming, adhering to naming conventions is crucial for code readability and maintainability.

Java has a set of widely accepted naming conventions, which mostly revolve around different uses of capitalization. Here’s a quick guide:

ElementConventionExample
ClassUpperCamelCasepublic class SavingsAccount { ... }
InterfaceUpperCamelCasepublic interface List { ... }
MethodlowerCamelCasevoid calculateInterest() { ... }
VariablelowerCamelCasedouble accountBalance;
ConstantUPPER_SNAKE_CASEstatic final int MAX_USERS = 100;

Let’s see these conventions in action in a small class. Notice how the naming style immediately tells you what each piece of the code is.

// Class name uses UpperCamelCase
public class Car {

    // Constant uses UPPER_SNAKE_CASE
    public static final int MAX_SPEED = 120;

    // Variable name uses lowerCamelCase
    private int currentSpeed;

    // Method name uses lowerCamelCase
    public void accelerate(int amount) {
        // Logic goes here
    }
}

Formatting for Clarity

Consistent code formatting is like using proper grammar and punctuation in an essay. It doesn't change what you're saying, but it makes it much easier for others to read and understand. When code is formatted neatly, your brain can focus on the logic instead of trying to untangle a visual mess.

The goal is to make the code look like it was written by a single, very careful person.

Here are a few core guidelines:

  • Indentation: Use 4 spaces for each level of indentation. Most code editors can be configured to insert 4 spaces when you press the Tab key.

  • Braces: For classes, methods, and control structures, place the opening brace ({) at the end of the same line, and the closing brace (}) on its own line.

  • Line Length: Keep lines from getting too long. A good rule of thumb is to stay under 120 characters. This prevents horizontal scrolling and makes code easier to read on different screen sizes.

Consider this poorly formatted code:

public class Example{public static void main(String[] args){
int x=10;if(x>5){System.out.println("x is greater than 5");}else{
System.out.println("x is not greater than 5");}}}

It’s hard to follow. Now, here is the same code with standard Java formatting:

public class Example {
    public static void main(String[] args) {
        int x = 10;

        if (x > 5) {
            System.out.println("x is greater than 5");
        } else {
            System.out.println("x is not greater than 5");
        }
    }
}

The second version is instantly more readable. Luckily, you don't have to do this all by hand. Modern Integrated Development Environments (IDEs) like IntelliJ IDEA, Eclipse, and VS Code have powerful tools to automatically format your code for you with a simple keyboard shortcut.

Quiz Questions 1/6

In a standard Java project structure, where does the main application source code typically reside?

Quiz Questions 2/6

According to standard Java naming conventions, which of the following is the correct way to name a class?

Adopting these conventions will make your code more professional, readable, and easier for you and others to maintain in the long run.