{"id":27969,"date":"2020-06-03T08:00:38","date_gmt":"2020-06-03T08:00:38","guid":{"rendered":"https:\/\/blog.jetbrains.com\/idea\/?p=21994"},"modified":"2024-06-06T10:26:00","modified_gmt":"2024-06-06T09:26:00","slug":"code-formatting","status":"publish","type":"idea","link":"https:\/\/blog.jetbrains.com\/en\/idea\/2020\/06\/code-formatting","title":{"rendered":"How to Format Java Code"},"content":{"rendered":"<p>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\u2019t have to think about formatting their code as they work.<\/p>\n<p><!--more--><\/p>\n<p style=\"text-align: center;\"><a class=\"jb-download-button\" href=\"https:\/\/jb.gg\/button-idea-download\" target=\"_blank\" rel=\"noopener\">Download IntelliJ IDEA<\/a><\/p>\n<p>While coding with IntelliJ IDEA, we don\u2019t need to manually format our code, as the IDE does it automatically. For example, if we press <i>Enter<\/i> (Windows\/Linux) or <b><i>\u23ce<\/i><\/b> (macOS), the caret goes into the correct place for us to start typing. The same is true if we use other shortcuts like <i>Shift+Enter<\/i> (Windows\/Linux) or <i>\u21e7\u23ce<\/i> (macOS) to move to the next line, or if we use code generation.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone  wp-image-480496\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2020\/06\/new-line.gif\" alt=\"Creating a new line in IntelliJ IDEA, preserving the code structure\" width=\"750\" height=\"300\" \/><\/p>\n<p>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\u2019s standards.<\/p>\n<h2>Reformatting Code<\/h2>\n<p>However, if we do have code that doesn&#8217;t meet the project&#8217;s standards, we can ask IntelliJ IDEA to format it.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-title=\"\">    public void horriblyFormattedMethod  (){\n        System.out.println(&quot;First line&quot;);\n            System.out.println(&quot;Second line&quot;);\n          System.out.println(&quot;Third line&quot;);\n        for (int i = 0; i &lt; 3; i++)\n        System.out.println(&quot;I have no idea where the indentation is supposed to be&quot;);\n    }\n<\/pre>\n<p>Highlight a specific piece of code, like the code above, and press <i>Ctrl+Alt+L<\/i> (Windows\/Linux) or<i>\u2325\u2318L<\/i> (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.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone  wp-image-480507\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2020\/06\/format-code.gif\" alt=\"Automatically reformat Java code in IntelliJ IDEA\" width=\"750\" height=\"300\" \/><\/p>\n<p>We can go to <i>Preferences\/Settings<\/i> | <i>Code Style<\/i> | <i>Java<\/i> and set our standards. From there, we can also copy the default code style settings and save them with a useful name.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone  wp-image-480518\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2020\/06\/copy-schema.png\" alt=\"Code Style copy to project\" width=\"750\" height=\"300\" \/><\/p>\n<p>If we want to specify that <code>if<\/code> statements should always have curly braces, we go into <i>Wrapping and Braces<\/i> and force <code>if<\/code> 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.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone  wp-image-480529\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2020\/06\/force-if.gif\" alt=\"Force braces for if statement in Java Code Style\" width=\"750\" height=\"300\" \/><\/p>\n<p>If we save changes to the code style, IntelliJ IDEA will reformat it to the new style.<\/p>\n<p>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.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-title=\"\">public void horriblyFormattedMethod() {\n    System.out.println(&quot;First line&quot;);\n    System.out.println(&quot;Second line&quot;);\n    System.out.println(&quot;Third line&quot;);\n    for (int i = 0; i &lt; 3; i++)\n        System.out.println(&quot;I have no idea where the indentation is supposed to be&quot;);\n}<\/pre>\n<p>For example, if we want <code>for<\/code> loops to also have curly braces, we can highlight a <code>for<\/code> loop, press <i>Alt+Enter<\/i> (Windows\/Linux) or <i>\u2325\u23ce<\/i> (macOS), and select <i>Adjust code style settings<\/i>. IntelliJ IDEA will display only the settings that apply to this bit of code.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone  wp-image-480540\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2020\/06\/adjust-code-styling.png\" alt=\"Adjust code style setting\" width=\"750\" height=\"300\" \/><\/p>\n<p>We can experiment with these settings and see the changes previewed live in our code. Under \u2018<i>for()\u2019 statement<\/i> in the <i>Wrapping and Braces<\/i> tab, we set <i>Force braces<\/i> to <i>Always<\/i> so IntelliJ IDEA will always insert curly braces around the body of our <code>for<\/code> loops. When we save these changes, they will be saved to our current Code Style scheme.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone  wp-image-480551\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2020\/06\/force-for.png\" alt=\"Force braces for statement result\" width=\"750\" height=\"300\" \/><\/p>\n<p>Often we don&#8217;t want to reformat the whole file. If we were working on a file with some inconsistently formatted code, but we&#8217;ve only changed a small part of it, running <em>Reformat Code<\/em> might change parts of the file we haven&#8217;t touched. We could highlight the code we&#8217;ve changed and just reformat that, but that won&#8217;t work if our changes are scattered throughout the file.<\/p>\n<p>There&#8217;s a better way: we can use <i>Ctrl+Alt+Shift+L<\/i> (Windows\/Linux) or <i>\u2325\u21e7\u2318L<\/i> (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&#8217;ve touched and nothing else.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone  wp-image-480562\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2020\/06\/reformat-file-settings.png\" alt=\"Reformat File changes scope: Only changes uncommitted to VCS\" width=\"750\" height=\"300\" \/><\/p>\n<h3>Example: Formatting Java 8 Streams<\/h3>\n<p>Let&#8217;s walk through setting specific formatting for use with Java 8 Streams. We&#8217;ll change the settings so that Stream operations are always on a separate line, and they are lined up underneath each other.<\/p>\n<p>Let&#8217;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.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-title=\"\">private int replaceWithMapToInt() {\n    int sum = integerStringMap.values().stream().filter(Objects::nonNull).flatMap(Collection::stream).filter(stringVal -&gt; stringVal.contains(&quot;error&quot;)).mapToInt(String::length).sum();\n    return sum;\n}\n<\/pre>\n<p>Highlight the stream all and use <i>Alt+Enter<\/i> (Windows\/Linux) or <i>\u2325\u23ce<\/i> (macOS) to see which settings can be changed for this code. Under the <i>Wrapping and Braces<\/i> tab, change the wrapping settings for <i>Chained method calls<\/i> to <i>Wrap always<\/i>. We can try out these different settings to see which combination we want, the changes are previewed in the editor.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone  wp-image-480573\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2020\/06\/adjust-code-styling-dots.png\" alt=\"Adjust Code Style Setting: Java Wrapping and Braces to Wrap always\" width=\"750\" height=\"300\" \/><\/p>\n<p>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 <i>Preferences\/Settings<\/i> | <i>Code Style<\/i> | <i>Java<\/i>.<\/p>\n<p>Go to the <i>Wrapping and Braces<\/i> tab, and find <i>Chained method calls<\/i>. This should already be set to <i>Wrap always<\/i> since we just set that. We also need to tick <i>Align when multiline<\/i>. The preview should show us this is what we wanted.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone  wp-image-480584\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2020\/06\/adjust-code-styling-aligned-dots.gif\" alt=\"Java Code Style: Wrapping and Braces &gt; Chained method calls &gt; Align when multiline\" width=\"750\" height=\"300\" \/><\/p>\n<p>Save this change to the code style settings, and then reformat the file &#8211; the stream call should be aligned the way we wanted.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-title=\"\">private int replaceWithMapToInt() {\n    int sum = integerStringMap.values()\n                                .stream()\n                                .filter(Objects::nonNull)\n                                .flatMap(Collection::stream)\n                                .filter(stringVal -&gt; stringVal.contains(&quot;error&quot;))\n                                .mapToInt(String::length)\n                                .sum();\n    return sum;\n}\n<\/pre>\n<h2>Using EditorConfig<\/h2>\n<p>These formatting settings are stored in a settings file in the project\u2019s <code>.idea<\/code> folder. IntelliJ IDEA also supports using an <code>EditorConfig<\/code> file to define the code style. You can create a new <code>EditorConfig<\/code> file by right-clicking on the <code>.idea<\/code> folder and then selecting <i>New<\/i> | <i>New EditorConfig File<\/i>. This will be our root, add the standard EditorConfig properties and IntelliJ IDEA-specific settings for Java code.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\" wp-image-480595 aligncenter\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2020\/06\/EditorConfig.png\" alt=\"New EditorConfig File setting\" width=\"395\" height=\"461\" \/><\/p>\n<p>IntelliJ IDEA populates this file with all the settings that we&#8217;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 <code>ij<\/code> prefix is a setting specific to IntelliJ IDEA. If we look through all these settings, we can see the ones we&#8217;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.<\/p>\n<p>Copy the Stream method call code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-title=\"\">public class Foo {\n    public int[] X = new int[]{1, 3, 5, 7, 9, 11};\n\t\n\tint count = integerStringMap.values()\n                                .stream()\n                                .filter(Objects::nonNull)\n                                .flatMap(Collection::stream)\n                                .filter(stringVal -&gt; stringVal.contains(&quot;error&quot;))\n                                .mapToInt(String::length)\n                                .sum();\n    return sum;\n}\n<\/pre>\n<p>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.<\/p>\n<p>Turn off the chained method calls wrapping by setting <code>ij_java_method_call_chain_wrap<\/code> to <code>off<\/code> (note that IntelliJ IDEA gives us code completion here).<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone  wp-image-480606\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2020\/06\/editor-config-changes.gif\" alt=\"EditorConfig file changes preview\" width=\"750\" height=\"199\" \/><\/p>\n<p>Set <code>ij_java_keep_line_breaks<\/code> to <code>false<\/code>. The preview shows us the Stream call is put back onto a single line.<\/p>\n<p>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 <i>Java Code Style<\/i> preferences, which still has our old settings for <i>Chained Method Calls<\/i>. If we look at the <i>Code Style<\/i> Settings, we can see that EditorConfig support is enabled, and that this setting warns us the <code>EditorConfig<\/code> file settings may override the IDE settings.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone  wp-image-480617\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2020\/06\/code-style-editor-config.png\" alt=\"Java Code Style enable EditorConfig support\" width=\"750\" height=\"401\" \/><\/p>\n<p>One of the advantages of using an <code>EditorConfig<\/code> 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.<\/p>\n<h2>Rearranging Code<\/h2>\n<p>We&#8217;ve seen how to reformat our code, how to change the settings for code style, including using an <code>EditorConfig<\/code> file to store the settings, and how reformatting can even do small code changes like adding braces. Let&#8217;s look now at one of the options mentioned in the reformat file settings \u2013 Rearrange Code.<\/p>\n<p>Open a class with a lot of methods and fields declared in it, <a href=\"https:\/\/github.com\/JetBrains\/intellij-samples\/blob\/master\/standard-java\/src\/main\/java\/com\/jetbrains\/code\/RearrangeCode.java\" target=\"_blank\" rel=\"noopener\">like this one<\/a>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-title=\"\">public class RearrangeCode {\n    private int id;\n\n    public int getId() {\n        return id;\n    }\n\n    public void setId(int id) {\n        this.id = id;\n    }\n\n    private String firstName;\n\n    public String getFirstName() {\n        return firstName;\n    }\n\n    @Override\n    public String toString() {\n        return &quot;RearrangeCode{&quot; +\n                &quot;id=&quot; + id +\n                &quot;, firstName=&#039;&quot; + firstName + &#039;\\&#039;&#039; +\n                &quot;, lastName=&#039;&quot; + lastName + &#039;\\&#039;&#039; +\n                &quot;, email=&#039;&quot; + email + &#039;\\&#039;&#039; +\n                &quot;, ordersById=&quot; + ordersById +\n                &#039;}&#039;;\n    }\n\n    public void setFirstName(String firstName) {\n        this.firstName = firstName;\n    }\n\n    private void privateHelperMethod() {\n        \/\/ does something in here\n    }\n\n    private String lastName;\n\n    public String getLastName() {\n        return lastName;\n    }\n\n    public void setLastName(String lastName) {\n        this.lastName = lastName;\n    }\n\n    private String email;\n\n    public String getEmail() {\n        return email;\n    }\n\n    public void setEmail(String email) {\n        this.email = email;\n    }\n\n    @Override\n    public boolean equals(Object o) {\n        if (this == o) return true;\n        if (o == null || getClass() != o.getClass()) return false;\n        RearrangeCode that = (RearrangeCode) o;\n        return id == that.id &amp;&amp;\n                Objects.equals(firstName, that.firstName) &amp;&amp;\n                Objects.equals(lastName, that.lastName) &amp;&amp;\n                Objects.equals(email, that.email) &amp;&amp;\n                Objects.equals(ordersById, that.ordersById);\n    }\n\n    @Override\n    public int hashCode() {\n        return Objects.hash(id, firstName, lastName, email, ordersById);\n    }\n\n    private Collection&lt;Order&gt; ordersById;\n\n    public Collection&lt;Order&gt; getOrdersById() {\n        return ordersById;\n    }\n\n    public void setOrdersById(Collection&lt;Order&gt; ordersById) {\n        this.ordersById = ordersById;\n    }\n}<\/pre>\n<p>This class has fields, setters, getters, and other standard methods, all scattered throughout the file. Use <i>Find Action<\/i> (<i>Shift+Ctrl+A<\/i> or <i>\u21e7\u2318A<\/i>), and start typing &#8220;rearrange&#8221; to find the <em>Rearrange Code<\/em> action. Select this and IntelliJ IDEA will reorder the code of this class according to the settings for the project.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone  wp-image-480639\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2020\/06\/Code-reformat.png\" alt=\"Rearrange code changes preview\" width=\"751\" height=\"447\" \/><br \/>\n<em>View via Local History<\/em><\/p>\n<p>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&#8217;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.<\/p>\n<p>Open up <i>Preferences\/Settings<\/i>. Once again, we need to be in <i>Code Style<\/i> | <i>Java<\/i>, but this time we need to look under the <i>Arrangement<\/i> 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&#8217;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&#8217;ll be put at the bottom of the file.<\/p>\n<p>Let\u2019s 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.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone  wp-image-480654\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2020\/06\/code-arrange.png\" alt=\"Arrange order for methods\" width=\"751\" height=\"481\" \/><\/p>\n<p>We could use <i>Find Action<\/i> (<i>Shift+Ctrl+A<\/i> or <i>\u21e7\u2318A<\/i>) again to rearrange the file, or reformat the file and tick the rearrange code option. But we can also use <i>Search Everywhere<\/i> (<i>Shift+Shift<\/i> or <i>\u21e7\u21e7<\/i>) and type &#8220;rearrange&#8221;. Once we&#8217;ve called the rearrange code action, we&#8217;ll see that our private method has been moved to the bottom of the file, underneath all the public methods.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone  wp-image-480671\" src=\"https:\/\/blog.jetbrains.com\/wp-content\/uploads\/2020\/06\/code-arrange-change.png\" alt=\"Code Arrange for methods applied (example)\" width=\"751\" height=\"269\" \/><\/p>\n<p>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\u2019s consistent with that of the rest of our team.<\/p>\n<p><iframe loading=\"lazy\" src=\"https:\/\/www.youtube.com\/embed\/vjVWjocENLg\" width=\"560\" height=\"315\" frameborder=\"0\" allowfullscreen=\"allowfullscreen\" data-mce-fragment=\"1\"><\/iframe><\/p>\n<p><em>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.<\/em><\/p>\n<p>See also:<\/p>\n<ul>\n<li><a href=\"https:\/\/www.jetbrains.com\/help\/idea\/reformat-and-rearrange-code.html#\" target=\"_blank\" rel=\"noopener\">Reformat and Rearrange Code<\/a><\/li>\n<li><a href=\"https:\/\/blog.jetbrains.com\/idea\/2020\/04\/tips-for-writing-code-in-intellij-idea\/\">Tips for Writing Code in IntelliJ IDEA<\/a><\/li>\n<\/ul>\n","protected":false},"author":360,"featured_media":27972,"comment_status":"open","ping_status":"open","template":"","categories":[601],"tags":[2923,155,3057],"cross-post-tag":[],"acf":[],"_links":{"self":[{"href":"https:\/\/blog.jetbrains.com\/en\/wp-json\/wp\/v2\/idea\/27969"}],"collection":[{"href":"https:\/\/blog.jetbrains.com\/en\/wp-json\/wp\/v2\/idea"}],"about":[{"href":"https:\/\/blog.jetbrains.com\/en\/wp-json\/wp\/v2\/types\/idea"}],"author":[{"embeddable":true,"href":"https:\/\/blog.jetbrains.com\/en\/wp-json\/wp\/v2\/users\/360"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.jetbrains.com\/en\/wp-json\/wp\/v2\/comments?post=27969"}],"version-history":[{"count":5,"href":"https:\/\/blog.jetbrains.com\/en\/wp-json\/wp\/v2\/idea\/27969\/revisions"}],"predecessor-version":[{"id":481024,"href":"https:\/\/blog.jetbrains.com\/en\/wp-json\/wp\/v2\/idea\/27969\/revisions\/481024"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.jetbrains.com\/en\/wp-json\/wp\/v2\/media\/27972"}],"wp:attachment":[{"href":"https:\/\/blog.jetbrains.com\/en\/wp-json\/wp\/v2\/media?parent=27969"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.jetbrains.com\/en\/wp-json\/wp\/v2\/categories?post=27969"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.jetbrains.com\/en\/wp-json\/wp\/v2\/tags?post=27969"},{"taxonomy":"cross-post-tag","embeddable":true,"href":"https:\/\/blog.jetbrains.com\/en\/wp-json\/wp\/v2\/cross-post-tag?post=27969"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}