Java Fundamentals Tutorial : Operators

4. Operators

Operators in Java

4.1. Arithmetic Operators

OperatorUseDescription

+

x + y

Adds x and y

-

x - y

Subtracts y from x

-x

Arithmetically negates x

*

x * y

Multiplies x by y

/

x / y

Divides x by y

%

x % y

Computes the remainder of dividing x by y

In Java, you need to be aware of the type of the result of a binary (two-argument) arithmetic operator.

  • If either operand is of type double, the other is converted to double.
  • Otherwise, if either operand is of type float, the other is converted to float.
  • Otherwise, if either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.

For unary (single-argument) arithmetic operators:

  • If the operand is of type byte, short, or char, the result is a value of type int.
  • Otherwise, a unary numeric operand remains as is and is not converted.

This can result in unexpected behavior for a newcomer to Java programming. For example, the code below results in a compilation error:

short a = 1;
short b = 2;
short c = a + b;    // Compilation error

The reason is that the result of the addition is an int value, which cannot be stored in a variable typed short unless you explicitly cast it, as in:

short c = (short) (a + b);

Also, there are a couple of quirks to keep in mind regarding division by 0:

  • A non-zero floating-point value divided by 0 results in a signed Infinity. 0.0/0.0 results in NaN.
  • A non-zero integral value divided by integral 0 results in an ArithmeticException thrown at runtime.
[Note]Note

In Java, unlike C/C++, it is legal to compute the remainder of floating-point numbers. The result is the remainder after dividing the dividend by the divisor an integral number of times. For example, 7.9 % 1.2 results in 0.7 (approximately, given the precision of a float or double type).

4.2. Shortcut Arithmetic Operators

OperatorUseDescription

++

x++

y = x++; is the same as y = x; x = x + 1;

++x

y = ++x; is the same as x = x + 1; y = x;

--

x--

y = x--; is the same as y = x; x = x - 1;

--x

y = --x; is the same as x = x - 1; y = x;

The location of the shortcut operator is only important if the operator is used in an expression where the operand value is assigned to another variable or returned from a method.

That is to say that:

x++;

is equivalent to:

++x;

But in an assignment:

y = x++;

is not the same as:

y = ++x;

Shortcut operators are often used in for loops to increment the loop index variable (as we will see soon).

4.3. String Concatenation

  • The plus (+) operator performs string concatenation.

    • The result is a new String object, for example:

      String first = "George";
      String last = "Washington";
      String name = first + " " + last;   // "George Washington"
  • You can concatenate a String with Java primitive types.

    • Java automatically generates a String representation of the primitive value for concatenation, for example:

      int count = 8;
      String msg = "There are " + count + " cows.";   // "There are 8 cows."
  • The arithmetic + operator has the same order of precedence as the String concatenation +.

    • In a complex expression, they are evaluated from left to right, unless you use parentheses to override, for example:

      String test = 1 + 1 + " equals " + 1 + 1;   // "2 equals 11"
  • For other object types used as string concatenation operands, Java automatically invokes the object’s toString() method, for example:

    Date now = new Date();
    String msg = "The time is: " + now;
    // "The time is: Mon Feb 07 18:04:48 PST 2011"

4.4. Relational Operators

OperatorUseDescription

>

x > y

x is greater than y

>=

x >= y

x is greater than or equal to y

<

x < y

x is less than y

<=

x <= y

x is less than or equal to y

==

x == y

x is equal to y

!=

x != y

x is not equal to y

Only numerical primitive types (byte, short, char, int, float, long, and double) can be compared using the ordering operators (>, >=, <, and <=). Objects and booleans can only be tested for [in]equality (==, !=).

Due to Java’s type safety (booleans are not integers and vice versa), it is not possible to make the common mistake:

int x = 5;
int y = 3 + 2;

// Does not compile
if (x = y) {
    // Do something
}

// You must use equality operator
if (x == y) {
    // Do something
}

4.5. Logical Boolean Operators

OperatorUseEvaluates to true if

&&

x && y

Both x and y are true

||

x || y

Either x or y are true

!

!x

x is not true

  • All operands to these operators must be boolean values.
  • The logical && and \\ operators are subject to short circuit evaluation.

These logical operators accept boolean values only. Attempting to use numerical or other operand types results in a compilation error.

As with many modern programming languages, Java uses short circuit evaluation when evaluating logical boolean operators. This means that conditional operators evaluate the second operand only when needed:

  • In x && y, y is evaluated only if x is true. If x is false, the expression immediately evaluates to false.
  • In x || y, y is evaluated only if x is false. If x is true, the expression immediately evaluates to true.

For example:

int i = 0;
int j = 5;
if ( (i != 0) && ((j / i) > 1) ) {
    // Do something
}

Because we use a logical AND (&&), the first expression evaluates to false and so the second expression is not tested and the overall condition is false.

4.6. Bitwise Operators

OperatorUseEvaluates to true if

~

~x

Bitwise complement of x

&

x & y

AND all bits of x and y

|

x | y

OR all bits of x and y

^

x ^ y

XOR all bits of x and y

>>

x >> y

Shift x right by y bits, with sign extension

>>>

x >>> y

Shift x right by y bits, with 0 fill

<<

x << y

Shift x left by y bits

In general, these bitwise operators may be applied to integral values only. For the ~, &, \|, and ^ operators:

  • If either operand is of type long, the other is converted to long.
  • Otherwise, both operands are converted to type int.

For the shift operators:

  • If the value being shifted is of type long, the result is of type long.
  • Otherwise, the result is of type int.
Operation Decimal Result Binary Result

x

71

00000000000000000000000001000111

y

5

00000000000000000000000000000101

~x

-72

11111111111111111111111110111000

x & y

5

00000000000000000000000000000101

x | y

71

00000000000000000000000001000111

x ^ y

66

00000000000000000000000001000010

x >> y

2

00000000000000000000000000000010

x >>> y

2

00000000000000000000000000000010

x << y

2272

00000000000000000000100011100000

The bitwise operators may also be used with boolean values to produce a boolean result. However, you cannot combine boolean and integral operands in a bitwise expression.

4.7. Assignment Operators

OperatorUseShortcut for

=

x = y

x = y

+=

x += y

x = x + y

-=

x -= y

x = x - y

*=

x *= y

x = x * y

/=

x /= y

x = x / y

%=

x %= y

x = x % y

&=

x &= y

x = x & y (also works for boolean values)

|=

x |= y

x = x | y (also works for boolean values)

^=

x ^= y

x = x ^ y (also works for boolean values)

>>=

x >>= y

x = x >> y

>>>=

x >>>= y

x = x >>> y

<<=

x <<= y

x = x << y

Actually, a compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E1)), where T is the type of E1.

For example, the following code is compiles without error:

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short) (x + 4.6);

4.8. Other Operators

OperatorUseDescription

()

(x + y) * z

Require operator precedence

?:

z = b ? x : y

Equivalent to: if (b) { z = x; } else { z = y; }

[]

array[0]

Access array element

.

str.length()

Access object method or field

(type)

int x = (int) 1.2;

Cast from one type to another

new

d = new Date();

Create a new object

instanceof

o instanceof String

Check for object type, returning boolean

The short-cut conditional operator (?:) (also known as the “if-then-else operator” or the “ternary operator”) is used very often to make Java code more compact, so it is worthwhile to get accustomed to it.

For example:

int x = 0;
int y = 5;

// Long way

int z1;
if (x == 0) {
    z1 = 0;
} else {
    z1 = x / y;
}

// Short-cut way
int z2 = (x == 0) ? 0 : x / y;

We’ll explore the other operators listed on this slide in more depth throughout this class.

4.9. Operator Precedence

  1. [], (), .
  2. ++, --, ~, !, (type), new, -
  3. *, /, %
  4. +, -
  5. <<, >>, >>>
  6. <, <=, >, >=, instanceof
  7. ==, !=
  8. &
  9. ^
  10. |
  11. &&
  12. ||
  13. ? :
  14. =, *=, /=, +=, -=, %=, <<=, >>=, >>>=, &=, ^=, |=

Use the () operator to change precedence of operators:

x << (((((x == 0 ? 0 : (x / y)) + 5) * z) > 4) ? 3 : 7)

Other than in the most trivial situations, It is always a good practice to use () to document your intentions, regardless of precedence rules.

For example, change:

int x = 5 - y * 2 > 0 ? y : 2 * y;

to:

int x = ((5 - (y * 2)) > 0) ? y : (2 * y);

even though both lines will assign the same value to x