Home
Examples
Labs
Assignment
Marks
Midterm
Final Exam
Resources

Breaking Tasks Down

It is good programming practise to break tasks down into small, more manageable pieces.  One way to do this is by writing helper methods.  When we define a helper method we package together the code associated with a particular task.  The helper method is called whenever we want the task to be carried out.

For example : in this HelloWorld program we define a helper method called printGreeting to print the Hello message on the screen.  The printGreeting method is called three times in the constructor - so the hello message will be printed on the screen three times when we run the program.
          class HelloWorld {
           // Java Program - prints a hello message.
           // Note that now we are using a constructor, and a
           // helper method.

              public HelloWorld () {
                    printGreeting();
                    printGreeting(); 
                    printGreeting();
                 } // end constructor

              private void printGreeting() {
                    System.out.println("Hello World!");
                } // end printGreeting


               public static void main (String[] Args) {
                     HelloWorld hwProgram = new HelloWorld();
                 } // end main    

            } // end class HelloWorld 
Notice that helper methods are defined as private.  They can only be used in the class where they are defined.  Also notice that helper methods are defined inside of the class, but outside of the other methods.



Return Types

A helper method must have a return type.  A return type defines what sort of value or object will be passed back to the calling code by the method whenever the method is executed.  A method may return an object or a primitive type.  If a method returns nothing, its return type is void.

For example : the program UseMethod uses a helper method to read in a number from the user.  The method getNum asks the user for a number, reads in a String, converts the String to an integer, and then returns the int value to whoever called the method.  The value returned by the method call is saved in the variable num out in the constructor where the method was called.
          class UseMethod {
           // Using a helper method to read an integer from
           // the keyboard.

              public UseMethod () { 
                    int num = getNum();
                    System.out.println("Your number is : " + num);
                } // end constructor 

              private int getNum() throws Exception {
                    BufferedReader kb = new BufferedReader(
                                     new InputStreamReader(System.in));
                    System.out.print("Enter a number > ");
                    int userNumber = Integer.parseInt(kb.readLine());
                    return userNumber;
                } // end getNum  

              public static void main (String[] Args) {
                    UseMethod umProgram = new UseMethod(); 
                } // end main 

            } // end class UseMethod 
Notice the use of the keyword return to pass back something (a value or object reference) from a method.  The type of the thing being returned must match the return type specified in the method header.  When you write a method that uses control structures like loops and/or decision statements make sure that, no matter what the path of execution through your method, it always returns something.



Local Variables

A variable declared inside of a method is a local variable.  Local variables only exist as long as their method is executing.  Local variables are only accessible inside of the method where they are declared.  For this reason, the name of a local variable in one method may be re-used as a name for a different local variable in another method.  In the example above, num, userNumber and kb are examples of local variables.



Parameters & Arguments

Parameters and Arguments are used to send information into methods.  Arguments are the values that the calling code sends into the method when the method call is made.  Parameters are the variables declared inside the parentheses of the method header.  When the method is called, the arguments from the method call are assigned to the parameters of the method.

For example : in the program ShowPara we define two helper methods.  The getNum method works the same here as it did in the UseMethod program above.  The showMultTable method accepts an int parameter and prints the multiplication table for the specified int value on the screen.  In the constructer we call the method showMultTable and pass the value in variable num as an argument.  The value of num is assigned to the parameter n when the method is executed.
          class ShowPara {
           // Using helper methods to read an integer from
           // the keyboard, and to print the multiplication
           // table for that integer on the screen.

              public ShowPara () {  
                    int num = getNum();
                    showMultTable(num);
                } // end constructor  

              private int getNum() throws Exception {
                    BufferedReader kb = new BufferedReader(
                                      new InputStreamReader(System.in));
                    System.out.println("Enter a number > ");
                    int userNumber = Integer.parseInt(kb.readLine());
                    return userNumber;
                } // end getNum  
 
              private void showMultTable(int n) {
                    for(int i = 1; i <= n; i++) {
                        System.out.print(n + " * " + i + " = ");
                        System.out.println(n * i);
                      } // end for
                }  // end showMultTable 

              public static void main (String[] Args) {
                    ShowPara spProgram = new ShowPara();
                } // end main 

            } // end class ShowPara 


Instance Variables

An instance variable is a variable declared within a class, but not inside of any method.  All methods in a class have access to the instance variables.  When we create an instance of a class, the instance variables continue to exist as long as the object exists - their values are maintained for the life of the object and are shared by all of the methods.

For example : because the BufferedReader kb is declared as an instance variable, all of the methods in the application class UseKB can share it.
          class UseKB {
           // Make the BufferedReader an instance variable so 
           // all of the methods can share it instead of
           // creating their own local BufferedReader
           // for keyboard input.  

              BufferedReader kb = new BufferedReader (
                                new InputStreamReader(System.in));

              public UseKB () {
                    System.out.print("Enter name > ");  
                    String name = kb.readLine();
                    int num = getNum();
                    System.out.println(name + "number is " + num);
                } // end constructor  

              private int getNum() {
                    System.out.println("Enter a number > ");
                    int userNumber = Integer.parseInt(kb.readLine());
                    return userNumber;
                } // end getNum  
 
              public static void main (String[] Args) {
                    UseKB ukbProgram = new UseKB();
                } // end main 

          } // end class showPara  


Constants

A constant is like a variable, but its value cannot be changed.  Use the keyword final to declare constants.  It is a naming convention in java for constants to be named using all capital letters.  This distinguishes them from variables to anyone reading your code.
           // Declaring constants
              final int DAYS_IN_A_WEEK = 7;
              final float GRAVITY_CONSTANT = 9.8f;
              final String CANADA_CAPITAL_CITY = "Ottawa";

              final private int MIN_AGE = 19;
              final private float GST = 0.07f;
              final private String DEFAULT_CEREAL = "Cheerios"; 
Using constants helps to make your programs more readible.  For example :
       // this expression will mean more to the reader 
          float totalCost = quanity * UNIT_PRICE * GST * PST;
       // than this one 
          float totalCost = quanity * 19.99f * 0.07f * 0.06f;

       // this expression will mean more to the reader 
          int total = quantity * NUM_PER_BAG * BAGS_PER_CASE;
       // than this one 
          int total = quantity * 24 * 12;
Using constants also helps to make your program more maintainable.  If the government changes the local sales tax, you only have to change the value of the constant SALES_TAX in your program.  This is easier than searching through the code and changing multiple literal values.