Computer Science Reference Operators
Computer Science Reference Operators
Operators
3. 1. Operators( 5 ) 3. 6. Relational Operators( 2 )
3. 2. Assignment Operators( 1 ) 3. 7. Logical Operators( 10 )
3. 3. Increment Decrement Operators( 5 ) 3. 8. Ternary Operator( 1 )
3. 4. Arithmetic Operators( 6 ) 3. 9. Comma Operator( 1 )
3. 5. Bitwise Operators( 23 ) 3. 10. instanceof( 4 )
3. 1. Operators
3. 1. 1. Six categories of operators
3. 1. 2. Operator Precedence
3. 1. 2. Operator Precedence
Operators with a higher precedence are executed before those of a lower precedence.
Operators on the same line have the same precedence:
Operator Precedence Group Associativity Operator Precedence
(), [], postfix ++, postfix -- left Highest
unary +, unary -, prefix ++, prefix --, ~, ! right
(type), new left
*, /, % left
+, - left
<<, >>, >>> left
< ,<= , >, >=, instanceof
==, !=
& left
^ left
| left
&& left
|| left
?: left
=, +=, -=, *=, /=, %=, <<=, >>=, >>>=, &=, |=, ^= right lowest
count += 5;
System.out.println(count);
count = count + 5;
System.out.println(count);
6
11
The complete set of op= operators:
1. +=
2. -=
3. *=
4. /=
5. %=
6. <<=
7. >>=
8. >>>=
9. &=
10. |=
11. ^=
A
B
3. 1. 5. Tests all the operators on all the primitive data types to show
ones are accepted by the Java compiler
3. 2. Assignment Operators
3. 2. 1. Several assignment operators
a += 5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
a = 6
b = 8
c = 3
a = 2
b = 3
c = 4
d = 1
System.out.println(count);
}
10
System.out.println(numA);
System.out.println(numC);
}
}
6
16
System.out.println(numA);
System.out.println(numC);
}
}
6
16
public class MainClass {
public static void main(String[] args) {
int numA = 5;
int numB = 10;
int numC = 0;
4
14
System.out.println( a-- );
System.out.println( a++ );
System.out.println( --a );
System.out.println( ++a );
}
12.12
11.12
11.12
12.12
3. 4. Arithmetic Operators
3. 4. 1. Arithmetic Calculations
3. 4. 2. Arithmetic Operators
3. 4. 1. Arithmetic Calculations
c = a + b;
System.out.println(c);
}
3. 4. 2. Arithmetic Operators
Operator Result
+ Addition
- Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
-- Decrement
Integer Arithmetic
a = 2
b = 6
c = 1
d = -1
e = 1
import java.util.Random;
j = 31
k = 84
j + k = 115
j - k = -53
k / j = 2
k * j = 2604
k % j = 22
j %= k = 31
v = 0.79780066
w = 0.9309381
v + w = 1.7287388
v - w = -0.13313746
v * w = 0.7427031
v / w = 0.8569857
u += v = 1.6547863
u -= v = 0.8569857
u *= v = 0.6837037
u /= v = 0.8569856
1
2
1
System.out.println( a % b );
}
0.1999999999999998
3. 5. Bitwise Operators
The Bitwise Operators can be applied to the integer types, long, int,
3. 5. 1.
short, char, and byte.
3. 5. 4. Bitwise OR (|)
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>> Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
A B A | B A & B A ^ B ~A
0 0 0 0 0 1
1 0 1 0 1 0
0 1 1 0 1 1
1 1 1 1 0 0
00101010 42
becomes
11010101
00101010 42
& 00001111 15
__________
00001010 10
The Bitwise OR
00101010 42
| 00001111 15
_________
00101111 47
3. 5. 4. Bitwise OR (|)
System.out.println(19 | 7);
}
}
//23
System.out.println(9 ^ 7);
}
}
//14
int j = ~i + 1;
System.out.println(j);
i = ~j + 1;
System.out.println(i);
}
}
/*
1
-1
1
*/
a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
~a = 1100
3. 5. 9. All bitwise operators in action
import java.util.Random;
long l = rand.nextLong();
long m = rand.nextLong();
printBinaryLong("-1L", -1L);
printBinaryLong("+1L", +1L);
long ll = 9223372036854775807L;
printBinaryLong("maxpos", ll);
long lln = -9223372036854775808L;
printBinaryLong("maxneg", lln);
printBinaryLong("l", l);
printBinaryLong("~l", ~l);
printBinaryLong("-l", -l);
printBinaryLong("m", m);
printBinaryLong("l & m", l & m);
printBinaryLong("l | m", l | m);
printBinaryLong("l ^ m", l ^ m);
printBinaryLong("l << 5", l << 5);
printBinaryLong("l >> 5", l >> 5);
printBinaryLong("(~l) >> 5", (~l) >> 5);
printBinaryLong("l >>> 5", l >>> 5);
printBinaryLong("(~l) >>> 5", (~l) >>> 5);
}
static void printBinaryInt(String s, int i) {
System.out.println(s + ", int: " + i + ", binary: ");
System.out.print(" ");
for (int j = 31; j >= 0; j--)
if (((1 << j) & i) != 0)
System.out.print("1");
else
System.out.print("0");
System.out.println();
}
a |= 4;
b >>= 1;
c <<= 1;
a ^= c;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
a = 3
b = 1
c = 6
i = a << 2;
b = (byte) (a << 2);
Original value of a: 64
i and b: 256 0
536870908
1073741816
2147483632
-32
int a = 32;
a = a >> 2; // a now contains 8
System.out.println(a);
}
}
int a = -1;
a = a >>> 24;
System.out.println(a);
}
}
255
b = 0xf1
b >> 4 = 0xff
b >>> 4 = 0xff
(b & 0xff) >> 4 = 0x0f
System.out.println(i);
int j = ~i + 1;
System.out.println(j);
i = ~j + 1;
System.out.println(i);
}
}
/*
1
-1
1
*/
import java.util.BitSet;
// Set a bit on
bits.set(2);
// Clear a bit
bits.clear(1);
import java.util.BitSet;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Operations on bit-mapped fields.
*
* @author Apache Jakarta POI
* @author Scott Sanders (sanders at apache dot org)
* @author Marc Johnson (mjohnson at apache dot org)
* @author Andrew C. Oliver (acoliver at apache dot org)
* @author Stephen Colebourne
* @author Pete Gieser
* @author Gary Gregory
* @since 2.0
* @version $Id: BitField.java 437554 2006-08-28 06:21:41Z bayard $
*/
public class BitField {
/**
* Creates a BitField instance.
*
* @param mask the mask specifying which bits apply to this
* BitField. Bits that are set in this mask are the bits
* that this BitField operates on
*/
public BitField(int mask) {
_mask = mask;
int count = 0;
int bit_pattern = mask;
if (bit_pattern != 0) {
while ((bit_pattern & 1) == 0) {
count++;
bit_pattern >>= 1;
}
}
_shift_count = count;
}
/**
* Obtains the value for the specified BitField, appropriately
* shifted right.
*
* Many users of a BitField will want to treat the specified
* bits as an int value, and will not want to be aware that the
* value is stored as a BitField (and so shifted left so many
* bits).
*
* @see #setValue(int,int)
* @param holder the int data containing the bits we're interested
* in
* @return the selected bits, shifted right appropriately
*/
public int getValue(int holder) {
return getRawValue(holder) >> _shift_count;
}
/**
* Obtains the value for the specified BitField, appropriately
* shifted right, as a short.
*
* Many users of a BitField will want to treat the specified
* bits as an int value, and will not want to be aware that the
* value is stored as a BitField (and so shifted left so many
* bits).
*
* @see #setShortValue(short,short)
* @param holder the short data containing the bits we're
* interested in
* @return the selected bits, shifted right appropriately
*/
public short getShortValue(short holder) {
return (short) getValue(holder);
}
/**
* Obtains the value for the specified BitField, unshifted.
*
* @param holder the int data containing the bits we're
* interested in
* @return the selected bits
*/
public int getRawValue(int holder) {
return holder & _mask;
}
/**
* Obtains the value for the specified BitField, unshifted.
*
* @param holder the short data containing the bits we're
* interested in
* @return the selected bits
*/
public short getShortRawValue(short holder) {
return (short) getRawValue(holder);
}
/**
* Returns whether the field is set or not.
*
* This is most commonly used for a single-bit field, which is
* often used to represent a boolean value; the results of using
* it for a multi-bit field is to determine whether *any* of its
* bits are set.
*
* @param holder the int data containing the bits we're interested
* in
* @return <code>true</code> if any of the bits are set,
* else <code>false</code>
*/
public boolean isSet(int holder) {
return (holder & _mask) != 0;
}
/**
* Returns whether all of the bits are set or not.
*
* This is a stricter test than {@link #isSet(int)},
* in that all of the bits in a multi-bit set must be set
* for this method to return <code>true</code>.
*
* @param holder the int data containing the bits we're
* interested in
* @return <code>true</code> if all of the bits are set,
* else <code>false</code>
*/
public boolean isAllSet(int holder) {
return (holder & _mask) == _mask;
}
/**
* Replaces the bits with new values.
*
* @see #getValue(int)
* @param holder the int data containing the bits we're
* interested in
* @param value the new value for the specified bits
* @return the value of holder with the bits from the value
* parameter replacing the old bits
*/
public int setValue(int holder, int value) {
return (holder & ~_mask) | ((value << _shift_count) & _mask);
}
/**
* Replaces the bits with new values.
*
* @see #getShortValue(short)
* @param holder the short data containing the bits we're
* interested in
* @param value the new value for the specified bits
* @return the value of holder with the bits from the value
* parameter replacing the old bits
*/
public short setShortValue(short holder, short value) {
return (short) setValue(holder, value);
}
/**
* Clears the bits.
*
* @param holder the int data containing the bits we're
* interested in
* @return the value of holder with the specified bits cleared
* (set to <code>0</code>)
*/
public int clear(int holder) {
return holder & ~_mask;
}
/**
* Clears the bits.
*
* @param holder the short data containing the bits we're
* interested in
* @return the value of holder with the specified bits cleared
* (set to <code>0</code>)
*/
public short clearShort(short holder) {
return (short) clear(holder);
}
/**
* Clears the bits.
*
* @param holder the byte data containing the bits we're
* interested in
*
* @return the value of holder with the specified bits cleared
* (set to <code>0</code>)
*/
public byte clearByte(byte holder) {
return (byte) clear(holder);
}
/**
* Sets the bits.
*
* @param holder the int data containing the bits we're
* interested in
* @return the value of holder with the specified bits set
* to <code>1</code>
*/
public int set(int holder) {
return holder | _mask;
}
/**
* Sets the bits.
*
* @param holder the short data containing the bits we're
* interested in
* @return the value of holder with the specified bits set
* to <code>1</code>
*/
public short setShort(short holder) {
return (short) set(holder);
}
/**
* Sets the bits.
*
* @param holder the byte data containing the bits we're
* interested in
*
* @return the value of holder with the specified bits set
* to <code>1</code>
*/
public byte setByte(byte holder) {
return (byte) set(holder);
}
/**
* Sets a boolean BitField.
*
* @param holder the int data containing the bits we're
* interested in
* @param flag indicating whether to set or clear the bits
* @return the value of holder with the specified bits set or
* cleared
*/
public int setBoolean(int holder, boolean flag) {
return flag ? set(holder) : clear(holder);
}
/**
* Sets a boolean BitField.
*
* @param holder the short data containing the bits we're
* interested in
* @param flag indicating whether to set or clear the bits
* @return the value of holder with the specified bits set or
* cleared
*/
public short setShortBoolean(short holder, boolean flag) {
return flag ? setShort(holder) : clearShort(holder);
}
/**
* Sets a boolean BitField.
*
* @param holder the byte data containing the bits we're
* interested in
* @param flag indicating whether to set or clear the bits
* @return the value of holder with the specified bits set or
* cleared
*/
public byte setByteBoolean(byte holder, boolean flag) {
return flag ? setByte(holder) : clearByte(holder);
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.Serializable;
/**
* Represents a collection of 64 boolean (on/off) flags. Individual flags
* are represented by powers of 2. For example,<br/>
* Flag 1 = 1<br/>
* Flag 2 = 2<br/>
* Flag 3 = 4<br/>
* Flag 4 = 8<br/><br/>
* or using shift operator to make numbering easier:<br/>
* Flag 1 = 1 << 0<br/>
* Flag 2 = 1 << 1<br/>
* Flag 3 = 1 << 2<br/>
* Flag 4 = 1 << 3<br/>
*
*
* There cannot be a flag with a value of 3 because that represents Flag 1
* and Flag 2 both being on/true.
*
*
* @version $Revision: 478334 $ $Date: 2006-11-
22 21:31:54 +0000 (Wed, 22 Nov 2006) $
*/
public class Flags implements Serializable {
/**
* Represents the current flag state.
*/
private long flags = 0;
/**
* Create a new Flags object.
*/
public Flags() {
super();
}
/**
* Initialize a new Flags object with the given flags.
*
* @param flags collection of boolean flags to represent.
*/
public Flags(long flags) {
super();
this.flags = flags;
}
/**
* Returns the current flags.
*
* @return collection of boolean flags represented.
*/
public long getFlags() {
return this.flags;
}
/**
* Tests whether the given flag is on. If the flag is not a power of 2
* (ie. 3) this tests whether the combination of flags is on.
*
* @param flag Flag value to check.
*
* @return whether the specified flag value is on.
*/
public boolean isOn(long flag) {
return (this.flags & flag) > 0;
}
/**
* Tests whether the given flag is off. If the flag is not a power of 2
* (ie. 3) this tests whether the combination of flags is off.
*
* @param flag Flag value to check.
*
* @return whether the specified flag value is off.
*/
public boolean isOff(long flag) {
return (this.flags & flag) == 0;
}
/**
* Turns on the given flag. If the flag is not a power of 2 (ie. 3) this
* turns on multiple flags.
*
* @param flag Flag value to turn on.
*/
public void turnOn(long flag) {
this.flags |= flag;
}
/**
* Turns off the given flag. If the flag is not a power of 2 (ie. 3) this
* turns off multiple flags.
*
* @param flag Flag value to turn off.
*/
public void turnOff(long flag) {
this.flags &= ~flag;
}
/**
* Turn off all flags.
*/
public void turnOffAll() {
this.flags = 0;
}
/**
* Turn off all flags. This is a synonym for <code>turnOffAll()</code>.
* @since Validator 1.1.1
*/
public void clear() {
this.flags = 0;
}
/**
* Turn on all 64 flags.
*/
public void turnOnAll() {
this.flags = Long.MAX_VALUE;
}
/**
* Clone this Flags object.
*
* @return a copy of this object.
* @see java.lang.Object#clone()
*/
public Object clone() {
try {
return super.clone();
} catch(CloneNotSupportedException e) {
throw new RuntimeException("Couldn't clone Flags object.");
}
}
/**
* Tests if two Flags objects are in the same state.
* @param obj object being tested
* @see java.lang.Object#equals(java.lang.Object)
*
* @return whether the objects are equal.
*/
public boolean equals(Object obj) {
if (!(obj instanceof Flags)) {
return false;
}
if (obj == this) {
return true;
}
/**
* The hash code is based on the current state of the flags.
* @see java.lang.Object#hashCode()
*
* @return the hash code for this object.
*/
public int hashCode() {
return (int) this.flags;
}
/**
* Returns a 64 length String with the first flag on the right and the
* 64th flag on the left. A 1 indicates the flag is on, a 0 means it's
* off.
*
* @return string representation of this object.
*/
public String toString() {
StringBuffer bin = new StringBuffer(Long.toBinaryString(this.flags));
for (int i = 64 - bin.length(); i > 0; i--) {
bin.insert(0, "0");
}
return bin.toString();
}
3. 6. Relational Operators
3. 6. 1. Relational Operators
3. 6. 1. Relational Operators
import java.util.Random;
System.out.println("(i < 10) && (j < 10) is " + ((i < 10) && (j < 10)));
System.out.println("(i < 10) || (j < 10) is " + ((i < 10) || (j < 10)));
}
}
i = 92
j = 22
i > j is true
i < j is false
i >= j is true
i <= j is false
i == j is false
i != j is true
(i < 10) && (j < 10) is false
(i < 10) || (j < 10) is false
3. 7. Logical Operators
3. 7. 5. Logical Operators
3. 7. 6. AND operator
3. 7. 8. Logical OR Operations
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
A B A | B A & B A ^ B !A
Conditional OR (||)
false || false: false
false || true: true
true || false: true
true || true: true
a = true
b = false
a|b = true
a&b = false
a^b = true
!a&b|a&!b = true
!a = false
3. 7. 5. Logical Operators
3. 7. 6. AND operator
if (a == 0 && b == 1) {
System.out.println("here");
} else {
System.out.println("there");
}
}
}
here
Conditional && will not evaluate the right-hand operand if the left-hand operand is false.
public class MainClass {
there
9
11
3. 7. 8. Logical OR Operations
The logical OR, ||, omits the evaluation of the right-hand operand when the left-hand operand is true.
public class MainClass {
there
9
11
a is 0
3. 7. 10. Demonstrates short-circuiting behavior
test1(0)
result: true
test2(2)
result: false
expression is false
3. 8. Ternary Operator
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
Absolute value of 10 is 10
Absolute value of -10 is 10
3. 9. Comma Operator
3. 9. 1. Comma Operator
3. 9. 1. Comma Operator
i= 1 j= 11
i= 2 j= 4
i= 3 j= 6
i= 4 j= 8
3. 10. instanceof
String s = "Hello";
if (s instanceof java.lang.String) {
System.out.println("is a String");
}
}
is a String
However, applying instanceof on a null reference variable returns false. For
example, the following if statement returns false.
public class MainClass {
public static void main(String[] a) {
String s = null;
if (s instanceof java.lang.String) {
System.out.println("true");
} else {
System.out.println("false");
}
}
false
Since a subclass 'is a' type of its superclass, the following if statement, where Child
is a subclass of Parent, returns true.
class Parent {
public Parent() {
}
}
class Child extends Parent {
public Child() {
super();
}
}
true
class Animal {
public String toString() {
return "This is an animal ";
}
}
class Dog extends Animal {
public void sound() {
System.out.println("Woof Woof");
}
}
public class MainClass {
public static void main(String[] a) {
Dog aDog = new Dog();
if (aDog instanceof Animal) {
Animal ani = (Animal) aDog;
System.out.println(ani);
}
}
}
This is an animal
}
}
//Object was an instance of the class java.util.Vector
class A {
int i, j;
}
class B {
int i, j;
}
class C extends A {
int k;
}
class D extends A {
int k;
}
class InstanceOf {
public static void main(String args[]) {
A a = new A();
B b = new B();
C c = new C();
D d = new D();
if (a instanceof A)
System.out.println("a is instance of A");
if (b instanceof B)
System.out.println("b is instance of B");
if (c instanceof C)
System.out.println("c is instance of C");
if (c instanceof A)
System.out.println("c can be cast to A");
if (a instanceof C)
System.out.println("a can be cast to C");
System.out.println();
A ob;
ob = d; // A reference to d
System.out.println("ob now refers to d");
if (ob instanceof D)
System.out.println("ob is instance of D");
System.out.println();
ob = c; // A reference to c
System.out.println("ob now refers to c");
if (ob instanceof D)
System.out.println("ob can be cast to D");
else
System.out.println("ob cannot be cast to D");
if (ob instanceof A)
System.out.println("ob can be cast to A");
System.out.println();