Operators
Abstract
 Contents of the lecture.
 Arithmetic operators.
 Relational and conditional operators.
 Shift and logical operators.
 Assignment operators.
 Other operators.
Operators
An operator performs a function on one, two, or three operands. An operator that
requires one operand is called an unary operator. For example, ++ is a unary operator
that increments the value of its operand by 1. An operator that requires two operands is a binary operator . For example, = is a binary operator that assigns the value from its right
hand operand to its lefthand operand. And finally, a ternary operator is one that requires
three operands. The Java programming language has one ternary operator, ?:, which is a
shorthand ifelse statement.
The unary operators support either prefix or postfix notation. Prefix notation means that
the operator appears before its operand:
operator op //prefix notation
Postfix notation means that the operator appears after its operand:
op operator //postfix notation
All of the binary operators use infix notation, which means that the operator appears between
its operands:
op1 operator op2 //infix notation
The ternary operator is also infix; each component of the operator appears between operands:
op1 ? op2 : op3 //infix notation
In addition to performing the operation, an operator returns a value. The return value
and its type depend on the operator and the type of its operands. For example, the arithmetic
operators, which perform basic arithmetic operations such as addition and subtraction, return
numbers  the result of the arithmetic operation. The data type returned by an arithmetic
operator depends on the type of its operands: If you add two integers, you get an integer back.
An operation is said to evaluate to its result.
Arithmetic operators
The Java programming language supports various arithmetic operators for all floating
point and integer numbers. These operators are + (addition),  (subtraction), * (multiplication),
/ (division), and % (modulo).
The following table summarises the binary arithmetic operations in the Java
programming language.
Operator 
Use 
Description 
+ 
op1 + op2 
Adds op1 and op2 
 
op1  op2 
Subtracts op2 from op1 
* 
op1 * op2 
Multiplies op1 by op2 
/ 
op1 / op2 
Divides op1 by op2 
% 
op1 % op2 
Computes the reminder of dividing op1 by op2 
Here's an example program, ArithmeticDemo, that defines two integers and two
doubleprecision floatingpoint numbers and uses the five arithmetic operators to perform
different arithmetic operations.
This program also uses + to concatenate strings.
Code: 
public class ArithmeticDemo {
public static void main(String[] args) {
//a few numbers
int i = 37;
int j = 42;
double x = 27.475;
double y = 7.22;
System.out.println("Variable values...");
System.out.println(" i = " + i);
System.out.println(" j = " + j);
System.out.println(" x = " + x);
System.out.println(" y = " + y);
//adding numbers
System.out.println("Adding...");
System.out.println(" i + j = " + (i + j));
System.out.println(" x + y = " + (x + y));
//subtracting numbers
System.out.println("Subtracting...");
System.out.println(" i  j = " + (i  j));
System.out.println(" x  y = " + (x  y));
//multiplying numbers
System.out.println("Multiplying...");
System.out.println(" i * j = " + (i * j));
System.out.println(" x * y = " + (x * y));
//dividing numbers
System.out.println("Dividing...");
System.out.println(" i / j = " + (i / j));
System.out.println(" x / y = " + (x / y));
//computing the remainder resulting from
//dividing numbers
System.out.println("Computing the remainder...");
System.out.println(" i % j = " + (i % j));
System.out.println(" x % y = " + (x % y));
//mixing types
System.out.println("Mixing types...");
System.out.println(" j + y = " + (j + y));
System.out.println(" i * x = " + (i * x));
}
}

The output from this program is:
Variable values...
i = 37
j = 42
x = 27.475
y = 7.22
Adding...
i + j = 79
x + y = 34.695
Subtracting...
i  j = 5
x  y = 20.255
Multiplying...
i * j = 1554
x * y = 198.37
Dividing...
i / j = 0
x / y = 3.8054
Computing the remainder...
i % j = 37
x % y = 5.815
Mixing types...
j + y = 49.22
i * x = 1016.58
Note that when an integer and a floatingpoint number are used as operands to a single
arithmetic operation, the result is floating point. The integer is implicitly converted to a floatingpoint number before the operation takes place. The following table summarises the data type
returned by the arithmetic operators, based on the data type of the operands. The necessary
conversions take place before the operation is performed.
Data type of result 
Data type of operands 
long 
Neither operand is a float or a double (integer arithmetic); at least one operand is a long 
int 
Neither operand is a float or a double (integer arithmetic); neither operand is a long 
double 
At least one operand is a double 
float 
At least one operand is a float: neither operand is a double 
In addition to the binary forms of + and , each of these operators has unary versions
that perform the following operations:
Operator 
Use 
Description 
+ 
+op 
Promotes op to int if it's a byte, short, or char 
 
op 
Arithmetically negates op 
Two shortcut arithmetic operators are ++, which increments its operand by 1, and ,
which decrements its operand by 1. Either ++ or  can appear before (prefix) or after (postfix)
its operand. The prefix version, ++op/op, evaluates to the value of the operand after the
increment/decrement operation. The postfix version, op++/op, evaluates the value of the
operand before the increment/decrement operation.
The following program, called SortDemo, uses ++ twice and  once.
Code: 
public class SortDemo {
public static void main(String[] args) {
int[] arrayOfInts = 32, 87, 3, 589, 12, 1076,
2000, 8, 622, 127 ;
for (int i = arrayOfInts.length; i >= 0; ) {
for (int j = 0; j < i; j++) {
if (arrayOfInts[j] > arrayOfInts[j+1]) {
int temp = arrayOfInts[j];
arrayOfInts[j] = arrayOfInts[j+1];
arrayOfInts[j+1] = temp;
}
}
}
for (int i = 0; i < arrayOfInts.length; i++) {
System.out.print(arrayOfInts[i] + " ");
}
System.out.println();
}
}

This program puts 10 integer values into an array  a fixed length structure that can
hold multiple values of the same type  then sorts them. The line of code in bold declares
an array referred to by arrayOfInts, creates the array, and puts 10 integer values into it.
The
program uses arrayOfInts.length to get the number of elements in the array. Individual
elements are accessed with this notation: arrayOfInts[index], where index is an integer
indicating the position of the element within the array. Note that indices begin at 0.
The output from this program is a list of numbers sorted from lowest to highest:
3 8 12 32 87 127 589 622 1076 2000
Let's look at how the SortDemo program uses  to control the outer of its two nested
sorting loops. Here's the statement that controls the outer loop:
Code: 
for (int i = arrayOfInts.length; i >= 0; ) {
...
}

The for statement is a looping construct, which you'll meet later in these lectures.
What's important here is the code in bold, which continues the for loop as long as the value
returned by i is greater than or equal to 0. Using the prefix version of  means that the
last iteration of this loop occurs when i is equal to 0. If we change the code to use the postfix
version of , the last iteration of this loop occurs when i is equal to 1, which is incorrect for
this program because i is used as an array index and 1 is not a valid array index.
The other two loops in the program use the postfix version of ++. In both cases, the
version used doesn't really matter, because the value returned by the operator isn't used for
anything. When the return value of one of these shortcut operations isn't used for anything,
convention prefers the postfix version.
The shortcut increment/decrement operators are summarised in the following table.
Operator 
Use 
Description 
++ 
op++ 
Increments op by 1; evaluates to the value of op before it was incremented 
++ 
++op 
Increments op by 1; evaluates to the value of op after it was incremented 
 
op 
Decrements op by 1; evaluates to the value of op before it was decremented 
 
op 
Decrements op by 1; evaluates to the value of op after it was decremented 
Relational and conditional operators
A relational operator compares two values and determines the relationship between
them. For example, != returns true if the two operands are unequal. This table summarises
the relational operators:
Operator 
Use 
Returns true if 
> 
op1>op2 
op1 is greater than op2 
>= 
op1>=op2 
op1 is greater than or equal op2 
< 
op1<op2 
op1 is less than op2 
<= 
op1<=op2 
op1 is less than or equal op2 
== 
op1==op2 
op1 and op2 are equal 
!= 
op1!=op2 
op1 and op2 are not equal 
Following is an example, RelationalDemo, that defines three integer numbers and uses
the relational operators to compare them. The relational operations are shown in bold:
Code: 
public class RelationalDemo {
public static void main(String[] args) {
//a few numbers
int i = 37;
int j = 42;
int k = 42;
System.out.println("Variable values...");
System.out.println(" i = " + i);
System.out.println(" j = " + j);
System.out.println(" k = " + k);
//greater than
System.out.println("Greater than...");
System.out.println(" i > j = " + (i > j));
System.out.println(" j > i = " + (j > i));
System.out.println(" k > j = " + (k > j));
//greater than or equal to
System.out.println("Greater than or equal to...");
System.out.println(" i >= j = " + (i >= j));
System.out.println(" j >= i = " + (j >= i));
System.out.println(" k >= j = " + (k >= j));
//less than
System.out.println("Less than...");
System.out.println(" i < j = " + (i < j));
System.out.println(" j < i = " + (j < i));
System.out.println(" k < j = " + (k < j));
//less than or equal to
System.out.println("Less than or equal to...");
System.out.println(" i <= j = " + (i <= j));
System.out.println(" j <= i = " + (j <= i));
System.out.println(" k <= j = " + (k <= j));
//equal to
System.out.println("Equal to...");
System.out.println(" i == j = " + (i == j));
System.out.println(" k == j = " + (k == j));
//not equal to
System.out.println("Not equal to...");
System.out.println(" i != j = " + (i != j));
System.out.println(" k != j = " + (k != j));
}
}

Here's the output from this program:
Variable values...
i = 37
j = 42
k = 42
Greater than...
i > j = false
j > i = true
k > j = false
Greater than or equal to...
i >= j = false
j >= i = true
k >= j = true
Less than...
i < j = true
j < i = false
k < j = false
Less than or equal to...
i <= j = true
j <= i = false
k <= j = true
Equal to...
i == j = false
k == j = true
Not equal to...
i != j = true
k != j = false
Relational operators often are used with conditional operators to construct more complex
decision  making expressions. The Java programming language supports six conditional
operators  five binary and one unary  as shown in the following table.
Operator 
Use 
Returns true if 
&& 
op1&&op2 
op1 and op2 are both true, conditionally evaluates op2 
 
op1op2 
either op1 or op2 is true, conditionally evaluates op2 
! 
!op 
op is false 
& 
op1&op2 
op1 and op2 are both true, always evaluates op1 and op2 
 
op1op2 
either op1 or op2 is true, always evaluates op1 and op2 
^ 
op1^op2 
if op1 and op2 are different  that is one or the other of the operands is true, but not both 
One such operator is &&, which performs the conditional AND operation. You can use two
different relational operators along with && to determine whether both relationships are true.
The following line of code uses this technique to determine whether an array index is between
two boundaries. It determines whether the index is both greater than or equal to 0 and less
than NUM_ENTRIES, which is a previously defined constant value.
0 <= index && index < NUM_ENTRIES
Note that in some instances, the second operand to a conditional operator may not be
evaluated. Consider this code segment:
(numChars < LIMIT) && (...)
The && operator will return true only if both operands are true. So, if numChars is
greater than or equal to LIMIT, the lefthand operand for && is false, and the return value
of && can be determined without evaluating the righthand operand. In such a case, the
interpreter will not evaluate the righthand operand. This has important implications if the
righthand operand has side effects, such as reading from a stream, updating a value, or
making a calculation.
When both operands are boolean, the operator & performs the same operation as &&.
However, & always evaluates both of its operands and returns true if both are true. Likewise,
when the operands are boolean,  performs the same operation as . The  operator always
evaluates both of its operands and returns true if at least one of its operands is true. When
their operands are numbers, & and  perform bitwise manipulations.
Shift and logical operators
A shift operator performs bit manipulation on data by shifting the bits of its first operand
right or left. This table summarises the shift operators available in the Java programming
language.
Operator 
Use 
Operation 
>> 
op1>>op2 
shift bits of op1 right by distance op2 
<< 
op1<<op2 
shift bits of op1 left by distance op2 
>>> 
op1>>>op2 
shift bits of op1 right by distance op2 (unsigned) 
Each operator shifts the bits of the lefthand operand over by the number of positions
indicated by the righthand operand. The shift occurs in the direction indicated by the operator
itself. For example, the following statement shifts the bits of the integer 13 to the right by one
position:
13 >> 1;
The binary representation of the number 13 is 1101. The result of the shift operation is
1101 shifted to the right by one position  110, or 6 in decimal. The lefthand bits are filled
with 0s as needed.
The following table shows the four operators the Java programming language provides
to perform bitwise functions on their operands:
Operator 
Use 
Operation 
& 
op1&op2 
bitwise and 
 
op1op2 
bitwise or 
^ 
op1^op2 
bitwise xor 
~ 
~op 
bitwise complement 
When its operands are numbers, the & operation performs the bitwise AND function on
each parallel pair of bits in each operand. The AND function sets the resulting bit to 1 if the
corresponding bit in both operands is 1, as shown in the following table.
op1 
op2 
Result 
0 
0 
0 
0 
1 
0 
1 
0 
0 
1 
1 
1 
Suppose that you were to AND the values 13 and 12, like this: 13 & 12. The result of this
operation is 12 because the binary representation of 12 is 1100, and the binary representation
of 13 is 1101.
1101
//13
& 1100 //12

1100 //12
If both operand bits are 1, the AND function sets the resulting bit to 1; otherwise, the
resulting bit is 0. So, when you line up the two operands and perform the AND function, you
can see that the two highorder bits (the two bits farthest to the left of each number) of each
operand are 1. Thus, the resulting bit in the result is also 1. The loworder bits evaluate
to 0 because either one or both bits in the operands are 0. When both of its operands are
numbers, the  operator performs the inclusive or operation, and ^ performs the exclusive
or (XOR) operation. Inclusive or means that if either of the two bits is 1, the result is 1. The
following table shows the results of inclusive or operations:
op1 
op2 
Result 
0 
0 
0 
0 
1 
1 
1 
0 
1 
1 
1 
1 
Exclusive or means that if the two operand bits are different the result is 1, otherwise the
result is 0. The following table shows the results of an exclusive or operation.
op1 
op2 
Result 
0 
0 
0 
0 
1 
1 
1 
0 
1 
1 
1 
0 
And finally, the complement operator inverts the value of each bit of the operand: if the
operand bit is 1 the result is 0 and if the operand bit is 0 the result is 1.
Among other things, bitwise manipulations are useful for managing sets of boolean flags.
Suppose, for example, that your program had several boolean flags that indicated the state of
various components in your program: is it visible, is it draggable, and so on. Rather than define
a separate boolean variable to hold each flag, you could define a single variable, flags, for all
of the.
Each bit within flags would represent the current state of one of the flags. You would
then use bit manipulations to set and to get each flag. First, set up constants that indicate the
various flags for your program. These flags should each be a different power of 2 to ensure
that each bit is used by only one flag. Define a variable, flags, whose bits would be set
according to the current state of each flag. The following code sample initialises flags to 0,
which means that all flags are false (none of the bits are set).
Code: 
static final int VISIBLE = 1;
static final int DRAGGABLE = 2;
static final int SELECTABLE = 4;
static final int EDITABLE = 8;
int flags = 0;

To set the "visible" flag when something became visible you would use this statement:
flags = flags  VISIBLE;
To test for visibility, you could then write:
if ((flags & VISIBLE) == VISIBLE) {
...
}
Here's the complete program, BitwiseDemo, that includes this code.
Code: 
public class BitwiseDemo {
static final int VISIBLE = 1;
static final int DRAGGABLE = 2;
static final int SELECTABLE = 4;
static final int EDITABLE = 8;
public static void main(String[] args) {
int flags = 0;
flags = flags  VISIBLE;
flags = flags  DRAGGABLE;
if ((flags & VISIBLE) == VISIBLE) {
if ((flags & DRAGGABLE) == DRAGGABLE) {
System.out.println("Flags are Visible and Draggable.");
}
}
flags = flags  EDITABLE;
if ((flags & EDITABLE) == EDITABLE) {
System.out.println("Flags are now also Editable.");
}
}
}

// integers
byte largestByte = Byte.MAX_VALUE;
short largestShort = Short.MAX_VALUE;
int largestInteger = Integer.MAX_VALUE;
long largestLong = Long.MAX_VALUE;
// real numbers
float largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;
// other primitive types
char aChar = āSā;
boolean aBoolean = true;
[/code]
The Java programming language also provides several shortcut assignment operators
that allow you to perform an arithmetic, shift, or bitwise operation and an assignment operation
all with one operator. Suppose you wanted to add a number to a variable and assign the result
back into the variable, like this:
i = i + 2;
You can shorten this statement using the shortcut operator +=, like this:
i += 2;
The two previous lines of code are equivalent.
The following table lists the shortcut assignment operators and their lengthy equivalents:
Operator 
Use 
Equivalent to 
+= 
op1 += op2 
op1 = op1 + op2 
= 
op1 = op2 
op1 = op1  op2 
*= 
op1 *= op2 
op1 = op1 * op2 
/= 
op1 /= op2 
op1 = op1 / op2 
%= 
op1 %= op2 
op1 = op1 % op2 
&= 
op1 &= op2 
op1 = op1 & op2 
= 
op1 = op2 
op1 = op1  op2 
^= 
op1 ^= op2 
op1 = op1 ^ op2 
<<= 
op1 <<= op2 
op1 = op1 << op2 
>>= 
op1 >>= op2 
op1 = op1 >> op2 
>>>= 
op1 >>>= op2 
op1 = op1 >>> op2 
Other operators
The following table lists the other operators that the Java programming language
supports.
Operator 
Description 
?: 
Shortcut ifelse statement 
[] 
Used to declare arrays, create arrays, and access array elements 
. 
Used to form qualified names 
(params) 
Delimits commaseparated list of parameters 
(type) 
Casts (converts) a value to the specified type 
new 
Creates a new object or a new array 
instanceof 
Determines whether its first operand is an instance of its second operand 
The ?: operator is a conditional operator that is shorthand for an ifelse statement:
op1 ? op2 : op3
The ?: operator returns op2 if op1 is true or returns op3 if op1 is false.
You use square brackets to declare arrays, to create arrays, and to access a particular
element in an array. Here's an example of an array declaration:
float[] arrayOfFloats = new float[10];
The previous code declares an array that can hold ten floating point numbers. Here's
how you would access the 7th item in that array:
arrayOfFloats[6];
Note that array indices begin at 0.
The dot (.) operator accesses instance members of an object or class members of a
class.
The (type) operator casts (or "converts") a value to the specified type.
You use the new operator to create a new object or a new array. Here's an example of
creating a new Integer object from the Integer class in the java.lang package:
Integer anInteger = new Integer(10);
The instanceof operator tests whether its first operand is an instance of its second.
op1 instanceof op2
op1 must be the name of an object and op2 must be the name of a class. An object is
considered to be an instance of a class if that object directly or indirectly descends from that
class.
by Anatoliy Malyarenko
31879 bytes more  comments?   Score: 0
