The Nuts and Bolts of the Java Language |
The character-counting program uses several operators includingclass Count { public static void main(String args[]) throws java.io.IOException { int count = 0; while (System.in.read() != -1) count++; System.out.println("Input has " + count + " chars."); } }[]
,=
,!=
,++
, and+
. As in other languages, Java operators fall into four categories: arithmetic, relational, logical, and string. With a few notable exceptions, Java operators use infix notation--the operator appears between its operands.op1 operator op2Arithmetic Operators
The Java language supports various arithmetic operations--including addition, subtraction, multiplication, and division--on all numbers. The statementcount++
uses a short cut operator++
, which increments a number.Relational Operators
The relational operators compare two values and determine the relationship between them. For example,!=
returns true if two values are unequal. The character-counting program uses!=
to determine whether the value returned bySystem.in.read()
is not equal to -1.Logical Operators
The logical operators take two values and perform boolean logic operations. Two such operators are&&
and||
, which perform boolean and and boolean or operations, respectively. Typically, programmers use logical operators to evaluate compound expressions. For example, this code snippet verifies that an array index is between two boundaries:if (0 < index && index < NUM_ENTRIES)String Operators
The Java language extends the definition of the operator+
to include string concatenation. The example program uses+
to contenate "Input has
", the value ofcount
, and "chars.
"String Concatenation contains more information.System.out.println("Input has " + count + " chars.");Operator Precedence
The Java language allows you to create compound expressions and statements such as this one:In this particular example, the order in which the expression is evaluated is unimportant because multiplication is commutative. However, this is not true of all expressions, for example:x * y * zgives different results if you perform the multiplication first or the division first. You can use balanced parenthesesx * y / 100(
and)
to explicitly tell the Java compiler the order in which to evaluate an expression, for examplex * (y / 100)
, or you can rely on the precedence the Java language assigns to each operator. This chart illustrates the relative precedence for all Java operators.
The Nuts and Bolts of the Java Language |