Section 3.1 Your First Java Program
In Subsection 1.7.1 we installed the JDK, which includes not only JShell, but several other tools including the Java compiler program (
javac
) and the program that launches compiled Java programs (java
). Beginning in this section we will start using these tools to compile and launch our Java programs. JShell remains an incredibly useful tool for testing Java expressions and small code snippets. Keep it close.Subsection 3.1.1 A Java Program File
Java programs can be composed of a sequence of the declarations, initializations, and expressions, including those we have studied thus far. There are several additional requirements that must be satisfied before your program will compile.
- Your statements must be written to a file with the proper name and the ".java" extension.
- All statements must be grouped into a named structure called a method.
- This and any other methods defined must be contained within an organizing structure called a class. The name of the class must match the name of the file.
- Unlike JShell, a Java program does not print results to the terminal automatially. Results must be printed explicitly. In Java, the command
System.out.println(…)
may be used to print the results of an expression to the terminal. We’ll need a print statement in order to see results in the terminal.
Let’s say we want to calculate the distance between two points. One point is at the coordinates and the other is at Once computed we want to print the result to the terminal. In order to write a complete Java program that will compile and run, we need to fulfill all the above requirements. The following program satisfies these requirements.
Using your programmer’s editor, create a new file at a known location and enter the text of the following program into that file. Save the program to a file with name
ComputeDistance.java
(satisfying the first requirement). Don’t forget the curly braces ({}
) that enclose the body of the entire class and the nested curly braces that enclose the statements in the main()
method. These are important syntactical elements that must be present. You may leave off the //
and comments to their right.public class ComputeDistance { // 1) Open the class
public static void main(String[] args) { // 2) Start the method
double x1 = 0.0, y1 = 20.0; // Declare and init point 1
double x2 = 30.0, y2 = 0.0; // Declare and init point 2
// Apply distance formula
double distance = Math.sqrt( Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2) );
System.out.println(distance); // 3) Print distance
} // Close the method
} // Close the class
ComputeDistance.java
Subsection 3.1.2 Compiling a Java Program
Once saved, open a terminal on your computer. The terminal will run a shell program automically that let’s you interact with your operating system. Use your shell’s commands to make sure the current working directory is set to the location on your file system where your Java program file is saved.
Different operating systems support a variety of terminal applications and shell programs implementing commands that you can use to interact with your operating system. Choose the terminal and shell that you prefer. Refer tp Appendix B for more information about common shell programs and shell commands.
Into your shell enter the following command, which compiles your Java program.
javac ComputeDistance.java
If you see errors, correct them and try again. When the command executes without error, your program has compiled successfully. If you list the files in your directory, you will see that the
javac
program created a new file named CalculateDistance.class
. This is your compiled program.Subsection 3.1.3 Launching a Compiled Java Program
To launch your compiled Java program, enter the following command into your shell. Note that the
java
command does not take the name of the compiled program, but rather takes the name of the Class with the main(…)
static method to run. In our case, the name of the class is ComputeDistance
. If you see the following output, you have successfully compiled and run your first Java program. Make sure you have mastered the javac
and java
commands, you will be using them quite a lot.java ComputeDistance 36.05551275463989
Once you have that working, try the following longer program, which computes and prints the roots of a quadratic polynomial using the quadratic formula. Study this program carefully. Every part of it should look familiar to you. Notice the use of the
+
and +=
operators to assemble the output.// Roots.java
public class Roots {
public static void main(String[] args) {
// Define coefficient values for the quadratic polynomial
double a = 1.0;
double b = 0.0;
double c = -4.0;
// Compute the roots
double discr = b * b - 4 * a * c; // the discriminant
double root1 = (-b - Math.sqrt(discr)) / (2 * a);
double root2 = (-b + Math.sqrt(discr)) / (2 * a);
// Print the results
String resp = "Coefficients: a=" + a + ", b=" + b + ", c=" + c;
resp += "\nRoots: " + root1 + " and " + root2;
System.out.println(resp);
}
}
javac Roots.java java Roots Coefficients: a=1.0, b=0.0, c=-4.0 Roots: -2.0 and 2.0
Many programming editors streamline the compile and run process by running all steps at the click of a button. Before relying on these conveniences, master at least one shell program and its commands that allow you to work with your computer’s operating system as well as the commands required to compile and run a Java program. After you feel comfortable with these core tools, then use your editor’s shortcut buttons. You’ll understand exactly what they do.