Programming Example 1: Java Program Structure

Introduction

In this example program you will see the basic elements and overall structure of a Java program. Every program that you write this semester will contain these basic elements and structure. Over the course of the semester, we will discuss additional elements that will appear in your programs, but these are the basics.

Basic Program Elements

As you read through this example, look for the following program elements:

  1. The file prologue: Every source code file must have a file prologue. The file prologue provides a description of what is in the file and identifies you as the owner of the file. One of the most important elements of the file prologue is the notice that you did not copy code from anyone else while developing this program.
  2. import statements The import statement tells the Java compiler to import the named class into the program so that the class can be used by the program In this case we need the Scanner class for input, and the constant math.PI for computing the circumference of a circle.
  3. class: Every Java program must contain at least one class. You can think of this class as the envelope that contains the main( ) method and any global, class level data. The body of the class is enclosed in curly braces "{" and "}".
  4. The main( ) method: Every program must have a method named main. When the computer executes your program it will search for a static method named main and start it's execution there. The body of every method, including main is enclosed in curly braces "{" and "}".
  5. Comments:Comments are used to add notes and documentation to your program. This program uses single line comments that begin with a double slash "//"
  6. Statements:The body of a Java program is made up of statements, much like a paragraph is made up of sentences. Each statement in a Java program ends with a semi-colon.

This example program is located here. For best viewing results, save this file and open it with NetBeans.