Summary: Earlier modules have touched briefly on the topic of operators. This module discusses Java operators in depth.
Earlier modules have touched briefly on the topic of operators . This module discusses Java operators in depth.
The first step in learning to use a new programming language is usually to learn the foundation concepts such as
This module concentrates on the operators used in Java.
Unary and binary operators
Java provides a set of operators that can be used to perform an action on one, two, or three operands. An operator that operates on one operand is called a unary operator. An operator that operates on two operands is called a binary operator. An operator that operates on three operands is called a ternary operator.
Some operators can behave either as a unary or as a binary operator. The best known such operator s probably the minus sign (-) . As a binary operator, the minus sign causes its right operand to be subtracted from its left operand. As a unary operator, the minus sign causes the algebraic sign of the right operand to be changed.
A ternary operator
Java has only one operator that takes three operands. It is a conditional operator, which I sometimes refer to as a cheap if statement.
The first operand is a boolean expression, which is followed by a question mark character (?) . The question mark is followed by a second operand, which is followed by a colon character (:) . The colon character is followed by the third operand.
If the boolean expression evaluates to true, the value of the operand following the ? is returned. Otherwise, the value of the operand following the : is returned.
An example of the syntax follows:
boolean expression ? value1 : value2
Overloaded operators
Unlike C++, Java does not support the creation of overloaded operators in program code. (If you don't know what this means, don't worry about it.)
Operators from previous programs
The statements in the following note box illustrate the use of the following operators from Java programs in earlier modules :
int ch1, ch2 = '0';
while( (ch1 = System.in.read() ) != '#') ch2 = ch1;
System.out.println("The char before the # was "
+ (char)ch2);The plus and cast operators
Of particular interest in this list is the plus sign (+) and the cast operator (char) .
In Java, the plus sign can be used to perform arithmetic addition. It can also be used to concatenate strings. When the plus sign is used in the manner shown above , the operand on the right is automatically converted to a character string before being concatenated with the operand on the left.
The cast operator is used in this case to purposely convert the integer value contained in the int variable ch2 to a character type suitable for concatenating with the string on the left of the plus sign. Otherwise, Java would attempt to convert and display the value of the int variable as a series of digits representing the numeric value of the character because the character is stored in a variable of type int .
The increment operator
An extremely important unary operator is the increment operator identified by two plus characters with no space between them (++) .
The increment operator causes the value of its operand to be increased by one.
There is also a decrement operator (--) that causes the value of its operand to be decreased by one.
The increment and decrement operators are used in both prefix and postfix notation.
Prefix and postfix increment and decrement operators
With the prefix version, the operand appears to the right of the operator ( ++X) , while with the postfix version, the operand appears to the left of the operator (X++) .
What's the difference in prefix and postfix?
The difference in prefix and postfix has to do with the point in the sequence of operations that the increment (or decrement) actually occurs if the operator and its operand appear as part of a larger overall expression.
(There is effectively no difference if the operator and its operand do not appear as part of a larger overall expression.)
Prefix behavior
With the prefix version, the variable is incremented (or decremented) before it is used to evaluate the larger overall expression.
Postfix behavior
With the postfix version, the variable is used to evaluate the larger overall expression before it is incremented (or decremented) .
Illustration of prefix and postfix behavior
The use of both the prefix and postfix versions of the increment operator is illustrated in the Java program shown in Listing 1 . The output produced by the program is show in the comments at the beginning of the program.
| Listing 1: Illustration of prefix and postfix notation. |
|---|
|
Binary operators and infix notation
Binary operators use infix notation, which means that the operator appears between its operands.
General behavior of an operator
As a result of performing the specified action, an operator can be said to return a value (or evaluate to a value) of a given type. The type of value returned depends on the operator and the type of the operands.
To evaluate to a value means that after the action is performed, the operator and its operands are effectively replaced in the expression by the value that is returned.
Operator categories
I will divide Java's operators into the following categories for further discussion:
Java supports various arithmetic operators on all floating point and integer numbers.
The binary arithmetic operators
The following table lists the binary arithmetic operators supported by Java.
Operator Description
+ Adds its operands
- Subtracts the right operand from the left
operand
* Multiplies the operands
/ Divides the left operand by the right operand
% Remainder of dividing the left operand by
the right operandString concatenation
As mentioned earlier, the plus operator (+) is also used to concatenate strings as in the following code fragment:
"MyVariable has a value of "
+ MyVariable + " in this program."Coercion
Note that this operation also coerces the value of MyVariable to a string representation for use in the expression only. However, the value stored in the variable is not modified in any lasting way.
Unary arithmetic operators
Java supports the following unary arithmetic operators.
Unary arithmetic operators
Operator Description
+ Indicates a positive value
- Negates, or changes algebraic sign
++ Adds one to the operand,
both prefix and postfix
-- Subtracts one from operand,
both prefix and postfixThe result of the increment and decrement operators being either prefix or postfix was discussed earlier .
Binary Relational operators
Java supports the set of binary relational operators shown in the following table. Relational operators in Java return either true or false as a boolean type.
Operator Returns true if
> Left operand is greater than right operand
>= Left operand is greater than or equal to
right operand
< Left operand is less than right operand
<= Left operand is less than or equal to
right operand
== Left operand is equal to right operand
!= Left operand is not equal to right operandConditional expressions
Relational operators are frequently used in the conditional expressions of control statement such as the one in the code fragment shown below.
if(LeftVariable <= RightVariable). . .Illustration of relational operators
The program shown in Listing 2 illustrates the result of applying relational operators in Java. The output is shown in the comments at the beginning of the program. Note that the program automatically displays true and false as a result of applying the relational operators.
| Listing 2: Illustration of relational operators. |
|---|
|
Conditional operators
The relational operators are often combined with another set of operators (referred to as conditional or logical operators) to construct more complex expressions.
Java supports three such operators as shown in the following table.
Operator Typical Use Returns true if
&& Left && Right Left and Right are both true
|| Left || Right Either Left or Right is true
! ! Right Right is falseThe operands shown in the table must be boolean types, or must have been created by the evaluation of an expression that returns a boolean type.
Left to right evaluation
An important characteristic of the behavior of the logical and and the logical or operators is that the expressions are evaluated from left to right, and the evaluation of the expression is terminated as soon as the result of evaluating the expression can be determined.
For example, in the following expression, if the variable a is less than the variable b , there is no need to evaluate the right operand of the || to determine that the result of evaluating the entire expression would be true . Therefore, evaluation will terminate as soon as the answer can be determined.
(a < b) || (c < d)Don't confuse bitwise and with logical and
As discussed in the next section, symbols shown below are the bitwise and and the bitwise or .
& bitwise and
| bitwise orOne author states that in Java, the bitwise and operator can be used as a synonym for the logical and and the bitwise or can be used as a synonym for the logical inclusive or if both of the operands are boolean . (I recommend that you don't do that because it could cause confusion for someone reading your code.)
Note however that according to a different author, in this case, the evaluation of the expression is not terminated until all operands have been evaluated, thus eliminating the possible advantage of the left-to-right evaluation.
Java provides a set of operators that perform actions on their operands one bit at a time as shown in the following table.
Operator Typical Use Operation
>> OpLeft >> Dist Shift bits of OpLeft right
by Dist bits (signed)
<< OpLeft << Dist Shift bits of OpLeft left
by Dist bits
>>> OpLeft >>> Dist Shift bits of OpLeft right
by Dist bits (unsigned)
& OpLeft & OpRight Bitwise and of the
two operands
| OpLeft | OpRight Bitwise Populating vacated bits for shift operations
The signed right shift operation populates the vacated bits with the sign bit, while the left shift and the unsigned right shift populate the vacated bits with zeros.
In all cases, bits shifted off the end are lost.
The rule for bitwise and
The bitwise and operation operates according to the rule that the bitwise and of two 1 bits is a 1 bit.
Any other combination results in a 0 bit.
Bitwise inclusive or
For the inclusive or , if either bit is a 1, the result is a 1.
Otherwise, the result is a 0.
Bitwise exclusive or
For the exclusive or , if either but not both bits is a 1, the result is a 1.
Otherwise, the result is a 0.
Another way to state this is if the bits are different, the result is a 1. If the two bits are the same, the result is a 0.
The complement operator
Finally, the complement operator changes each 1 to a 0 and changes each 0 to a 1.
Simple assignment operator
The (=) is a value assigning binary operator in Java. The value stored in memory and represented by the right operand is copied into the memory represented by the left operand.
Using the assignment operator with reference variables
You need to be careful and think about what you are doing when you use the assignment operator with reference variables in Java. If you assign one reference variable to another, you simply end up with two reference variables that refer to the same object. You do not end up with two different objects.
(If what you need is another copy of the object, you may be able to use the clone method to accomplish that.)
Shortcut assignment operators
Java supports the following list of shortcut assignment operators. These operators allow you to perform an assignment and another operation with a single operator.
+=
-=
*=
/=
%=
&=
|=
^=
<<=
>>=
>>>=
For example, the two statements that follow perform the same operation.
x += y;
x = x + y;This section contains a variety of miscellaneous information.
Financial : Although the Connexions site makes it possible for you to download a PDF file for this module at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should be aware that some of the HTML elements in this module may not translate well into PDF.
I also want you to know that, I receive no financial compensation from the Connexions website even if you purchase the PDF version of the module.
In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle books, and placed them for sale on Amazon.com showing me as the author. I neither receive compensation for those sales nor do I know who does receive compensation. If you purchase such a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it was made and published without my prior knowledge.
Affiliation : I am a professor of Computer Information Technology at Austin Community College in Austin, TX.
-end-