Operators


Every language defines operators for performing mathematical operations, making comparisons, or for creating logical expressions. In addition to the operators that perform these functions, Java defines other operators that create or evaluate objects, call methods , and access data members .

There are three general kinds of operators, based on the number of operands they act upon. Unary operators act upon one operand. The increment and decrement operators are examples. Binary operators are placed between a left-hand side and right-hand side operator. The addition operator ( + ) is an example. Ternary operators work with three operands. Java defines one ternary operator that provides a shorthand version of an if-else statement.

This section describes the operators supported by Java according to operator type. Specifically we will cover ”

  • Arithmetic operators

  • Assignment operators

  • Increment/Decrement operators

  • Relational operators

  • Boolean operators

  • Bitwise operators

  • Miscellaneous operators

Arithmetic Operators

The operators in Table 6.1 perform the basic math functions of addition, subtraction, multiplication, and division. They are binary operators, meaning that they are placed between two operands. The modulus operator returns the remainder of its left-hand operand divided by its right-hand operand. The - operator also has a unary form that changes the sign of its operand. A positive value becomes negative and vice versa. The + operator is also used for concatenating strings.

Table 6.1. Arithmetic Operators

O PERATOR

P URPOSE

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Modulus (remainder)

The return value for the math operators depends on the data type of the operands. Floating point types ( float and double ) have precedence over integer types ( short , int , and long ). Higher precision types ( double , long ) have precedence over lower precision types ( float , int ). What this means is that a float added to a long will result in a float , a double multiplied by a float will result in a double , and so on.

Example: Using Arithmetic Operators

This example demonstrates some of the basic arithmetic operators in action. The output may look a little odd to you. There can be a small round-off error with floating point math. You have to be careful of this because, small though it may be, if you compared the value of the variable a to the value 15.28 ( if (a == 15.28) ) the comparison would be false. Note that the + operator is used in two contexts in this example. It is used as the addition operator and as a String concatenation operator with the println() method.

 public class ArithOpDemo {   public static void main(String args[]) {      double a = 2.3*8 - 4.12;      System.out.println("answer is " + a);      a = a + 1.0;      System.out.println("answer is " + a);   } } 

Output ”

 answer is 14.27999999998 answer is 15.27999999998 

Assignment Operators

The assignment operators supported by Java are shown in Table 6.2. The = operator is the basic binary assignment operator. The value of the right-hand operand is assigned to the left-hand operand. The other operators are shorthand operators that combine an assignment with an arithmetic or bitwise operation. For example, a += b is equivalent to a = a + b . The other compound assignment operators work in the same manner.

Example: Using Assignment Operators

This example is the same as the "Using Arithmetic Operators" example except the += operator is used. In addition to being more compact, assignment operators can help prevent bugs in your code. Let's say you defined two variables named N202 and N02 . You might accidentally type "N202 = N02 + 0.1" when you meant to type "N202 = N202 + 0.1." Using the += assignment operator would eliminate this possibility.

Table 6.2. Assignment Operators

O PERATOR

P URPOSE

=

Simple assignment

+=

a = a + b

“=

a = a “ b

*=

a = a * b

/=

a = a / b

%=

a = a%b

&=

a = a & b

=

a = a b

^=

a = a ^ b

>>=

a = a >> b

>>>=

a = a >>> b

<<=

a = a << b

 public class AssignOpDemo {   public static void main(String args[]) {     double a = 2.3*8.0 - 4.12;     System.out.println("answer is " + a);     a += 1.0;     System.out.println("answer is " + a);   } } 

Output ”

 answer is 14.27999999998 answer is 15.27999999998 

Increment/Decrement Operators

The unary operators in Table 6.3 are used to increment or decrement the value of their operands. The operand can be an integer or floating point type. The operator can perform the increment or decrement in either a prefix or postfix manner.

Table 6.3. Increment/Decrement Operators

O PERATOR

P URPOSE

++

Increment value by 1

Decrement value by 1

With a prefix operation, the operator is placed before the operand ( ++variable ). The increment or decrement occurs before any other operations are performed. When the operand is placed after the variable ( variable++ ), the increment or decrement is performed in a postfix manner, meaning it is done after any other operations take place. Because of this difference, you should be careful when combining an increment or decrement with other operations. To be safe, you can place the increment/decrement statement on a line by itself.

Example: Using the Increment Operator

The increment operator is used twice in this example ”to cycle through the elements of an array and to increment the value of the integer variable j .

 public class IncOpDemo {   public static void main(String args[]) {     int j = 0;     int[] intArray = new int[4];     for(int k=0; k<intArray.length; ++k) {       intArray[k] = ++j;       System.out.println("intArray["+k+"] = " +                             intArray[k]);     }   } } 

Output ”

 intArray[0] = 1 intArray[1] = 2 intArray[2] = 3 intArray[3] = 4 

The output of this program depends on whether the prefix or postfix version of the ++ operator is used. The way it is written, the increment happens and then the value is assigned to the array element. If the line were written as

 intArray[k] = j++; 

then the increment would have taken place after the assignment was performed. In this case, the output would have been

 intArray[0] = 0 intArray[1] = 1 intArray[2] = 2 intArray[3] = 3 

Relational Operators

The binary operators in Table 6-4 are used to compare one operand to another. They are commonly used in flow control structures such as if , while , and do-while statements. The return value from these operators is a boolean true or false . Unlike C where you can get into trouble by mistakenly typing = instead of == , Java will perform a type check of a conditional statement and won't allow syntax such as if (b = 2.0) .

Table 6.4. Relational Operators

O PERATOR

P URPOSE

==

Equal to

!=

Not equal to

>

Greater than

>=

Greater than or equal to

<

Less than

<=

Less than or equal to

Example: Using Relational Operators

This is a typical use of a relational operator in a scientific or engineering application. A while loop is used to test whether a computation has converged . The current error is compared against a preset tolerance and the calculation continues until the error is less than or equal to the tolerance. In this simple case, the error is simply cut in half during every iteration.

 public class RelationalOpDemo {   public static void main(String args[]) {     double tol = 0.001;     double error = 1.0;     int iteration = 0;     while (error >= tol) {       error *= 0.5;       ++iteration;     }     System.out.println("convergence achieved in " +                          iteration + " steps");   } } 

Output ”

 convergence achieved in 10 steps 

Boolean Operators

The boolean operators shown in Table 6-5 are used with boolean operands. A boolean operand is one that evaluates to a true or false value. The first five are binary operators that are used to link two boolean expressions. The logical AND operator ( & ) returns true if both operands are true. The logical OR operator ( ) returns true if either operand is true. The exclusive OR operator ( ^ ) returns true if either ”but not both ” operand is true. With these three operators, the right-hand operand will always be evaluated.

Table 6.5. Boolean Operators

O PERATOR

P URPOSE

&

Logical AND

Logical OR

^

Exclusive OR

&&

Conditional AND

Conditional OR

!

NOT

The conditional AND and OR operators work somewhat differently than their logical counterparts. With the conditional AND, the right-hand expression is only evaluated if the left-hand expression was true. With the conditional OR, the right-hand expression is only evaluated if the left-hand expression was false.

The NOT operator ( ! ) is a unary operator. It is placed before a boolean operand and changes the value from true to false or vice versa. The return values for the binary boolean operators are summarized in Table 6.6.

Table 6.6. Results from Boolean Operators
 

A&B A&&B

AB AB

A^B

a=true, b=true

true

true

false

a=true, b=false

false

true

true

a=false, b=true

false

true

true

a=false, b=false

false

false

false

Example: Using Boolean Operators

In this example, the && operator is used to connect two boolean operands. If both operands are true, the statement following the if statement is executed. This is a situation where you need to use the conditional AND ( && ) operator rather than the logical AND ( & ) operator. If you used the & operator both expressions are evaluated regardless of whether the first is true and you can get a divide by zero exception. With the && operator, the second expression is not evaluated if j=0 .

 public class BooleanOpDemo {   public static void main(String args[]) {     int j = 0;     if ( j != 0 && 1/j < 10 ) {         System.out.println("Conditions met");     } else {        System.out.println("Conditions not met");     }   } } 

Output ”

 Conditions not met 

Bitwise Operators

The bitwise operators shown in Table 6.7 accept only integral operands ( byte , short , int , long , char ). These operators act on the bits of their operands. The bitwise AND, OR, and exclusive OR operators are binary operators that evaluate each parallel pair of bits in each operand and return the appropriate value. For example, the bitwise OR returns 1 if either of the bits it is evaluating is 1.

The right and left bit shift operators ( >> and << ) shift the bits of the left-hand operand right or left by the number of bits specified by the right-hand operand. The unsigned right shift operator ( >>> ) shifts the bits of the left-hand operand to the right by the number of bits specified by the right-hand operand and then places zeros in the vacated high order bit. The ~ operator is the bitwise complement. It is a unary operator that flips the bits of the operand it acts upon. Zeros become ones and vice versa. If you do use these operators in your scientific and engineering programming, you have to be careful. It is easy to think you are doing one thing when you are actually doing something else.

Table 6.7. Bitwise Operators

O PERATOR

P URPOSE

&

Bitwise AND

Bitwise OR

^

Bitwise exclusive OR

>>

Right bit shift

>>>

Unsigned right shift

<<

Left bit shift

~

Bitwise complement

Example: Using Bitwise Operators

In this example, the bitwise OR operator is used between two integers. The binary representation of the number 12 is 1100. The binary representation of 13 is 1101. The statement 12 13 would return the value 1101 or 13 .

 public class BitwiseOpDemo {   public static void main(String args[]) {     int j=12, k=13;     int i = jk;     System.out.println("i is "+i);   } } 

Output ”

 i is 13 

Miscellaneous Operators

Table 6.8 lists miscellaneous operators that don't fall into the other general categories. The ternary operator ( ?: ) is shorthand for an if-else statement. As its name implies, it acts upon three operands. The general usage of the ternary operator is

 variable = condition ? value1 : value2; 

This is equivalent to the syntax

 if ( condition ) {     variable = value1; } else  {    variable = value2; } 
Table 6.8. Miscellaneous Operators

O PERATOR

P URPOSE

? :

Ternary operator

(variable_type)

Cast operator

[ ]

Array index

.

Member call/access operator

new

Class instance creator

instanceof

Type comparison

The cast operator is used to temporarily convert or cast a variable of one type into another type. See Chapter 7 for more information on casting. Parentheses are also used to define method parameter lists and to designate operator precedence. The array indexer operator ( [] )is used to access the elements of an array. It is also used to declare and size arrays. See Chapter 13 for more information on this operator.

A period is used in the syntax to call methods and to access data members of a class. The new operator is used to create an object, allocating memory for it on the part of memory known as the heap. The instanceof operator is a binary operator that returns true if the left-hand operand is an instance of (part of the same class or interface hierarchy as) the right-hand operand.

Example: Miscellaneous Operators

This example shows three of the miscellaneous operators in action. The new keyword is used to create a Stack object. The instanceof operator is used to determine if the variable is an instance of the Vector class. The operator will also return true if the variable is a subclass of Vector . In this case, the Stack class is a subclass of Vector so the operator returns true . For more information on what a subclass is, consult Chapter 7. The Stack and Vector classes are contained in the java.util package of the Java API. To access these classes, we must import that package into our program. That is the reason for the import statement at the top of the program. For more information on packages, see Chapter 11. In the second part of the example, the ternary operator is used to implement an absolute value evaluation.

 import java.util.*; public class MiscOpDemo {   public static void main(String args[]) {     Stack myStack = new Stack();     double deltaT = -12.3;     if (myStack instanceof Vector) {        System.out.println("Variable is a Vector");     }     double temp = deltaT<0.0?-deltaT:deltaT;     System.out.println("temp is "+temp);   } } 

Output ”

 Variable is a Vector temp is 12.3 

The ternary syntax in the program is equivalent to

 if (deltaT < 0.0) {    temp = -deltaT; } else {    temp = deltaT; } 

Operator Precedence

If you use more than one operator in a given statement, how do you know which operation will be performed first? In many situations, the order in which things are done will make a difference. Fortunately, Java has a well-defined system of operator precedence to resolve these issues. The general hierarchy from highest to lowest precedence is ”

  1. Increment/Decrement

  2. Casting

  3. Arithmetic

  4. Bitwise shift

  5. Relational

  6. Boolean

  7. Ternary

  8. Assignment

When binary operators of the same precedence appear in an expression, they are evaluated left-to-right except for assignment operators that are evaluated right-to-left . You can manually specify precedence by placing parentheses around the operation you want performed first.

Example: Operator Precedence Example

This example should be nothing new to anyone with programming experience. The basic rules are the same for most languages. Without the parentheses, the multiplication is performed before the addition. If you want the addition to be performed first, place parentheses around the operation.

 public class OpPrecedence {   public static void main(String args[]) {     int j;     j = 8*4 + 2;     System.out.println("j is " + j);     j = 8*(4 + 2);     System.out.println("j is " + j);   } } 

Output ”

 j is 34 j is 48 


Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

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