Skip to main content
Engineering LibreTexts

9.7: Formatting Code

  • Page ID
    17636
  • In Java programs, some spaces are required. For example, you need at least one space between words, so this program is not legal:

    publicclassGoodbye {
    
        publicstaticvoidmain(String[] args) {
            System.out.print("Goodbye, ");
            System.out.println("cruel world");
        }
    }
    

    But most other spaces are optional. For example, this program is legal:

    public class Goodbye {
    public static void main(String[] args) {
    System.out.print("Goodbye, ");
    System.out.println("cruel world");
    }
    }
    

    The newlines are optional, too. So we could just write:

    public class Goodbye { public static void main(String[] args) { System.out.print("Goodbye, "); System.out.println ("cruel world");}}
    

    It still works, but the program is getting harder and harder to read. Newlines and spaces are important for organizing your program visually, making it easier to understand the program and find errors when they occur.

    Many editors will automatically format source code with consistent indenting and line breaks. For example, in DrJava (see Appendix A) you can indent the code by selecting all text (Ctrl+A) and pressing the Tab key.

    Organizations that do a lot of software development usually have strict guidelines on how to format source code. For example, Google publishes its Java coding standards for use in open-source projects: http://google.github.io/styleguide/javaguide.html.

    You might not understand these guidelines now, because they refer to language features we haven’t yet seen. But you might want to refer back to them periodically as you read this book.