Section 3.6. Operators

   

3.6 Operators

Binary operators are used to perform tasks with two operands. There are operators for arithmetic, incrementing and decrementing , logical operations, and bitwise operations.

3.6.1 Arithmetic Operators

These are as you would expect: +, “, /, and * for addition, subtraction, division, and multiplication. The remainder of an integer operation is given by mod (%).

Note

Instead of writing out MOD as you might in ColdFusion (for example, 10 MOD 3), Java uses the % sign. So 10 % 3 is 1.


It is common to have to modify an existing value. Java offers a concise way to use arithmetic operators. Instead of writing

 x = x + 1; 

you can write

 x += 1; 

These are equivalent operations. You can also perform other mathematical operations ( “, *, /) in this manner.

Note

ColdFusion does not offer this shortcut.


3.6.2 Incrementing and Decrementing Operators

Increment and decrement operations are something we need to do very frequently. Looping over a result set or an array one item at a time are common examples. Java makes this convenient with special operators that increase or decrease a variable by one.

The straightforward way to do an operation like this is to simply state the variable name and add one to it. For instance:

 int x = 0;  int y = x + 1; 

It is more concise, however, to write this:

 int x = 0;  int y = x++; // value of y is 0 

By the same token you can subtract like this:

 int x = 10;  int y = x--; // value of y is 10 

The above examples make use of what is called post-increment and post-decrement operations. The adjustment by one is made after the current value of the variable is evaluated. Note that you can only use these operators on variables , not only literal numbers themselves . For instance, this is illegal:

 10++; // illegal! 

You can also pre-increment and pre-decrement, as shown here:

 int x = 10;  int y = --x; // value of y is 9 

This seems straightforward enough. However, you should use these operators with some degree of caution. This is because they can be confusing and difficult to keep track of. Consider the code in prepostOps.java :

3.6.3 prepostOps.java

 /*  File: chp3.prepostOps.java Purpose: demonstrate post-increment and pre-increment */ public class prepostOps { public static void main(String [] args) { int x = 10; int y = 2; int z = y + x--; System.out.println("z is: " + z); // z is 12 z += --x; System.out.println("now z is: " + z); // z is 20! // here's why: System.out.println("x is: " + x); // x is 8     } } // eof 

In prepostOps.java , z is assigned the value of y (2) + x , which is 10 when the operation occurs. Because of post-decrementing, one is subtracted from x only after the operation is performed. So z is 12 ( y + x ). Immediately after this operation, x becomes 9. Next, we take the current value of z (12) and then subtract one from x (9 “ 1 = 8) before performing the addition.

3.6.4 Logical and Boolean Operators

There are logical operators such as < and > for less than and greater than. Boolean operators also exist to express different conditions, such as && for AND , and for OR . Logical operators are shown in Table 3.7 and boolean operators are shown in Table 3.8.

Table 3.7. Logical Operators

Operation

Operator

Example

Equal to

  ==  

(x == 1 )

Not equal to

  !=  

(x != 1 )

Less than

<

(x < 1 )

Greater than

>

(x > 1 )

Less than or equal to

  <=  

(x <= 1)

Greater than or equal to

  >=  

(x >= 1)

Note

In ColdFusion, you cannot use these same operator symbols because of how ColdFusion expressions work. You are used to writing expressions like this: <cfif x EQ y> . That is in part because assignment and evaluation in ColdFusion are somewhat conflated (i.e., ColdFusion has no == operator, and = always means assignment).


Table 3.8. Boolean Operators

Operation

Operator

Example

AND

  &&  
 int x = 3; int y = 6; ((x = 3) && (y == 6)) 
  OR  
   
 int x = 3; int y = 6; (( x < 2)  ( y >= 6 )) 

NOT

!

 int x = 3; int y = 6; ( !( x == 2) ) 

The logical operators, as you would expect, are used in expressions that reduce to a boolean value. For instance,

 int x = 5;  x > 2; // true x != 5; // false 

Note

Java "short circuits" the same way that ColdFusion does. That is, when using && in an expression, if the first part is determined to be false, the second part is never evaluated, because the outcome is already necessarily false. Likewise, when using , if the first part is determined to be true, then the second part is not evaluated, because the outcome is already necessarily true. The syntax of the operators is a little different, but the behavior as you expect it to work in ColdFusion is the same. Note that there is no short circuit XOR operation.


Java also supports ternary operations. A ternary expression is written as

 condition ? action1 : action2 

If the condition evaluates to true , the first action is taken; if false , the second action is taken. The ternary operator is shorthand for the following construct:

 if  (aCondition) trueCode else falseCode  // conditional      (aCondition) ? trueCode : falseCode // ternary 

The result expressions must have types that are assignment-compatible. That is, you must be able to assign the value of the result of one expression to the type of the other expression without an explicit cast. Casting, which is discussed in detail later, is the practice of sending a value of one type into another type. For example, you can assign an int value to a double value without requiring an explicit cast. If neither type is assignable to the other, the operation is not valid.

The usefulness of a ternary operator is that it can appear in the middle of an expression; if statements cannot. You can use the ternary operator in an expression because it has a value. Though it is more concise to use the ternary operator than the corresponding if statement, programmers' use of it varies widely.

Note

Ternary expressions are represented in ColdFusion as an Immediate If (the IIF function). You may have written something like iif(y eq 0, DE("Error"), x/y) . It might seem at first that the corresponding Java expression would be something like: int x = 8; int y = 4; String msg = "Error"; System.out.println( y == 0 ? msg : x/y); . This won't compile. Remember that Java is strongly typed; ColdFusion is not. Use of the Immediate If is generally discouraged in ColdFusion, as it can add a slight decrease in performance. This is not the case with Java.


3.6.5 Bit Manipulation Operators

The bitwise operators allow you to manipulate individual bits that make up an integer value (which, you may recall, includes char ) in accordance with the rules for AND ( & ), OR ( ), and the exclusive or ( XOR , represented as ^ ). For instance, given an integer, you can get the value for the bit in a specified position (whether the bit is a 0 or a 1).

An AND operator results in 1 if both bits are 1. The OR operator results in 1 if either bit is a 1. The XOR operator results in 1 if the bits are of different values.

Note that while the operators for bitwise and logical operations appear the same, Java knows the difference based on the types of the operands involved. If you ask Java to mix, say, a boolean and an int in an expression, it will refuse .

You can also use >> and << operators; these shift the bit pattern of an integer to the right or left, respectively. The left-hand side of the expression indicates what to shift, and the right-hand side of the expression indicates how far to shift.

  <<  

Shift bits left and fill with zero bits on the right-hand side.

  >>  

Shift bits right and fill with the highest sign bit on the left-hand side.

>>>

Shift bits right and fill with zero bits on the left-hand side.

For example:

3.6.6 bitwise.java

 /*  File: chp3.bitwise.java Purpose: demonstrate bit manipulation Author: E Hewitt */ public class bitwise { public static void main(String [] args) { int x = 0; int y = (x & 8) / 8; // prints 0 x = 1; y = (x  4) / 4; System.out.println("result: " + y); // prints 1 int i = 7; // in binary, 7 = 111 /* shifting everything to the right 1 and filling    the remaining bits with 0 would result in    11 (base 2), or 3 (base 10) */ System.out.println("result: " + (i >>> 1)); //prints 3 // try it again--guess the result int j = 10; // in binary, 10 is written 1010 System.out.println("result: " + (j >>> 2)); // j now 0010 // answer: convert j to base10 (prints 2)     } } 

While that may seem arcane, these operators can be useful because Java will often have return values declared as int s, and these can be manipulated at the most fundamental level.

3.6.7 instanceof

The instanceof operator evaluates whether a given reference refers to an object that is an instance of a certain class (or interface). instanceof is useful in downcasting a reference, which we will discuss in detail later.


   
Top


Java for ColdFusion Developers
Java for ColdFusion Developers
ISBN: 0130461806
EAN: 2147483647
Year: 2005
Pages: 206
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net