Java Language


Operators All Versions

Java SE 1.0
Java SE 1.1
Java SE 1.2
Java SE 1.3
Java SE 1.4
Java SE 5
Java SE 6
Java SE 7
Java SE 8
Java SE 9 (Early Access)

This draft deletes the entire topic.

expand all collapse all

Examples

  • 12

    Variables can be incremented or decremented by 1 using the ++ and -- operators, respectively.

    When the ++ and -- operators follow variables, they are called post-increment and post-decrement respectively.

    int a = 10;
    a++; // a now equals 11
    a--; // a now equals 10 again
    

    When the ++ and -- operators precede the variables the operations are called pre-increment and pre-decrement respectively.

    int x = 10;
    --x; // x now equals 9
    ++x; // x now equals 10
    

    If the operator precedes the variable, the value of the expression is the value of the variable after being incremented or decremented. If the operator follows the variable, the value of the expression is the value of the variable prior to being incremented or decremented.

    int x=10;
    
    System.out.println("x=" + x + " x=" + x++ + " x=" + x); // outputs x=10 x=10 x=11
    System.out.println("x=" + x + " x=" + ++x + " x=" + x); // outputs x=11 x=12 x=12
    System.out.println("x=" + x + " x=" + x-- + " x=" + x); // outputs x=12 x=12 x=11
    System.out.println("x=" + x + " x=" + --x + " x=" + x); // outputs x=11 x=10 x=10
    
  • 10

    Syntax

    {condition-to-evaluate} ? {statement-executed-on-true} : {statement-executed-on-false}

    As shown in the syntax, Ternary Operator uses the ? (question mark) and : (colon) characters to enable a conditional expression of two possible outcomes. It can be used to replace longer if-else blocks to return one of two values based on condition.

    result = testCondition ? value1 : value2
    

    Is equivalent to

    if (testCondition) { 
        result = value1; 
    }
    else { 
        result = value2; 
    }
    

    It can be read as “If testCondition is true, set result to value1; otherwise, set result to value2”.

    While the ternary operator can at times be a nice replacement for an if/else statement, the ternary operator may be at its most useful as an operator on the right hand side of a statement. For example:

    // get absolute value using ternary operator 
    a = -10;
    int absValue = (a < 0) ? -a : a;
    System.out.println("abs = " + absValue); // prints "abs = 10"
    

    Is equivalent to

    // get absolute value using if/else loop
    a = -10;
    int absValue = 0;
    if(a < 0) {
        absValue = -a;
    } else {
        absValue = a;
    }
    System.out.println("abs = " + absValue); // prints "abs = 10"
    

    Common Usage

    You can use the ternary operator for conditional assignments (like null checking).

    String x = (y != null) ? y.toString() : ""; //where y is an object
    

    This example is equivalent to:

    String x = "";
    
    if (y != null) {
        x = y.toString();
    }
    

    Ternary operators nesting can also be done in the third part, where it works more like chaining or like a switch statement.

    a ? "a is true" :
    b ? "a is false, b is true" :
    c ? "a and b are false, c is true" :
        "a, b, and c are false"
    
    //Operator precedence can be illustrated with parenthesis:
    
    a ? x : (b ? y : (c ? z : w))
    
  • 5

    The Java language provides 4 operators that perform bitwise logical operations on integer operands operands.

    • The bitwise complement (~) operator is a unary operator that performs a bitwise inversion of the bits of one operand; see JLS 15.15.5..
    • The bitwise AND (&) operator is a binary operator that performs a bitwise "and" of two operands; see JLS 15.22.2..
    • The bitwise OR (|) operator is a binary operator that performs a bitwise "inclusive or" of two operands; see JLS 15.22.2..
    • The bitwise XOR (^) operator is a binary operator that performs a bitwise "exclusive or" of two operands; see JLS 15.22.2..

    The logical operations performed these operators can be summarized as follows:

    AB~AA & BA | BA ^ B
    001000
    011011
    100011
    110110

    Note that the above table describes what happens for individual bits. The operators actually operate on all 32 or 64 bits of the operand or operands in parallel.

    Operand types and result types.

    As we stated above, these 4 operators apply to integer operands. (There are 3 overloaded operators for non-short-circuit logical operations, but the Java Language Specification treats them as separate operators.)

    In fact, Java only supports integer bitwise operations for int and long values. The operands are are converted as follows:

    • A byte, short or char operand is promoted to int,
    • A Byte Short or Character operand is unboxed and promoted to int.
    • An Integer is unboxed to an int.
    • An Long is unboxed to a `long.

    For the unary operator, the type of the converted operand determines the type of the result.

    For the binary operators:

    • If both operands are int, a 32 bit operation is performed giving an int result.
    • If both operands are long a 64 bit operation is performed, giving an long result.
    • One operand is int and the other is long, the int operand is promoted to long. Then a 64 bit operation is performed, giving a long result.

    This means that if you perform a bitwise operation on a byte, short or char, you cannot directly assign the result to a byte, short or char variable. For example:

    byte b = 0x11;
    b = b & 0x01;             // COMPILATION ERROR
    

    The solution is to cast the result of the bitwise operation before assigning; e.g.

    b = (byte) (b & 0x01);    // CORRECT
    

    Common use-cases for the bitwise operators

    The ~ operator is rarely used on its own.

    The & operator is often used for "masking out" some of the bits in a word represented as an integer. For example:

    int word = 0b00101010;
    int mask = 0b00000011;   // Mask for masking out all but the bottom 
                             // two bits of a word
    int lowBits = word & mask;            // -> 0b00000010
    int highBits = word & ~mask;          // -> 0b00101000
    

    The | operator is often used for combining part of one word with another. For example:

    int word2 = 0b01011111; 
    // Combine the bottom 2 bits of word1 with the top 30 bits of word2
    int combined = (word & mask) | (word2 & ~mask);   // -> 0b01011110
    

    The ^ operator is most often used for toggling or "flipping" bits:

    int word3 = 0b00101010;
    int word4 = word3 ^ mask;             // -> 0b00101001
    

    The ^ operator is also used in some hashing algorithms.

    For more examples of the use of the bitwise operators, see Bit manipulation

Please consider making a request to improve this example.

Syntax

  • x++; OR x--; // Post-increment
  • --x; OR ++x: // Pre-increment
  • (condition) ? -do if true- : -do if false- // Tenerary Operator
  • if( x == 1 ) { // Relational operator (==, !=, >, <, >=, <=)
  • if( x == 1 && y == 0) { // Logical operator (AND, OR, XOR, etc)

Parameters

Parameters

Remarks

Remarks

Still have a question about Operators? Ask Question

Topic Outline