Separators and Operators
One of a compiler's first tasks is to parse input characters into basic language elements. Each element is known as a token. Examples of tokens include Unicode escape sequences, identifiers, and the various characters composing literals, separators, and operators.
Separators
A separator is one or two tokens that separate some language features from other language features. Separators include the following:
Parentheses ( and ) for specifying a precedence change in an expression (by separating that part of an expression which is to be given higher precedence from the rest of the expression) or a cast operator (by separating a typeIdentifier from the rest of an expression)
Braces { and } for grouping zero or more statements into a block of statements and separating those statements from statements appearing outside the block
Square brackets [ and ] for declaring an array or accessing an array element's value (by separating an array index from the rest of an array access expression)
Semicolon (;) for separating one statement from another
Comma (,) for separating variable names and optional initializations in a variable declaration
Period (.) for separating fields and methods in a field or method access expression
Not all of the preceding concepts will make sense to you right now, but don't worry. As you keep reading through this and future chapters, you'll find that those concepts aren't incomprehensible.
Caution
When specifying the parentheses, braces, or square brackets separators, you must specify both opening and closing characters that make up the separator. Otherwise, you will receive one or more compiler error messages.
Operators
An operator is a language feature, represented by a token, that transforms one or more values (of a certain type) into a new value. Each value being operated on is known as an operand. A classic example of an operator is the additive operator that performs addition (+). That operator adds its two numeric operands together and yields a new numeric valuethe sum.
The Java Language Specification (JLS) identifies all operators supported by Java. It states that "37 tokens are the operators." Table 3.2 lists those operator tokens.
Table 3.2: Operator Tokens
= |
> |
< |
! |
~ |
? |
: |
== |
<= |
>= |
!= |
&& |
|| |
++ |
-- |
+ |
- |
* |
/ |
& |
| |
^ |
% |
<< |
>> |
>>> |
+= |
-= |
*= |
/= |
&= |
|= |
^= |
%= |
<<= |
>>= |
>>>= |
|
|
|
In addition to Table 3.2's list of operator tokens, the JLS refers to the instanceof token as an operator and also refers to the cast operatora combination of a parentheses separator and a typeIdentifier.
Classifying Operators: Unary, Binary, and Ternary
An operator can be classified by the number of required operands. Resulting classifications include unary, binary, and ternary. A unary operator takes one operand. Negation is an example. If an operator takes a pair of operands, that operator is known as a binary operator. The previously mentioned additive operators that perform addition and subtraction are examples of binary operators. Finally, a ternary operator takes three operands. The conditional operator is Java's only ternary operator.
A potential problem arises when dealing with binary and ternary operators. Suppose the types of a binary/ternary operator's operands do not match. What does the compiler do? In many cases, the compiler uses a widening conversion rule (see Chapter 2) to make sure that the types of a binary or ternary operator's operands are the same. For example, if the type of one of the operands to an additive operator is integer and the other operand's type is short integer, the compiler will generate bytecode instructions that convert the short integer to an integer prior to generating bytecode instructions that perform the additive operation. However, if operand types are very different (such as one operand having the Boolean type and another operand having the character type), the compiler will display one or more error messages.
Classifying Operators: Prefix, Postfix, and Infix
Operators can also be classified as prefix, postfix, or infix. A prefix operator precedes its operand, whereas a postfix operator trails its operand. The bitwise complement operator is an example of a prefix operator, and the postincrement operator is an example of a postfix operator. All unary operators are either prefix or postfix operators.
If an operator is situated between its operands, that operator is known as an infix operator. The additive operators are examples of infix operators because their tokens appear between pairs of operands. All binary and ternary operators are infix operators.
Additive Operators
The additive operators perform addition, string concatenation. and subtraction. Those operators are represented in source code by the + and - tokens.
The additive operator (+) is one example of Java's overloaded operators. When applied to numeric operands, + performs addition by adding those operands together. However, + also performs string concatenation when applied to at least one String operand. In either case, that operator has the following syntax:
operand1 '+' operand2When + is used for addition, each operand type must be one of byte, character, double-precision floating-point, floating-point, integer, long integer, or short integer. If the operand types don't match, the compiler will use a widening rule to convert the operand whose type represents a more restricted range of values to the type of the other operand. When + is used for string concatenation, either or both operand types must be String. If only one type is String, it is legal for the other type to be any valid type.
The following code fragment demonstrates the additive operator for addition and string concatenation:
int count = 10; count = count + 1; System.out.println ("count = " + count);
count + 1 adds 1 to the value stored in count. "count = " + count converts the value stored in count to a String object (behind the scenes) and concatenates the resulting object's characters to the "count = " string literal. The result is: count = 11.
The additive operator (-) performs subtraction by subtracting the right operand from the left operand. That operator has the following syntax:
operand1 '-' operand2Each operand type must be one of byte, character, double-precision floating-point, floating-point, integer, long integer, or short integer. If the operand types don't match, the compiler will use a widening rule to convert the operand whose type represents a more restricted range of values to the type of the other operand.
The following code fragment demonstrates the additive operator for subtraction:
int i = 1; // i is initialized to 1 int j = i - 1; // j is initialized to the value of i - 1
i - 1 subtracts 1 from the value stored in i.
Assignment Operators
The assignment operators either simply assign the result of an expression to a variable or perform an operation in conjunction with assignment. Those operators are represented in source code by the =, +=, -=, *=, /=, &=, |=, ^=, %=, <<=, >>=, and >>>= tokens.
The simple assignment operator (=) evaluates its right operand and assigns the result to its left operand (which must be a variable). That operator has the following syntax:
operand1 '=' operand2The types of both operands must agree. Otherwise, the compiler will either use a widening conversion rule or report an error.
The following code fragment demonstrates the simple assignment operator:
String name = "Java Jeff";Each compound assignment operator evaluates its left operand (which must be a variable), evaluates its right operand, performs the operation on both values, and stores the result in its left operand. Those operators adhere to the following syntax:
operand1 ( '+=' | '-=' | '*=' | '/=' | '&=' | '|=' | '^=' | '%=' | '<<=' | '>>=' | '>>>=') operand2
As with simple assignment, the types of both operands must agree. Otherwise, the compiler will either use a widening conversion rule or report an error.
The following code fragment demonstrates the compound assignment operator that performs addition/string concatenation in addition to assignment:
double amount = 30000.0; amount += 60000; // equivalent to amount = amount + 60000; System.out.println (amount); // Print: 90000.0
In the example, amount is of type double-precision floating-point and 60000 is of type integer. Before the += operation is performed, 60000 is converted from integer to double-precision floating-point.
Bitwise and Logical Operators
The bitwise and logical operators perform bitwise/logical AND, bitwise/ logical exclusive OR, and bitwise/logical inclusive OR operations at either the binary digit (bit) or Boolean levels. Those three operators are a second example of Java's overloaded operators and are represented in source code by the &, ^, and | tokens.
For each operator, their operand types must be one of Boolean, byte, character, integer, long integer, or short integer. If the operand types don't match, the compiler will either use a widening rule to convert the operand whose type represents a more restricted range of values to the type of the other operand, or display an error message if the types are radically different (such as using Boolean with integer).
The bitwise/logical AND operator (&) works as follows: From a numeric perspective, if corresponding bits in both numeric operands are 1, the result is 1. Otherwise, the result is 0. However, from a Boolean perspective, if both Boolean operands evaluate to true, the result is true. Otherwise, the result is false. That operator has the following syntax:
operand1 '&' operand2The following code fragment demonstrates the bitwise/logical AND operator:
byte b = 0x14; // b contains 20 (decimal). b &= 7; // b now contains 6. boolean first = true; // first contains true first &= false; // first now contains false;
The bitwise/logical exclusive OR operator (^) works as follows: From a numeric perspective, if corresponding bits in both numeric operands are 1 or 0, the result is 0. Otherwise, the result is 1. However, from a Boolean perspective, if both Boolean operands are true or false, the result is false. Otherwise, the result is true. That operator has the following syntax:
operand1 '^' operand2The following code fragment demonstrates the bitwise/logical exclusive OR operator:
byte b1 = 0x14; // b1 contains 20 (decimal). byte b2 = 8; // b2 contains 8 b1 ^= b2; // b1 contains 6 b2 = (byte) (b1 ^ b2); // b2 contains 20 b1 ^= b2; // b1 contains 8 boolean first = true; // first contains true boolean second = true; // second contains true first = first ^ second; // first contains false
The example demonstrates using the bitwise/logical exclusive OR operator to exchange (also known as swap) values without the need for a temporary variable. That "bitwise exclusive OR exchange" is just one of three techniques for exchanging variable contents. To see all of those techniques, check out Listing 3.1's source code to the Exchange application.
Listing 3.1: Exchange.java.
// Exchange.java class Exchange { public static void main (String [] args) { int num1 = 10, num2 = 20, temp; // Perform a traditional exchange. This requires the use of a // temporary variable. Any data types can be exchanged. System.out.println ("Traditional Exchange"); temp = num1; num1 = num2; num2 = temp; System.out.println ("num1 = " + num1); System.out.println ("num2 = " + num2); // Reset variables to original values. num1 = 10; num2 = 20; // Perform an additive exchange. No temporary variable is // needed. Only numeric types can be exchanged. System.out.println ("\nAdditive Exchange"); num1 += num2; num2 = num1 - num2; num1 -= num2; System.out.println ("num1 = " + num1); System.out.println ("num2 = " + num2); // Reset variables to original values. num1 = 10; num2 = 20; // Perform a bitwise exclusive OR exchange. No temporary // variable is needed. All numeric types except floating- // point and double-precision floating-point can be exchanged. System.out.println ("\nBitwise exclusive OR Exchange"); num1 ^= num2; num2 = num1 ^ num2; num1 ^= num2; System.out.println ("num1 = " + num1); System.out.println ("num2 = " + num2); } }
Finally, the bitwise/logical inclusive OR operator works as follows: From a numeric perspective, if corresponding bits in both numeric operands are 0, the result is 0. Otherwise, the result is 1. However, from a Boolean perspective, if both Boolean operands are false, the result is false. Otherwise, the result is true. That operator has the following syntax:
operand1 '|' operand2The following code fragment demonstrates the bitwise/logical inclusive OR operator:
byte b1 = 0x10; // b1 contains 16 (decimal). byte b2 = 4; // b2 contains 4 b1 |= b2; // b1 contains 20 (decimal). boolean first = true; // first contains true boolean second = true; // second contains true first = first | second; // first contains true
Conditional Operators
The conditional operators either evaluate the left operand and conditionally evaluate the right operand, or evaluate one of two operands based on a third operand. You represent those operators in source code by using the &&, ||, and ?: tokens.
The conditional AND operator (&&) behaves in a manner that is similar to bitwise/logical AND. However, with conditional AND, if the left operand evaluates to false, the right operand is not evaluated (because the final result is guaranteed to be false). That operator has the following syntax:
operand1 '&&' operand2Each operand type must be Boolean.
The following code fragment demonstrates the conditional AND operator:
int numApplicants = 0; int age = 60; boolean stopCondition = age > 64 && ++numApplicants < 100;
The example introduces two operators not yet covered: > (relational greater than) and ++ (preincrement). age > 64 returns true if the value stored in age is greater than 64. ++numApplicants < 100 first adds one to the value stored in numApplicants and then returns true if the new value is less than 100. If both age is greater than 64 and the new value stored in numApplicants is still less than 100, && returns truewhich subsequently assigns to stopCondition.
In the example, age is assigned 60 and age > 64 returns false. Because the left operand evaluates to false, && does not evaluate the right operand. As a result, numApplicants is not incrementeda side effect of evaluating age > 64 && ++numApplicants < 100. That is a problem if numApplicants should always be incremented, whether age is greater than 64 or not. In that situation, the problem is solved by replacing && with &which evaluates both operands before performing a logical AND.
So why does conditional AND differ from logical AND by short circuiting the evaluation of its right operand? The answer has to do with objects.
Suppose you have the following code fragment:
String s = null; boolean result = s != null && s.length () > 5;
The code fragment declares a String variable initialized to null and then uses the && operator to evaluate the left operand. Because s != null returns false, && does not evaluate the right operand. It is a good thing that && does not evaluate s.length () > 5. The reason is that s contains null and an attempt to call s.length()to return the number of characters contained in the String object referenced by s (the string's length)would result in a runtime exception, which would terminate the program. But if & (bitwise/logical AND) is substituted for &&, that exception occurs because bitwise/logical AND evaluates both operands.
The conditional OR operator (||) behaves in a manner that is similar to bitwise/logical OR. However, with conditional OR, if the left operand evaluates to true, the right operand is not evaluated (because the final result is guaranteed to be true). That operator has the following syntax:
operand1 '||' operand2Each operand type must be Boolean.
The following code fragment demonstrates the conditional OR operator:
int i = 2; int j = 2; boolean result = i > 1 || (j = 3); System.out.println ("j = " + j);
Because i is greater than 1, j is not assigned the value 3. As a result, j = 2 is output. However, if you change j to 1, you will see something different.
The conditional operator (?:) uses the Boolean value of one operand to determine which of two other operands should be evaluated. That operator has the following syntax:
operand1 '?' operand2 ':' operand3operand1 (which must be a Boolean operand) is evaluated. If the result is true, operand2 is evaluated and its result is returned by the conditional operator. Otherwise, operand3 is evaluated and the conditional operator returns the result. The types of operand2 and operand3 must agree: The compiler might use a widening conversion rule to ensure that happens.
The following code fragment demonstrates using the conditional operator to convert from Boolean to integer and back:
boolean b = true; int x = (b == true) ? 1 : 0; b = (x != 0) ? true : false;
Equality Operators
The equality operators do one of three things: They compare two numeric operands to see whether those operands are identical or not; they compare two Boolean operands to see whether they are identical or not; or they compare two reference operands to see whether both operands contain the same references or not. The equality operators are represented in source code by the == and != tokens.
For each operator, if the operand types don't match, the compiler will either use a widening rule to convert the operand whose type represents a more restricted range of values to the type of the other operand, or display an error message if the types are radically different (such as using Boolean with integer).
The equality operator (==) checks to see whether two operands are equal. It returns true if they are equal. Otherwise, false is returned. That operator has the following syntax:
operand1 '==' operand2The following code fragment demonstrates the equality operator:
String s = "abc"; String t = "abc"; System.out.println (s == t);
The equality operator (!=) checks to see whether two operands are not equal. It returns true if they are not equal. Otherwise, false is returned. That operator has the following syntax:
operand1 '!=' operand2The following code fragment demonstrates the inequality operator:
String s = "abc"; String t = "abc"; System.out.println (s != t);
Multiplicative Operators
The multiplicative operators perform multiplication, division, and remainder. Those operators are represented in source code by the *, /, and % tokens.
For each operator, the operand types must be one of byte, character, double-precision floating-point, floating-point, integer, long integer, or short integer. If the operand types don't match, the compiler will use a widening rule to convert the operand whose type represents a more restricted range of values to the type of the other operand.
The multiplicative operator (*) performs multiplication. That operator has the following syntax:
operand1 '*' operand2The following code fragment demonstrates the multiplicative operator that performs multiplication:
double PI = 3.14159; double diameter = 10.0; double circumference = PI * diameter;
The multiplicative operator (/) performs division. That operator has the following syntax:
operand1 '/' operand2The following code fragment demonstrates the multiplicative operator that performs division:
double totalPaid = 20000.0; int itemsSold = 5000; double unitCost = totalPaid / itemsSold; float f = 1.0f / 0.0f; int i = 1 / 0;
In the example, the last two lines of code attempt to divide by zero. When an attempt is made to perform a floating-point division by zero (such as 1.0f / 0.0f), a special value is stored in the variable (such as +Infinity). However, when an attempt is made to perform an integer division by zero (such as 1 / 0), an exception is thrown.
4 To learn more about special mathematical values (such as +Infinity), see "Java and
Mathematics," p. 580. To learn more about throwing exceptions, see
"Throwing Exceptions," p. 342.
In addition to +Infinity, what other special mathematical values can be generated from dividing by zero? Give up? Compile and run Listing 3.2's source code to the DivideByZero application for an answer. That application also demonstrates the exception that is thrown when an attempt is made to perform an integer division.
Listing 3.2: DivideByZero.java.
// DivideByZero.java class DivideByZero { public static void main (String [] args) { System.out.println (1.0 / 0.0); System.out.println (-1.0 / 0.0); System.out.println (0.0 / 0.0); System.out.println (1 / 0); } }
To round out the multiplicative operators, the multiplicative operator (%) performs integer remainder. That operator has the following syntax:
operand1 '%' operand2The following code fragment demonstrates the multiplicative operator that performs remainder:
short num = 57; int tens = num / 10; // tens contains 5 int ones = num % 10; // ones contains 7
Relational Operators
The relational operators relate operands to each other either numerically or referentially. They are represented in source code by the <, <=, >, >=, and instanceof tokens.
For each operator (other than instanceof), the operand types must be one of byte, character, double-precision floating-point, floating-point, integer, long integer, or short integer. If the operand types don't match, the compiler will use a widening rule to convert the operand whose type represents a more restricted range of values to the type of the other operand.
The relational less than operator (<) compares two values and returns a Boolean true value if the left operand is numerically less than the right operand. Otherwise, it returns false. That operator has the following syntax:
operand1 '<' operand2The following code fragment demonstrates the relational less than operator:
System.out.println ('A' < 'B');The relational less than or equal to operator (<=) compares two values and returns a Boolean true value if the left operand is numerically less than or equal to the right operand. Otherwise, it returns false. That operator has the following syntax:
operand1 '<=' operand2The following code fragment demonstrates the relational less than or equal to operator:
int score = 75; System.out.println (score <= 49 ? "failed" : "passed");
The relational greater than operator (>) compares two values and returns a Boolean true value if the left operand is numerically greater than the right operand. Otherwise, it returns false. That operator has the following syntax:
operand1 '>' operand2The following code fragment demonstrates the relational greater than operator:
double temp = 100.0; System.out.println (temp > 99.9 ? "boiling" : "coming to a boil");
The relational greater than or equal to operator (>=) compares two values of the same numeric type and returns a Boolean true value if the left operand is numerically greater than or equal to the right operand. Otherwise, it returns false. That operator has the following syntax:
operand1 '>=' operand2The following code fragment demonstrates the relational greater than or equal to operator:
double temp = 100.0; System.out.println (temp >= 100.0 ? "boiling" : "coming to a boil");
The relational type checking operator (instanceof) compares an object reference to a reference type to see if the object is an instance of the type. A Boolean true value is returned if the object is an instance. Otherwise, false is returned. That operator has the following syntax:
operand1 'instanceof' operand2The left operand must be an object reference variable (which implies a reference type), and the right operand must be a reference type.
The following code fragment demonstrates instanceof:
System.out.println ("" instanceof String);Shift Operators
The shift operators shift the bits of their left operands either left or right using the amount specified by their right operands. Those operators are represented in source code by the <<, >>, and >>> tokens.
For each operator, the operand types must be one of byte, character, integer, long integer, or short integer. If the operand types don't match, the compiler will use a widening rule to convert the operand whose type represents a more restricted range of values to the type of the other operand.
The left shift operator (<<) left-shifts the bits of its left operand using the number of positions specified by its right operand. For each shift, a 0 is shifted into the operand's rightmost bit, and the leftmost bit is discarded. That operator has the following syntax:
operand1 '<<' operand2The following code fragment demonstrates the left shift operator:
int num = 35; num = num << 1;
Figure 3.4 illustrates the left shift. A 0 is shifted into the rightmost bit, and the leftmost bit is discarded. The result can be interpreted as decimal number 70 (46 hexadecimal). Left shift preserves negative numbers so that -1 << 1 yields -2.
Figure 3.4: A left shift operation is equivalent to (but faster than) multiplying by powers of 2.
The signed right shift operator (>>) right-shifts the bits of its left operand using the number of positions specified by its right operand. For each shift, a copy of the sign bit is shifted to the right and the rightmost bit is discarded. That operator has the following syntax:
operand1 '>>' operand2The following code fragment demonstrates the signed right shift operator:
int num = -2; num = num >> 1;
Figure 3.5 illustrates the signed right shift. A 1 is shifted into the leftmost bit and the rightmost bit is discarded. The result can be interpreted as decimal number 1 (FF hexadecimal). Signed right shift preserves negative numbers.
Figure 3.5: A signed right shift operation is equivalent to (but faster than) dividing by powers of 2.
The unsigned right shift operator (>>>) right-shifts the bits of its left operand using the number of positions specified by its right operand. For each shift, a 0 is shifted into the leftmost bit and the rightmost bit is discarded. That operator has the following syntax:
operand1 '>>>' operand2The following code fragment demonstrates the unsigned right shift operator:
int num = -2; num = num >>> 1;
Figure 3.6 illustrates the unsigned right shift. A 0 is shifted into the leftmost bit, and the rightmost bit is discarded. The result is decimal number 2,147,483,647 (the highest positive value of type integer). Unlike signed right shift, unsigned right shift does not preserve negative numbers.
Figure 3.6: An unsigned right shift operation is equivalent to (but faster than) dividing by powers of 2 for positive numbers only.
Tip
Use the shift operators to quickly multiply and divide in computationally intensive graphics programs where performance is important.
Unary Operators
So far, only binary and ternary operators have been examined. The JLS also mentions a variety of unary operators. Those operators are represented by the +, -, ++, --, ~, and ! tokens. The cast operator is also included as a unary operator.
The unary plus operator (+) is a prefix operator that returns its operand. That operator has the following syntax:
'+' operandThe operand's type must be one of byte, character, double precision-floating point, floating-point, integer, long integer, or short integer.
The following code fragment demonstrates the unary plus operator:
System.out.println (+3);The unary minus operator (-)also known as the negation operatoris a prefix operator that returns the arithmetic negative of its operand. That operator has the following syntax:
'-' operandThe operand's type must be one of byte, character, double-precision, floating-point, integer, long integer, or short integer.
The following code fragment demonstrates the unary minus operator:
System.out.println (-3);The preincrement operator (++) is a prefix operator that first adds one to its operand (which must be a variable) and then returns the result. That operator has the following syntax:
'++' operandIn a similar fashion, the predecrement operator () is a prefix operator that first subtracts one from its operand (which must be a variable) and then returns the result. That operator has the following syntax:
'--' operandWith either operator, the operand's type must be one of byte, character, double-precision floating-point, floating-point, integer, long integer, or short integer.
The following code fragment demonstrates the preincrement and predecrement operators:
int num = 2; System.out.println (++num); // 3 is output. System.out.println (num); // 2 is output
The postincrement operator (++) is a postfix operator that saves the value of its variable operand in a temporary variable, adds one to the value in the variable operand, and returns the value of the temporary variable. That operator has the following syntax:
operand '++'In a similar fashion, the postdecrement operator (--) is a postfix operator that saves the value of its variable operand in a temporary variable, subtracts one from the value in the variable operand, and returns the value of the temporary variable. That operator has the following syntax:
operand '--'With either operator, the operand's type must be one of byte, character, double-precision floating-point, floating-point, integer, long integer, or short integer.
The following code fragment demonstrates the postincrement and postdecrement operators:
int num = 2; System.out.println (num++); // 2 is output. System.out.println (num); // 3 is output
The bitwise complement operator (~) is a prefix operator that flips the bits of its operand1s become 0s and 0s become 1s. That operator has the following syntax:
'~' operandThe operand's type must be one of byte, character, integer, long integer, or short integer.
The following code fragment demonstrates the bitwise complement operator:
System.out.println (~0xff00);The logical complement operator (!) is a prefix operator that flips the Boolean state of its operandtrue becomes false and false becomes true. That operator has the following syntax:
'!' operandThe operand's type must be Boolean.
The following code fragment demonstrates the logical complement operator:
System.out.println (!true);There is one final unary operator to examinecast. That operator is either used to explicitly specify a narrowing rule (for primitive types) or to explicitly convert a superclass type to a subclass type (for reference types). The cast operator has the following syntax:
'(' typeIdentifier ')' operandtypeIdentifier is the type to which operand is to be converted. If the conversion is legal, that will typically result in a new storage representation for the operand. For example, a floating-point value being converted to an integer will have a different storage representation (from sign bit/exponent/mantissa to twos complement).
The following code fragment demonstrates the cast operator:
short s = (short) 50000; // 50000 is of type integer.The 32-bit integer 50000 is converted to a 16-bit short integer by truncating (throwing away) the upper 16 bits.