To create a program, Java requires us to define
at least one class. For now
we’re not going to worry much about what exactly is a class. Let’s just think of it as a construct that
contains all our Java statements (our code).
A class must have a name, and since this is our first program will
output a quote from Albert Einstein we’ll call the class EinsteinQuote. Another essential element needed to create
a program is what’s called the main method or main for
short. The main method designates the
starting point of our program’s execution; the first Java statement in main
is the first one to execute, and so forth.
Both the class and main require that we clearly define their
boundaries, and in Java this is done using a set of curly braces, ‘{‘ and ‘}’. These
symbols allow Java to separate groups of statements into what’s called a code
block and are used extensively with many constructs that we’ll
encounter later on. As you might guess
the opening curly brace designates the start of a code block and the closing
brace the end of a block. We’re now
ready to write our first program. Here
we go (you should be typing this in the Editor pane of DrJava
– the top right-hand pane): public
class EinsteinQuote { public
static void main(String[] args) { System.out.println(“The important thing is not to stop questioning.”); System.out.println(“Curiosity has its own reason for existing.”); System.out.println(“ Albert
Einstein.”); } } After typing the code, you should save it into
a Java file (the file must have a .java extension), and the name of the file
must match that of the class. In this
case, the file will be EinsteinQuote.java. Before we can run or execute the program,
we need to compile it. Compilation
is the process of checking for errors and converting Java code into machine
understandable code (remember that computers represent all information as 0’s
and 1’s). We refer to the program that
compiles the code as the compiler. In DrJava we can
invoke the compiler by clicking the Compile button at the top of the window. Any error messages will be displayed at the
bottom tab labeled Compiler Output.
If all goes well and there are no errors, you can click on the Run
button at the top to execute the program.
You can view the output of your program by selecting the Console
tab at the bottom. Let’s go back to all the code we typed in for
our first program. Some of the terms
used (such as static) seem a bit puzzling,
and you’re right to think that. But
these will be more meaningful as we learn more about Java. At this point, our focus should be on the
Java statements inside the main method (the ones between the inner set
of braces). After writing your first few programs all this extra stuff will
be difficult to forget. |