Saturday, 9 May 2015

Operators in Java

A language's operators can be used to combine or alter a program's values. Java contains a very rich set of operators. The complete list of Java operators is as follows:


Operators on Integers

The bulk of the Java operators work on integer values. The binary operators (those that require two operands) are shown in Table 3.9. The unary operators (those that require a single operand) are shown in Table 3.10. Each table gives an example of the use of each operator.



 In addition to the operators shown in Tables 3.9 and 3.10, Java also includes an assortment of assignment operators that are based on the other operators. These operators will operate on an operand and store the resulting value back in the same operand. For example, to increase the value of a variable x, you could do the following:
x += 3;
This is equal to the more verbose x = x + 3. Each of the specialized Java assignment operators performs its normal function on the operand and then stores the value in the operand. The following assignment operators are available:


Operators on Floating-Point Values



Operators on Boolean Values

The Java Boolean operators are summarized in Table 3.12. If you are coming to Java from a C or C++ background, you are probably already familiar with these. If not, however, the conditional operator will be a new experience.


 The conditional operator is Java's only ternary (three-operand) operator and has the following syntactic form:
booleanExpr ? expr1 : expr2
The value of booleanExpris evaluated and if true, the expression expr1 is executed; if false, expression expr2is executed. This makes the conditional operator a convenient shorthand for the following:
if(booleanExpression)
    expr1
else
    expr2

1 comment: