Section 4.11. Composition of the main Method

   

4.11 Composition of the main Method

Let's take a moment to look at the now familiar main method and break it apart to see how it is composed . The purpose of the main method is to have a starting place for programs to execute. So far all of the code we have written has been confined to one class file. As our programs grow in complexity, we will define different classes distributed in different files to handle particular aspects of the programs' work.

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

The main method is declared public . That means that it is accessible by other classes. It is also static . Remember that static methods are called on a class, not on an object. main is necessarily static because at the start of a program's execution, no objects exist. main starts, and the code written inside its body instantiates the objects and calls the methods required to execute the program.

In the argument list, (String[] args) , we see that main accepts one argument: an array whose cells hold String objects. Referencing the cells of this array gives you access to the arguments passed in from the command line.

The purpose of the main method is to start program execution, so a program may have only one main method.

Note

It is legal to have one main method per class. Sometimes programmers will write a main method into every class for unit testing. Instead of having to run the entire application, you can find bugs in confined parts of a program by simply calling the main method to execute the class you want to test.


4.11.1 Calling Methods

Let's write a couple of programs that offload some of the program's work into methods.

4.11.2 Square1.java

[View full width]
 
[View full width]
/* this program tells you the square of a hardcoded int and demonstrates how to write a graphics/ccc.gif program that calls a method other than main. */ class Square1 { // execution starts here public static void main (String [] args) { // define a number to square int number = 3; // 'answer' holds the result of the method call // to square(), which calculates the square of the number // passed to it as an argument int answer = square(number); // now we call the 'show' method to display the result show(answer); } // the program processing really ends here. // the remainder of the program just defines these // methods we're calling // square() method accepts an int and returns an int public static int square(int x) { return x * x; } // show() method accepts an int and prints it out public static void show(int result) { System.out.println("The answer is " + result); } }

Square1.java can be compiled and run to produce this output:

 The answer is 9 

As you can see, defining methods changes the structure of your program a bit. While the comments in the program should explain what's happening fairly well, the main thing to notice is the end of the program. After calling show(answer) , we close the main method with a } , stopping execution of the program. Our methods, square() and show() , are defined below that. This is perhaps similar to defining a file called lib.cfm that holds several custom functions for a ColdFusion application, and including them in the template that you need to call them from.

The square() and show() methods as defined in Square1.java are class-level methods. They do not have an object associated with them. They are defined as part of the class itself.

The square() method is defined with this code block:

 public static int square(int x) {         ... } 

The method is declared public , which means that it is accessible anywhere that the class is accessible.

The static access modifier indicates that the method is a class-level method and that the method is not associated with an object. Such methods are invoked on behalf of the class and are meant to perform general sorts of tasks . For instance, our square() method is static for a couple of reasons. First, we don't have any objects (we'll get to those later). However, even if this program did create some objects, we could still reasonably declare a square() method as static because it might not make sense to associate it with an instance of an object. A static method only has access to the static fields and other static methods of its class. non-static members must be accessed via an object, and static methods do not have an available object reference.

Populating the return position of our method declaration is int , indicating that the method will return a value of type int .

Then we name the method square and open a parens for the arguments.

Arguments are written as (type identifier) . So, this method accepts an int called x . If x existed previously in the program, we could just refer to the identifier, as we recall from using the println() method of System.out :

 String msg = "Hello, dude.";   System.out.println(msg); 

The body of the method defines the statements that do the work of the method. We could have written a more verbose square() method to demonstrate how statements might work in a method body:

 public static int square(int x) { // statements making up the method body:     int y = x * x;      return y; } 

This makes a nice way to demonstrate the difference between the return statement and the method body, but otherwise there is certainly no advantage to adding this unnecessary complexity.

It does, however, bring up an important point. As with loops , variables declared inside a method are only available to that method. For instance, this is illegal:

 ...     } // end main      public static int square(int x) { int y = x*x; return y;     }     public static void show(int ans) {         System.out.println("The answer is " + ans);  System.out.println("y is: " + y); // ERROR!  } 

The compiler does not have access to the value of y because it was declared inside the body of the square() method.

Here is a slightly revised version of the Square program. It now accepts an argument to be squared and features a touch of handling in the event that no argument is passed. If the argument is an integer, processing continues normally.

4.11.3 Square2.java

 /* just like Square1, but accept an arg from cmd line     as int to square    also demonstrates use of Integer.parseInt */ public class Square2 {     public static void main(String[] args) { /* add some conditional logic in case user    does not supply an argument    so our program doesn't just    inelegantly fail */  if (args.length == 0) {   // no argument supplied   String msg = "Please supply a number for me to square.   Thank you.";   System.out.println(msg);   } // end if   else {   // convert passed number to an int.   // we had to move this guy down here so it's inside the else   int number = Integer.parseInt(args[0]);  // make a new int to hold the result of // calling the square method on the number         int answer = square(number); // print to the command line         show(answer);  } // end else  } // end main method declarations same... } 

This revised version of Square1 is just a little more realistic and combines a few of the things we've learned in this chapter. What would be nice is if we could determine what type of item is being passed into the method. We can do that, and if you type an argument that cannot be converted to an int , Java will throw a java.lang.IllegalNumberFormat exception. In order to deal with this, we would want to catch and throw the exception, which we will do later.

While we have not discussed objects much yet, the following simple program will perhaps help demonstrate how putting the work of your program into discrete methods can be valuable , and how simple it can be to use methods. This program, called SquareAndCube , simply takes an integer and does two different things with it: the square() method squares it and the cube() method cubes it.

4.11.4 SquareAndCube.java

 /* File: SquareAndCube.java  Purpose: demonstrate using a method other than main, defining two different methods that each perform different tasks with the same value. Notes: Must be passed an int Author: E Hewitt */ public class SquareAndCube {     public static void main (String [] args) {         int number = Integer.parseInt(args[0]);         int theSquare = square(number);         int theCube = cube(number);         showSquare(theSquare);         showCube(theCube);     }     // the square method returns the square     public static int square(int x) {         return x*x;     }     // the cube method returns the cube     public static int cube(int x) {         return x*x*x;     }     // the showSquare method will display     // a string and the result of the square() method     public static void showSquare(int ans) {         System.out.println("The square is: " + ans);     }     // the showCube method will display     // a string and the result of the cube() method     public static void showCube(int ans) {         System.out.println("The cube is: " + ans);     } } 

Here is the output from running the program.

 C:\jdk1.4\JavaForCF\chp4>java SquareAndCube 6  The square is: 36 The cube is: 216 

While SquareAndCube defines no objects, it does encapsulate the operations of the program into small methods that perform simple tasks. This is good practice for the upcoming discussion of objects. A primary challenge of writing a Java program is often determining what methods you will need, but once you've done that, it is perhaps a relief to find that the methods themselves are often fairly simple.


   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net