Witscale Test Center

9.1 Operators


9.1 Operators

Ability to manipulate a data value is a fundamental need of any programming language. You often perform basic functions such as addition, subtraction on numeric values. Most programming languages use symbols to indicate these operations. In Java, these symbols are called as operators and the values on which they operate are commonly known as the operands. With Java operators, you can specify a range of operations you wish to perform on the operands. All operations produce a new value as a result. For example, the expression a + b has variables a and b are operands and the symbol + is an operator. This operator indicates that the addition operation is to be performed on its operands.

Java has various operators to symbolize the wide range of operations right from simple arithmetic to shifting of bits. Since the data values are usually stored in variables, often the variables are used as operands. However, you can also use Java expressions as operands. An expression itself is made up of variables, operators, and method calls. When used as operands, the expressions are first evaluated to a value. Then these values acts as operands.

Certain operations are relevant for two operands while some are relevant to only one operand. Table 9.1 summarizes all java operators based on the number of operands and the operations they perform.

 

Table 9.1 Java operators

 

Category (No of operands)

Subcategory

Operators

Format and example

Unary (1)

Arithmetic

++   --   +   -

Format:

Operator operand1

     Or

operand1 Operator

Examples:

++i  j--

Boolean complement

!

Bitwise  inversion

~

Cast

()

Binary (2)

 

Arithmetic

Shift

Comparison

Bitwise

Logical short circuit

*   /   %   +   -

<<   >>   >>>

<   >   <=   >=   instanceof   ==   !=

&   ^   |

&&   ||

   

Format:

operand1 Operator operand2

Examples:

2 + 8

2 ^ 8

Simple assignment

Compound assignment*

=

op=

Ternary (3)

Conditional

?:

Format:

operand1 PartialOperator operand2 PartialOperator operand3

 

Examples:

(2>3)? 0 :1;

 

 

 

 

*

In compound assignment, op can be any of the binary operators (* / % + - << >> >>> & ^ |) for numeric data types

                                                

The operands can either be primitive values or object references. Almost all operators are applicable to numeric values. The operators, = == !=  and cast operator are applicable to all primitives as well as the object references. Two other operators, + and += are applicable to numeric values and String objects. The operator instanceof is applicable to only object references. The next sections discuss these operators in detail. However, before that, let us see how the expressions involving multiple operators are evaluated and how operator precedence plays a role in the evaluation.