Java Fundamentals Tutorial : Operators
Operators in Java
| Operator | Use | Description |
|---|---|---|
|
| Adds |
|
| Subtracts |
| Arithmetically negates | |
|
| Multiplies |
|
| Divides |
|
| Computes the remainder of dividing |
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 todouble. -
Otherwise, if either operand is of type
float, the other is converted tofloat. -
Otherwise, if either operand is of type
long, the other is converted tolong. -
Otherwise, both operands are converted to type
int.
For unary (single-argument) arithmetic operators:
-
If the operand is of type
byte,short, orchar, the result is a value of typeint. - 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.0results inNaN. -
A non-zero integral value divided by integral 0 results in an
ArithmeticExceptionthrown at runtime.
![]() | 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, |
| Operator | Use | Description |
|---|---|---|
|
|
|
|
| |
|
|
|
|
|
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).
The plus (
+) operator performs string concatenation.The result is a new
Stringobject, for example:String first = "George"; String last = "Washington"; String name = first + " " + last; // "George Washington"
You can concatenate a
Stringwith Java primitive types.Java automatically generates a
Stringrepresentation 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 theStringconcatenation+.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"
| Operator | Use | Description |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
}| Operator | Use | Evaluates to true if |
|---|---|---|
|
| Both |
|
| Either |
|
|
|
-
All operands to these operators must be
booleanvalues. -
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,yis evaluated only ifxistrue. Ifxisfalse, the expression immediately evaluates tofalse. -
In
x || y,yis evaluated only ifxisfalse. Ifxistrue, the expression immediately evaluates totrue.
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.
| Operator | Use | Evaluates to true if |
|---|---|---|
|
| Bitwise complement of |
|
| AND all bits of |
|
| OR all bits of |
|
| XOR all bits of |
|
| Shift |
|
| Shift |
|
| Shift |
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 tolong. -
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 typelong. -
Otherwise, the result is of type
int.
| Operation | Decimal Result | Binary Result |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.
| Operator | Use | Shortcut for |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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);
| Operator | Use | Description |
|---|---|---|
|
| Require operator precedence |
|
| Equivalent to:
|
|
| Access array element |
|
| Access object method or field |
|
| Cast from one type to another |
|
| Create a new object |
|
| Check for object type, returning |
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.
-
[],(),. -
++,--,~,!,(type),new,- -
*,/,% -
+,- -
<<,>>,>>> -
<,<=,>,>=,instanceof -
==,!= -
& -
^ -
| -
&& -
|| -
? : -
=,*=,/=,+=,-=,%=,<<=,>>=,>>>=,&=,^=,|=
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
![[Note]](../images/note.png)