Prev: none | Next: Dialog Box Output
Here is just about the smallest legal program you can write. It starts up, does nothing, and stops. Programs that actually do something will build on this basic structure.
1 2 3 4 5 6 7 8 9 10 11 12 |
// Description: This is the smallest program. It does NOTHING. // File: doNothing/FirstProgram.java // Author: Michael Maus // Date: 29 Jan 2005 public class FirstProgram { public static void main(String[] args) { // If the program did anything, it would go here. } } |
Every program should have some identifying information at the front. This is information for the human reader -- comments are ignored by the compiler. This is some information I like to see: what the program is/does, the directory/file it's in (doNothng/FirstProgram.java), the author's name, and date. The exact formatting and other requirements vary, depending on your instructor or organization.
Comments can be written in any of three styles (//, /*...*/, and /**...*/). I recommend the // style for all you comments to begin with. Everything from // to the end of the line is ignored by the compiler.
public class
or just class
(the difference
at this point is irrelevant). Then you must name your class (here it is
"FirstProgram").
.java
"
extension.Everything in the class is written between curly braces, {}
.
The left brace is written at the end of the class declaration line here, and the
matching right brace that ends the class declaration is on line 12.
main
method.
A method is a named group of instructions for doing something.
You may define additional methods of your own, but you must write a
main method with a first line that looks exactly like this. Like a class, the
body of the method is enclosed between left and right braces.
This body is empty. It does nothing.
Indentation. You will notice that everything inside of braces for the class and main method is indented (space at the front). For every set of braces, the indentation should be increased one level. Typically each indentation level consists of 4 spaces.