Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Creating Methods

We've been using methods ever since printing out our first message with out.println, so we're familiar with the concept—a method contains code that you can execute by calling that method:

<% out.println("Hello there!"); %>

In this case, the code is passing the text "Hello there!" to out.println, and that method writes that text to the Web page.

Now it's time to get this power for ourselves. Here's how you create a method in Java:

[access] [static] type methodName (argument_list)
  .
  .
  .
}

To declare and define a method in Java, you can use an access specifier, which can be public, private, or protected. These access specifiers are used when you're creating Java classes, and we'll see more about them in Day 11, "Creating More Powerful JavaBeans." The keyword static is also all about working with classes, and lets programmers use your method without creating an object from it. We won't need that here, so we'll also defer that to Day 11.

Next, you must specify the return type of a method, which is specified by type in the preceding code. The return type indicates what kind of data the method returns when you call it. For example, if you have a method named addem that you pass two integers to, and it adds those integers and returns the sum—of type int—the return type for the method will be int. Return types include any valid type, such as the simple data types int, float, double, and so on. You can also return an array, using return types like int[], double[], and so on. If your method does not return a value, use the return type void.

Next, you give the method's name and place the list of the arguments you intend to pass to the method after that name. Note that you must specify the type of each argument, as in this case, in which the code is declaring the addem method (to which you pass two integers), and it's naming those integers op1 and op2 (for "operand 1" and "operand 2"):

int addem(int op1, int op2)

The actual body of the method—the code that will be executed when you call the method—is enclosed in a code block (delimited with curly braces, { and }) following the method's declaration. Note in particular that you must declare methods in JSP declarations (surrounded by <%! and %>), and not in scriptlets (which are surrounded by <% and %>):

<HTML>
 <HEAD>
  <TITLE>Creating a Method</TITLE>
 </HEAD>

 <BODY>
  <H1>Creating a Method</H1>
  <%!
  int addem(int op1, int op2)
  {
    .
    .
    .
  }
  %>
 </BODY>
</HTML>

The code has named the two integers passed to this method part of the method declaration, and now you can refer to those integers in the body of the method with those names. To return their sum from this method, you can use the return statement:

<HTML>
 <HEAD>
  <TITLE>Creating a Method</TITLE>
 </HEAD>

 <BODY>
  <H1>Creating a Method</H1>
  <%!
  int addem(int op1, int op2)
  {
   return op1 + op2;
  }
  %>
 </BODY>
</HTML>

The code in a method like addem isn't run until you call it. On the other hand, the code in a general scriplet, outside any method, is run as soon as the page is loaded. Listing 3.17 shows how to call the new addem method, add 2 + 2, and display the result.

Listing 3.17 Creating a Method (ch03_17.jsp)

<HTML>
 <HEAD>
  <TITLE>Creating a Method</TITLE>
 </HEAD>

 <BODY>
  <H1>Creating a Method</H1>
  <%!
  int addem(int op1, int op2)
  {
   return op1 + op2;
  }
  %>

  <%
  out.println("2 + 2 = " + addem(2, 2));
  %>
 </BODY>
</HTML>

You can see the results of this code in Figure 3.14, where we're using the full power of Java to tell us that 2 + 2 = 4.

Figure 3.14 Creating a method.

Here's something to note—because you must declare methods in JSP declarations, not scriplets, the code in your methods does not have access to the built-in JSP objects like out. That might appear to be a serious drawback if you want to send text to a Web page from a method, but you can get around this problem if you pass the out object to a method. We'll see how this works later today.

Declaring Multiple Methods

You can declare multiple methods in the same JSP declaration, as seen in Listing 3.18. This example declares a method named subractem that subtracts one integer from another and returns the difference.

Listing 3.18 Declaring Multiple Methods (ch03_18.jsp)

<HTML>
 <HEAD>
  <TITLE>Declaring Multiple Methods</TITLE>
 </HEAD>

 <BODY>
  <H1>Declaring Multiple Methods</H1>
  <%!
  int addem(int op1, int op2)
  {
   return op1 + op2;
  }

  int subtractem(int op1, int op2)
  {
   return op1 - op2;
  }
  %>

  <%
  out.println("2 + 2 = " + addem(2, 2) + "<BR>");
  out.println("8 - 2 = " + subtractem(8, 2) + "<BR>");
  %>
 </BODY>
</HTML>

You can see the results of this code in Figure 3.15.

Figure 3.15 Declaring and using multiple methods.

Using Built-In JSP Methods

The Java class that JSP pages are built on, HttpJspBase, has two methods built into it that are automatically called at specific times in the lifecycle of a JSP-enabled page. The first method, jspInit, is automatically called when the page is first created, and the second, jspDestroy, is automatically called when the page is unloaded and destroyed by the server.

The purpose of jspInit is to let you run initialization code for the page, and the purpose of jspDestroy is to let you run clean-up code after the page is done, which can involve opening and closing database connections. Here's an example using jspInit to set a variable to 5 when the page loads, and setting that variable to 0 when the page is destroyed. Note that neither jspInit nor jspDestroy take any arguments or return a value. Also, note that in this case we have to use the public keyword, because we're actually overriding (overriding means redefining, as you'll see in Day 11) the jspInit and jspDestroy methods. Because they were declared in HttpJspBase with the public keyword, Java insists that you use that same keyword here when redefining these methods (more on the public keyword in Day 11), as you see in Listing 3.19.

Listing 3.19 Using jspInit and jspDestroy (ch03_19.jsp)

<HTML>
 <HEAD>
  <TITLE>Using jspInit and jspDestroy</TITLE>
 </HEAD>

 <BODY>
  <H1>Using jspInit and jspDestroy</H1>
  <%!
  int number; 

  public void jspInit()
  {
   number = 5;
  }
  public void jspDestroy()
  {
   number = 0;
  }
  %>

  <%
  out.println("The number is " + number + "<BR>");
  %>
 </BODY>
</HTML>

And that's all it takes—now this page has both initialization and clean-up code that the server runs automatically at the right time.

Recursion

It's also worth knowing that JSP methods can call themselves, a process called recursion. This isn't necessary knowledge for the work we'll do in this book, so you can skip it if you like.

You've already seen how factorials work (for example, the factorial of 6 is 6 x 5 x 4 x 3 x 2 x 1 = 720), and factorials lend themselves to recursion. This example supports a method named factorial that you pass an integer to, and it returns an integer. If the integer we're passed is 1, we're all done, because the factorial of 1 is 1, so we return that value:

int factorial(int n)
{
  if (n == 1) {
    return n;
  }
    .
    .
    .
}

Otherwise, all we have to do is return the current number—say that's n, multiplied by the factorial of n-1 (which we can find by calling the factorial method again):

int factorial(int n)
{
  if (n == 1) {
    return n;
  }
  else {
    return n * factorial(n - 1);
  }
}

Here's how this method looks in an example, in which the code is calling it to find the factorial of 6, as you see in Listing 3.20.

Listing 3.20 Using Recursion (ch03_20.jsp)

<HTML>
 <HEAD>
  <TITLE>Using Recursion</TITLE>
 </HEAD>

 <BODY>
  <H1>Using Recursion</H1>
  <%!
  int factorial(int n)
  {
    if (n == 1) {
      return n;
    }
    else {
      return n * factorial(n - 1);
    }
  }
  %>

  <%
    out.println("The factorial of 6 is " + factorial(6));
  %>
 </BODY>
</HTML>

You can see the results of this code in Figure 3.16, where we see that the factorial of 6 is 720.

Figure 3.16 Using recursion.

Scope

When you discuss the creation of methods, the issue of scope becomes important. An item's scope is the area of your program in which you can reference it—that is, it's where an item in visible. For example, in the following code, the variable named number is declared outside any method, so it's accessible inside the body of any method:

  <%!
  int number;

  public void jspInit()
  {
   number = 5;
  }

  public void jspDestroy()
  {
   number = 0;
  }
  %>

However, if you had declared number inside a method, it would be private to that method, and you couldn't access it in the other method:

  <%!

  public void jspInit()
  {
   int number;
   number = 5;
  }

  public void jspDestroy()
  {
    //Can't use number here!
    .
    .
    .
  }
  %>

In this way, declaring variables in methods limits the scope of those variables, which compartmentalizes your code—if a variable is limited to a method, there's less chance that other code might inadvertently affect its value.

NOTE

You'll see more on scope later in the book—for example, in Day 6, "Creating JSP Components: JavaBeans," you'll see how to limit the scope of your data to a Web page or an entire Web application.

Passing Objects to Methods

When you pass simple data items like integers or floating-point values to a method, a copy of those values is made, and the copy is actually passed to the method. That's called the act of passing by value. However, when you pass an object to a method, a copy of the object is not made (because some objects can be huge); instead, the location of the object in memory is passed to the method. That's called passing by reference.

That's important to know, because when an object is passed by reference, you then have direct access to that object—if you change some data in the object in your method, you'll be changing the data in the original object passed to the method (which doesn't happen when you pass by value).

Let's take a look at an example to make this clearer—here, you can pass an array (remember that arrays and strings are both objects) to a method named doubler. That method won't return anything, but it will double the value of each element in the array. Because the array was passed by reference, that will double each element in the original array as well. Here's how that looks when you declare doubler to take an integer array:

void doubler(int a[])
{
    .
    .
    .
}

And in the body of doubler, you might loop over the array and double each value:

void doubler(int a[])
{
  for (int loopIndex = 0; loopIndex < a.length; loopIndex++) {
    a[loopIndex] *= 2;
  }
}

And that's all it takes—the final code displays both the original values in the array and values after the call to doubler, as you see in Listing 3.21.

Listing 3.21 Passing Arrays to Methods (ch03_21.jsp)

<HTML>
 <HEAD>
  <TITLE>Passing Arrays to Methods</TITLE>
 </HEAD>

 <BODY>
  <H1>Passing Arrays to Methods</H1>
  <%!
  void doubler(int a[])
  {
    for (int loopIndex = 0; loopIndex < a.length;
      loopIndex++) {
      a[loopIndex] *= 2;
    }
  }
  %>

  <%
    int array[] = {1, 2, 3, 4, 5};

    out.println("Before the call to doubler...<BR>");
    for (int loopIndex = 0; loopIndex < array.length;
      loopIndex++) {
      out.println("array[" + loopIndex + "] = " +
        array[loopIndex] + "<BR>");
    }

    doubler(array);

    out.println("After the call to doubler...<BR>");
    for (int loopIndex = 0; loopIndex < array.length;
      loopIndex++) {
      out.println("array[" + loopIndex + "] = " +
        array[loopIndex] + "<BR>");
    }
  %>
 </BODY>
</HTML>

You can see the results of this code in Figure 3.17—note that each element in the array that we passed to doubler was indeed doubled, even though doubler didn't return any values.

Figure 3.17 Passing arrays to methods.

Passing objects to methods is especially valuable when it comes to working with built-in objects like the out object (which are otherwise not accessible to you in methods, because methods have to be declared in JSP declarations, not scriptlets).

Here's an example that passes the out object to a method named printem, so that method can display some text in a Web page. Note that we have to specify the type of object we're passing to printem, and as we saw in Day 2, out is an object of the Java javax.servlet.jsp.JspWriter class. In addition, note the throws java.io.IOException clause added to the declaration of printem. We need this clause, because if there's been an error, the out object can "throw" an exception of the java.io.IOException class—that's how Java handles runtime errors, as we're going to see in Day 8, "Handling Errors." Because the out object can throw an exception of the java.io.IOException class, you're getting a sneak peek at exception handling here by adding the throws java.io.IOException clause to the declaration of printem (Java will insist that we do this), as you see in Listing 3.22.

Listing 3.22 Passing the out Object to a Method (ch03_22.jsp)

<HTML>
 <HEAD>
  <TITLE>Passing the out Object to a Method</TITLE>
 </HEAD>

 <BODY>
  <H1>Passing the out Object to a Method</H1>
  <%!
  void printem(javax.servlet.jsp.JspWriter out) throws java.io.IOException
  {
    out.println("Hello from JSP!");
  }
  %>

  <%
    printem(out);
  %>
 </BODY>
</HTML>

As you can see in Figure 3.18, you can use the out object in a method.

Figure 3.18 Passing the out object to a method.

Here's another easier way of doing this—you can simply declare a new variable, such as out2, in the JSP declaration, copy out to out2 in scriptlet code, then use out2 in the methods in the declaration as you see in Listing 3.23.

Listing 3.23 Using the out Object (ch03_23.jsp)

<HTML>
 <HEAD>
  <TITLE>Passing the out Object to a Method</TITLE>
 </HEAD>

 <BODY>
  <H1>Passing the out Object to a Method</H1>
  <%!
  javax.servlet.jsp.JspWriter out2;

  void printem() throws java.io.IOException
  {
    out2.println("Hello from JSP!"); 
  }
  %>

  <%
    out2 = out;
    printem();
  %>
 </BODY>
</HTML>
  • + Share This
  • 🔖 Save To Your Account