The programs we have been looking at have all looked like this. The parts in red pick out the only things that have changed from one program to the next.
// Print out an expression class ProgramName { static public void main (String[] args) { System.out.println ("expression"); } }
This is about as simple as a Java program can be. However, Java wasn't specifically designed for beginners, so even though it is very simple, it still has some advanced features in it. Here's an explanation, even though it may not make much sense until later.
The program is an application, which is Java jargon for a complete stand-alone program (i.e. not an applet or servlet, which are program fragments designed to run as part of a Web browser or Web server).
The comment at the top explains what the program does and, if necessary, how
to use it, for the benefit of human readers. All Java code lives inside
classes, which group code and data together into program components.
A simple program has a single class inside a single file, and the class name,
e.g. Hello, must match the file name, e.g. Hello.java.
Curly brackets { and } mark the beginning and end of
the class.
A program must include a method called main where
the program starts. A method is Java jargon for a procedure or function. The
result type must be void which means that main
doesn't return a result. The argument to main must always be a
string array (containing any command line arguments). This particular program
ignores any command line arguments which are passed to it. Curly brackets
{ and } mark the beginning and end of the method.
The main method must be declared as public and
static, unlike most methods. Declaring it as public
makes it officially visible outside the current directory, so the
java command has access to it as the starting point for the program.
Declaring main as static means that it is a
stand-alone method which can be called without reference to a current object
(and there are no objects in existence when the program starts).
The program writes out its result using System.out.println.
Using println rather than print adds a newline to the
output. You will probably use System.out.println a lot, at least
before writing graphics programs. The long name means: go to the
System class and find the static out variable which
represents console output, and call println on this. (If you
don't like the long name, you can create a local method which abbreviates
it.)