Home > Articles > Programming > Java

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>

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020