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. Below is an explanation of the basic parts.
1 2 3 4 5 6 7 8 |
// FirstProgram.java
// Michael Maus, 25 August 2004
// This is the smallest program. It does NOTHING.
public class FirstProgram {
public static void main(String[] args) {
}
}
|
Every program you write should have some identifying information at the front. This is information for the human reader -- comments are ignored by the compiler. As your instructor, I want to see the name of the program or file (FirstProgram.java) on the first line. You must include your name and the date. And finally, a (at least) one-line description should be included.
Comments can be written in any of three styles (//, /*...*/, and /**...*/). I recommend the // style because it's most commonly used. Everything from the // 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.
.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 8.
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 like this. Like a class, the
body of the method is enclosed between left and right braces.
This body is empty. It does nothing.