Tips & Tricks

How to Format Java Code

Just about every developer has an opinion on the formatting of Java code! With IntelliJ IDEA, your team can define its own standards and have the IDE apply them automatically so individual developers don’t have to think about formatting their code as they work.

Download IntelliJ IDEA

While coding with IntelliJ IDEA, we don’t need to manually format our code, as the IDE does it automatically. For example, if we press Enter (Windows/Linux) or (macOS), the caret goes into the correct place for us to start typing. The same is true if we use other shortcuts like Shift+Enter (Windows/Linux) or ⇧⏎ (macOS) to move to the next line, or if we use code generation.

Creating a new line in IntelliJ IDEA, preserving the code structure

If we copy some code that is inconsistently formatted and paste it into the editor, IntelliJ IDEA will format the code according to the project’s standards.

Reformatting Code

However, if we do have code that doesn’t meet the project’s standards, we can ask IntelliJ IDEA to format it.

    public void horriblyFormattedMethod  (){
        System.out.println("First line");
            System.out.println("Second line");
          System.out.println("Third line");
        for (int i = 0; i < 3; i++)
        System.out.println("I have no idea where the indentation is supposed to be");
    }

Highlight a specific piece of code, like the code above, and press Ctrl+Alt+L (Windows/Linux) or⌥⌘L (macOS) to format just the highlighted code. Or we can use this same shortcut without selecting the code and the whole file will be reformatted.

Automatically reformat Java code in IntelliJ IDEA

We can go to Preferences/Settings | Code Style | Java and set our standards. From there, we can also copy the default code style settings and save them with a useful name.

Code Style copy to project

If we want to specify that if statements should always have curly braces, we go into Wrapping and Braces and force if statements to always have curly braces. The preview on the right shows what selecting this setting will do to the code, so we can experiment with these settings to see which one we want.

Force braces for if statement in Java Code Style

If we save changes to the code style, IntelliJ IDEA will reformat it to the new style.

There are a lot of code style settings to look through and change. There is a simpler way, if we have a section of code that we know needs reformatting differently.

public void horriblyFormattedMethod() {
    System.out.println("First line");
    System.out.println("Second line");
    System.out.println("Third line");
    for (int i = 0; i < 3; i++)
        System.out.println("I have no idea where the indentation is supposed to be");
}

For example, if we want for loops to also have curly braces, we can highlight a for loop, press Alt+Enter (Windows/Linux) or ⌥⏎ (macOS), and select Adjust code style settings. IntelliJ IDEA will display only the settings that apply to this bit of code.

Adjust code style setting

We can experiment with these settings and see the changes previewed live in our code. Under ‘for()’ statement in the Wrapping and Braces tab, we set Force braces to Always so IntelliJ IDEA will always insert curly braces around the body of our for loops. When we save these changes, they will be saved to our current Code Style scheme.

Force braces for statement result

Often we don’t want to reformat the whole file. If we were working on a file with some inconsistently formatted code, but we’ve only changed a small part of it, running Reformat Code might change parts of the file we haven’t touched. We could highlight the code we’ve changed and just reformat that, but that won’t work if our changes are scattered throughout the file.

There’s a better way: we can use Ctrl+Alt+Shift+L (Windows/Linux) or ⌥⇧⌘L (macOS), to bring up the reformatting options. We can say we only want to format the lines of the file that have been changed, and leave everything else alone. Now when the file is formatted, it only changes the lines that we’ve touched and nothing else.

Reformat File changes scope: Only changes uncommitted to VCS

Example: Formatting Java 8 Streams

Let’s walk through setting specific formatting for use with Java 8 Streams. We’ll change the settings so that Stream operations are always on a separate line, and they are lined up underneath each other.

Let’s assume the current code style settings allow the chained method calls on the Streams API to stay on the same line, making an extremely long line of code.

private int replaceWithMapToInt() {
    int sum = integerStringMap.values().stream().filter(Objects::nonNull).flatMap(Collection::stream).filter(stringVal -> stringVal.contains("error")).mapToInt(String::length).sum();
    return sum;
}

Highlight the stream all and use Alt+Enter (Windows/Linux) or ⌥⏎ (macOS) to see which settings can be changed for this code. Under the Wrapping and Braces tab, change the wrapping settings for Chained method calls to Wrap always. We can try out these different settings to see which combination we want, the changes are previewed in the editor.

Adjust Code Style Setting: Java Wrapping and Braces to Wrap always

This is a good first step towards what we want, but we want the dots to all line up vertically. To do this, we need to go back into our code style settings Preferences/Settings | Code Style | Java.

Go to the Wrapping and Braces tab, and find Chained method calls. This should already be set to Wrap always since we just set that. We also need to tick Align when multiline. The preview should show us this is what we wanted.

Java Code Style: Wrapping and Braces > Chained method calls > Align when multiline

Save this change to the code style settings, and then reformat the file – the stream call should be aligned the way we wanted.

private int replaceWithMapToInt() {
    int sum = integerStringMap.values()
                                .stream()
                                .filter(Objects::nonNull)
                                .flatMap(Collection::stream)
                                .filter(stringVal -> stringVal.contains("error"))
                                .mapToInt(String::length)
                                .sum();
    return sum;
}

Using EditorConfig

These formatting settings are stored in a settings file in the project’s .idea folder. IntelliJ IDEA also supports using an EditorConfig file to define the code style. You can create a new EditorConfig file by right-clicking on the .idea folder and then selecting New | New EditorConfig File. This will be our root, add the standard EditorConfig properties and IntelliJ IDEA-specific settings for Java code.

New EditorConfig File setting

IntelliJ IDEA populates this file with all the settings that we’ve already defined for our code style. The properties are split into those which apply to all files, and those which apply only to Java files. Anything with an ij prefix is a setting specific to IntelliJ IDEA. If we look through all these settings, we can see the ones we’ve just defined for Java 8 streams: that we want chained method calls to be aligned; that we want chained method calls to be wrapped with one operation on each line.

Copy the Stream method call code:

public class Foo {
    public int[] X = new int[]{1, 3, 5, 7, 9, 11};
	
	int count = integerStringMap.values()
                                .stream()
                                .filter(Objects::nonNull)
                                .flatMap(Collection::stream)
                                .filter(stringVal -> stringVal.contains("error"))
                                .mapToInt(String::length)
                                .sum();
    return sum;
}

and paste it into the preview panel for the editor config. Then we can see what happens to our code when we make changes to the EditorConfig properties.

Turn off the chained method calls wrapping by setting ij_java_method_call_chain_wrap to off (note that IntelliJ IDEA gives us code completion here).

EditorConfig file changes preview

Set ij_java_keep_line_breaks to false. The preview shows us the Stream call is put back onto a single line.

If we go back to our code and reformat it, we can see IntelliJ IDEA uses the new EditorConfig settings to format the changed lines in the file. Note that our EditorConfig settings are used instead of the settings we defined in our Java Code Style preferences, which still has our old settings for Chained Method Calls. If we look at the Code Style Settings, we can see that EditorConfig support is enabled, and that this setting warns us the EditorConfig file settings may override the IDE settings.

Java Code Style enable EditorConfig support

One of the advantages of using an EditorConfig file is that we can define a file for each directory. This is useful if we have different code settings for test code and production code, or if a legacy part of the code base has a different style.

Rearranging Code

We’ve seen how to reformat our code, how to change the settings for code style, including using an EditorConfig file to store the settings, and how reformatting can even do small code changes like adding braces. Let’s look now at one of the options mentioned in the reformat file settings – Rearrange Code.

Open a class with a lot of methods and fields declared in it, like this one.

public class RearrangeCode {
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    private String firstName;

    public String getFirstName() {
        return firstName;
    }

    @Override
    public String toString() {
        return "RearrangeCode{" +
                "id=" + id +
                ", firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", email='" + email + '\'' +
                ", ordersById=" + ordersById +
                '}';
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    private void privateHelperMethod() {
        // does something in here
    }

    private String lastName;

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    private String email;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        RearrangeCode that = (RearrangeCode) o;
        return id == that.id &&
                Objects.equals(firstName, that.firstName) &&
                Objects.equals(lastName, that.lastName) &&
                Objects.equals(email, that.email) &&
                Objects.equals(ordersById, that.ordersById);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, firstName, lastName, email, ordersById);
    }

    private Collection<Order> ordersById;

    public Collection<Order> getOrdersById() {
        return ordersById;
    }

    public void setOrdersById(Collection<Order> ordersById) {
        this.ordersById = ordersById;
    }
}

This class has fields, setters, getters, and other standard methods, all scattered throughout the file. Use Find Action (Shift+Ctrl+A or ⇧⌘A), and start typing “rearrange” to find the Rearrange Code action. Select this and IntelliJ IDEA will reorder the code of this class according to the settings for the project.

Rearrange code changes preview
View via Local History

We can see all the fields are placed at the top of the file and the getters and setters for a field are placed next to each other. This definitely helps to see at a glance what’s included in the state of an instance of this class. However, we might want to go further in organising the code in a class. For example, we might want to put private methods to the bottom of the class, underneath all the public ones.

Open up Preferences/Settings. Once again, we need to be in Code Style | Java, but this time we need to look under the Arrangement tab. There are some standard rules which can be turned on or off, like keeping the getters and setters together. The bottom section shows all the rules for arranging the file. By default, fields will be ordered according to the modifiers that apply to them, and they’ll always be at the top of the file. Initialisers and constructors will come after the fields, methods come after that, and if there are any inner enums, interfaces or classes, they’ll be put at the bottom of the file.

Let’s make the existing method rule apply to public methods and then add a new rule for private ones. These rules will cause the public methods to appear above the private ones.

Arrange order for methods

We could use Find Action (Shift+Ctrl+A or ⇧⌘A) again to rearrange the file, or reformat the file and tick the rearrange code option. But we can also use Search Everywhere (Shift+Shift or ⇧⇧) and type “rearrange”. Once we’ve called the rearrange code action, we’ll see that our private method has been moved to the bottom of the file, underneath all the public methods.

Code Arrange for methods applied (example)

IntelliJ IDEA offers a lot of automation and configuration features that let us define exactly how our files should be formatted, and it even lets us specify the order in which things appear in our code files. This lets us customize a consistent style for our project and makes it easier to write code that’s consistent with that of the rest of our team.

This blog post covers the same material as the video. This provides an easy way for people to skim the content quickly if they prefer reading to watching, and to give the reader/watcher code samples and links to additional information.

See also:

image description