Anatomy of a Program

From CompSciWiki
Jump to: navigation, search

COMP 1010 Home > What is Programming?


Getting Started

Every program has some common parts. Let's examine HelloWorld--the most basic program you'll ever write--and discuss each part of the program. Remember, here's the full code for HelloWorld.

import javax.swing.*;

/**************************************************************
* Author: 		Christina Penner
* File:			D3HelloWorld -- demos programming concepts
* Purpose:		Display a message. Also, review basic programming
                concepts and introduce comments and JOptionPane and String "variables"
********************************************************************************************/

public class HelloWorld{
//note class name and file name must be the same
   public static void main (String [] args) {
	//variables declared here
	String firstName;
	String lastName;

	//get input
	firstName = JOptionPane.showInputDialog("Please type your first name:");
	lastName = JOptionPane.showInputDialog("Please type your last name:");

	//output greeting two ways
	System.out.println ("Howdy " + firstName);
	JOptionPane.showMessageDialog(null, "Hi " + firstName +" " + lastName);

   }//close main method
}//close class HelloWorld
//closes class

Importing Libraries

Java contains a very large set of pre-written code that developers can use. Generic utilities, like lists, tables, input/output functions, etc... are mostly written already and stored in libraries. To make use of these libraries you need to import them. Importing simply means that you are telling the computer what libraries you are using, so that it knows where to find the code you need.

In COMP 1010 you will typically be using only one library, the javax.swing library. This contains code for input dialog boxes, which you will be using to prompt the user for input interactively.

To import the javax.wsing library use the following code:

import javax.swing.*;

The import statement should be the very first line in your .java file, outside of all class and method definitions.

Comments

Every program should have some comments. Usually you add a comment at the top of the progam, which is called a prologue comment. You should also add a comment for each significant line of code.

Comments are pieces of plain English inserted into a program to make it easier to read and understand. Comments are ignored by the computer; they are only there so that humans can read and understand the code more easily. Typically programmers use comments to explain the though process behind parts of code, or to explain particularly complicated areas of the program.

In Java there are two ways of writing comments. The first is to use two forward-slash characters ://. Any text entered to the right of those characters, up until the end of a line will be treated as a comment.

The second way of writing a comment is to surround it with /*...*/ characters. All text between the /* and the */ will be ignored, even if it spans multiple lines.

The following are some examples of comment syntax:

// this is a single line comment.

System.out.println("This is an example");     //comments can occur on their own line, or on the same line as code

//Code should never be placed to the right of a comment: it will be ignored!   System.out.println("This is an example");

/* This is a
multi-line comment. */


Class Name

In Java every program is made up of one or more classes. In COMP 1010 your programs will consist of a single class, so we will not enter into a long discussion about what classes are. If you would like to learn more about classes consider taking the COMP 1020 course.

The main class in a Java program is class in which your main method is defined. To define your class use the following code:

public class MyClass
{
    public static void main(String[] args)
    {
        ...
    }
}

In this example we have defined a class called "MyClass". Java requires that the name of the class and the filename be the same. Therefore, for this program to work the file would have to be called "MyClass.java". You can name your class anything you want, but always make sure that the name of the class and the filename are the same, down to what letters are in upper-case and which are not. Likewise, if you rename your file, make sure to change the name of the class inside it.

Typically class names should start with an upper-case letter. There is nothing wrong with naming your classes with lower-case letters, but it is not a standard practice. Class names must start with a letter (A to Z), but may also contain numbers and underscore characters.


Main Method

Every program has exactly one main method. The main method tells the computer where to start running the code. Since this program is so small the only method is the main method! After the midterm we will start writing additional methods in our programs. Notice that in HelloWorld, the main method is located inside the class. Also, use braces ({ and }) to put code inside the main method.

When you run your program the first thing the computer does is to run your main function. The first line executed is the first line in main. When the last line of main is reached the program will end.

To write your main method use the following code:


public static void main(String[] args)
{
   //your code here
}

The meaning of public static void main(String[] args) is too complicated to explain at this point, but as you go through the course you will learn what the various parts of it mean. For the moment all you need to know is all Java programs require the main method, and the main method starts with this line.


Variables

Often a program will require the use of variables. Variables are essentially places to store bits and pieces of information your program requires in order to execute properly. Typically the first thing you do in any method (including the main method) is to declare what variables you will need. Declaring all your variables in one place per method makes reading the code much easier; people trying to understand your code will know where to look to find out what a variable is.

For more on how to use and declare variables see Variables and Literals.


Variable Initialization

Usually after the variables have been declared you set them to some initial value to be used in the program. This can be done either directly with some sort of assignment or from user input. If you try to use a variable without initializing it the Java Virtual Machine will signal that an error has occurred. Initializing variables to a known default value will prevent these errors from occurring. Again, for more information on variable initialization see Variables and Literals.


Processing Data

The rest of the main method performs the work of the program. Operations are performed on the variables, the user is prompted for input, data is read from and written to memory, etc...

Because every program is different it is very difficult to define exactly what data processing should look like. Usually loops and control structures are used to control the flow of the program and repeat specific operations over and over.


Output and Clean-up

After the data has been processed the output should be written to either the screen (as text) or to a file. In COMP 1010 your output will always be done by printing text to the screen for the user to read. A program that does not output any information is useless; what use is a program that doesn't do anything?

Sometimes output and data processing can be inter-woven, to the extent that they are inseparable. This is fine. In your first programs you will tend to find that you write programs that follow a very simple get input --> process input --> write output format. As your programs become more and more complex the output and data processing will become increasingly interwoven.

After you have finished outputting the results of the program you should perform clean-up functions and exit. Fortunately Java has a built-in garbage collector that will do most of the clean-up for you. All you need to do is call one single function:

System.exit(0);

System.exit terminates the program and releases all memory it used back to the operating system. The argument 0 (zero) tells the operating system that the program exited normally without any errors. If you forget to use System.exit(0) in your program nothing catastrophically bad will happen, but it's a good habit to use it.


Another Example

This example brings together all the elements of a program. The different sections are commented so you can see how they relate to each other.

This is a fairly simple program: it asks the user to enter a string (sequence of text characters such as "Hello, how are you today?") and then counts the number of times the first letter occurs in the string. So, with the string "Hello, how are you this fine Thursday?" the program would count 4 occurrences of the letter h and print this result to the screen.

/************************************************************************************************/
//
// import whatever libraries we need for the program.
// in this case we only need javax.swing.*
//
import javax.swing.*;


/************************************************************************************************/
//
// define the class Example.
// This file would have to be called "Example.java" in order to run properly
//
public class Example
{


/************************************************************************************************/
    //
    // declare the main method
    //
    public static void main(String[] args)
    {


/************************************************************************************************/
        //
        // Declare variables
        //
        char firstLetter;        // firstLetter: a single character
        int frequency;           // frequency: an integer (whole number 0, 1, 2, ...)
        String inputString;      // inputString: a string of characters ("hello", "I am in 1st year university", ...)


/************************************************************************************************/
        //
        // Initialize variables
        //

        //  Get input from the user and convert it all to lower-case
        inputString = JOptionPane.showInputDialog(null,"Enter a string:").toLowerCase();

        //  find the first letter in inputString and assign it to firstLetter
        firstLetter = inputString.charAt(0);

        //  initialize the frequency to zero
        frequency = 0;


/************************************************************************************************/
        //
        // Process the data
        // in this program we use a loop to count the number of times the first
        // character in the input string occurs
        //
        for( int i = 0; i < inputString.length(); i++ )
        {
             if( firstLetter == inputString.charAt(i) )
             {
                 frequency++;
             }
        }


/************************************************************************************************/
        //
        // Output the results
        // in this program we use print the frequency to the screen as text
        //
        System.out.println("The first character, " + firstLetter + ", occurs " 
                           + frequency + " times in the string " + inputString);


/************************************************************************************************/
        //
        // Clean-up and exit
        //
        System.out.println("*** Application Terminated Normally ***");
        System.exit(0);

    }//end main
}//end class Example

Do not worry if parts of this program confuse you. Just remember the basic form of the program. The details of what every line actually means will be explained in later chapters throughout the course.

Previous Page: The Programming Process Next Page: What Is Programming Questions