Friday, February 4, 2011

Chapter 25: Arithmetic Operators

Arithmetic Operators are those operators that are used for arithmetic or mathematical operators. I am sure you are already familiar with the basic arithmetic operators. They are:

• + addition
• – subtraction
• * multiplication
• / division

These operators can be used in the standard way:
int x = 5 * 3;
int y = x - 4;

System.out.println("x - 4 is " + y); // Prints 11

The Remainder (%) Operator

One operator you might not be as familiar with is the remainder operator, %. The remainder operator divides the left operand by the right operand, and the result is the remainder, as the following code demonstrates:

class TestReminderOperator {
public static void main (String [] args) {
int x = 15;
int y = x % 4;
System.out.println("The result of 15 % 4 is the "
+ "remainder of 15 divided by 4. The remainder is " + y);

Running class TestReminderOperator prints the following:
The result of 15 % 4 is the remainder of 15 divided by 4. The
remainder is 3

Tip: Expressions are evaluated from left to right by default. You can change this sequence, or precedence, by adding parentheses. Also remember that the *, /, and % operators have a higher precedence than the + and - operators.

String Concatenation Operator

The plus ‘+’ operator can also be used to concatenate two strings together:

String animal = "Indian" + "Tiger";

String concatenation gets interesting when you combine numbers with Strings. Check out the following:
String a = "String";
int b = 3;
int c = 7;
System.out.println(a + b + c);

Will the + operator act as a plus sign when adding the int variables b + c? Or will the + operator treat 3 and 7 as characters, and concatenate them individually? Will the result be String10 or String37? The int values were simply treated as characters and glued on to the right side of the String, giving the result:


So we could read the previous code as

“Start with String a, String, and add the character 3 (the value of b) to it, to produce a new string String3, and then add the character 7 (the value of c) to that, to produce a new string String37, then print it out.”

However, if you put parentheses around the two int variables, as follows,
System.out.println(a + (b + c));

you’ll get this: String10

Using parentheses causes the (b + c) to evaluate first, so the rightmost + operator functions as the addition operator, given that both operands are int values. The key point here is that within the parentheses, the left-hand operand is not a String. If it were, then the + operator would perform String concatenation. The previous code can be read as

“Add the values of b + c together, then take the sum and convert it to a String and concatenate it with the String from variable a.”

The rule to remember here is:

If either operand is a String, the + operator becomes a String concatenation operator. If both operands are numbers, the + operator is the addition operator.

You’ll find that sometimes you might have trouble deciding whether, say, the left-hand operator is a String or not. On the exam, don’t expect it to always be obvious. (Actually, now that we think about it, don’t expect it ever to be obvious.) Look at the following code:

System.out.println(x.doSomething() + 7);

You can’t know how the + operator is being used until you find out what the doSomething() method returns! If doSomething() returns a String, then 7 is concatenated to the returned String. But if doSomething() returns a number, then the + operator is used to add 7 to the return value of doSomething().

Finally, you need to know that it’s legal to mush together the compound additive operator (+=) and Strings, like so:

String s = "123";
s += "45";
s += 67;

Since both times the += operator was used and the left operand was a String, both operations were concatenations, resulting in


Exam Tip:
If you don’t understand how String concatenation works, especially within a print statement, you could actually fail the exam even if you know the rest of the answer to the questions! Because so many questions ask, “What is the result?”, you need to know not only the result of the code running, but also how that result is printed. Although there will be at least a few questions directly testing your String knowledge, String concatenation shows up in other questions on virtually every objective. Experiment! For example, you might see a line such as
int b = 2;
System.out.println("" + b + 3);

which prints 23
but if the print statement changes to
System.out.println(b + 3);

then the result becomes 5

Increment and Decrement Operators

Java has two operators that will increment or decrement a variable by exactly one. These operators are composed of either two plus signs (++) or two minus signs (--):

• ++ increment (prefix and postfix)
• -- decrement (prefix and postfix)

The operator is placed either before (prefix) or after (postfix) a variable to change its value. Whether the operator comes before or after the operand can change the outcome of an expression. Examine the following:

1. class TestIncAndDecOperators {
2. static int gamers = 0;
3. public static void main (String [] args) {
4. System.out.println("gamers online: " + gamers++);
5. System.out.println("The value of gamers is "
+ gamers);
6. System.out.println("The value of gamers is now "
+ ++gamers);
7. }
8. }

Notice that in the fourth line of the program the increment operator is after the variable gamers. That means we’re using the postfix increment operator, which causes gamers to be incremented by one but only after the value of gamers is used in the expression. When we run this program, it outputs the following:

%java TestIncAndDecOperators
gamers online: 0
The value of gamers is 1
The value of gamers is now 2

Notice that when the variable is written to the screen, at first it says the value is 0. Because we used the postfix increment operator, the increment doesn’t happen until after the gamers variable is used in the print statement. Get it? The “post” in postfix means after. Line 5 doesn’t increment gamers; it just outputs its value to the screen, so the newly incremented value displayed is 1. Line 6 applies the prefix increment operator to gamers, which means the increment happens before the value of the variable is used, so the output is 2.

Expect to see questions mixing the increment and decrement operators with other operators, as in the following example:

int x = 2; int y = 3;

if ((y == x++) | (x < ++y)) {

System.out.println("x = " + x + " y = " + y);


The preceding code prints: x = 3 y = 4

You can read the code as follows: “If 3 is equal to 2 OR 3 < 4”

The first expression compares x and y, and the result is false, because the increment on x doesn’t happen until after the == test is made. Next, we increment x, so now x is 3. Then we check to see if x is less than y, but we increment y before comparing it with x! So the second logical test is (3 < 4). The result is true, so the print statement runs.

As with String concatenation, the increment and decrement operators are used throughout the exam, even on questions that aren’t trying to test your knowledge of how those operators work. You might see them in questions on for loops, exceptions, even threads. Be ready.

Exam Tip: Watch out for questions that use the increment or decrement operators on a final variable. Because final variables can’t be changed, the increment and decrement operators can’t be used with them, and any attempt to do so will result in a compiler error. The following code won’t compile:

final int x = 5;
int y = x++;

and produces the error: cannot assign a value to final variable x
int y = x++;
You can expect a violation like this to be buried deep in a complex piece of code. If you spot it, you know the code won’t compile and you can move on without working through the rest of the code.

This question might seem to be testing you on some complex arithmetic operator trivia, when in fact it’s testing you on your knowledge of the final modifier.

Conditional Operator

The conditional operator or the ternary operator (has three operands) is used to evaluate boolean expressions, much like an if statement except instead of executing a block of code if the test is true, a conditional operator will assign a value to a variable. In other words, the goal of the conditional operator is to decide which of two values to assign to a variable. This operator is constructed using a ? (question mark) and a : (colon). The parentheses are optional. Its structure is:

x = (boolean expression) ? value to assign if true : value to assign if false

Let’s take a look at a conditional operator in code:

class TestTernaryOperator {

public static void main(String [] args) {

int numOfCars = 3;

String status = (numOfCars<4) ? "Car limit not exceeded"

: "too many Cars";

System.out.println("This Car status is " + status);



You can read the preceding code as

Set numOfCars equal to 3. Next we’re going to assign a String to the status variable. If numOfCars is less than 4, assign “Car limit not exceeded” to the status variable; otherwise, assign “too many Cars” to the status variable.

A conditional operator starts with a boolean operation, followed by two possible values for the variable to the left of the assignment (=) operator. The first value (the one to the left of the colon) is assigned if the conditional (boolean) test is true, and the second value is assigned if the conditional test is false

Exam Tip:
Don’t expect many questions using conditional operators, but remember that conditional operators are sometimes confused with assertion statements, so be certain you can tell the difference. Don’t worry about Assertions, we will be looking into them in great detail in one of the future chapters.

Previous Chapter: Chapter 24 - instanceOf Operator

Next Chapter: Chapter 26 - Logical Operators

No comments:

Post a Comment

© 2013 by All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.


Google+ Followers