Home : Course Map : Chapter 2 : Java : Operators
Operators
JavaTech
Course Map
Chapter 2

Introduction
Essentials
Structure

Keywords
Primitive Types
Comments
Literals
Expressions
Operators
Statements
Casts & Mixing
Strings
Console Output 
   Demo
Exercises

    Supplements
Conditional: if-else
Repetitions
Flow Control

Java vs C/C++
JVM Instructions 1

     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

The tables below group the Java operators according to similar actions. For newcomers to Java, you can just scan these tables for now, especially for operations dealing with class and objects, and then refer back to them as you encounter more of the language.

Most of the operators are fairly straightforward but there can be subtle details in their implementation that you must understand. For example, you must know the difference in the pre- and post-increment operations with regard to when the operation executes versus when the value of the operand value returns.

We will return to many of these operators as the course proceeds.

General Properties of Operators

In Java, an expression carries out some operation or operations that are directed by a list of allowed operators. An operator acts upon one, two or three operands. Here are some general properties of operators:

Operands

An operand can be:

  • a numeric variable - integer, floating point or character
  • any primitive type variable - numeric and boolean
  • reference variable to an object
  • a literal - numeric value, boolean value, or string.
  • an array element, "a[2]"
  • char primitive, which in numeric operations is treated as an unsigned two byte integer

The operator is unary if it acts on a single operand; binary if it requres two operands. The conditional operator is the only ternary operator in Java.

Each operator places specific requirements on the operand types allowed. For example, the subtractive operator "- " in x=a-b; requires that a and b variables be numeric types. The assignment operator "=" then requires that x also be a numeric type. (If a and b were wider types than x, a casting operation would also be required.)

Returned Value

A value is "returned" at the completion of an operation. The following statements use the assignment operator "=" and the addition operator "+"

  int x = 3;
  int y = x+5;

and result in x holding the value 3 and y holding the value 8. The entire expression y= x+5 could be used in another expression:

  int x=3;
  int y;
  int z = (y=x+5) * 4;

which results in y holding 8 and z holding 32. The assignment operator "=" in the expression "y=x+5" produces a new value for y and also returns the value of y to be used in the expression for z.

Effects on Operands

In most of the operations, the operands themselves are not changed. However, for some operators, the operand(s) do undergo a change:

  • Assignment operators: "x=y" replaces the value of the first operand with that of the second. The other assignment operators, "*=, +=, etc" will also replace the value of the first operand but only after using its initial value in the particular operation indicated by the symbol before the = sign.

  • Increment & decrement operators: The operand is incremented or decremented, before or after the operand's value is returned, depending on whether it is a pre- or post- increment of decrement.

If an operand is changed by the operation, note that if the statement holding that expression is processed again, e.g. in a loop, the resulting value can be different for each pass.

Expression Evaluation

The operands of an operator are always evaluated left to right. For example, in

   x = a + b;

the first "+" operator will determine the value of a and then b.

Do not get this rule confused with the precedence and associativity rules.

  • Precedence determines the order in which operators act in an expression of more than one operator. The table below gives the rating for each operator, the higher number indicating higher precedence.

  • Associativity rules determine the grouping of operands and operators in an expression with more than one operator of the same precedence.

For example, in the expression

   x = a + b * c;

the first "+" operator still first determines its left operand ("a" in this case) and then its right operand. But in this case the right operand consists of the expression "b*c". The multiplication operator "*" has a higher precedence than the additive "+".

Precedence can be overridden with parentheses, e.g.

   x = (a + b) * c;

will force the addition of b to a, and then this sum is multiplied by c.

Although the precedence ratings, which are similar to those in C/C++, were chosen for the most "natural" ordering of the operator evaluations, it never hurts to use the parentheses if you are unsure of the precedence and don't have the table handy.

When the operations in an expression all have the same precedence rating, the associativity rules determine the order of the operations. For most operators, the evaluation is done left to right, e.g.

   x = a + b - c;

Here, addition and subtraction have the same precedence rating and so a and b are added and then from this sum c is subtracted. Again, parentheses can be used to overrule the default associativity, e.g.

   x = a + (b - c);

However, the assignment and unary operators, are associated right to left, e.g.

   x += y -= -~4;

is equivalent to

   x += (y -= (-(~4)));

or in long hand,

   int a = ~4;
   a = -a;
   y = y - a;
   x = x + y;

Other Operator Tricks

Finally, here are some other miscellaneous notes about operators. As indicated in the last example above, assignment operations can be chained:

   x = y = z = 4;

with the evaluations proceeding right to left.

Assignments can be combined into other operations, to compact the code, e.g.

   if( (x = 5) == b) y = 10;

which first sets x to 5, then returns that value for the test of b. You should not overuse this technique else it makes the code unreadable. Occasionally, though, it can be a neat approach.


Tables of Java Operators

Assignment Operators

x operation= y
is equivalent to
x = x operation y

x and y must be numeric or char types except for "=", which allows x and y also to be object references. In this case, x must be of the same type of class or interface as y. If mixed floating-point and integer types, the rules for mixed types in expressions apply.

=
Assignment operator.
    x = y;
y is evaluated and x set to this value.
The value of x is then returned.

 +=, -=, *=, /=, %=

Arithmetic operation and then assignment, e.g.
    x += y;
is equivalent to
    x = x + y;

      &=, |=, ^= Bitwise operation and then assignment, e.g.
    x &= y;
is equivalent to
    x = x & y;
    <<=, >>=, >>>= Shift operations and then assignment, e.g.
    x <<= n;
is equivalent to
    x = x << n;

 

Arithmetic Operators

x and y are numeric or char types. If mixed floating-point and integer types, then floating-point arithmetic used and a floating-point value returned. If mixed integer types, the wider type is returned. If double and float mixed, double is returned.

   x + y

Addition
   x - y Subtraction
   x * y Multiplication
   x / y Division
If FP arithmetic and y = 0.0, then infinity returned if x is not zero, NaN if x is zero.
ArthmeticException thrown if x & y are integer types and y is zero.
   x % y Modulo - remainder of x/y returned.
If FP arithmetic and y = 0.0 or infinity,
then NaN returned
ArthmeticException thrown if x & y are integer types and y is zero.
   -x Unary minus
Negation of x value

 

Increment & Decrement Operators
x and y are numeric (FP & integer) or char types.

  x++

Post-increment : add 1 to the value.
The value is returned before the increment is made, e.g.
       x = 1;
       y = x++;

Then y will hold 1 and x will hold 2

  x--

Post-decrement : subtract 1 from the value.
The value is returned before the decrement is made, e.g. :
       x = 1;
       y = x--;
Then y will hold 1 and x will hold 0.

  ++x

Pre-increment : add 1 to the value.
The value is returned after the increment is made, e.g.
       x = 1;
       y = ++x;
Then y will hold 2 and x will hold 2.

  --x

Pre-decrement : subtract 1 from the value.
The value is returned after the decrement is made, e.g.
       x = 1;
       y = --x;
Then y will hold 0 and x will hold 0.

 

Boolean Operators

x and y are boolean types. x and y can be expressions that result in a boolean value.
Result is a boolean true or false value.

   x && y Conditional
AND
If both x and y are true, result is true.
If either x or y are false, the result is false
If x is false, y is not evaluated.
   x & y Boolean
AND
If both x and y are true,the result is true.
If either x or y are false, the result is false
Both x and y are evaluated before the test.
   x || y Conditional
OR
If either x or y are true, the result is true.
If x is true, y is not evaluated.
   x | y Boolean
OR
If either x or y are true, the result is true.
Both x & y are evaluated before the test.
   !x Boolean
NOT
If x is true, the result is false.
If x is false, the result is true.
   x ^ y Boolean
XOR
If x is true and y is false, the result is true.
If x is false and y is true, the result is true.
Otherwise, the result is false.
Both x and y are evaluated before the test.

 

Comparison Operators

x and y are numeric or char types only except for "==" and "!=" operators, which can also compare references. If mixed types, then the narrower type converted to wider type. Returned value is boolean true or false.

x < y

Is x less than y ?
x <= y Is x less than or equal to y ?
x > y Is x greater than y ?
x >= y Is x greater than or equal to y ?
x == y Is x equal to y ?
x != y Is x not equal to y ?

 

Bitwise Operators

x and y are integers. If mixed integer types, such as int and long, the result will be of the wider type.

Note: Operations on byte and short types may give unexpected results since operands are promoted to integers during intermediate operations. For example,
  byte x = (byte)0xFF;
  x >>>= 1;

will result in 0xFF in x rather than 0x7F. That is because the operation is carried out on a signed integer rather than simply on 8 bits. Here the signed byte is promoted to the signed integer 0xFFFFFFFF.

Use of an integer would go as follows:
  int i = 0xFF;
  i >>>= 1;

This results in 0x7F in the variable i.

   ~x

Compliment Flip each bit, ones to zeros, zeros to ones
   x & y AND AND each bit a with corresponding bit in b
   x | y OR OR each bit in a with corresponding bit in b
   x ^ y XOR XOR each bit in x with corresponding bit in y
   x << y Shift left Shift x to the left by y bits. High order bits lost.
Zero bits fill in right bits.
   x >> y Shift Right -
Signed
Shift x to the right by y bits. Low order bits lost.
Same bit value as sign (0 for positive numbers, 1 for negative) fills in the left bits.
   x >>> y Shift Right -
Unsigned
Shift x to the right by y bits. Low order bits lost.
Zeros fill in left bits regardless of sign.

 

Class and Object Operators
x instanceof c Class Test Operator

The first operand must be an object reference.
c is the name of a class or interface.
If x is an instance of type c or a subclass of c, then true returned.
If x is an instance of interface type c or a sub-interface, then true is returned.
Otherwise, false is returned.

   new c(args)
Class
Instantiation
Create an instance of class c using constructor c(args)
"."
Class Member Access Access a method or field of a class or object :
   o.f - field access for object o
   o.m() - method access for object o
()
Method Invocation Parentheses after a method name invokes
(i.e. calls) the code for the method, e.g.
   o.m()
   o.m(x,y)
(c)
Object
Cast
Treat an object as the type of class or interface c:
   c x=(c)y;
Treat y as an instance of class or interface c
+ String Concatenation

This binary operator will concatenate one string to another. E.g.

  String str1 = "abc";
  String str2 = "def";
  String str3 = str1 + str2

results in str3 holding "abcdef".

For mixed operands, if either a or b in (a + b) is a string, concatenation to a string will occur. Primitives will be converted to strings and the toString() methods of objects will be called.

(This is the only case of operator overloading in Java.)

Note that the equivalence operator "+=" will also perform string concatenation.

[] Array Element Access

In Java, arrays are classes. However, the bracket operators work essentially the same as in the C/C++.

To access a given element of an array, place the number of the element as an int value (long values cannot be used in Java arrays) into the brackets, e.g.

  float a = b[3];
  int n = 5;
  char c=c[n];

where b is a float array and c is a char array.

 

Other Operators
 x=boolean?y:x Conditional
Operator
The first operand - boolean - is a boolean variable or expression.
First this boolean operand is evaluated. If it is true then the second operator evaluated and x is set to that value.
If the boolean operator is false, then the third operand is evaluated and x is set to that value.
(primitive type) Type Cast

To assign a value of one primitive numeric type a more narrow type, e.g. long to int, an explicit cast operation is required, e.g.

          long a = 5;
          int b = (int)a;

 

Operator Precedence

The larger the number, the higher the precedence.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

=
*=
/=
%=
+=
-=
<<=
>>=
>>>=
&=
^=
|=

?: || && | ^

&

==
!=
<
<=
>
>=
<<
>>
>>>
+
-
*
/
%
new
(type)
++x
--x
+x
-x
~
!
.
[]
(args)
x++
x--
Notes:
  • (type) refers to the casting operator
  • "." is the object member access operator
  • [] is the array access operator
  • (args) indicates the invocation of a method.
  • In column 11, the + and - refer to binary addition and subtraction. Also, the + refers tothe string append operator. Whereas in column 14, the + & - refer to the unary operations +x and -x specify the sign of the value.
  • |, ^, and & refer to both the bitwise and boolean operators.

 

Operator Associativity

The following operators have Right to Left associativity. All other operators (see precedence table above) are evaluated left to right.

=
*=
/=
%=
+=
-=
<<=
>>=
>>>=
&=
^=
|=

?:
new
(type cast)
++x
--x
+x
-x
~
!

 

References & Web Resources

Latest update: May 22, 2008

            Tech
Arithmetic Ops
Math Class
More on Integers
FP : Overview
FP : Java  
  
Demo 1
More Mix/Cast
  Demo 2
Exercises

           Physics
Differential Eq.
Euler Method
  
Demo 1
Predictor-Corrector
  
Demo 2
Exercises

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.