Structured Programming   «Prev  Next»
Lesson 9 Comments and indentation
ObjectiveUse comments and indentation.

Cmments and Indentation (Java Code)


Most source code consists not only of instructions to be executed by the computer, but also comments to be read by programmers. Comments are a form of documentation used to clarify source code to a human reader of the source code. Comments can consist of anything the programmer likes, but typical comments include information such as:
  1. Who wrote the code
  2. When it was written
  3. Modification history
  4. What the code does

For short comments in Java you typically use //. Here is an example:
// This is a short comment

The Java compiler ignores everything appearing after // to the end of the line.
For comments that span multiple lines you can use // at the beginning of each line, or you can enclose the comments between /* and */.
Here's an example of the latter approach:
/* This is a 
comment that 
spans multiple 
lines */

Java Compiler

The Java compiler ignores everything appearing between /* and */. The programs you will be working on in this course are simple enough so that comments are not really necessary, but you are encouraged to use a few comments in your code anyway. It's a good habit to get into, and you may be surprised at how helpful they are when you return to your code after a lengthy absence.


Indentation[1] is used within Java programs to improve the readability of the source code. Consider the following program named Beatles that displays some lyrics from the Beatles' song "A Hard Day's Night." Move your mouse cursor over the source code to see a description of how indentation is used in this program.
Code Description
Code Description

The use of indentation is not required by the Java compiler, but it is strongly encouraged. Not only does it improve the readability of your code, but it also helps you avoid simple syntax errors such as a missing "}".
The next lesson concludes your introduction to writing programs using the Java programming language.

[1]Indentation: Used to improve readability of source code.