Java operators and Precedence
An operator takes one or more arguments and produces a new value. The arguments are in a different form than ordinary method calls, but the effect is the same. Addition and unary plus (+), subtraction and unary minus (-), multiplication (*), division (/), and assignment (=) all work much the same in any programming language.
All operators produce a value from their operands. In addition, some operators change the value of an operand. This is called a side effect. The most common use for operators that modify their operands is to generate the side effect, but you should keep in mind that the value produced is available for your use, just as in operators without side effects.
Almost all operators work only with primitives. The exceptions are ‘=‘, ‘==‘ and ‘!=‘, which work with all objects (and are a point of confusion for objects). In addition, the String class supports ‘+’ and ‘+=‘.
Precedence
Operator precedence defines how an expression evaluates when several operators are present. Java has specific rules that determine the order of evaluation. The easiest one to remember is that multiplication and division happen before addition and subtraction. Programmers often forget the other precedence rules, so you should use parentheses to make the order of evaluation explicit. For example, look at statements (1) and (2):
public class Test { public static void main(String[] args) { int x = 1, y = 2, z = 3; int a = x + y - 2/2 + z; // (1) int b = x + (y - 2)/(2 + z); // (2) System.out.println("a = " + a + " b = " + b); } }
Output:
a = 5 b = 1
These statements look roughly the same, but from the output you can see that they have very different meanings which depend on the use of parentheses.
Notice that the System.out.println( ) statement involves the ‘+’ operator. In this context, ‘+’ means “string concatenation” and, if necessary, “string conversion.” When the compiler sees a String followed by a ‘+’ followed by a non-String, it attempts to convert the non-String into a String. As you can see from the output, it successfully converts from int into String for a and b.
No comments: