Using Expressions In Java

Workshop: Using Expressions


As you worked on a particularly unpleasant math problem in school, did you ever complain to a higher power, protesting that you would never use this knowledge again in your life? Sorry to break this to you, but all your teachers were right: Those math skills are going to be used in your computer programming.

That's the bad news. The good news is that the computer will do any of the math that you ask it to do. As mentioned earlier in this hour, any instructions you give a computer program involving math are called expressions. Expressions will be used frequently in your computer programs. You can use them for tasks such as the following:

·         Changing the value of a variable

·         Counting the number of times something has happened in a program

·         Using a mathematical formula in a program

As you write computer programs, you will find yourself drawing upon your old math lessons as you use expressions. Expressions can use addition, subtraction, multiplication, division, and modulus division.

To see expressions in action, return to your word processor and close the Variable.java file if it is still open. Create a new file and save it as Elvis.java. The Elvis program creates a fictional person whose weight loss and weight gain can be tracked with mathematical expressions. Instead of adding statements to the program piece by piece, enter the full text of Listing 5.2 into the word processor. Each part of the program will be discussed in turn.

Listing 5.2. The Elvis program.

 

 1: class Elvis {

 2:    public static void main(String[] arguments) {

 3:        int weight = 250;

 4:        System.out.println("Elvis weighs " + weight);

 5:        System.out.println("Elvis visits a few all-you-can-eat rib joints.");

 6:        System.out.println("Elvis throws a Thanksgiving luau.");

 7:        weight = weight + 10;

 8:        System.out.println("Elvis now weighs " + weight);

 9:        System.out.println("Elvis discovers aerobics.");

10:        weight = weight - 15;

11:        System.out.println("Elvis now weighs " + weight);

12:        System.out.println("Elvis falls into a washing machine during the 13:        shrink cycle.");

14:        weight = weight / 3;

15:        System.out.println("Elvis now weighs " + weight);

16:        System.out.println("Elvis accidentally clones himself 12 times.");

17:        weight = weight + (weight * 12);

18:        System.out.println("The 13 Elvii now weigh " + weight);

19:     }

20: }


When you're done, save the file and use the javac tool to compile the program. In the same directory as the Elvis.java file, type the following command to compile the Elvis program:

javac Elvis.java

If it compiles without any errors, you will not see any output; javac responds only if something goes wrong. If you do see error messages, check the line number that is listed in the error message to look for typos. Correct any typos that you find and compile the program.

Next, run the program by typing the following command:

java Elvis

Listing 5.3 shows the output for this program.

Listing 5.3. The output of the Elvis program.

 

Elvis weighs 250

Elvis visits a few all-you-can-eat rib joints.

Elvis throws a Thanksgiving luau.

Elvis now weighs 260

Elvis discovers aerobics.

Elvis now weighs 245

Elvis falls into a washing machine during the shrink cycle.

Elvis now weighs 81

Elvis accidentally clones himself 12 times.

The 13 Elvii now weigh 1053


As in the other programs that you have created, the Elvis program uses a main() block statement for all of its work. This statement can be divided into the following five sections:

1. Lines 3-4: The initial weight of Elvis is set to 250.

2.
Lines 5-8: Elvis gains weight.

3.
Lines 9-11: Elvis loses weight.

4.
Lines 12-14: Elvis reduces in size dramatically.

5.
Lines 15-17: Elvis multiplies.

Line 3 creates the weight variable and designates it as an integer variable with int. The variable is given the initial value 250, and it is used throughout the program to monitor Elvis' weight.

The next line is similar to several other statements in the program:

System.out.println("Elvis weighs " + weight);

The System.out.println() command displays a string that is contained within the parentheses. In the preceding line, the text Elvis weighs is displayed, followed by the value of the weight variable. There are numerous System.out.println() statements in the program. If you're still unclear about how these statements work, look at each of them in Listing 5.2 and compare them to the corresponding lines in Listing 5.3.

All About Operators

Four different mathematical expressions are used in the Elvis program to add weight to Elvis, subtract weight from Elvis, divide it, and finish it off with some multiplication. Each of these expressions uses symbols (+, -, *, /, and %) called operators. You will be using these operators to crunch numbers throughout your Java programs.

An addition expression in Java uses the + sign, as in Line 7 of your program:

weight = weight + 10;

This line sets the weight variable equal to its current value plus 10. Because the weight was set to 250 when it was created, Line 7 changes weight to 260.

A subtraction expression uses the - sign, as in Line 10:

weight = weight - 15;

This expression sets the weight variable equal to its current value minus 15. The weight variable is now equal to 245.

A division expression uses the / sign, as in Line 13:

weight = weight / 3;

The weight variable is set to its current value divided by 3 and rounded down because weight is an integer. The weight variable is now equal to 81.

There's another expression that you can use to find the remainder of a division. When the value of the weight variable was divided by 3 in Line 13, a remainder of 2 was discarded in order for weight to remain as an integer value. To find a remainder from an expression, use the % operator. You could use the following statement to find the remainder of 245 divided by 3:

remainder = 245 % 3;

A multiplication expression uses the * sign. Line 16 uses a multiplication expression as part of a more complicated statement:

 

weight = weight + (weight * 12);

The weight * 12 part of the expression multiplies weight by 12. The full statement takes the current value of weight and adds it to weight multiplied by 12. This example shows how more than one expression can be combined in a statement. The result is that weight becomes 1,053--in other words, 81 + (81 * 12).

Incrementing and Decrementing a Variable

One thing you will need to do often is to change the value of a variable by 1. Because this task is so common, there are special, simplified ways to accomplish it in your Java programs. You can increase the value by 1, which is called incrementing the variable, or decrease the value by 1, which is decrementing the variable. You use special operators for each of these tasks.

To increment the value of a variable by 1, use the ++ operator, as in the following statement:

x++;

This statement adds 1 to the value stored in the x variable.

To decrement the value of a variable by 1, use the -- operator:

y--;

This statement reduces y by 1.

During Hour 1, "Becoming a Programmer," the name of the C++ programming language was described as a joke you'd understand later on. Now that you've been introduced to the increment operator ++, you have all the information you need to figure out why C++ has two plus signs instead of just one. If you're still having trouble, C++ adds new features and functionality to the C programming language in the same way that the ++ operator adds 1 to a variable. Just think: After you work through all 24 hours of this book, you'll be able to tell jokes that are incomprehensible to more than 99 percent of the world's population.

Operator Precedence

When you are using an expression with more than one operator, you need to know what order the computer will use as it works out the expression. Consider the following statement:

x = y * 3 + 5;

Unless you know what order the computer will use when working out the math in this expression, you cannot be sure what the x variable will be set to. If y is equal to 10 and multiplication occurs before addition, x will equal 35. If y equals 10 and addition occurs before multiplication, x will equal 80.

The following order is used when working out an expression:

·         Incrementing and decrementing take place first.

·         Multiplication, division, and modulus division occur next.

·         Addition and subtraction follow.

·         Comparisons take place next.

·         The equal sign = is used to set a variable's value.

Comparisons will be discussed during Hour 7. The rest has been described during this hour, so you should be able to figure out the result of the following statement:

int number = 5++ * 6 + 4 * 10 / 2;

This statement sets the number variable to 56. How does the computer come up with this number? First, the increment operator is handled, and 5++ is set to the value of 5 increased by 1--in other words, 6. The expression then becomes the following:

int number = 6 * 6 + 4 * 10 / 2;

Now, multiplication and division are handled from left to right. First, 6 is multiplied by 6. Then 4 is multiplied by 10 and that result is divided by 2 (4 * 10 / 2). The expression becomes the following:

int number = 36 + 20;

This expression results in the number variable being set to 56.

If you want an expression to be evaluated in a different order, you can use parentheses to group parts of an expression that should be handled first. For example, the expression x = 5 * 3 + 2; would normally cause x to equal 17 because multiplication is handled before addition. However, look at a modified form of that expression:

x = 5 * (3 + 2);

In this case, the expression within the parentheses is handled first, so the result equals 25. You can use parentheses as often as needed in a statement.

Summary

Now that you have been introduced to variables and expressions, you can give a wide range of instructions to your computer in a program. Programs that you write can accomplish many of the same tasks as a calculator by handling sophisticated mathematical equations with ease. Manipulating numbers is only one element of variable use. You also can handle characters, strings of characters, and special true-or-false values called boolean variables. The next hour will expand your knowledge of String variables and how they are used.

Post a Comment

Previous Post Next Post