A Java program is like an outline. With an outline, you can organize thoughts and ideas, help people see forests instead of trees, and generally show that you’re a member of the Tidy Persons Club. The program in the listing starts with a big header line that says, “Here comes a class named Displayer.” After that first big header, a subheader announces, “Here comes a method named main.”
Now, if a Java program is like an outline, why doesn’t a program look like an outline? What takes the place of the Roman numerals, capital letters, and other things? The answer is twofold:
In a Java program, curly braces enclose meaningful units of code.
You, the programmer, can (and should) indent lines so that other programmers can see the outline form of your code at a glance.
In an outline, everything is subordinate to the item in Roman numeral I. In a Java program, everything is subordinate to the top line — the line with class in it. To indicate that everything else in the code is subordinate to this class line, you use curly braces. Everything else in the code goes inside these curly braces.
public class Displayer { public static void main(String args[]) { System.out.println("You'll love Java!"); } }
In an outline, some stuff is subordinate to a capital letter A item. In a Java program, some lines are subordinate to the method header. To indicate that something is subordinate to a method header, you use curly braces.
public class Displayer { <b>public static void main(String args[]) { </b> System.out.println("You'll love Java!"); <b>} </b> }
In an outline, some items are at the bottom of the food chain. In the Displayer class, the corresponding line is the line that begins with System.out.println. Accordingly, this System.out.println line goes inside all the other curly braces and is indented more than any other line.
Never lose sight of the fact that a Java program is, first and foremost, an outline.
If you put curly braces in the wrong places or omit curly braces where the braces should be, your program probably won’t work at all. If your program works, it’ll probably work incorrectly.
If you don’t indent lines of code in an informative manner, your program will still work correctly, but neither you nor any other programmer will be able to figure out what you were thinking when you wrote the code.
If you’re a visual thinker, you can picture outlines of Java programs in your head. You might visualize an actual numbered outline morphing into a Java program. See this figure.
Another person might use more bizarre imagery. See this figure.
Failing to indent your Java code is inexcusable. In fact, many Java IDEs have tools to indent your code automatically.