Operators All Versions
This draft deletes the entire topic.
Examples
-
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
-
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 longerif-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))
-
-
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:
A B ~A A & B A | B A ^ B 0 0 1 0 0 0 0 1 1 0 1 1 1 0 0 0 1 1 1 1 0 1 1 0 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
andlong
values. The operands are are converted as follows:- A
byte
,short
orchar
operand is promoted toint
, - A
Byte
Short
orCharacter
operand is unboxed and promoted toint
. - An
Integer
is unboxed to anint
. - 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 anint
result. - If both operands are
long
a 64 bit operation is performed, giving anlong
result. - One operand is
int
and the other islong
, theint
operand is promoted tolong
. Then a 64 bit operation is performed, giving along
result.
This means that if you perform a bitwise operation on a
byte
,short
orchar
, you cannot directly assign the result to abyte
,short
orchar
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
- The bitwise complement (
-
Description Operators Level grouping & accessing ( ) [ ] . 15 postfix expr++ expr-- 14 unary ++expr --expr +expr -expr ~ ! 13 multiplicative * / % 12 additive + - 11 shift << >> >>> 10 relational < > <= >= instanceof 9 equality == != 8 bitwise AND & 7 bitwise exclusive OR ^ 6 bitwise inclusive OR | 5 logical AND && 4 logical OR || 3 ternary ? : 2 assignment = += -= *= /= %= &= ^= |= <<= >>= >>>= 1 Higher level means higher precedence
Given an expressions
expr
with more than one operator -- the higher the operator precedence (level), the sooner it is evaluated inexpr
. In case two operators ofexpr
have the same precedence, the evaluation is from left to right, as the following example shows:int x = 11; int expr = 20 / --x + 5 * 4 % 6; // 4
where:
--x
has the higher precedence (level 13) so it is evaluated before any other operator inexpr
, and therefore before/
;*
,/
and%
have all the same precedence (level 12), so5*4%6
is evaluated from left to right;+
(level 11) has a lower precedence than*
,/
and%
so it is evaluated afterwards;=
(level 1) has the lower precedence inexpr
, so it is the last evaluated operator.
Parentheses,
(
and)
, can be used to make the meaning of an expression more obvious:int x1 = 11; int expr1 = 20 / (--x1) + (5 * 4) % 6; // 4 - same result as expr, but easier // to understand for many
They can also be used to override the normal operator precedence:
int x2 = 11; int expr2 = 20 / (--x2 + 5 * 4) % 6; // 0 - different result
-
Addition can be done using the
+
operator:int a = 5; int b = 3; int c = -2; a + b // 5 + 3 = 8 a + c // 5 + (-2) = 3 c + c // (-2) + (-2) = -4
The
+
operator is defined for the datatypeslong
,int
,short
,byte
,double
,float
andString
.For
String
s the operator concatenates the two operands:String s1 = "a String"; String s2 = "This is " + s1; // s2 contains "This is a String"
If a
String
is concatenated with a non-String
, the non-String
is first converted to aString
by thetoString
method of the object. If the operand is a primitive, the statictoString
method of the appropriate wrapper class is used.(Note that there are performance issues with using '+' to do string concatenation in a loop; see String concatenation in a loop does not scale .)
When operands are from different numeric types, the type of the result will be the type of the one with more capacity. However, the result will not be smaller than
int
, e.g. the sum of twoshort
values will be anint
.short s1 = 3; short s2 = 4; s1 + s2 // This is an int int a = 5; long b = 1; a + b // This is a long (long > int) long b = 1; float f = 3.0f; b + f // This is a float (float > long) String s = "hello"; double d = 3.4; s + d // This is a String
-
Division can be done using the
/
operator, if both operands are integer numbers a integer division is performed.int a = 1; int b = 2; int c = a / b; // 1 / 2 = 0.5 truncated = 0 double a = 6; double b = 3; double c = -2; a / b // 6 / 3 = 2 b / c // 3 / -2 = -1.5 c / c // -2 / -2 = 1
To get a double or a float out of an integer division you need to perform a cast.
int a = 5; int b = 2; float c = a / (float) b; // 2.5 instead of 2
Division of integral types
Two integral expressions are divided, the result is rounded to the value closer to 0.
System.out.println(5 / 2); // 2 System.out.println(-5 / 2); // -2 System.out.println(8 / -3); // -2
Division by 0 results in a
ArithmeticException
being thrown.int i = 50 / 0; // throws exception
Floating point arithmetic: Division by 0
Division by a floating point value 0 result in
NaN
,Infinity
or-Infinity
, if both values have a absolute value of 0, have the same sign and the dividend is != 0 or have a different sign and the dividend is != 0.System.out.println(Double.POSITIVE_INFINITY / 0d); // Infinity System.out.println(Double.NEGATIVE_INFINITY / 0d); // -Infinity System.out.println(5d / 0d); // Infinity System.out.println(-5d / 0d); // -Infinity System.out.println(5d / -0d); // -Infinity System.out.println(0d / -0d); // NaN
Floating point arithmetic: Division by Infinity
Division by an infinite value yields
NaN
,0.0
or-0.0
, if both values are infinite, the divident is finite and the signs match or the dividend is finite and the signs are different.System.out.println(5d / Double.POSITIVE_INFINITY); // 0.0 System.out.println(-5d / Double.NEGATIVE_INFINITY); // 0.0 System.out.println(5d / Double.NEGATIVE_INFINITY); // -0.0 System.out.println(0d / Double.POSITIVE_INFINITY); // 0.0 System.out.println(Double.POSITIVE_INFINITY / Double.POSITIVE_INFINITY); // NaN System.out.println(Double.POSITIVE_INFINITY / Double.NEGATIVE_INFINITY); // NaN
NaN as operand
If one of the operands is
NaN
, the result is alwaysNaN
.System.out.println(Double.NaN / Double.NaN); // NaN System.out.println(Double.POSITIVE_INFINITY / Double.NaN); // NaN System.out.println(1d / Double.NaN); // NaN System.out.println(0d / Double.NaN); // NaN System.out.println(Double.NaN / 0d); // NaN System.out.println(Double.NaN / 1d); // NaN
-
This operator checks whether the object is of a particular class/interface type. instanceof operator is written as:
( Object reference variable ) instanceof (class/interface type)
Example:
public class Test { public static void main(String args[]){ String name = "Buyya"; // following will return true since name is type of String boolean result = name instanceof String; System.out.println( result ); } }
This would produce the following result:
true
This operator will still return true if the object being compared is the assignment compatible with the type on the right.
Example:
class Vehicle {} public class Car extends Vehicle { public static void main(String args[]){ Vehicle a = new Car(); boolean result = a instanceof Car; System.out.println( result ); } }
This would produce the following result:
true
-
Calculating a remainder is performed using the
%
operator. Performingx % y
returns the whole number remainder after performingx / y
.That means that the following conditions hold true:
10 % 5 == 0
as10 / 5 == 2
and10 - 2 * 5 == 0
10 % 3 == 1
as10 / 3 == 3
and10 - 3 * 3 == 1
It is worth noting that Java's
%
operator may return a negative result. The remainder operator isn't therefore a modulus operator that always returns a result between 0 and the divider:-10 % 3 == -1
as-10 / 3 == -3
, and-10 - (-3 * 3) == -1
10 % -3 == 1
as10 / -3 == -3
, and10 - (-3 * -3) == 1
-10 % -3 == -1
as-10 / -3 == 3
, and-10 - (3 * -3) == -1
To use a moderator function, use:
public static int mod(int x, int y) { int result = x % y; if (result < 0) { result += y; } return result; }
So long as
y > 0
, this will return a result in the range 0 to y - 1, consistent with the mathematical definition of modulus. In other words, the result will be within the mathematical group Y consisting of 0 .. y - 1.The results for
y < 0
are still inconsistent; disallowing a negativey
could be considered.
Beware that calculations are performed using integers unless the leftmost argument is a
long
. This means that operands are first widened to an integer before the operation is performed. -
Java provides 6 logical operators; i.e., operators that take one or two operands of type
boolean
and produce aboolean
result. These are:!
- the NOT operator,&
and&&
- the AND operators,|
and||
- the inclusive OR operators, and^
- the exclusive OR operator.
The values produced by these operators are given the following "truth table".
X Y !X X && Y
X & YX || Y
X | YX ^ Y true true false true true false true false false false true true false true true false true true false false true false false false The difference between the regular (
&
and|
) and short-circuit (&&
and||
) operators is in the way that the operand expressions are evaluated:-
The evaluation of
<left-expr> & <right-expr>
is equivalent to the following pseudo-code:{ boolean L = evaluate(<left-expr>); boolean R = evaluate(<right-expr>); return L AND R; }
-
The evaluation of
<left-expr> && <right-expr>
is equivalent to the following pseudo-code:{ boolean L = evaluate(<left-expr>); if (L) { return evaluate(<right-expr>); } else { // short-circuit the evaluation of the 2nd operand expression return false; } }
-
The evaluation of
<left-expr> | <right-expr>
is equivalent to the following pseudo-code:{ boolean L = evaluate(<left-expr>); boolean R = evaluate(<right-expr>); return L OR R; }
-
The evaluation of
<left-expr> || <right-expr>
is equivalent to the following pseudo-code:{ boolean L = evaluate(<left-expr>); if (!L) { return evaluate(<right-expr>); } else { // short-circuit the evaluation of the 2nd operand expression return true; } }
As the pseudo-code above illustrates, the behavior of the short-circuit operators are equivalent to using
if
/else
statements.Example - using && as a guard in an expression
The following example shows the most common usage pattern for the
&&
operator. Compare these two versions of a method to test if a suppliedInteger
is zero.public boolean isZero(Integer value) { return value == 0; } public boolean isZero(Integer value) { return value != null && value == 0; }
The first version works in most cases, but if the
value
argument isnull
, then aNullPointerException
will be thrown.In the second version we have added a "guard" test. The
value != null && value == 0
expression is evaluated by first performing thevalue != null
test. If thenull
test succeeds (i.e. it evaluates totrue
) then thevalue == 0
expression is evaluated. If thenull
test fails, then the evaluation ofvalue == 0
is skipped (short-circuited), and we don't get aNullPointerException
.Example - using && to avoid a costly calculation
The following example shows how
&&
can be used to avoid a relatively costly calculation:public boolean verify(int value, boolean needPrime) { return !needPrime | isPrime(value); } public boolean verify(int value, boolean needPrime) { return !needPrime || isPrime(value); }
In the first version, both operands of the
|
will always be evaluated, so the (expensive)isPrime
method will be called unnecessarily. The second version avoids the unnecessary call by using||
instead of|
. -
Subtraction can be done using the
-
operatorint a = 5; int b = 3; int c = -2; a - b // 5 - 3 = 2 a - c // 5 - (-2) = 7 c - c // (-2) - (-2) = 0
-
The left hand operand for these operators must be a either a non-final variable or an element of an array. The right hand operand must be assignment compatible with the left hand operand. This means that either the types must be the same, or the right operand type must be convertible to the left operands type by a combination of boxing, unboxing or widening. (For complete details refer to JLS 5.2.)
The precise meaning of the "operation and assign" operators is specified by JLS 15.26.2 as:
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T) ((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.Note that there is an implicit type-cast before the final assignment.
1.
=
The simple assignment operator: assigns the value of the right hand operand to the left hand operand.
Example:
c = a + b
will add the value ofa + b
to the value ofc
and assign it toc
2.
+=
The "add and assign" operator: adds the value of right hand operand to the value of the left hand operand and assigns the result to left hand operand. If the left hand operand has type
String
, then this a "concatenate and assign" operator.Example:
c += a
is roughly the same asc = c + a
3.
-=
The "subtract and assign" operator: subtracts the value of the right operand from the value of the left hand operand and assign the result to left hand operand.
Example:
c -= a
is roughly the same asc = c - a
4.
*=
The "multiply and assign" operator: multiplies the value of the right hand operand by the value of the left hand operand and assign the result to left hand operand. .
Example:
c *= a
is roughly the same asc = c * a
5.
/=
The "divide and assign" operator: divides the value of the right hand operand by the value of the left hand operand and assign the result to left hand operand.
Example:
c /*= a
is roughly the same asc = c / a
6.
%=
The "modulus and assign" operator: calculates the modulus of the value of the right hand operand by the value of the left hand operand and assign the result to left hand operand.
Example:
c %*= a
is roughly the same asc = c % a
7.
<<=
The "left shift and assign" operator.
Example:
c <<= 2
is roughly the same asc = c << 2
8.
>>=
The "arithmetic right shift and assign" operator.
Example:
c >>= 2
is roughly the same asc = c >> 2
9.
>>>=
The "logical right shift and assign" operator.
Example:
c >>>= 2
is roughly the same asc = c >>> 2
10.
&=
The "bitwise and and assign" operator.
Example:
c &= 2
is roughly the same asc = c & 2
11.
|=
The "bitwise or and assign" operator.
Example:
c |= 2
is roughly the same asc = c | 2
12.
^=
The "bitwise exclusive or and assign" operator.
Example:
c ^= 2
is roughly the same asc = c ^ 2
-
The Java language provides three operator for performing bitwise shifting on 32 and 64 bit integer values. These are all binary operators with the first operand being the value to be shifted, and the second operand saying how far to shift.
-
The
<<
or left shift operator shifts the value given by the first operand leftwards by the number of bit positions given by the second operand. The empty positions at the right end are filled with zeros. -
The '>>' or arithmetic shift operator shifts the value given by the first operand rightwards by the number of bit positions given by the second operand. The empty positions at the left end are filled by copying the left-most bit. This process is known as sign extension.
-
The '>>>' or logical right shift operator shifts the value given by the first operand rightwards by the number of bit positions given by the second operand. The empty positions at the left end are filled with zeros.
Notes:
-
These operators require an
int
orlong
value as the first operand, and produce a value with the same type as the first operand. (You will need to use an explicit type cast when assigning the result of a shift to abyte
,short
orchar
variable.) -
If you use a shift operator with a first operand that is a
byte
,char
orshort
, it is promoted to anint
and the operation produces anint
.) -
The second operand is reduced modulo the number of bits of the operation to give the amount of the shift. For more about the mod mathematical concept, see Modulus examples.
-
The bits that are shifted off the left or right end by the operation are discarded. (Java does not provide a primitive "rotate" operator.)
-
The arithmetic shift operator is equivalent dividing a (two's complement) number by a power of 2.
-
The left shift operator is equivalent multiplying a (two's complement) number by a power of 2.
The following table will help you see the effects of the three shift operators. (The numbers have been expressed in binary notation to aid vizualization.)
Operand1 Operand2 <<
>>
>>>
0b0000000000001011 0 0b0000000000001011 0b0000000000001011 0b0000000000001011 0b0000000000001011 1 0b0000000000010110 0b0000000000000101 0b0000000000000101 0b0000000000001011 2 0b0000000000101100 0b0000000000000010 0b0000000000000010 0b0000000000001011 28 0b1011000000000000 0b0000000000000000 0b0000000000000000 0b0000000000001011 31 0b1000000000000000 0b0000000000000000 0b0000000000000000 0b0000000000001011 32 0b0000000000001011 0b0000000000001011 0b0000000000001011 ... ... ... ... ... 0b1000000000001011 0 0b1000000000001011 0b1000000000001011 0b1000000000001011 0b1000000000001011 1 0b0000000000010110 0b1100000000000101 0b0100000000000101 0b1000000000001011 2 0b0000000000101100 0b1110000000000010 0b00100000000000100 0b1000000000001011 31 0b1000000000000000 0b1111111111111111 0b0000000000000001 There examples of the user of shift operators in Bit manipulation
-
-
The
==
operator checks returns whether two values are equal. When using the==
operator with primitive values, such asint
orbool
, they are compared by value:int a = 5; double b = 0.0; boolean c = true; a == a // true a == 5 // true a == 6 // false b == 0 // true b == 0.0 // true b == 1.0 // false c // true c == true // true c == false // false
The not equals operator
!=
will simply return the inverse of what the equals operator==
returns.int a = 5; double b = 0.0; boolean c = true; a != a // false a != 6 // true b != 0.0 // false c != true // false
If the 2 operands are object references, the
==
and!=
operators test if the two operands refer to the same object. This often not what you want. To test if two objects are equal by value, the.equals()
method should be used instead.String s1 = "We are equal"; String s2 = new String("We are equal"); s1.equals(s2); // true // WARNING - don't use == or != with String values s1 == s2; // false
Warning: using
==
and!=
to compareString
values is incorrect in most cases; see http://stackoverflow.com/documentation/java/4388/java-pitfalls/16290/using-to-compare-strings . A similar problem applies to primitive wrapper types; see http://stackoverflow.com/documentation/java/4388/java-pitfalls/8996/using-to-compare-primitive-wrappers-objects-such-as-integer . -
Note: This section contains examples for the mathematical concept important in the explanation of both left and right shift operators.
x x mod 32 x mod 64 0 0 0 5 5 5 31 31 31 63 31 63 32 0 32 64 0 0 -1 32 63 -10 22 54 1023 = 210
= 32 * 25
= 64 * 2431 63 a + b ((a mod 32)+(b mod 32))
mod 32((a mod 64)+(b mod 64))
mod 64a + n * 32 (a mod 32)
a - n * 32 (a mod 32)
a + n * 64 (a mod 32)
(a mod 64)
a - n * 64 (a mod 32)
(a mod 64)
-
Multiplication can be done using the
*
operatorint a = 5; int b = 3; int c = -2; a * b; // 5 * 3 = 15 b * c; // 3 * -2 = -6 c * c; // -2 * -2 = 4
Topic Outline
- Increment/Decrement Operators (++/--)
- Ternary Operator (? :)
- Integer Bitwise Operators (~, &, |, ^)
- Operator Precedence and Parentheses
- Addition/Concatenation Operator (+)
- Division Operator (/)
- Instanceof Operator
- Modulus Operator (%)
- Regular and short-circuit logical operators ( !, &, |, ^, && and || )
- Subtraction Operator (-)
- The Assignment Operators (=, +=, -=, *=, /=, %=, <<=, >>= , >>>=, &=, |= and ^=)
- The Shift Operators (<<, >> and >>>)
- Equals/Not Equals Operators (==/!=)
- Modulus examples
- Multiplication Operator (*)
Syntax
Sign up or log in
Save edit as a guest
Join Stack Overflow
Using Google
Using Facebook
Using Email and Password
We recognize you from another Stack Exchange Network site!
Join and Save Draft