Chapter 2. Handling Data and Operators

Welcome to Day 2! Today, you'll see how to get down to the brass tacks of JSP programming as we see how to work with and handle data in JSP. Working with data is the very heart of programming, and it's our logical first step. In fact, the capability to work with and handle data is what separates JSP from static HTML—and we have the full power of Java behind us when we work with data in JSP.

Handling Data and Operators
  • The JSP programming environment

  • Handling data

  • Creating variables and arrays

  • Working with strings

  • Using operators

  • Understanding operator precedence

Now that we're digging into real programming in JavaServer Pages, the first thing to note is that we are indeed dealing with Java. You'll see what that means next.

Java in JSP

Note the word Java in JavaServer Pages. Java itself is a very large programming language, but you don't have to be a Java expert to use this book, or even know it at all—we're going to cover what we need. But you should know that Java programming is a huge topic, and we're not going to have space to cover it all here. There are thick multiple-volume book sets on Java containing thousands of pages that don't cover Java programming completely—and because this is a book about JSP, it's clear we're not going to be able to cover all of Java here, either.

If you press on in JSP programming, you might want to pick up a good book on Java programming. You can also find the complete Java documentation online, as well as Java tutorials—see the “Online JSP Resources” topic in Day 1, “Getting Started!”.

Java in JSP
<HTML> 
  <HEAD>
    <TITLE>Creating a Greeting</TITLE>
  </HEAD>

  <BODY>
    <H1>Creating a Greeting</H1>
    <%
        out.println("Hello from JSP!");
     %>
  </BODY>
</HTML>
Java in JSP

You can also comment your Java code using the Java // comment marker, which makes Java ignore all the rest of the text on a line. As with JSP comments, Java comments are meant as notes to yourself or other programmers explaining what's going on in the code, as you can see in Listing 2.1.

Example 2.1. Using Comments (ch02_01.jsp)

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

  <BODY>
    <H1>Creating a Greeting</H1>
    <%
        out.println("Hello from JSP!");    //Display the greeting
     %>
  </BODY>
</HTML>

If this were a book on Java programming, we'd have to cover a great many more details before writing any code, such as how to create Java classes, and so on, which you need just to get started. We're lucky in that this is a book on JSP, where those background details are taken care of for us—as we're going to see. We just need to use the Java code that we'll actually want to execute; no extras that Java would normally need to set the stage. That's because JSP already sets the stage for us, as we'll discuss next.

The JSP Programming Environment

When you create a pure-Java Web application, like a servlet, you need to set up a Java class and perform all kinds of other work just to get started. That's not necessary in JSP—you just put the actual Java statements you want to execute into scriptlets, and you're set. The JSP server does the rest, creating a full servlet for you automatically.

In fact, JSP even does more for us—we've already seen that JSP comes with a built-in Java object named out, which we can use to send text to a Web page. There are a number of built-in objects like out already set for us to use in JSP pages, and we'll list them here for reference.

Each of these objects is created from a Java class (we'll see how to create Java classes ourselves in Day 6, “Creating JSP Components: JavaBeans”). Here, you'll see which Java class each built-in object is created from, so that if you want to find out more about any object, you can check the Java documentation (see http://java.sun.com/j2se/1.4/docs/index.html for the online documentation, or http://java.sun.com/j2se/1.4/download.html to download it). Note that there's no need to read the Java documentation directly—these objects are covered in detail in the coming days.

Here's a list of the built-in JSP objects; it'll be hard to appreciate this list right now, but it's good to have for later reference:

  • application—. Holds data for the current Web application (see Day 7, “Tracking Users with Sessions and Cookies”). This is an object of the Java javax.servlet.http.HttpSession class.

  • config—. Holds configuration data like passwords. This is an object of the Java javax.servlet.ServletConfig class.

  • exception—. Lets you handle errors (see Day 8, “Handling Errors”). This is an object of the Java java.lang.Throwable class.

  • out—. The object you use to send text to a Web page. This is an object of the Java javax.servlet.jsp.JspWriter class.

  • page—. Gives you access to the current JSP page's underlying servlet (see Day 6). This is an object of the Java javax.servlet.jsp.HttpJspPage class.

  • pageContext—. Holds data from the JSP page's underlying servlet (see Day 10, “Creating Custom Tags”). This is an object of the Java javax.servlet.jsp.PageContext class.

  • request—. Holds data sent to you from the browser (see Day 4, “Reading Data from Web Pages: Buttons and Text Fields”). This is an object of the Java javax.servlet.http.HttpServletRequest class.

  • response—. Holds data you are sending back to the browser (see Day 7). This is an object of the Java javax.servlet.http.HttpServletResponse class.

  • session—. Holds data about the current session (see Day 7). This is an object of the Java javax.servlet.http.HttpSession class.

We're going to introduce and use these objects as we need them. Today, you're only going to use the out object. We've seen that object has a method named println, which you can use to send text to a Web page. For example, here's how we print “Hello from JSP!” to a Web page:

out.println("Hello from JSP!"); 
session—

Besides println, there are other methods available in the out object, and you can see them all in Table 2.1. You pass different types of data to these various methods, and the type of data you can pass is indicated in that table. We're going to see all these data types today—for example, this entry in Table 2.1

println(char x); 

means that you can pass an individual character (such as 'a' or 'x') to the println method.

Note that the print and println methods in Table 2.1 have multiple versions with the same name that take different data types. This means you can call the same method with different types of data—for example, you can pass a single character to the println method, or a String object (as we'll see today), or a floating point value, and so on, as indicated in Table 2.1.

Tip

Here's something useful to know about the println method—because its name means “print line,” you might think it'll write output to a Web page and then skip to the next line. In fact, the output only skips to the next line when you're writing plain-text files. Although that lets you format the text in your HTML files nicely, when the browser displays that HTML, it will ignore the attempt to skip to the next line. If you want to skip to the next line in the browser, make sure you print the HTML to do that, such as using a <BR> element (for example, out.println("<BR>");). Note that the out object also has a print method, which doesn't skip to the next line after printing its text.

Table 2.1. Methods of the out Object

Method

Does This

clear()

Clears all internal data in the object.

clearBuffer()

Clears the contents of the internal data buffer.

close()

Closes the output “stream,” which is the stream of data going to the Web page.

flush()

Flushes the output stream, sending any data in it to the Web page.

getBufferSize()

Gets the size of the internal data buffer.

getRemaining()

Gets the number of unused bytes in the data buffer.

isAutoFlush()

Indicates if out autoflushes, which means it writes its data out fully each time you write.

newLine()

Skips to the next line in plain text files.

print(boolean b)

Prints a Boolean value.

print(char c)

Prints a character.

print(char[] s)

Prints an array of characters.

print(double d)

Prints a double-precision floating-point number.

print(float f)

Prints a floating-point number.

print(int i)

Prints an integer.

print(long l)

Prints a long integer.

print(java.lang.Object obj)

Prints an object.

print(java.lang.String s)

Prints a string.

println()

Skips to the next line in plain text files.

println(boolean x)

Prints a Boolean value and then skips to the next line in plain text files.

println(char x)

Prints a character and then skips to the next line in plain text files.

println(char[] x)

Prints an array of characters and then skips to the next line in plain text files.

println(double x)

Prints a double-precision floating-point number and then skips to the next line in plain text files.

println(float x)

Prints a floating-point number and then skips to the next line in plain text files.

println(int x)

Prints an integer and then skips to the next line in plain text files.

println(long x)

Prints a long integer and then skips to the next line in plain text files.

println(java.lang.Object x)

Prints an Object and then skips to the next line in plain text files.

println(java.lang.String x)

Prints a String and then skips to the next line in plain text files.

Handling Data in JSP

Handling Data in JSP

Example 2.2. Using Literals (ch02_02.jsp)

<HTML>
  <HEAD>
    <TITLE>Using a Literal</TITLE>
  </HEAD>

  <BODY>
    <H1>Using a Literal</H1>
    <%
        out.println("Number of days = ");
        out.println(365);
     %>
  </BODY>
</HTML>

This code displays those literals, as you see in Figure 2.1.

Using a literal in Java.

Figure 2.1. Using a literal in Java.

You can't work with or change the value of literals in your code, so Java also has variables.

Creating Variables

Creating Variables
Creating Variables
type name [= value][, name [= value]...]; 

Let's see how this works; here's an example showing how to declare a variable of the int type, which means you can store an integer in it. This variable is named days, like the following:

int days; 

Now you can assign a value to this variable, which stores the integer 365 in days:

int days; 
days = 365;

Now days holds 365, as you can see in Listing 2.3. Here, the code is using the + operator to join the value in days to the text "Number of days = "—you'll see more on joining text together like this later today.

Example 2.3. Creating Variables (ch02_03.jsp)

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

  <BODY>
    <H1>Creating a Variable</H1>
    <%
        int days;
        days = 365;
        out.println("Number of days = " + days);
     %>
  </BODY>
</HTML>

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

Creating a variable.

Figure 2.2. Creating a variable.

As we know, you can also declare variables in declaration scripting elements, enclosed in <%! and %> this way:

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

  <BODY>
    <H1>Creating a Variable</H1>
    <%!
        int days;
    %>
    <%
        days = 365;
        out.println("Number of days = " + days);
     %>
  </BODY>
</HTML>

Initializing Variables

Initializing Variables
<HTML> 
  <HEAD>
    <TITLE>Creating a Variable</TITLE>
  </HEAD>

  <BODY>
    <H1>Creating a Variable</H1>
    <%
        int days = 365;
        out.println("Number of days = " + days);
     %>
  </BODY>
</HTML>

In this case, the code is assigning a value of 365 to days at the same time that the variable is declared, which is a handy shortcut.

Data Types

The int type is only one kind of simple variable that you can use. Here are the possibilities in overview:

  • Integers—. These types are: byte, short, int, and long, which hold signed, whole-value numbers.

  • Floating-point numbers—. These types are: float and double, which hold signed floating-point numbers.

  • Characters—. This is the char type, which holds representations of characters such as letters and numbers.

  • Boolean—. This type is designed to hold only two types of values: true and false.

You can see these types in more depth in Table 2.2.

Table 2.2. Data Types

Type

Bytes Used

Range

boolean

2

true, false

byte

1

–128–127

char

2

N/A

double

8

–1.79769313486232E308 to –4.94065645841247E-324 for negative values, and from 4.94065645841247E-324 to 1.79769313486232E308 for positive values

float

4

–3.402823E38 to –1.401298E-45 for negative values, and from 1.401298E-45 to 3.402823E38 for positive values

int

4

–2,147,483,648 to 2,147,483,647

long

8

–9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

short

2

–32,768 to 32,767

For example, the double type holds “double-precision” floating-point numbers, which you can use to store floating-point numbers with greater precision than with the ordinary floating-point type, float. Here's how you can declare a double variable named pi to hold the value of pi to 10 decimal places:

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

  <BODY>
    <H1>Creating a Variable</H1>
    <%
        double pi = 3.1415926535;
        out.println("Pi = " + pi);
     %>
  </BODY>
</HTML>

Converting Between Data Types

Converting Between Data Types
<HTML> 
  <HEAD>
    <TITLE>Mixing Data Types</TITLE>
  </HEAD>

  <BODY>
    <H1>Mixing Data Types</H1>
    <%
        float float1;
        double double1 = 1;

        float1 = double1;

        out.println("float1 = " + float1);
     %>
  </BODY>
</HTML>

In cases like this, you need to convert between data types. There are two ways you can do that—using automatic type conversion, or doing the type conversion yourself.

Automatic Conversions

When you're assigning one type of data to a variable of another type, Java will convert the data to the new variable type automatically. For example, you can assign a float value to a double variable, because double variables have a larger range than float values, so no data will be lost in the type conversion. You can see an example in Listing 2.4.

Example 2.4. Automatic Data Conversions (ch02_04.jsp)

<HTML>
  <HEAD>
    <TITLE>An Automatic Data Conversion</TITLE>
  </HEAD>

  <BODY>
    <H1>An Automatic Data Conversion</H1>
    <%
        double double1;
        float float1 = 1;

        double1 = float1;

        out.println("double1 = " + float1);
     %>
  </BODY>
</HTML>

Java will have no problem with this code, as you see in Figure 2.3. These types of conversions, where you convert to a data type with a larger range, are called widening conversions.

An automatic data conversion.

Figure 2.3. An automatic data conversion.

Performing Type Conversions

If you're assigning a data value to a variable of a type that has a larger range than the variable you're assigning it to, which is called a narrowing conversion, the Java compiler will not perform narrowing conversions automatically, because there is the possibility that precision will be lost. If you want to perform a narrowing conversion, you must use an explicit type cast.

Performing Type Conversions

Example 2.5. Casting to a New Data Type (ch02_05.jsp)

<HTML>
  <HEAD>
    <TITLE>Casting to a New Type</TITLE>
  </HEAD>

  <BODY>
    <H1>Casting to a New Type</H1>
    <%
        float float1;
        double double1 = 1;

        float1 = (float) double1;

        out.println("float1 = " + float1);
     %>
  </BODY>
</HTML>

Without the explicit type cast, Java would object, but with the type cast, there's no problem. Java decides what you know about the possibility of losing some data when you cram a possibly larger value into a smaller type, and are taking responsibility for the results. You can see the results in Figure 2.4.

Using a type cast.

Figure 2.4. Using a type cast.

Note

For information on converting text strings to numbers and vice versa, see “Using Named Targets” in Day 5, “Reading Data from Web Pages: Check Boxes, Radio Buttons, and Select Controls.”

Strings

Besides numbers, text strings are an important part of programming. In Java, strings are supported by their own class, the String class, and you can think of the String class as defining a new data type. For example, you can create a string named greeting, which holds the text “Hello from JSP!” in Listing 2.6.

Example 2.6. Creating a String (ch02_06.jsp)

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

  <BODY>
    <H1>Creating a String</H1>
    <%
        String greeting = "Hello from JSP!";

        out.println(greeting);
     %>
  </BODY>
</HTML>

You can see the results in Figure 2.5.

Creating a string.

Figure 2.5. Creating a string.

Although strings are not one of the simple data types in Java, they deserve a place here, because most programmers treat them as they would any other data type. For example, here's how you can create three strings and join them into one string with the + operator:

String string1 = "Hello "; 
String string2 = "from ";
String string3 = "JSP!";
String greeting = string1 + string2 + string3;

In this case, the resulting string in greeting would be "Hello from JSP!".

You can see a selection of the Java String class's methods in Table 2.3. For example, take a look at the entry int indexOf(String str) in that table. This method searches a string for a substring:

index = string1.indexOf("JSP"); 

Here, the code is searching the text in the String string1 for the text "JSP". Besides passing data to methods, methods can also return data, and the int in this entry in Table 2.3, int indexOf(String str), meaning this method returns an integer value. In this case, the indexOf method returns the character index at which the substring was found in the string you're searching (the first character in the main string has index 0, the next index 1, and so on). In the previous line of code, then, I'm assigning the index at which "JSP" was found in the text in string1 to the variable index. If the substring was not found, indexOf will return a value of –1.

Table 2.3. Selected Methods of the String Object

Method

Does This

boolean equals(Object anObject)

Compares this string to an object. Returns true if the strings are equal.

int indexOf(int ch)

Returns the index within this string of the first occurrence of the given character, or –1 if the search was unsuccessful.

int indexOf(int ch, int fromIndex)

Returns the index within this string of the first occurrence of the given character starting at the given index, or –1 if the search was unsuccessful.

int indexOf(String str)

Returns the index within this string of the first occurrence of the given substring, or –1 if the search was unsuccessful.

int indexOf(String str, int fromIndex)

Returns the index within this string of the first occurrence of the given substring starting at the given index, or –1 if the search was unsuccessful.

int lastIndexOf(String str)

Returns the index within this string of the rightmost occurrence of the given substring, or –1 if the search was unsuccessful.

int lastIndexOf(String str, int fromIndex)

Returns the index within this string of the last occurrence of the given substring, or –1 if the search was unsuccessful.

int length()

Returns the length of this string.

String replace(char oldChar, char newChar)

Returns a new string by replacing all occurrences of oldChar in this string with newChar.

String substring(int beginIndex)

Returns a new string that is a substring of this string.

String substring(int beginIndex, int endIndex)

Returns a new string that is a substring of this string, allowing you to specify the end index.

String toLowerCase()

Converts all the characters in this string to lowercase, returning a new string.

String toUpperCase()

Converts all the characters in this string to uppercase, returning a new string object.

String trim()

Removes white space from both ends of this string.

 

Now let's get to the details of creating and using strings.

Creating Strings

There are many ways to create strings. Here's a way we've already seen:

String s1 = "Hello from JSP!"; 
        .
        .
        .

The code is assigning a string literal to s1. In fact, when you use a string literal like "Hello from JSP!" in your code, Java treats it as a String object, so what's really happening here is that the code is assigning one String object to another.

Tip

String literals like "Hello from JSP!" are enclosed in double quotes. Java also supports single character literals, which you can assign to variables of the character type char. To create a character literal in Java, you must enclose the literal in single quotes, not double quotes (which will create a string), like 'a' or 'x'.

You can also, of course, declare a string first and then assign a value to it, like this:

String s1; 
s1 = "Hello from JSP!";
        .
        .
        .

There are other ways of creating strings as well—and they rely on the fact that strings are really string objects. To understand these other ways of creating strings, you need to understand the object nature of strings.

Strings Are Objects

Strings aren't exactly like the other kinds of variables we've been seeing, because they're really objects of the String class, not simple variables of types like int or double. As mentioned in Day 1, an object can have built-in methods—such as the println method we've seen in the out object, as well as data members you use to store data in the object. We've already seen a selection of methods built into String objects in Table 2.3.

You can think of Java classes, like the String class, as a sort of template or cookie cutter. You use that cookie cutter to create objects. In this way, a class is an object's type, just like int is the type of an integer variable. You can store objects in variables that you declare to be of that object's type (for example, you can store String objects in variables declared to be of type String).

Strings Are Objects
String s1 = new String("Hello from JSP!"); 
out.println(s1);
        .
        .
        .

This creates the new object s1, which holds the string "Hello from JSP!". We can pass this object to println to display that text in a Web page, as the code is doing here.

Note also the use of the new keyword in this code. When you create a new object using a constructor, you need to use the new keyword in this way. We didn't have to do that when initializing a simple variable of the types int and float that you see in Table 2.2, but when you create a new object using a constructor, you have to use the new keyword as we're doing here. Doing so indicates to Java that it must create and initialize a new object, not just a simple variable.

Determining String Length

There are plenty of methods built into String objects available for use, as you can see in Table 2.3. For example, you can find the length of a string (in characters) using the String length method, as shown in Listing 2.7.

Example 2.7. Getting String Length (ch02_07.jsp)

<HTML>
  <HEAD>
    <TITLE>Getting String Length</TITLE>
  </HEAD>

  <BODY>
    <H1>Getting String Length</H1>
    <%
        String s1 = "Hello from JSP!";

        out.println(""" + s1 + """ + " is " + s1.length()
            + " characters long.");
     %>
  </BODY>
</HTML>

You can see the results in Figure 2.6.

Determining string length.

Figure 2.6. Determining string length.

Determining string length.
  • '—. Single quote

  • —. Double quote

  • \—. Backslash

  • —. Backspace

  • ddd—. Octal character, where ddd is the code for the character

  • f—. Form feed

  • —. Newline (skips to the next line in plain text files)

  • —. Carriage return

  • —. Tab

  • uxxxx—. Hexadecimal Unicode character, where xxxx is the code for the character

For example, if you want to display a quotation mark using out.println, you must escape it in the text you pass to that method: "He said, "hello," when he saw me." This way, println will not get confused and think the two quotation marks in the middle of the text are actually beginning or ending the text itself.

Creating and Working with Arrays

Creating and Working with Arrays

Using an array, you can group simple data types into a more compound data structure, and refer to that new data structure by name. More importantly, you can refer to the individual data items stored in the array by numeric index. That's important, because computers excel at performing millions of operations very quickly, so if your data may be referenced with a numeric index, you can work through a whole set of data very quickly simply by incrementing the array index.

In this case, you might start JSP Bank with 100 new accounts, and each one will have its own entry in an array named accounts[]. The square braces at the end of accounts[] indicate that it's an array, and you place the index number of the item in the array you want to access in the braces. Here's how you can create the accounts[] array, giving each entry in it the double type for a little extra precision. First, you can declare the array, and then create it with the new operator—arrays are actually objects in Java, which means you need to use the new operator to create them:

<HTML> 
  <HEAD>
    <TITLE>Creating an Array</TITLE>
  </HEAD>

  <BODY>
    <H1>Creating an Array</H1>
    <%
        double accounts[];
        accounts = new double[100];
        .
        .
        .
     %>
  </BODY>
</HTML>

This creates an array of 100 double values. You can refer to the individual elements in the array using an index number in square brackets like this: accounts[0], which refers to the first element in the array (array indices are zero-based in Java, so accounts[0] refers to the first element), accounts[1], which refers to the second element in the array, and so on. For example, you can store $119.63 in accounts[3], and retrieve that value to display it, as shown in Listing 2.8.

Example 2.8. Creating an Array (ch02_08.jsp)

<HTML>
  <HEAD>
    <TITLE>Creating an Array</TITLE>
  </HEAD>

  <BODY>
    <H1>Creating an Array</H1>
    <%
        double accounts[];
        accounts = new double[100];
        accounts[3] = 119.63;

        out.println("Account 3 holds $" + accounts[3]);
     %>
  </BODY>
</HTML>

You can see this code at work in Figure 2.7.

Creating an array.

Figure 2.7. Creating an array.

You can now refer to the items in the array using a numeric index, which organizes them in an easy way. You can also combine the declaration and creation steps into one step:

<HTML> 
  <HEAD>
    <TITLE>Creating an Array</TITLE>
  </HEAD>

  <BODY>
    <H1>Creating an Array</H1>
    <%
        double accounts[] = new double[100];
        accounts[3] = 119.63;

        out.println("Account 3 holds $" + accounts[3]);
     %>
  </BODY>
</HTML>

In fact, you can also initialize arrays with values when you create the array. To do that, you enclose the list of values you want to store in the array in curly braces ({ and }). For example, this code creates four accounts, and stores $23.66 in accounts[0], $68.09 in accounts[1], $2889.00 in accounts[2], and $119.63 in accounts[3]:

<HTML> 
  <HEAD>
    <TITLE>Initializing an Array</TITLE>
  </HEAD>

  <BODY>
    <H1>Initializing an Array</H1>
    <%
        double accounts[] = {23.66, 68.09, 2889.00, 119.63};

        out.println("Account 3 holds $" + accounts[3]);
     %>
  </BODY>
</HTML>

Tip

Here's another thing to remember about arrays—you can get the length of an array (that is, the number of elements in an array) with the length data member. For example, the expression accounts.length will hold 4 in the previous example. See “The for Loop” in Day 3, “Branching, Looping, and Creating Methods,” for an example.

This is fine as far as it goes, but there's more. For example, what if our customers want a checking account in addition to a savings account? How can we handle that and still keep things indexed by account number?

The accounts[] array we've already created is a one-dimensional array, which means you can think of it as a single list of numbers that you can index with one index number. However, arrays can have multiple dimensions in Java, which means that you can have multiple array indexes. In this next example, you can extend accounts[] into a two-dimensional array, accounts[][], to handle both a savings and checking account. The first index of accounts[][] will be 0 for savings accounts and 1 for checking accounts, and the second index will be the account number as before. You can see how that looks in code in Listing 2.9.

Example 2.9. Using Multidimensional Arrays (ch02_09.jsp)

<HTML>
  <HEAD>
    <TITLE>Using Multidimensional Arrays</TITLE>
  </HEAD>

  <BODY>
    <H1>Using Multidimensional Arrays</H1>
    <%
        double accounts[][] = new double[2][100];

        accounts[0][3] = 119.63;
        accounts[1][3] = 194.07;

        out.println("Savings Account 3 holds $" + accounts[0][3] + "<BR>");
        out.println("Checking Account 3 holds $" + accounts[1][3]);
     %>
  </BODY>
</HTML>

Now that accounts[][] is a two-dimensional array, each item in it is referred to using two index values; for example, the savings balance for account 3 is now accounts[0][3], and the checking balance is accounts[1][3]. You can see the results in Figure 2.8.

Creating a multidimensional array.

Figure 2.8. Creating a multidimensional array.

That gives us a solid start with storing data in Java—we've taken a look at working with literals, simple variables, strings, objects, and arrays. We've gotten data storage down, now let's take a look at how to work with and manipulate that data using operators.

Working with Operators

The most basic way to work with the data in a program is with the built-in Java operators. For example, say you have stored a value of 23 in one variable and a value of 4 in another. You can multiply those two values with the Java multiplication operator, *, which you can see in Listing 2.10.

Example 2.10. Using Operators(ch02_10.jsp)

<HTML>
  <HEAD>
    <TITLE>Using Operators</TITLE>
  </HEAD>

  <BODY>
    <H1>Using Operators</H1>
    <%
        int operand1 = 23, operand2 = 4, product;

        product = operand1 * operand2;

        out.println(operand1 + " * " + operand2 +
            " = " + product);
     %>
  </BODY>
</HTML>

You can see the results in Figure 2.9, where we learn that 23 * 4 is 92.

Using Java operators.

Figure 2.9. Using Java operators.

The following operators are available in Java:

  • Decrement operator (--)

  • Subtraction operator (-) This is also the negation operator if you use it in front of a value; for example, the expression -x evaluates to the value in x with that value's numeric sign flipped—positive values become negative and negative values become positive.

  • Logical unary NOT operator (!)

  • Not equal to operator (!=)

  • Modulus operator (%)

  • Modulus assignment operator (%=)

  • Logical AND operator (&)

  • Short-circuit AND operator (&&)

  • Bitwise AND assignment operator (&=)

  • Multiplication operator (*)

  • Multiplication assignment operator (*=)

  • Division operator (/)

  • Division assignment operator (/=)

  • if-then-else operator (?:)

  • Logical Xor operator (^)

  • Bitwise Xor assignment operator (^=)

  • Logical OR operator (|)

  • Short-circuit OR operator (||)

  • Bitwise OR assignment operator (|=)

  • Bitwise unary NOT operator (~)

  • Addition operator (+)

  • Increment operator (++)

  • Addition assignment operator (+=)

  • Less than operator (<)

  • Shift left operator (<<)

  • Shift left assignment operator (<<=)

  • Less than or equal to operator (<=)

  • Assignment operator (=)

  • Subtraction assignment operator (-=)

  • Equal to operator (==)

  • Greater than operator (>)

  • Greater than or equal to operator (>=)

  • Shift right operator (>>)

  • Shift right assignment operator (>>=)

  • Shift right with zero fill operator (>>>)

  • Shift right zero fill assignment operator (>>>=)

We'll see these various operators, and how to use them, throughout the book—starting right here, with a look at the common Java operators.

Assignment Operators

The most basic operators are the assignment operators, which we've already seen. You use the = operator to assign a variable a literal value, the value in another variable, and so on, like this, where the code is assigning the variable named var1 a value of 12:

<HTML> 
  <HEAD>
    <TITLE>Assignment Operators</TITLE>
  </HEAD>

  <BODY>
    <H1>Assignment Operators</H1>
    <%
        int var1;

        var1 = 12;

        out.println("The total value = " + var1);
     %>
  </BODY>
</HTML>
Assignment Operators
int var1 = 15; 

To add 12 to the value in this variable, we can use this code:

int var1 = 15; 
var1 = var1 + 12;

On the other hand, we can use the combination operator += to do the same thing; this operator is short for “add the value of the second operand to the value of the first operand and assign the result to the first operand”:

int var1 = 15; 
var1 += 12;

There are quite a few combination assignment operators in Java:

  • Modulus assignment (%=)

  • Bitwise AND assignment (&=)

  • Multiplication assignment (*=)

  • Division assignment (/=)

  • Bitwise Xor assignment (^=)

  • Bitwise OR assignment (|=)

  • Addition assignment (+=)

  • Shift left assignment (<<=)

  • Less than or equal to (<=)

  • Subtraction assignment (-=)

  • Shift right assignment (>>=)

  • Shift right zero fill assignment (>>>=)

Incrementing and Decrementing Operators

The Java ++ operator increments its operand by one, and the -- operator decrements its operand by one. For example, if value holds 0, then after you execute value++, value will hold 1.

Incrementing and Decrementing Operators
value2 = value1++; 

when the statement is completed, value2 will actually be left with the original value in value1 (not the incremented value), and the value in value1 will have been incremented. You can see an example showing code using ++ as both a prefix and postfix operator in Listing 2.11.

Example 2.11. Incrementing and Decrementing Using Operators (ch02_11.jsp)

<HTML>
  <HEAD>
    <TITLE>Incrementing and Decrementing</TITLE>
  </HEAD>

  <BODY>
    <H1>Incrementing and Decrementing</H1>
    <%
        int value1 = 0, value2 = 0;

        out.println("value1 = " + value1 + "<BR>");
        out.println("value2 = " + value2 + "<BR>");


        value2 = value1++;

        out.println("After <B>value2 = value1++</B>:" + "<BR>");
        out.println("value1 = " + value1 + "<BR>");
        out.println("value2 = " + value2 + "<BR>");

        int value3 = 0, value4 = 0;

        out.println("<BR>");
        out.println("value3 = " + value3 + "<BR>");
        out.println("value4 = " + value4 + "<BR>");

        value4 = ++value3;

        out.println("After <B>value4 = ++value3</B>:" + "<BR>");
        out.println("value3 = " + value3 + "<BR>");
        out.println("value4 = " + value4 + "<BR>");
     %>
  </BODY>
</HTML>

You can see the results of this code in Figure 2.10, where you can see the ++ operator working as both a prefix and postfix operator.

Using ++ as both a prefix and postfix operator.

Figure 2.10. Using ++ as both a prefix and postfix operator.

Multiplication and Division Operators

You use * to multiply values and / to divide values in Java. You can see an example where the code uses * and / on double values in Listing 2.12.

Example 2.12. Multiplication and Division (ch02_12.jsp)

<HTML>
  <HEAD>
    <TITLE>Multiplication and Division</TITLE>
  </HEAD>

  <BODY>
    <H1>Multiplication and Division</H1>
    <%
        double double1 = 6, double2 = 8, double3 = 5, doubleResult;
        doubleResult = double1 * double2 / double3;
        out.println("6 * 8 / 5 = " + doubleResult);
     %>
  </BODY>
</HTML>

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

Using multiplication and division.

Figure 2.11. Using multiplication and division.

Caution

You don't have to use double values with multiplication and division, of course, but note that if you use division on integer values, you run the risk of having your results truncated, losing the decimal part when the results are stored in integer format.

Addition and Subtraction Operators

As you might expect, the most basic operators are + and -, which you use for addition and subtraction. You can see an example putting them to work in Listing 2.13.

Example 2.13. Addition and Subtraction (ch02_13.jsp)

<HTML>
  <HEAD>
    <TITLE>Addition and Subtraction</TITLE>
  </HEAD>

  <BODY>
    <H1>Addition and Subtraction</H1>
    <%
        int operand1 = 15, operand2 = 24, sum, difference;

        sum = operand1 + operand2;
        difference = operand1 - operand2;

        out.println(operand1 + " + " + operand2 + " = " + sum + "<BR>");
        out.println(operand1 + " - " + operand2 + " = " + difference);
     %>
  </BODY>
</HTML>

You can see these two operators at work in Figure 2.12, where Java is performing various additions and subtractions for us.

Using addition and subtraction.

Figure 2.12. Using addition and subtraction.

Relational Operators

Relational Operators

Suppose we set an integer variable named temperature to 70; in that case, the logical expression temperature < 55 evaluates to false. You can use this logical expression in an if statement, as we'll see in Day 3; if the logical expression in the if statement is true, the code in the body of the if statement is executed (and not otherwise). For example, the message "Just right." is written to the Web page if the value in temperature is less than 80 degrees in Listing 2.14.

Example 2.14. Using Relational Operators (ch02_14.jsp)

<HTML>
  <HEAD>
    <TITLE>Using Relational Operators</TITLE>
  </HEAD>

  <BODY>
    <H1>Using Relational Operators</H1>
    <%
        int temperature = 70;

        if (temperature < 80) {
            out.println("Just right.");
        }
     %>
  </BODY>
</HTML>

You can see the results in Figure 2.13, where we see that the temperature is just right.

Using relational operators.

Figure 2.13. Using relational operators.

Here are all the Java relational operators, and we'll see them at work tomorrow and throughout the book:

  • Greater than (>) For example, operand1 > operand2 returns true if operand1 is greater than operand2.

  • Greater than or equal to (>=)

  • Less than (<)

  • Less than or equal to (<=)

  • Equal to (==)

  • Not equal to (!=)

You can combine multiple logical expressions with the logical operators—coming up next.

Tip

Here's a pitfall to avoid—when you're creating a logical expression to test if two values are equal, make sure you use == instead of just =. For example, the expression budget == 0 is true if the value in budget is 0, but the expression budget = 0 assigns a value of 0 to budget. Using = instead of == in logical expressions is a very common mistake.

Logical Operators

You use the logical operators, && and ||, to connect logical expressions, as when you want to make sure the temperature is both above 60 degrees and below 90 degrees. The two logical operators are the logical AND (&&), and the logical OR (||).

Here's how these operators work: the OR operator || returns false when both its operands are false, and true otherwise. The AND operator && returns true when both its operands are true, and false otherwise. You use these operators to tie logical expressions together—use && when you want two logical expressions to both be true, and || when you only require one of two expressions to be true. For example, you can see how to make sure the temperature is both above 60 degrees and below 90 degrees in Listing 2.15.

Example 2.15. Using Logical Operators (ch02_15.jsp)

<HTML>
  <HEAD>
    <TITLE>Using Logical Operators</TITLE>
  </HEAD>

  <BODY>
    <H1>Using Logical Operators</H1>
    <%
        int temperature = 70;

        if (temperature < 90 && temperature > 60) {
            out.println("Picnic time!");
        }
     %>
  </BODY>
</HTML>

You can see the results in Figure 2.14, where we see it's time for a picnic.

Using logical operators.

Figure 2.14. Using logical operators.

You can see how the || and && operators work on their two operands (named a and b here) in Table 2.4. For example, if a is true and b is false, a || b is true, but a && b is false.

Table 2.4. The Logical Operators

a

b

a || b (OR)

a && b (AND)

false

false

false

false

true

false

true

false

false

true

true

false

true

true

true

true

Understanding Operator Precedence

As you've seen today, Java supports a large number of operators. But what happens if you start mixing them in the same statement? Which operator will Java execute first? For example, take a look at this example, where the code is trying to add 10 and 24 (to get 34) and then divide the sum by 2 (to get 17):

double value; 
value = 10 + 24 / 2;
out.println("The value = " + value);

But here's what you see when you execute this code:

The value = 22.0 
Understanding Operator Precedence

To specify to Java the exact order in which you want the operators to be evaluated, you can use parentheses to group those operations you want performed first. You can see how that looks in Listing 2.16, where the parentheses around 10 + 24 make sure the addition operation is performed first.

Example 2.16. Using Operator Precedence (ch02_16.jsp)

<HTML>
  <HEAD>
    <TITLE>Checking Operator Precedence</TITLE>
  </HEAD>

  <BODY>
    <H1>Checking Operator Precedence</H1>
    <%
        double value;

        value = (10 + 24) / 2;

        out.println("The value = " + value);
     %>
  </BODY>
</HTML>

You can see the results in Figure 2.15, where we do indeed get the answer we expected.

Using operator precedence.

Figure 2.15. Using operator precedence.

You'll find the Java operator precedence in Table 2.5, from highest to lowest—operators with higher precedence are executed before operators with lower precedence in a compound expression. Operators on the same line have the same precedence, and if Java finds a number of operators of the same precedence in a compound expression, those operators are executed from left to right.

Table 2.5. Java Operator Precedence

( )

[ ]

.

 

++

~

!

*

/

%

 

+

-

  

>>

>>>

<<

 

>

>=

<

<=

==

!=

  

&

   

^

   

|

   

&&

   

||

   

?:

   

=

[operator]=

  

Now you have the foundation you'll need to work with data and operators throughout the book. Tomorrow, you're going to build on that Java foundation, seeing how to make decisions in code, as well as how to create looping statements and methods.

Summary

Today you've made a lot of progress in working with Java. You've gotten the basics down of the Java environment that you'll be working with in JSP, including getting an overview of the ready-made Java objects (like out) that are already available for you to use in that environment.

Today you've started getting to the very heart of programming—working with data. There are a number of ways of handling data in Java. The first is simply to use literals, which are literal numbers or text entered directly into your code statements. Literals are fine, but you can't really manipulate them in code—for that, you need variables.

Variables enable you to store data in a program and refer to that data by name. For example, if you name an integer variable temperature, you can store integer values in temperature and use that name to refer to the stored value in your code. In addition, you can combine a whole set of data into arrays.

There are plenty of data types in Java, each with its own capacity—for example, a double variable can store values with higher mathematical precision than a simple float variable. Java is a stickler about maintaining type integrity, so you don't lose any precision inadvertently, and there are two ways to convert between data types—automatically, and with a type cast.

You also learned more about Java objects today. You can create objects from classes, and in that way, a class is an object's type, much like int is the type of the temperature variable we just discussed. You can also store objects in variables whose type is the object's class.

Unlike simple variables, objects can contain methods and multiple data members. You can create objects using a constructor, which is a special method with the same name as the class you're creating objects from, together with the new operator. The constructor method will return the newly created object.

You can manipulate and work on the data in your code with Java operators. There's a good selection of operators in Java, as we've seen, and they provide us with a basic way of working on data. Besides numerical operators, Java also supports relational and logical operators that enable you to work with values of true and false of the kind we'll use in if statements tomorrow.

Q&A

Q1:

I can't change the contents of a String object—is there any string class I can change the context of, after an object of that class has been created?

A1:

Yes. You can use the StringBuffer class, which we'll see in Day 4.

Q2:

How are Java objects different from Java's built-in basic data types like int?

A2:

All Java objects are based on the java.lang.Object class, whereas basic data types are not. That is, all objects already have methods and data members built into them from java.lang.Object, which the basic data types don't. You'll see more on this issue in Day 7.

Workshop

This workshop tests whether you understand all the concepts you learned today. It's a good idea to master today's concepts by honing your knowledge here before starting tomorrow's material. You can find the answers to the quiz questions in Appendix A.

Quiz

1:

What are the built-in objects in JSP?

2:

How do you skip to the next line in the browser when using println?

3:

Name all the floating-point built-in data types in Java.

4:

What values can Boolean variables hold?

5:

If you can't change a String object after it's been created, why are there String methods like toLowerCase, toUpperCase, and replace?

Exercises

1:

Can you guess what the expression 2 + 3 / 5 * 17 + 7 * 9 evaluates to? Try it out in a JSP page to check your answer.

2:

Using the String object's indexOf and substring methods, find and display the sixth word in the sentence “JavaServer Pages is going to dominate the world!” (Hint: search for spaces repeatedly!)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.165.70