Skip to main content
Logo image

Java, Java, Java: Object-Oriented Problem Solving, 2024E

Section A.2 Indentation and White Space

The use of indentation and white space helps to improve the readability of the program. White space refers to the use of blank lines and blank space in a program. It should be used to separate one program element from another, with the goal being to draw attention to the important elements of the program.
  • Use a blank line to separate method definitions and to separate a class’s instance variables from its methods.
  • Use blank spaces within expressions and statements to enhance their readability.
  • Be consistent in the way you use white space in your program.
Code should be indented in a way that shows the logical structure of the program. You should use a consistent number of spaces as the size of the indentation tab. The Java Language Specification recommends four spaces.
In general, indentation should represent the contained in relationships within the program. For example, a class definition contains declarations for instance variables and definitions of methods. The declarations and definitions should be indented by the same amount throughout the class definition. The statements contained in the body of a method definition should be indented:
public void instanceMethod() {
    System.out.println("Hello");
    return;}
An if statement contains an if clause and an else clause, which should be indented:
if (condition)
    System.out.println("If part");   // If clause
else
    System.out.println("Else part"); // Else clause
The statements contained in the body of a loop should be indented:
for (int k = 0; k < 100; k++) {
    System.out.println("Hello " + 'k'); // Loop body}
Finally, indentation should be used whenever a statement or expression is too long to fit on a single line. Generally, lines should be no longer than 80 characters.
You have attempted of activities on this page.