Operators and Assignments

Category
Operators
Unary ++ ,--, + ,- ,! ,~, (), :
Arithmetic *, / ,% ,
+ ,- ,
Shift <<, >>, >>>
Comparison < ,<= ,> ,>= ,instanceof
== ,!= ,
Bitwise &, ^ ,|
Short-Circuit &&, ||,
Conditional ?:
Assignment ==, "op="

Return to top


Arithmetic Promotion of Operands

data types GUO International

Arithmetic promotion of operands takes place before any binary operator is applied, so that all numeric operands are at least int type.

byte b = 5;
byte b2 = 6;
byte sum = b + b2;//won't compile because b and b2 have been promoted to int type before
                  //adding them together.
int sum = b + b2; //works or
byte sum2 = (byte)(b + b2); // cast back to byte type

char c = 'B';
int i = c + 5; // c will be promoted to int(66), printout: 71

double d = 7.0; 
double result = d + i; //i will be promoted to double first. printout: 78.0

Return to top


Unary

There are seven(7) unary operators.

++, --: the increment and decrement operators

Initial Value of x
Expression
Final Value of y
Final Value of x
5 y = x++; 5 6
5 y = ++x; 6 6
5 y = x--; 5 4
5 y = --x; 4 4

public class Test {
    public static void main(String[] args) {
        int x = 5;
        int y = x++;
        int m = 5;
        int n = ++m;
        int o = 5;
        int p = o--;
        int j = 5;
        int k = --j;
        System.out.println("x="+x +", y="+y);//6 5
        System.out.println("m="+m +", n="+n);//6 6
        System.out.println("o="+o +", p="+p);//4 5
        System.out.println("j="+j +", k="+k);//4 4
    }
}

+, -: the unary plus and minus operators

 int x = -5;
 int y = +5;
 int z = -(y+6);

~: the bitwise inversion operator performs bitwise inversion on integral types.

int i = 5;  // 0...00000101
int i2 = ~i; // 1...11111010 ==> -6

!: the boolean complement operator inverts the value of a boolean expression.

boolean b = true;
boolean b2 = !b; // b2 = false

(): the cast operator(type) is used for explicit conversion of the type of an expression.

  int i = (int)(Math.PI*2); //3.14*2 ==>prints 6
  
  int character = (int)'A'; //65

:: the in operator(type) is used for loop constructs (since jdk1.5)

void aMethod(Collection c) {
    for (Object o : c)
        ((Myclass)o).doingSth();
}

Return to top


Arithmetic

There are five arithmetic operators.

*, / the multiplication and division operators perform multiplication and division on all primitive numeric types and char.

int a = 123, b = 234, c, d;

c = a * b / b; //a
d = a / b * b; //a
Note: watch calculation overflows

% the modulo operator gives a value which is related to the remainder of a division.


int a = 7, b = 4, c, d;
c = 7 % 4; // 3
d = 7 / 4; // 1

int m, n, o, p;
m = -5 % 2;  //-1 
p = 5 % -2;  // 1
n = -5 % -2; // -1
o = 7.6 % 2.9; //1.8

//7.6 - 2.9 = 4.7
//4.7 - 2.9 = 1.8 since 1.8 < 2.9, so the remainder is 1.8
Note: Simply drop any negative signs from either operand and calculate the result. Then, if the original left operand was negative, negate the result. The sign of the right operand is irrelevant.

+ and - : the addition and subtraction operators perform addition and subtraction. They apply to operands of any numeric type. Uniquely, + addition applies String object.


byte b = 5 + 7;
int i = b - 10;
byte b2 = 3;
byte b3 = b + b2; //won't compile
String s = "this is ";
String s2 = "a test";
String s3 = s + s2; //this is a test
String s4 = s + b; //this is a 12
String s5 = s + i; // this is a 2

Note:
  1. A + expression with two operands of primitive numeric type, the result is of a primitive numeric type, at least, int because of normal promotions. and at least as wide as the wider of the two operands.
  2. If one of the operands is not a String object, then the non-String operand is converted to a String object before the concatenation takes place.

Return to top


Shift Operators

There are three shift operators.

They perform bit shifts of the binary representation of the left operand. The operands should be int or long type. The smaller operands will be promoted before the shift starts. The right operand is reduced modulo x. int x is 32, long x is 64.

<< left shift --(lower order or at the least significant bit position, zero fill)

>>> unsigned right-shift operator(higher order or at the most significant bit position, zero fill).

>> signed right shift(keep sign). Positive number fill zero, negative number fill 1.

int i = 192;          //00000000 00000000 00000000 11000000 192
int result = i >>> 4; //00000000 00000000 00000000 00001100  12
//192/24

int i2 = 48;           //00000000 00000000 00000000 00110000
int result2 = i2 >> 2; //00000000 00000000 00000000 00001100 12
//28/22

int i3 = 12;           //00000000 00000000 00000000 00001100 12
int result3 = i3 << 4; //00000000 00000000 00000000 11000000 192
//12 * 24

int i4 = -192;          //11111111 11111111 11111111 01000000 -192
int result4 = i4 >> 1;  //11111111 11111111 11111111 10100000 -96

int result5 = i4 >>> 30; //00000000 00000000 00000000 00000011 3

int result6 = i4 << 24; //01000000 00000000 0000000 00000000 230

Return to top


Comparison Operators

There are 7 comparison operators which return a boolean result. There are three types of comparison:

int p = 19;
int q = 65;
int r = -12;
float f = 9.0f;
char c = 'A'; //A's Unicode value is 65 System.out.println((int)c);

p < q //true
f < q
f <= c
c > r
c >= q 

Return to top


Bitwise Operators

There are three bitwise operators and only applicable to integral types.

AND Operation

operand1
operand2
operand1 AND operand2
0 0 0
0 1 0
1 0 0
1 1 1

XOR Operation

operand1
operand2
operand1 XOR operand2
0 0 0
0 1 1
1 0 1
1 1 0

OR Operation

operand1
operand2
operand1 OR operand2
0 0 0
0 1 1
1 0 1
1 1 1

Usage: deal with boolean values, or represent the states of a collection of binary inputs from physical devices. Save storage space.

Calculate the result on a bit-by-bit basis.

     00110011               00110011               00110011
     11110000               11110000               11110000
  AND--------             OR--------            XOR--------
     00110000               11110011               11000011
             
int i = 5;             //00000000 00000000 00000000 00000101
int i2 = 7;            //00000000 00000000 00000000 00000111
int res1 = i & i2;     //...00000101 5
int res2 = i ^ i2;     //...00000010 2
int res3 = i | i2;     //...00000111 7

Order of Precedent: AND-->XOR-->OR

int result = i & i2 | i ^ i2; //(i & i2) | (i ^ i2) = 7

boolean values keep the same rule.

boolean b = false;
boolean b2 = true;
boolean result1 = b ^ b2; // true
boolean result2 = b | b2; // true
boolean result3 = b & b2; // false

boolean result = b & b2 | b ^ b2; //true

Return to top


Short-Circuit Logical Operators

Two short-circuit logical operators, AND(&&) and OR(||) provide logical operation only on boolean types. Similar to & and |.

But the main difference between && and & and between || and | is that when the left operand is evaluated and the definitely known the result, the right operand will not be evaluated. Such feature is called short-circuit. It has been used to check null-reference-handling and improve efficiency.

Short-Circuit features:

String str = "Something assigned on the runtime";
if ((str != null) && (str.length() > 15)) {
    System.out.println(str);
	//or doing something else
}
If the str reference is null, the right operand will not be evaluated. If you change the above to the following:
String str = "Something assigned on the runtime";
if ((str != null) & (str.length() > 15)) {
    System.out.println(str);
	//or doing something else
}
If the str == null, the right operand will be evaluated and a NullPointerException will be thrown.
int counter = 10;
if (counter == 10 || ++counter == 15) {
    System.out.println(counter); // 10
}
int counter = 10;
if (counter == 10 | ++counter == 15) {
    System.out.println(counter); // 11
}

Return to top


Conditional Operator

?: is also known as the ternary operator, because it takes three operands. It is a short way to express conditions.

boolean start = true;
int a, b, c;
if (start) {
    a = b;
}
else {
    a = c;
}
==
a = start? b : c;
If start is true, b will be assigned to a. If start is false, c will be assigned to a.
NOTE: a, b, c should be type-compatible.

Return to top


Assignment Operators

There are at least 12 assignment or compound assignment operators.

= , op= operators set the value of a variable or expresion to a new value. = is a simple assignment. op can be any of the binary, non-boolean operators. op= like "*=, +=, etc." are called compound operators.

x op= y equals x = x op y

x += y equals x = x + y.
x *= y equals x = x * y.
NOTE: compound assignments include implicit cast.
byte b = 3;
b += 4; // b = 7

b = b + 4;//won't compile because b has been promoted to int before it adds 4.
b = (byte)(b + 4); //OK

int x = 3, y = 5;
y += x; // 8
y *= x; // 24

An assignment is an operator because it has value.

int a, b, c, d;
a = b = c = d = 5; 

Return to top