Previous | Next | Trail Map | Writing Java Programs | The Nuts and Bolts of the Java Language


Operators

class 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.");
    }
}    
The character-counting program uses several operators including [], =, !=, ++, 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 op2

Arithmetic Operators

The Java language supports various arithmetic operations--including addition, subtraction, multiplication, and division--on all numbers. The statement count++ 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 by System.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 of count, and " chars."
System.out.println("Input has " + count + " chars.");
String Concatenation contains more information.

Operator Precedence

The Java language allows you to create compound expressions and statements such as this one:
x * y * z
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 / 100
gives different results if you perform the multiplication first or the division first. You can use balanced parentheses ( and ) to explicitly tell the Java compiler the order in which to evaluate an expression, for example x * (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.


Previous | Next | Trail Map | Writing Java Programs | The Nuts and Bolts of the Java Language